keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointTriangle.h
.h
16,824
493
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once // Compute the distance between a point and a solid triangle in nD. // // The triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The input point is stored in closest[0]. The closest point on the triangle // is stored in closest[1] with barycentric coordinates (b[0],b[1],b[2]). // // For a description of the algebraic details of the quadratic minimization // approach used by operator(), see // https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf // Although the document describes the 3D case, the construction applies in // general dimensions N. The UseConjugateGradient function uses conjugate // gradient minimization. #include <Mathematics/DCPQuery.h> #include <Mathematics/Triangle.h> namespace gte { template <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, Triangle<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), barycentric{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 3> barycentric; std::array<Vector<N, T>, 2> closest; }; // This query is exact when using arbitrary-precision arithmetic. It // can be used also for floating-point arithmetic, but rounding errors // can sometimes lead to inaccurate result. For floating-point, // consider UseConjugateGradient(...) which is more robust. Result operator()(Vector<N, T> const& point, Triangle<N, T> const& triangle) { // The member result.sqrDistance is set in each block of the // nested if-then-else statements. The remaining members are all // set at the end of the function. Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const two = static_cast<T>(2); Vector<N, T> diff = triangle.v[0] - point; Vector<N, T> edge0 = triangle.v[1] - triangle.v[0]; Vector<N, T> edge1 = triangle.v[2] - triangle.v[0]; T a00 = Dot(edge0, edge0); T a01 = Dot(edge0, edge1); T a11 = Dot(edge1, edge1); T b0 = Dot(diff, edge0); T b1 = Dot(diff, edge1); T det = std::max(a00 * a11 - a01 * a01, zero); T s = a01 * b1 - a11 * b0; T t = a01 * b0 - a00 * b1; if (s + t <= det) { if (s < zero) { if (t < zero) // region 4 { if (b0 < zero) { t = zero; if (-b0 >= a00) { s = one; } else { s = -b0 / a00; } } else { s = zero; if (b1 >= zero) { t = zero; } else if (-b1 >= a11) { t = one; } else { t = -b1 / a11; } } } else // region 3 { s = zero; if (b1 >= zero) { t = zero; } else if (-b1 >= a11) { t = one; } else { t = -b1 / a11; } } } else if (t < zero) // region 5 { t = zero; if (b0 >= zero) { s = zero; } else if (-b0 >= a00) { s = one; } else { s = -b0 / a00; } } else // region 0 { // minimum at interior point s /= det; t /= det; } } else { T tmp0{}, tmp1{}, numer{}, denom{}; if (s < zero) // region 2 { tmp0 = a01 + b0; tmp1 = a11 + b1; if (tmp1 > tmp0) { numer = tmp1 - tmp0; denom = a00 - two * a01 + a11; if (numer >= denom) { s = one; t = zero; } else { s = numer / denom; t = one - s; } } else { s = zero; if (tmp1 <= zero) { t = one; } else if (b1 >= zero) { t = zero; } else { t = -b1 / a11; } } } else if (t < zero) // region 6 { tmp0 = a01 + b1; tmp1 = a00 + b0; if (tmp1 > tmp0) { numer = tmp1 - tmp0; denom = a00 - two * a01 + a11; if (numer >= denom) { t = one; s = zero; } else { t = numer / denom; s = one - t; } } else { t = zero; if (tmp1 <= zero) { s = one; } else if (b0 >= zero) { s = zero; } else { s = -b0 / a00; } } } else // region 1 { numer = a11 + b1 - a01 - b0; if (numer <= zero) { s = zero; t = one; } else { denom = a00 - two * a01 + a11; if (numer >= denom) { s = one; t = zero; } else { s = numer / denom; t = one - s; } } } } result.closest[0] = point; result.closest[1] = triangle.v[0] + s * edge0 + t * edge1; diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); result.barycentric[0] = one - s - t; result.barycentric[1] = s; result.barycentric[2] = t; return result; } // The query is designed to be robust when using floating-point // arithmetic. For arbitrary-precision arithmetic, use the function // operator()(...). Result UseConjugateGradient(Vector<N, T> const& point, Triangle<N, T> const& triangle) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector<N, T> diff = point - triangle.v[0]; Vector<N, T> edge0 = triangle.v[1] - triangle.v[0]; Vector<N, T> edge1 = triangle.v[2] - triangle.v[0]; T a00 = Dot(edge0, edge0); T a01 = Dot(edge0, edge1); T a11 = Dot(edge1, edge1); T b0 = -Dot(diff, edge0); T b1 = -Dot(diff, edge1); T f00 = b0; T f10 = b0 + a00; T f01 = b0 + a01; std::array<T, 2> p0{}, p1{}, p{}; T dt1{}, h0{}, h1{}; // Compute the endpoints p0 and p1 of the segment. The segment is // parameterized by L(z) = (1-z)*p0 + z*p1 for z in [0,1] and the // directional derivative of half the quadratic on the segment is // H(z) = Dot(p1-p0,gradient[Q](L(z))/2), where gradient[Q]/2 = // (F,G). By design, F(L(z)) = 0 for cases (2), (4), (5), and // (6). Cases (1) and (3) can correspond to no-intersection or // intersection of F = 0 with the triangle. if (f00 >= zero) { if (f01 >= zero) { // (1) p0 = (0,0), p1 = (0,1), H(z) = G(L(z)) GetMinEdge02(a11, b1, p); } else { // (2) p0 = (0,t10), p1 = (t01,1-t01), // H(z) = (t11 - t10)*G(L(z)) p0[0] = zero; p0[1] = f00 / (f00 - f01); p1[0] = f01 / (f01 - f10); p1[1] = one - p1[0]; dt1 = p1[1] - p0[1]; h0 = dt1 * (a11 * p0[1] + b1); if (h0 >= zero) { GetMinEdge02(a11, b1, p); } else { h1 = dt1 * (a01 * p1[0] + a11 * p1[1] + b1); if (h1 <= zero) { GetMinEdge12(a01, a11, b1, f10, f01, p); } else { GetMinInterior(p0, h0, p1, h1, p); } } } } else if (f01 <= zero) { if (f10 <= zero) { // (3) p0 = (1,0), p1 = (0,1), H(z) = G(L(z)) - F(L(z)) GetMinEdge12(a01, a11, b1, f10, f01, p); } else { // (4) p0 = (t00,0), p1 = (t01,1-t01), H(z) = t11*G(L(z)) p0[0] = f00 / (f00 - f10); p0[1] = zero; p1[0] = f01 / (f01 - f10); p1[1] = one - p1[0]; h0 = p1[1] * (a01 * p0[0] + b1); if (h0 >= zero) { p = p0; // GetMinEdge01 } else { h1 = p1[1] * (a01 * p1[0] + a11 * p1[1] + b1); if (h1 <= zero) { GetMinEdge12(a01, a11, b1, f10, f01, p); } else { GetMinInterior(p0, h0, p1, h1, p); } } } } else if (f10 <= zero) { // (5) p0 = (0,t10), p1 = (t01,1-t01), // H(z) = (t11 - t10)*G(L(z)) p0[0] = zero; p0[1] = f00 / (f00 - f01); p1[0] = f01 / (f01 - f10); p1[1] = one - p1[0]; dt1 = p1[1] - p0[1]; h0 = dt1 * (a11 * p0[1] + b1); if (h0 >= zero) { GetMinEdge02(a11, b1, p); } else { h1 = dt1 * (a01 * p1[0] + a11 * p1[1] + b1); if (h1 <= zero) { GetMinEdge12(a01, a11, b1, f10, f01, p); } else { GetMinInterior(p0, h0, p1, h1, p); } } } else { // (6) p0 = (t00,0), p1 = (0,t11), H(z) = t11*G(L(z)) p0[0] = f00 / (f00 - f10); p0[1] = zero; p1[0] = zero; p1[1] = f00 / (f00 - f01); h0 = p1[1] * (a01 * p0[0] + b1); if (h0 >= zero) { p = p0; // GetMinEdge01 } else { h1 = p1[1] * (a11 * p1[1] + b1); if (h1 <= zero) { GetMinEdge02(a11, b1, p); } else { GetMinInterior(p0, h0, p1, h1, p); } } } Result result{}; result.closest[0] = point; result.closest[1] = triangle.v[0] + p[0] * edge0 + p[1] * edge1; diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); result.barycentric[0] = one - p[0] - p[1]; result.barycentric[1] = p[0]; result.barycentric[2] = p[1]; return result; } private: void GetMinEdge02(T const& a11, T const& b1, std::array<T, 2>& p) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); p[0] = zero; if (b1 >= zero) { p[1] = zero; } else if (a11 + b1 <= zero) { p[1] = one; } else { p[1] = -b1 / a11; } } inline void GetMinEdge12(T const& a01, T const& a11, T const& b1, T const& f10, T const& f01, std::array<T, 2>& p) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T h0 = a01 + b1 - f10; if (h0 >= zero) { p[1] = zero; } else { T h1 = a11 + b1 - f01; if (h1 <= zero) { p[1] = one; } else { p[1] = h0 / (h0 - h1); } } p[0] = one - p[1]; } inline void GetMinInterior(std::array<T, 2> const& p0, T const& h0, std::array<T, 2> const& p1, T const& h1, std::array<T, 2>& p) { T z = h0 / (h0 - h1); T omz = static_cast<T>(1) - z; p[0] = omz * p0[0] + z * p1[0]; p[1] = omz * p0[1] + z * p1[1]; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPPointTriangle = DCPQuery<T, Vector<N, T>, Triangle<N, T>>; template <typename T> using DCPPoint2Triangle2 = DCPPointTriangle<2, T>; template <typename T> using DCPPoint3Triangle3 = DCPPointTriangle<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox3Cylinder3.h
.h
2,500
68
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/OrientedBox.h> #include <Mathematics/IntrCanonicalBox3Cylinder3.h> // The query is for finite cylinders. The cylinder and box are considered to // be solids. The cylinder has center C, unit-length axis direction D, radius // r and height h. The oriented box is converted to a canonical box after // which a test-intersection query is performed on the finite cylinder and the // canonical box. See the comments in IntrCanonicalBox3Cylinder3.h for a brief // description. The details are in // https://www.geometrictools.com/Documentation/IntersectionBoxCylinder.pdf namespace gte { template <typename T> class TIQuery<T, OrientedBox3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(OrientedBox3<T> const& box, Cylinder3<T> const& cylinder) { LogAssert( cylinder.IsFinite(), "Infinite cylinders are not yet supported."); // Convert the problem to one involving a finite cylinder and a // canonical box. This involves translating the box center to the // origin and then rotating the box axes to the standard coordinate // axes. The cylinder center must also be translated and rotated // accordingly. CanonicalBox3<T> cbox(box.extent); Vector3<T> diff = cylinder.axis.origin - box.center; Cylinder3<T> transformedCylinder{}; transformedCylinder.radius = cylinder.radius; transformedCylinder.height = cylinder.height; for (int32_t i = 0; i < 3; ++i) { transformedCylinder.axis.origin[i] = Dot(box.axis[i], diff); transformedCylinder.axis.direction[i] = Dot(box.axis[i], cylinder.axis.direction); } TIQuery<T, CanonicalBox3<T>, Cylinder3<T>> bcQuery{}; auto bcResult = bcQuery(cbox, transformedCylinder); Result result{}; result.intersect = bcResult.intersect; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace3Capsule3.h
.h
1,490
50
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/Capsule.h> #include <Mathematics/Halfspace.h> // Queries for intersection of objects with halfspaces. These are useful for // containment testing, object culling, and clipping. namespace gte { template <typename T> class TIQuery<T, Halfspace3<T>, Capsule3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Halfspace3<T> const& halfspace, Capsule3<T> const& capsule) { Result result{}; // Project the capsule onto the normal line. The plane of the // halfspace occurs at the origin (zero) of the normal line. T e0 = Dot(halfspace.normal, capsule.segment.p[0]) - halfspace.constant; T e1 = Dot(halfspace.normal, capsule.segment.p[1]) - halfspace.constant; // The capsule and halfspace intersect when the projection // interval maximum is nonnegative. result.intersect = (std::max(e0, e1) + capsule.radius >= (T)0); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MassSpringSurface.h
.h
8,520
227
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ParticleSystem.h> namespace gte { template <int32_t N, typename Real> class MassSpringSurface : public ParticleSystem<N, Real> { public: // Construction and destruction. This class represents an RxC array // of masses lying on a surface and connected by an array of springs. // The masses are indexed by mass[r][c] for 0 <= r < R and 0 <= c < C. // The mass at interior position X[r][c] is connected by springs to // the masses at positions X[r-1][c], X[r+1][c], X[r][c-1], and // X[r][c+1]. Boundary masses have springs connecting them to the // obvious neighbors ("edge" mass has 3 neighbors, "corner" mass has // 2 neighbors). The masses are arranged in row-major order: // position[c+C*r] = X[r][c] for 0 <= r < R and 0 <= c < C. The // other arrays are stored similarly. virtual ~MassSpringSurface() = default; MassSpringSurface(int32_t numRows, int32_t numCols, Real step) : ParticleSystem<N, Real>(numRows* numCols, step), mNumRows(numRows), mNumCols(numCols), mConstantR(static_cast<size_t>(numRows) * static_cast<size_t>(numCols)), mLengthR(static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mConstantC(static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mLengthC(static_cast<size_t>(numRows)* static_cast<size_t>(numCols)) { std::fill(mConstantR.begin(), mConstantR.end(), (Real)0); std::fill(mLengthR.begin(), mLengthR.end(), (Real)0); std::fill(mConstantC.begin(), mConstantC.end(), (Real)0); std::fill(mLengthC.begin(), mLengthC.end(), (Real)0); } // Member access. inline int32_t GetNumRows() const { return mNumRows; } inline int32_t GetNumCols() const { return mNumCols; } inline void SetMass(int32_t r, int32_t c, Real mass) { ParticleSystem<N, Real>::SetMass(GetIndex(r, c), mass); } inline void SetPosition(int32_t r, int32_t c, Vector<N, Real> const& position) { ParticleSystem<N, Real>::SetPosition(GetIndex(r, c), position); } inline void SetVelocity(int32_t r, int32_t c, Vector<N, Real> const& velocity) { ParticleSystem<N, Real>::SetVelocity(GetIndex(r, c), velocity); } inline Real const& GetMass(int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetMass(GetIndex(r, c)); } inline Vector<N, Real> const& GetPosition(int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetPosition(GetIndex(r, c)); } inline Vector<N, Real> const& GetVelocity(int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetVelocity(GetIndex(r, c)); } // The interior mass at (r,c) has springs to the left, right, bottom, // and top. Edge masses have only three neighbors and corner masses // have only two neighbors. The mass at (r,c) provides access to the // springs connecting to locations (r,c+1) and (r+1,c). Edge and // corner masses provide access to only a subset of these. The caller // is responsible for ensuring the validity of the (r,c) inputs. // to (r+1,c) inline void SetConstantR(int32_t r, int32_t c, Real constant) { mConstantR[GetIndex(r, c)] = constant; } // to (r+1,c) inline void SetLengthR(int32_t r, int32_t c, Real length) { mLengthR[GetIndex(r, c)] = length; } // to (r,c+1) inline void SetConstantC(int32_t r, int32_t c, Real constant) { mConstantC[GetIndex(r, c)] = constant; } // to (r,c+1) inline void SetLengthC(int32_t r, int32_t c, Real length) { mLengthC[GetIndex(r, c)] = length; } inline Real const& GetConstantR(int32_t r, int32_t c) const { return mConstantR[GetIndex(r, c)]; } inline Real const& GetLengthR(int32_t r, int32_t c) const { return mLengthR[GetIndex(r, c)]; } inline Real const& GetConstantC(int32_t r, int32_t c) const { return mConstantC[GetIndex(r, c)]; } inline Real const& GetLengthC(int32_t r, int32_t c) const { return mLengthC[GetIndex(r, c)]; } // The default external force is zero. Derive a class from this one // to provide nonzero external forces such as gravity, wind, friction, // and so on. This function is called by Acceleration(...) to compute // the impulse F/m generated by the external force F. virtual Vector<N, Real> ExternalAcceleration(int32_t, Real, std::vector<Vector<N, Real>> const&, std::vector<Vector<N, Real>> const&) { return Vector<N, Real>::Zero(); } protected: // Callback for acceleration (ODE solver uses x" = F/m) applied to // particle i. The positions and velocities are not necessarily // mPosition and mVelocity, because the ODE solver evaluates the // impulse function at intermediate positions. virtual Vector<N, Real> Acceleration(int32_t i, Real time, std::vector<Vector<N, Real>> const& position, std::vector<Vector<N, Real>> const& velocity) { // Compute spring forces on position X[i]. The positions are not // necessarily mPosition, because the RK4 solver in ParticleSystem // evaluates the acceleration function at intermediate positions. // The edge and corner points of the surface of masses must be // handled separately, because each has fewer than four springs // attached to it. Vector<N, Real> acceleration = ExternalAcceleration(i, time, position, velocity); Vector<N, Real> diff, force; Real ratio; int32_t r, c, prev, next; GetCoordinates(i, r, c); if (r > 0) { prev = i - mNumCols; // index to previous row-neighbor diff = position[prev] - position[i]; ratio = GetLengthR(r - 1, c) / Length(diff); force = GetConstantR(r - 1, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (r < mNumRows - 1) { next = i + mNumCols; // index to next row-neighbor diff = position[next] - position[i]; ratio = GetLengthR(r, c) / Length(diff); force = GetConstantR(r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (c > 0) { prev = i - 1; // index to previous col-neighbor diff = position[prev] - position[i]; ratio = GetLengthC(r, c - 1) / Length(diff); force = GetConstantC(r, c - 1) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (c < mNumCols - 1) { next = i + 1; // index to next col-neighbor diff = position[next] - position[i]; ratio = GetLengthC(r, c) / Length(diff); force = GetConstantC(r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } return acceleration; } inline int32_t GetIndex(int32_t r, int32_t c) const { return c + mNumCols * r; } void GetCoordinates(int32_t i, int32_t& r, int32_t& c) const { c = i % mNumCols; r = i / mNumCols; } int32_t mNumRows, mNumCols; std::vector<Real> mConstantR, mLengthR; std::vector<Real> mConstantC, mLengthC; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RootsBrentsMethod.h
.h
8,614
227
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cmath> #include <cstdint> #include <functional> // This is an implementation of Brent's Method for computing a root of a // function on an interval [t0,t1] for which F(t0)*F(t1) < 0. The method // uses inverse quadratic interpolation to generate a root estimate but // falls back to inverse linear interpolation (secant method) if // necessary. Moreover, based on previous iterates, the method will fall // back to bisection when it appears the interpolated estimate is not of // sufficient quality. // // maxIterations: // The maximum number of iterations used to locate a root. This // should be positive. // negFTolerance, posFTolerance: // The root estimate t is accepted when the function value F(t) // satisfies negFTolerance <= F(t) <= posFTolerance. The values // must satisfy: negFTolerance <= 0, posFTolerance >= 0. // stepTTolerance: // Brent's Method requires additional tests before an interpolated // t-value is accepted as the next root estimate. One of these // tests compares the difference of consecutive iterates and // requires it to be larger than a user-specified t-tolerance (to // ensure progress is made). This parameter is that tolerance // and should be nonnegative. // convTTolerance: // The root search is allowed to terminate when the current // subinterval [tsub0,tsub1] is sufficiently small, say, // |tsub1 - tsub0| <= tolerance. This parameter is that tolerance // and should be nonnegative. namespace gte { template <typename Real> class RootsBrentsMethod { public: // It is necessary that F(t0)*F(t1) <= 0, in which case the function // returns 'true' and the 'root' is valid; otherwise, the function // returns 'false' and 'root' is invalid (do not use it). When // F(t0)*F(t1) > 0, the interval may very well contain a root but we // cannot know that. The function also returns 'false' if t0 >= t1. static bool Find(std::function<Real(Real)> const& F, Real t0, Real t1, uint32_t maxIterations, Real negFTolerance, Real posFTolerance, Real stepTTolerance, Real convTTolerance, Real& root) { // Parameter validation. if (t1 <= t0 || maxIterations == 0 || negFTolerance > (Real)0 || posFTolerance < (Real)0 || stepTTolerance < (Real)0 || convTTolerance < (Real)0) { // The input is invalid. return false; } Real f0 = F(t0); if (negFTolerance <= f0 && f0 <= posFTolerance) { // This endpoint is an approximate root that satisfies the // function tolerance. root = t0; return true; } Real f1 = F(t1); if (negFTolerance <= f1 && f1 <= posFTolerance) { // This endpoint is an approximate root that satisfies the // function tolerance. root = t1; return true; } if (f0 * f1 > (Real)0) { // The input interval must bound a root. return false; } if (std::fabs(f0) < std::fabs(f1)) { // Swap t0 and t1 so that |F(t1)| <= |F(t0)|. The number t1 // is considered to be the best estimate of the root. std::swap(t0, t1); std::swap(f0, f1); } // Initialize values for the root search. Real t2 = t0, t3 = t0, f2 = f0; bool prevBisected = true; // The root search. for (uint32_t i = 0; i < maxIterations; ++i) { Real fDiff01 = f0 - f1, fDiff02 = f0 - f2, fDiff12 = f1 - f2; Real invFDiff01 = ((Real)1) / fDiff01; Real s; if (fDiff02 != (Real)0 && fDiff12 != (Real)0) { // Use inverse quadratic interpolation. Real infFDiff02 = ((Real)1) / fDiff02; Real invFDiff12 = ((Real)1) / fDiff12; s = t0 * f1 * f2 * invFDiff01 * infFDiff02 - t1 * f0 * f2 * invFDiff01 * invFDiff12 + t2 * f0 * f1 * infFDiff02 * invFDiff12; } else { // Use inverse linear interpolation (secant method). s = (t1 * f0 - t0 * f1) * invFDiff01; } // Compute values need in the accept-or-reject tests. Real tDiffSAvr = s - ((Real)0.75) * t0 - ((Real)0.25) * t1; Real tDiffS1 = s - t1; Real absTDiffS1 = std::fabs(tDiffS1); Real absTDiff12 = std::fabs(t1 - t2); Real absTDiff23 = std::fabs(t2 - t3); bool currBisected = false; if (tDiffSAvr * tDiffS1 > (Real)0) { // The value s is not between 0.75*t0 + 0.25*t1 and t1. // NOTE: The algorithm sometimes has t0 < t1 but sometimes // t1 < t0, so the between-ness test does not use simple // comparisons. currBisected = true; } else if (prevBisected) { // The first of Brent's tests to determine whether to // accept the interpolated s-value. currBisected = (absTDiffS1 >= ((Real)0.5) * absTDiff12) || (absTDiff12 <= stepTTolerance); } else { // The second of Brent's tests to determine whether to // accept the interpolated s-value. currBisected = (absTDiffS1 >= ((Real)0.5) * absTDiff23) || (absTDiff23 <= stepTTolerance); } if (currBisected) { // One of the additional tests failed, so reject the // interpolated s-value and use bisection instead. s = ((Real)0.5) * (t0 + t1); if (s == t0 || s == t1) { // The numbers t0 and t1 are consecutive // floating-point numbers. root = s; return true; } prevBisected = true; } else { prevBisected = false; } // Evaluate the function at the new estimate and test for // convergence. Real fs = F(s); if (negFTolerance <= fs && fs <= posFTolerance) { root = s; return true; } // Update the subinterval to include the new estimate as an // endpoint. t3 = t2; t2 = t1; f2 = f1; if (f0 * fs < (Real)0) { t1 = s; f1 = fs; } else { t0 = s; f0 = fs; } // Allow the algorithm to terminate when the subinterval is // sufficiently small. if (std::fabs(t1 - t0) <= convTTolerance) { root = t1; return true; } // A loop invariant is that t1 is the root estimate, // F(t0)*F(t1) < 0 and |F(t1)| <= |F(t0)|. if (std::fabs(f0) < std::fabs(f1)) { std::swap(t0, t1); std::swap(f0, f1); } } // Failed to converge in the specified number of iterations. return false; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ThreadSafeQueue.h
.h
2,257
96
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <mutex> #include <queue> namespace gte { template <typename Element> class ThreadSafeQueue { public: // Construction and destruction. ThreadSafeQueue(size_t maxNumElements = 0) : mMaxNumElements(maxNumElements) { } virtual ~ThreadSafeQueue() = default; // All the operations are thread-safe. size_t GetMaxNumElements() const { size_t maxNumElements; mMutex.lock(); { maxNumElements = mMaxNumElements; } mMutex.unlock(); return maxNumElements; } size_t GetNumElements() const { size_t numElements; mMutex.lock(); { numElements = mQueue.size(); } mMutex.unlock(); return numElements; } bool Push(Element const& element) { bool pushed; mMutex.lock(); { if (mQueue.size() < mMaxNumElements) { mQueue.push(element); pushed = true; } else { pushed = false; } } mMutex.unlock(); return pushed; } bool Pop(Element& element) { bool popped; mMutex.lock(); { if (mQueue.size() > 0) { element = mQueue.front(); mQueue.pop(); popped = true; } else { popped = false; } } mMutex.unlock(); return popped; } protected: size_t mMaxNumElements; std::queue<Element> mQueue; mutable std::mutex mMutex; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrTetrahedron3Tetrahedron3.h
.h
8,317
196
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.1.2022.02.06 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/Tetrahedron3.h> // The queries consider the tetrahedron to be a solid. // // The test-intersection query uses the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The set of potential separating directions includes the 4 face normals of // tetra0, the 4 face normals of tetra1, and 36 directions, each of which is // the cross product of an edge of tetra0 and and an edge of tetra1. // // The separating axes involving cross products of edges has numerical // robustness problems when the two edges are nearly parallel. The cross // product of the edges is nearly the zero vector, so normalization of the // cross product may produce unit-length directions that are not close to the // true direction. Such a pair of edges occurs when an object0 face normal N0 // and an object1 face normal N1 are nearly parallel. In this case, you may // skip the edge-edge directions, which is equivalent to projecting the // objects onto the plane with normal N0 and applying a 2D separating axis // test. The ability to do so involves choosing a small nonnegative epsilon. // It is used to determine whether two face normals, one from each object, are // nearly parallel: |Dot(N0,N1)| >= 1 - epsilon, where 0 <= epsilon <= 1. // The epsilon input to the operator()(...) function is clamped to [0,1]. // // The pair of integers 'separating', say, (i0,i1), identifies the axes that // reported separation; there may be more than one but only one is reported. // If the separating axis is a face normal N[i0] of object0, then (i0,smax) is // returned, where smax = std::numeric_limits<size_t>::max(). If the axis is a // face normal N[i1], then (smax,i1) is returned. If the axis is a cross // product of edges, Cross(N[i0],N[i1]), then (i0,i1) is returned. If // 'intersect' is true, the separating[] values are invalid because there is // no separation. namespace gte { template <typename T> class TIQuery<T, Tetrahedron3<T>, Tetrahedron3<T>> { public: struct Result { Result() : intersect(false), separating{ std::numeric_limits<size_t>::max(), std::numeric_limits<size_t>::max() } { } bool intersect; std::array<size_t, 2> separating; }; Result operator()(Tetrahedron3<T> const& tetra0, Tetrahedron3<T> const& tetra1, T epsilon = static_cast<T>(0)) { Result result{}; // Test face normals of tetra0 for separation. Because of the // counterclockwise ordering of the face vertices relative to an // observer outside the tetrahedron, the projection interval for // the face is [T,0], where T < 0. Determine whether tetra1 is on // the positive side of the face-normal line. for (size_t i = 0; i < 4; ++i) { auto const& faceIndices = Tetrahedron3<T>::GetFaceIndices(i); Vector3<T> P = tetra0.v[faceIndices[0]]; Vector3<T> N = tetra0.ComputeFaceNormal(i); if (WhichSide(tetra1, P, N) > 0) { // Tetra1 is entirely on the positive side of the // normal line P + t * N. result.intersect = false; result.separating[0] = i; result.separating[1] = std::numeric_limits<size_t>::max(); return result; } } // Test face normals of tetra1 for separation. Because of the // counterclockwise ordering of the face vertices relative to an // observer outside the tetrahedron, the projection interval for // the face is [T,0], where T < 0. Determine whether tetra1 is on // the positive side of the face-normal line. for (size_t i = 0; i < 4; ++i) { auto const& faceIndices = Tetrahedron3<T>::GetFaceIndices(i); Vector3<T> P = tetra1.v[faceIndices[0]]; Vector3<T> N = tetra1.ComputeFaceNormal(i); if (WhichSide(tetra0, P, N) > 0) { // Tetra1 is entirely on the positive side of the // normal line P + t * N. result.intersect = false; result.separating[0] = std::numeric_limits<size_t>::max(); result.separating[1] = i; return result; } } // Test cross products of pairs of edge directions, one edge from // each tetrahedron. T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const cutoff = std::min(std::max(one - epsilon, zero), one); for (size_t i0 = 0; i0 < 6; ++i0) { auto const& edge0Indices = Tetrahedron3<T>::GetEdgeIndices(i0); Vector3<T> P0 = tetra0.v[edge0Indices[0]]; Vector3<T> E0 = tetra0.v[edge0Indices[1]] - P0; for (size_t i1 = 0; i1 < 6; ++i1) { auto const& edge1Indices = Tetrahedron3<T>::GetEdgeIndices(i1); Vector3<T> P1 = tetra0.v[edge1Indices[0]]; Vector3<T> E1 = tetra1.v[edge1Indices[1]] - P1; if (std::fabs(Dot(E0, E1)) < cutoff) { Vector3<T> N = Cross(E0, E1); int32_t side0 = WhichSide(tetra0, P0, N); if (side0 == 0) { continue; } int32_t side1 = WhichSide(tetra1, P0, N); if (side1 == 0) { continue; } if (side0 * side1 < 0) { // The projections of tetra0 and tetra1 onto the // line P + t * N are on opposite sides of the // projection of P. result.intersect = false; result.separating[0] = i0; result.separating[1] = i1; return result; } } } } result.intersect = true; result.separating[0] = std::numeric_limits<size_t>::max(); result.separating[1] = std::numeric_limits<size_t>::max(); return result; } private: static int32_t WhichSide(Tetrahedron3<T> const& tetra, Vector3<T> const& P, Vector3<T> const& N) { // The vertices of tetra are projected to the form P + t * N. // The return values is +1 if all t > 0, -1 if all t < 0, but // 0 otherwise, in which case tetra has points on both sides // of the plane Dot(N,X-P) = 0. T const zero = static_cast<T>(0); size_t positive = 0, negative = 0; for (size_t i = 0; i < 4; ++i) { // Project a vertex onto the normal line. T t = Dot(N, tetra.v[i] - P); if (t > zero) { ++positive; } else if (t < zero) { ++negative; } if (positive > 0 && negative > 0) { // Tetra has vertices on both sides of the line, so the // line is not a separating axis. return 0; } } // Either positive > 0 or negative > 0 but not both are positive. return (positive > 0 ? +1 : -1); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CircleThroughTwoPointsSpecifiedRadius.h
.h
3,566
91
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector2.h> // This file provides an implementation of the algorithm in Section 8.6 of the // book // Geometric Tools for Computer Graphics, // Philip J. Schneider and David H. Eberly, // Morgan Kaufmnn, San Francisco CA, 2002 // // Given two distinct points P and Q and given a radius r, compute the centers // of circles, each containing the points and having the specified radius. // // The book states that the circle centers are the points of intersection of // circles |X-P|^2 = r^2 and |X-Q|^2 = r^2. The pseudocode simply calls a // function to compute these intersections. // // In my opinion, a simpler approach uses the fact that the bisector of the // line segment with endpoints P and Q is a line that contains the centers. // The bisector is parameterized by X(t) = t*Perp(P-Q)+(P+Q)/2, where // Perp(P-Q) is perpendicular to P-Q and has the same length as that of P-Q. // We need values of t for which X(t)-P has length r, // X(t)-P = t*Perp(P - Q)-(P-Q)/2 // r^2 = |X(t)-P|^2 // = |t*Perp(P-Q)-(P-Q)/2|^2 // = |Perp(P-Q)|^2 * t^2 - 2*t*Dot(Perp(P-Q),P-Q) + |P-Q|^2/4 // = |P-Q|^2 * t^2 + |P-Q|^2/4 // = |P-Q|^2 * (t^2 + 1/4) // Observe that t^2+1/4 >= 1/4, which implies that r >= |P-Q|/2. This // condition is clear geometrically. The radius must be at least half the // length of the segment connecting P and Q. // // If r = |P-Q|/2, there is a single circle with center (P+Q)/2. If // r > |P-Q|/2, there are two circles whose centers occur when // t^2 = r^2/|P-Q|^2 - 1/4, which implies t = +/- sqrt(r^2/|P-Q|^2-1/4). namespace gte { // The function returns the number of circles satisfying the constraints. // The number is 2 when r > |P-Q|/2, 1 when r = |P-Q|/2 or 0 when P = Q // or r < |P-Q|/2. Any circle[i] with i >= numIntersections has members // set to zero. template <typename T> size_t CircleThroughTwoPointsSpecifiedRadius(Vector2<T> const& P, Vector2<T> const& Q, T const& r, std::array<Circle2<T>, 2>& circle) { T const zero = static_cast<T>(0); Vector2<T> PmQ = P - Q; T sqrLengthPmQ = Dot(PmQ, PmQ); if (sqrLengthPmQ != zero) { T argument = r * r / sqrLengthPmQ - static_cast<T>(0.25); if (argument > zero) { T root = std::sqrt(argument); Vector2<T> bisectorOrigin = static_cast<T>(0.5) * (P + Q); Vector2<T> bisectorDirection = Perp(PmQ); circle[0].center = bisectorOrigin - root * bisectorDirection; circle[0].radius = r; circle[1].center = bisectorOrigin + root * bisectorDirection; circle[1].radius = r; return 2; } if (argument == zero) { circle[0].center = static_cast<T>(0.5) * (P + Q); circle[0].radius = r; circle[1].center = { zero, zero }; circle[1].radius = zero; return 1; } } circle[0].center = { zero, zero }; circle[0].radius = zero; circle[1].center = { zero, zero }; circle[1].radius = zero; return 0; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContCone.h
.h
705
23
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Cone.h> namespace gte { // Test for containment of a point by a cone. template <int32_t N, typename Real> bool InContainer(Vector<N, Real> const& point, Cone<N, Real> const& cone) { Vector<N, Real> diff = point - cone.ray.origin; Real h = Dot(cone.ray.direction, diff); return cone.HeightInRange(h) && h * h >= cone.cosAngleSqr * Dot(diff, diff); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TriangulateCDT.h
.h
44,443
1,106
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/PolygonTree.h> #include <Mathematics/ConstrainedDelaunay2.h> #include <numeric> // The fundamental problem is to compute the triangulation of a polygon tree. // The outer polygons have counterclockwise ordered vertices. The inner // polygons have clockwise ordered vertices. The algorithm uses Constrained // Delaunay Triangulation and the implementation allows polygons to share // vertices and edges. // // The polygons are not required to be simple in the sense that a vertex can // be shared by an even number of edges, where the number is larger than 2. // The input points can have duplicates, which the triangulator handles // correctly. The algorithm supports coincident vertex-edge and coincident // edge-edge configurations. See the document // https://www.geometrictools.com/Documentation/TriangulationByCDT.pdf // for examples. // // If two edges intersect at edge-interior points, the current implementation // cannot handle this. A pair of such edges cannot simultaneously be inserted // into the constrained triangulation without affecting each other's local // re-triangulation. A pending work item is to add validation code and fix // an incoming malformed polygon tree during the triangulation. // // The input points are a vertex pool. The input tree is a PolygonTree object, // defined in PolygonTree.h. Any outer polygon has vertices points[outer[0]] // through points[outer[outer.size()-1]] listed in counterclockwise order. Any // inner polygon has vertices points[inner[0]] through // points[inner[inner.size()-1]] listed in clockwise order. The output tree // contains the triangulation of the polygon tree on a per-node basis. If // coincident vertex-edge or coincident edge-edge configurations exist in // the polygon tree, the corresponding output polygons differ from the input // polygons in that they have more vertices due to edge splits. The triangle // chirality (winding order) is the same as the containing polygon. // // TriangulateCDT uses the ComputeType only for the ConstrainedDelaunay2 // object. To avoid the heap management costs of BSNumber<UIntegerAP32> when // the input datasets are large, use BSNumber<UIntegerFP32<N>>. The worst-case // choices of N for ComputeType are listed in the next table. // // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 70 // double | BSNumber | 525 // float | BSRational | 573 // double | BSRational | 4329 namespace gte { // The variadic template declaration supports the class // TriangulateCDT<InputType, ComputeType>, which is deprecated and will // be removed in a future release. The declaration also supports the // replacement class TriangulateCDT<InputType>. template <typename T, typename...> class TriangulateCDT {}; } namespace gte { // The code has LogAssert statements that throw exceptions when triggered. // For a correct algorithm using exact arithmetic, these should not occur. // When using floating-point arithmetic, it is possible that rounding errors // lead to a malformed triangulation. It is strongly recommended that you // choose ComputeType to be a rational type. No divisions are required, // either in Delaunay2 or ConstrainedDelaunay2, so you may choose the type // to be BSNumber<UInteger> rather than BSRational<UInteger>. However, if // you choose ComputeType to be 'float' or 'double', you should call the // Insert(...) function in a try-catch block and take appropriate action. // // The worst-case choices of N for ComputeType of type BSNumber or BSRational // with integer storage UIntegerFP32<N> are listed in the next table. The // expression requiring the most bits is in the last else-block of ComputePSD. // We recommend using only BSNumber, because no divisions are performed in the // insertion computations. // // input type | compute type | ComputePSD | Delaunay | N // -----------+--------------+------------+----------+------ // float | BSNumber | 70 | 35 | 70 // double | BSNumber | 525 | 263 | 525 // float | BSRational | 555 | 573 | 573 // double | BSRational | 4197 | 4329 | 4329 // // The recommended ComputeType is BSNumber<UIntegerFP32<70>> for the // InputType 'float' and BSNumber<UIntegerFP32<526>> for the InputType // 'double' (525 rounded up to 526 for the bits array to be a multiple // of 8 bytes.) template <typename InputType, typename ComputeType> class // [[deprecated("Use TriangulateCDT<InputType> instead.")]] TriangulateCDT<InputType, ComputeType> { public: void operator()( std::vector<Vector2<InputType>> const& inputPoints, std::shared_ptr<PolygonTree> const& inputTree, PolygonTreeEx& outputTree) { operator()(static_cast<int32_t>(inputPoints.size()), inputPoints.data(), inputTree, outputTree); } void operator()(int32_t numInputPoints, Vector2<InputType> const* inputPoints, std::shared_ptr<PolygonTree> const& inputTree, PolygonTreeEx& outputTree) { LogAssert(numInputPoints >= 3 && inputPoints != nullptr && inputTree, "Invalid argument."); CopyAndCompactify(inputTree, outputTree); Triangulate(numInputPoints, inputPoints, outputTree); } private: void CopyAndCompactify(std::shared_ptr<PolygonTree> const& input, PolygonTreeEx& output) { output.nodes.clear(); output.interiorTriangles.clear(); output.interiorNodeIndices.clear(); output.exteriorTriangles.clear(); output.exteriorNodeIndices.clear(); output.insideTriangles.clear(); output.insideNodeIndices.clear(); output.outsideTriangles.clear(); output.allTriangles.clear(); // Count the number of nodes in the tree. size_t numNodes = 1; // the root node std::queue<std::shared_ptr<PolygonTree>> queue; queue.push(input); while (queue.size() > 0) { std::shared_ptr<PolygonTree> node = queue.front(); queue.pop(); numNodes += node->child.size(); for (auto const& child : node->child) { queue.push(child); } } // Create the PolygonTreeEx nodes. output.nodes.resize(numNodes); for (size_t i = 0; i < numNodes; ++i) { output.nodes[i].self = i; } output.nodes[0].chirality = +1; output.nodes[0].parent = std::numeric_limits<size_t>::max(); size_t current = 0, last = 0, minChild = 1; queue.push(input); while (queue.size() > 0) { std::shared_ptr<PolygonTree> node = queue.front(); queue.pop(); auto& exnode = output.nodes[current++]; exnode.polygon = node->polygon; exnode.minChild = minChild; exnode.supChild = minChild + node->child.size(); minChild = exnode.supChild; for (auto const& child : node->child) { auto& exchild = output.nodes[++last]; exchild.chirality = -exnode.chirality; exchild.parent = exnode.self; queue.push(child); } } } void Triangulate(int32_t numInputPoints, Vector2<InputType> const* inputPoints, PolygonTreeEx& tree) { // The constrained Delaunay triangulator will be given the unique // points referenced by the polygons in the tree. The tree // 'polygon' indices are relative to inputPoints[], but they are // temporarily mapped to indices relative to 'points'. Once the // triangulation is complete, the indices are restored to those // relative to inputPoints[]. std::vector<Vector2<InputType>> points; std::vector<int32_t> remapping; RemapPolygonTree(numInputPoints, inputPoints, tree, points, remapping); LogAssert(points.size() >= 3, "Invalid polygon tree."); ETManifoldMesh graph; std::set<EdgeKey<false>> edges; ConstrainedTriangulate(tree, points, graph, edges); ClassifyTriangles(tree, graph, edges); RestorePolygonTree(tree, remapping); } // On return, 'points' are the unique inputPoints[] values referenced by // the tree. The tree 'polygon' members are modified to be indices // into 'points' rather than inputPoints[]. The 'remapping' allows us to // restore the tree 'polygon' members to be indices into inputPoints[] // after the triangulation is computed. The 'edges' stores all the // polygon edges that must be in the triangulation. void RemapPolygonTree( int32_t numInputPoints, Vector2<InputType> const* inputPoints, PolygonTreeEx& tree, std::vector<Vector2<InputType>>& points, std::vector<int32_t>& remapping) { std::map<Vector2<InputType>, int32_t> pointMap; points.reserve(numInputPoints); int32_t currentIndex = 0; // The remapping is initially the identity, remapping[j] = j. remapping.resize(numInputPoints); std::iota(remapping.begin(), remapping.end(), 0); std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { PolygonTreeEx::Node& node = tree.nodes[queue.front()]; queue.pop(); size_t const numIndices = node.polygon.size(); for (size_t i = 0; i < numIndices; ++i) { auto const& point = inputPoints[node.polygon[i]]; auto iter = pointMap.find(point); if (iter == pointMap.end()) { // The point is encountered the first time. pointMap.insert(std::make_pair(point, currentIndex)); remapping[currentIndex] = node.polygon[i]; node.polygon[i] = currentIndex; points.push_back(point); ++currentIndex; } else { // The point is a duplicate. On the remapping, the // polygon[] value is set to the index for the // first occurrence of the duplicate. remapping[iter->second] = node.polygon[i]; node.polygon[i] = iter->second; } } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } } void RestorePolygonTree(PolygonTreeEx& tree, std::vector<int32_t> const& remapping) { std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { auto& node = tree.nodes[queue.front()]; queue.pop(); for (auto& index : node.polygon) { index = remapping[index]; } for (auto& tri : node.triangulation) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } for (auto& tri : tree.interiorTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.exteriorTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.insideTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.outsideTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.allTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } } void ConstrainedTriangulate( PolygonTreeEx& tree, std::vector<Vector2<InputType>> const& points, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { // Use constrained Delaunay triangulation. ConstrainedDelaunay2<InputType, ComputeType> cdt; int32_t const numPoints = static_cast<int32_t>(points.size()); cdt(numPoints, points.data(), static_cast<InputType>(0)); std::vector<int32_t> outEdge; std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { auto& node = tree.nodes[queue.front()]; queue.pop(); std::vector<int32_t> replacement; size_t numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { // Insert the polygon edge into the constrained Delaunay // triangulation. std::array<int32_t, 2> edge = { node.polygon[i0], node.polygon[i1] }; outEdge.clear(); (void)cdt.Insert(edge, outEdge); if (outEdge.size() > 2) { // The polygon edge intersects additional vertices in // the triangulation. The outEdge[] edge values are // { edge[0], other_vertices, edge[1] } which are // ordered along the line segment. replacement.insert(replacement.end(), outEdge.begin() + 1, outEdge.end()); } else { replacement.push_back(node.polygon[i1]); } } if (replacement.size() > node.polygon.size()) { node.polygon = std::move(replacement); } numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { edges.insert(EdgeKey<false>(node.polygon[i0], node.polygon[i1])); } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } // Copy the graph to the compact arrays mIndices and // mAdjacencies for use by the caller. cdt.UpdateIndicesAdjacencies(); // Duplicate the graph, which will be modified during triangle // extration. The original is kept intact for use by the caller. graph = cdt.GetGraph(); // Store the triangles in allTriangles for potential use by the // caller. int32_t const numTriangles = cdt.GetNumTriangles(); int32_t const* indices = cdt.GetIndices().data(); tree.allTriangles.resize(numTriangles); for (int32_t t = 0; t < numTriangles; ++t) { int32_t v0 = *indices++; int32_t v1 = *indices++; int32_t v2 = *indices++; graph.Insert(v0, v1, v2); tree.allTriangles[t] = { v0, v1, v2 }; } } void ClassifyTriangles(PolygonTreeEx& tree, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { ClassifyDFS(tree, 0, graph, edges); LogAssert(edges.size() == 0, "The edges should be empty for a correct implementation."); GetOutsideTriangles(tree, graph); GetInsideTriangles(tree); } void ClassifyDFS(PolygonTreeEx& tree, size_t index, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { auto& node = tree.nodes[index]; for (size_t c = node.minChild; c < node.supChild; ++c) { ClassifyDFS(tree, c, graph, edges); } auto const& emap = graph.GetEdges(); std::set<TriangleKey<true>> region; size_t const numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { int32_t v0 = node.polygon[i0]; int32_t v1 = node.polygon[i1]; EdgeKey<false> ekey(v0, v1); auto eiter = emap.find(ekey); LogAssert(eiter != emap.end(), "Unexpected condition."); auto const& edge = eiter->second; LogAssert(edge, "Unexpected condition."); auto tri0 = edge->T[0]; LogAssert(tri0, "Unexpected condition."); if (tri0->WhichSideOfEdge(v0, v1) == node.chirality) { region.insert(TriangleKey<true>(tri0->V[0], tri0->V[1], tri0->V[2])); } else { auto tri1 = edge->T[1]; if (tri1) { region.insert(TriangleKey<true>(tri1->V[0], tri1->V[1], tri1->V[2])); } } } FillRegion(graph, edges, region); ExtractTriangles(graph, region, node); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { edges.erase(EdgeKey<false>(node.polygon[i0], node.polygon[i1])); } } // On input, the set has the initial seeds for the desired region. A // breadth-first search is performed to find the connected component // of the seeds. The component is bounded by an outer polygon and the // inner polygons of its children. void FillRegion(ETManifoldMesh& graph, std::set<EdgeKey<false>> const& edges, std::set<TriangleKey<true>>& region) { std::queue<TriangleKey<true>> regionQueue; for (auto const& tkey : region) { regionQueue.push(tkey); } auto const& tmap = graph.GetTriangles(); while (regionQueue.size() > 0) { TriangleKey<true> tkey = regionQueue.front(); regionQueue.pop(); auto titer = tmap.find(tkey); LogAssert(titer != tmap.end(), "Unexpected condition."); auto const& tri = titer->second; LogAssert(tri, "Unexpected condition."); for (size_t j = 0; j < 3; ++j) { auto edge = tri->E[j]; if (edge) { auto siter = edges.find(EdgeKey<false>(edge->V[0], edge->V[1])); if (siter == edges.end()) { // The edge is not constrained, so it allows the // search to continue. auto adj = tri->T[j]; if (adj) { TriangleKey<true> akey(adj->V[0], adj->V[1], adj->V[2]); auto riter = region.find(akey); if (riter == region.end()) { // The adjacent triangle has not yet been // visited, so place it in the queue to // continue the search. region.insert(akey); regionQueue.push(akey); } } } } } } } // Store the region triangles in a triangulation object and remove // those triangles from the graph in preparation for processing the // next layer of triangles. void ExtractTriangles(ETManifoldMesh& graph, std::set<TriangleKey<true>> const& region, PolygonTreeEx::Node& node) { node.triangulation.reserve(region.size()); if (node.chirality > 0) { for (auto const& tri : region) { node.triangulation.push_back({ tri.V[0], tri.V[1], tri.V[2] }); graph.Remove(tri.V[0], tri.V[1], tri.V[2]); } } else // node.chirality < 0 { for (auto const& tri : region) { node.triangulation.push_back({ tri.V[0], tri.V[2], tri.V[1] }); graph.Remove(tri.V[0], tri.V[1], tri.V[2]); } } } void GetOutsideTriangles(PolygonTreeEx& tree, ETManifoldMesh& graph) { auto const& tmap = graph.GetTriangles(); tree.outsideTriangles.resize(tmap.size()); size_t t = 0; for (auto const& tri : tmap) { auto const& tkey = tri.first; tree.outsideTriangles[t++] = { tkey.V[0], tkey.V[1], tkey.V[2] }; } graph.Clear(); } // Get the triangles in the polygon tree, classifying each as // interior (in region bounded by outer polygon and its contained // inner polygons) or exterior (in region bounded by inner polygon // and its contained outer polygons). The inside triangles are the // union of the interior and exterior triangles. void GetInsideTriangles(PolygonTreeEx& tree) { size_t const numTriangles = tree.allTriangles.size(); size_t const numOutside = tree.outsideTriangles.size(); size_t const numInside = numTriangles - numOutside; tree.interiorTriangles.reserve(numTriangles); tree.interiorNodeIndices.reserve(numTriangles); tree.exteriorTriangles.reserve(numTriangles); tree.exteriorNodeIndices.reserve(numTriangles); tree.insideTriangles.reserve(numInside); tree.insideNodeIndices.reserve(numInside); for (size_t nIndex = 0; nIndex < tree.nodes.size(); ++nIndex) { auto const& node = tree.nodes[nIndex]; for (auto& tri : node.triangulation) { if (node.chirality > 0) { tree.interiorTriangles.push_back(tri); tree.interiorNodeIndices.push_back(nIndex); } else { tree.exteriorTriangles.push_back(tri); tree.exteriorNodeIndices.push_back(nIndex); } tree.insideTriangles.push_back(tri); tree.insideNodeIndices.push_back(nIndex); } } } }; } namespace gte { // The input type must be 'float' or 'double'. The user no longer has // the responsibility to specify the compute type. template <typename T> class TriangulateCDT<T> { public: void operator()( std::vector<Vector2<T>> const& inputPoints, std::shared_ptr<PolygonTree> const& inputTree, PolygonTreeEx& outputTree) { LogAssert(inputPoints.size() >= 3 && inputTree, "Invalid argument."); CopyAndCompactify(inputTree, outputTree); Triangulate(inputPoints.size(), inputPoints.data(), outputTree); } void operator()( size_t numInputPoints, Vector2<T> const* inputPoints, std::shared_ptr<PolygonTree> const& inputTree, PolygonTreeEx& outputTree) { LogAssert(numInputPoints >= 3 && inputPoints != nullptr && inputTree, "Invalid argument."); CopyAndCompactify(inputTree, outputTree); Triangulate(numInputPoints, inputPoints, outputTree); } private: void CopyAndCompactify(std::shared_ptr<PolygonTree> const& input, PolygonTreeEx& output) { output.nodes.clear(); output.interiorTriangles.clear(); output.interiorNodeIndices.clear(); output.exteriorTriangles.clear(); output.exteriorNodeIndices.clear(); output.insideTriangles.clear(); output.insideNodeIndices.clear(); output.outsideTriangles.clear(); output.allTriangles.clear(); // Count the number of nodes in the tree. size_t numNodes = 1; // the root node std::queue<std::shared_ptr<PolygonTree>> queue; queue.push(input); while (queue.size() > 0) { auto const& node = queue.front(); queue.pop(); numNodes += node->child.size(); for (auto const& child : node->child) { queue.push(child); } } // Create the PolygonTreeEx nodes. output.nodes.resize(numNodes); for (size_t i = 0; i < numNodes; ++i) { output.nodes[i].self = i; } output.nodes[0].chirality = +1; output.nodes[0].parent = std::numeric_limits<size_t>::max(); size_t current = 0, last = 0, minChild = 1; queue.push(input); while (queue.size() > 0) { auto const& node = queue.front(); queue.pop(); auto& exnode = output.nodes[current++]; exnode.polygon = node->polygon; exnode.minChild = minChild; exnode.supChild = minChild + node->child.size(); minChild = exnode.supChild; for (auto const& child : node->child) { auto& exchild = output.nodes[++last]; exchild.chirality = -exnode.chirality; exchild.parent = exnode.self; queue.push(child); } } } void Triangulate(size_t numInputPoints, Vector2<T> const* inputPoints, PolygonTreeEx& tree) { // The constrained Delaunay triangulator will be given the unique // points referenced by the polygons in the tree. The tree // 'polygon' indices are relative to inputPoints[], but they are // temporarily mapped to indices relative to 'points'. Once the // triangulation is complete, the indices are restored to those // relative to inputPoints[]. std::vector<Vector2<T>> points; std::vector<int32_t> remapping; RemapPolygonTree(numInputPoints, inputPoints, tree, points, remapping); LogAssert(points.size() >= 3, "Invalid polygon tree."); ETManifoldMesh graph; std::set<EdgeKey<false>> edges; ConstrainedTriangulate(tree, points, graph, edges); ClassifyTriangles(tree, graph, edges); RestorePolygonTree(tree, remapping); } // On return, 'points' are the unique inputPoints[] values referenced by // the tree. The tree 'polygon' members are modified to be indices // into 'points' rather than inputPoints[]. The 'remapping' allows us to // restore the tree 'polygon' members to be indices into inputPoints[] // after the triangulation is computed. The 'edges' stores all the // polygon edges that must be in the triangulation. void RemapPolygonTree( size_t numInputPoints, Vector2<T> const* inputPoints, PolygonTreeEx& tree, std::vector<Vector2<T>>& points, std::vector<int32_t>& remapping) { std::map<Vector2<T>, int32_t> pointMap; points.reserve(numInputPoints); int32_t currentIndex = 0; // The remapping is initially the identity, remapping[j] = j. remapping.resize(numInputPoints); std::iota(remapping.begin(), remapping.end(), 0); std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { PolygonTreeEx::Node& node = tree.nodes[queue.front()]; queue.pop(); size_t const numIndices = node.polygon.size(); for (size_t i = 0; i < numIndices; ++i) { auto const& point = inputPoints[node.polygon[i]]; auto iter = pointMap.find(point); if (iter == pointMap.end()) { // The point is encountered the first time. pointMap.insert(std::make_pair(point, currentIndex)); remapping[currentIndex] = node.polygon[i]; node.polygon[i] = currentIndex; points.push_back(point); ++currentIndex; } else { // The point is a duplicate. On the remapping, the // polygon[] value is set to the index for the // first occurrence of the duplicate. remapping[iter->second] = node.polygon[i]; node.polygon[i] = iter->second; } } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } } void RestorePolygonTree(PolygonTreeEx& tree, std::vector<int32_t> const& remapping) { std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { auto& node = tree.nodes[queue.front()]; queue.pop(); for (auto& index : node.polygon) { index = remapping[index]; } for (auto& tri : node.triangulation) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } for (auto& tri : tree.interiorTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.exteriorTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.insideTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.outsideTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } for (auto& tri : tree.allTriangles) { for (size_t j = 0; j < 3; ++j) { tri[j] = remapping[tri[j]]; } } } void ConstrainedTriangulate( PolygonTreeEx& tree, std::vector<Vector2<T>> const& points, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { // Use constrained Delaunay triangulation. ConstrainedDelaunay2<T> cdt; cdt(points); size_t counter = 0; std::vector<int32_t> outEdge; std::queue<size_t> queue; queue.push(0); while (queue.size() > 0) { auto& node = tree.nodes[queue.front()]; queue.pop(); std::vector<int32_t> replacement; size_t numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { // Insert the polygon edge into the constrained Delaunay // triangulation. std::array<int32_t, 2> edge = { node.polygon[i0], node.polygon[i1] }; outEdge.clear(); (void)cdt.Insert(edge, outEdge); ++counter; if (outEdge.size() > 2) { // The polygon edge intersects additional vertices in // the triangulation. The outEdge[] edge values are // { edge[0], other_vertices, edge[1] } which are // ordered along the line segment. replacement.insert(replacement.end(), outEdge.begin() + 1, outEdge.end()); } else { replacement.push_back(node.polygon[i1]); } } if (replacement.size() > node.polygon.size()) { node.polygon = std::move(replacement); } numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { edges.insert(EdgeKey<false>(node.polygon[i0], node.polygon[i1])); } for (size_t c = node.minChild; c < node.supChild; ++c) { queue.push(c); } } // Copy the graph to the compact arrays mIndices and // mAdjacencies for use by the caller. cdt.UpdateIndicesAdjacencies(); // Duplicate the graph, which will be modified during triangle // extration. The original is kept intact for use by the caller. graph = cdt.GetGraph(); // Store the triangles in allTriangles for potential use by the // caller. size_t const numTriangles = cdt.GetNumTriangles(); int32_t const* indices = cdt.GetIndices().data(); tree.allTriangles.resize(numTriangles); for (size_t t = 0; t < numTriangles; ++t) { int32_t v0 = *indices++; int32_t v1 = *indices++; int32_t v2 = *indices++; graph.Insert(v0, v1, v2); tree.allTriangles[t] = { v0, v1, v2 }; } } void ClassifyTriangles(PolygonTreeEx& tree, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { ClassifyDFS(tree, 0, graph, edges); LogAssert(edges.size() == 0, "The edges should be empty for a correct implementation."); GetOutsideTriangles(tree, graph); GetInsideTriangles(tree); } void ClassifyDFS(PolygonTreeEx& tree, size_t index, ETManifoldMesh& graph, std::set<EdgeKey<false>>& edges) { auto& node = tree.nodes[index]; for (size_t c = node.minChild; c < node.supChild; ++c) { ClassifyDFS(tree, c, graph, edges); } auto const& emap = graph.GetEdges(); std::set<TriangleKey<true>> region; size_t const numIndices = node.polygon.size(); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { int32_t v0 = node.polygon[i0]; int32_t v1 = node.polygon[i1]; EdgeKey<false> ekey(v0, v1); auto eiter = emap.find(ekey); LogAssert(eiter != emap.end(), "Unexpected condition."); auto const& edge = eiter->second; LogAssert(edge, "Unexpected condition."); auto tri0 = edge->T[0]; LogAssert(tri0, "Unexpected condition."); if (tri0->WhichSideOfEdge(v0, v1) == node.chirality) { region.insert(TriangleKey<true>(tri0->V[0], tri0->V[1], tri0->V[2])); } else { auto tri1 = edge->T[1]; if (tri1) { region.insert(TriangleKey<true>(tri1->V[0], tri1->V[1], tri1->V[2])); } } } FillRegion(graph, edges, region); ExtractTriangles(graph, region, node); for (size_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { edges.erase(EdgeKey<false>(node.polygon[i0], node.polygon[i1])); } } // On input, the set has the initial seeds for the desired region. A // breadth-first search is performed to find the connected component // of the seeds. The component is bounded by an outer polygon and the // inner polygons of its children. void FillRegion(ETManifoldMesh& graph, std::set<EdgeKey<false>> const& edges, std::set<TriangleKey<true>>& region) { std::queue<TriangleKey<true>> regionQueue; for (auto const& tkey : region) { regionQueue.push(tkey); } auto const& tmap = graph.GetTriangles(); while (regionQueue.size() > 0) { TriangleKey<true> tkey = regionQueue.front(); regionQueue.pop(); auto titer = tmap.find(tkey); LogAssert(titer != tmap.end(), "Unexpected condition."); auto const& tri = titer->second; LogAssert(tri, "Unexpected condition."); for (size_t j = 0; j < 3; ++j) { auto edge = tri->E[j]; if (edge) { auto siter = edges.find(EdgeKey<false>(edge->V[0], edge->V[1])); if (siter == edges.end()) { // The edge is not constrained, so it allows the // search to continue. auto adj = tri->T[j]; if (adj) { TriangleKey<true> akey(adj->V[0], adj->V[1], adj->V[2]); auto riter = region.find(akey); if (riter == region.end()) { // The adjacent triangle has not yet been // visited, so place it in the queue to // continue the search. region.insert(akey); regionQueue.push(akey); } } } } } } } // Store the region triangles in a triangulation object and remove // those triangles from the graph in preparation for processing the // next layer of triangles. void ExtractTriangles(ETManifoldMesh& graph, std::set<TriangleKey<true>> const& region, PolygonTreeEx::Node& node) { node.triangulation.reserve(region.size()); if (node.chirality > 0) { for (auto const& tri : region) { node.triangulation.push_back({ tri.V[0], tri.V[1], tri.V[2] }); graph.Remove(tri.V[0], tri.V[1], tri.V[2]); } } else // node.chirality < 0 { for (auto const& tri : region) { node.triangulation.push_back({ tri.V[0], tri.V[2], tri.V[1] }); graph.Remove(tri.V[0], tri.V[1], tri.V[2]); } } } void GetOutsideTriangles(PolygonTreeEx& tree, ETManifoldMesh& graph) { auto const& tmap = graph.GetTriangles(); tree.outsideTriangles.resize(tmap.size()); size_t t = 0; for (auto const& tri : tmap) { auto const& tkey = tri.first; tree.outsideTriangles[t++] = { tkey.V[0], tkey.V[1], tkey.V[2] }; } graph.Clear(); } // Get the triangles in the polygon tree, classifying each as // interior (in region bounded by outer polygon and its contained // inner polygons) or exterior (in region bounded by inner polygon // and its contained outer polygons). The inside triangles are the // union of the interior and exterior triangles. void GetInsideTriangles(PolygonTreeEx& tree) { size_t const numTriangles = tree.allTriangles.size(); size_t const numOutside = tree.outsideTriangles.size(); size_t const numInside = numTriangles - numOutside; tree.interiorTriangles.reserve(numTriangles); tree.interiorNodeIndices.reserve(numTriangles); tree.exteriorTriangles.reserve(numTriangles); tree.exteriorNodeIndices.reserve(numTriangles); tree.insideTriangles.reserve(numInside); tree.insideNodeIndices.reserve(numInside); for (size_t nIndex = 0; nIndex < tree.nodes.size(); ++nIndex) { auto const& node = tree.nodes[nIndex]; for (auto& tri : node.triangulation) { if (node.chirality > 0) { tree.interiorTriangles.push_back(tri); tree.interiorNodeIndices.push_back(nIndex); } else { tree.exteriorTriangles.push_back(tri); tree.exteriorNodeIndices.push_back(nIndex); } tree.insideTriangles.push_back(tri); tree.insideNodeIndices.push_back(nIndex); } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GMatrix.h
.h
20,932
703
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.23 #pragma once #include <Mathematics/GVector.h> #include <Mathematics/GaussianElimination.h> #include <algorithm> namespace gte { template <typename Real> class GMatrix { public: // The table is length zero and mNumRows and mNumCols are set to zero. GMatrix() : mNumRows(0), mNumCols(0), mElements{} { } // The table is length numRows*numCols and the elements are // initialized to zero. GMatrix(int32_t numRows, int32_t numCols) : mNumRows(0), mNumCols(0), mElements{} { SetSize(numRows, numCols); std::fill(mElements.begin(), mElements.end(), (Real)0); } // For 0 <= r < numRows and 0 <= c < numCols, element (r,c) is 1 and // all others are 0. If either of r or c is invalid, the zero matrix // is created. This is a convenience for creating the standard // Euclidean basis matrices; see also MakeUnit(int32_t,int32_t) and // Unit(int32_t,int32_t). GMatrix(int32_t numRows, int32_t numCols, int32_t r, int32_t c) : mNumRows(0), mNumCols(0), mElements{} { SetSize(numRows, numCols); MakeUnit(r, c); } // The copy constructor, destructor, and assignment operator are // generated by the compiler. // Member access for which the storage representation is transparent. // The matrix entry in row r and column c is A(r,c). The first // operator() returns a const reference rather than a Real value. // This supports writing via standard file operations that require a // const pointer to data. void SetSize(int32_t numRows, int32_t numCols) { if (numRows > 0 && numCols > 0) { mNumRows = numRows; mNumCols = numCols; mElements.resize(static_cast<size_t>(mNumRows) * static_cast<size_t>(mNumCols)); } else { mNumRows = 0; mNumCols = 0; mElements.clear(); } } inline void GetSize(int32_t& numRows, int32_t& numCols) const { numRows = mNumRows; numCols = mNumCols; } inline int32_t GetNumRows() const { return mNumRows; } inline int32_t GetNumCols() const { return mNumCols; } inline int32_t GetNumElements() const { return static_cast<int32_t>(mElements.size()); } inline Real const& operator()(int32_t r, int32_t c) const { if (0 <= r && r < GetNumRows() && 0 <= c && c < GetNumCols()) { #if defined(GTE_USE_ROW_MAJOR) return mElements[c + static_cast<size_t>(mNumCols) * r]; #else return mElements[r + static_cast<size_t>(mNumRows) * c]; #endif } LogError("Invalid index."); } inline Real& operator()(int32_t r, int32_t c) { if (0 <= r && r < GetNumRows() && 0 <= c && c < GetNumCols()) { #if defined(GTE_USE_ROW_MAJOR) return mElements[c + static_cast<size_t>(mNumCols) * r]; #else return mElements[r + static_cast<size_t>(mNumRows) * c]; #endif } LogError("Invalid index."); } // Member access by rows or by columns. The input vectors must have // the correct number of elements for the matrix size. void SetRow(int32_t r, GVector<Real> const& vec) { if (0 <= r && r < mNumRows) { if (vec.GetSize() == GetNumCols()) { for (int32_t c = 0; c < mNumCols; ++c) { operator()(r, c) = vec[c]; } return; } LogError("Mismatched sizes."); } LogError("Invalid index."); } void SetCol(int32_t c, GVector<Real> const& vec) { if (0 <= c && c < mNumCols) { if (vec.GetSize() == GetNumRows()) { for (int32_t r = 0; r < mNumRows; ++r) { operator()(r, c) = vec[r]; } return; } LogError("Mismatched sizes."); } LogError("Invalid index."); } GVector<Real> GetRow(int32_t r) const { if (0 <= r && r < mNumRows) { GVector<Real> vec(mNumCols); for (int32_t c = 0; c < mNumCols; ++c) { vec[c] = operator()(r, c); } return vec; } LogError("Invalid index."); } GVector<Real> GetCol(int32_t c) const { if (0 <= c && c < mNumCols) { GVector<Real> vec(mNumRows); for (int32_t r = 0; r < mNumRows; ++r) { vec[r] = operator()(r, c); } return vec; } LogError("Invalid index."); } // Member access by 1-dimensional index. NOTE: These accessors are // useful for the manipulation of matrix entries when it does not // matter whether storage is row-major or column-major. Do not use // constructs such as M[c+NumCols*r] or M[r+NumRows*c] that expose the // storage convention. inline Real const& operator[](int32_t i) const { return mElements[i]; } inline Real& operator[](int32_t i) { return mElements[i]; } // Comparisons for sorted containers and geometric ordering. inline bool operator==(GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements == mat.mElements; } inline bool operator!=(GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements != mat.mElements; } inline bool operator< (GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements < mat.mElements; } inline bool operator<=(GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements <= mat.mElements; } inline bool operator> (GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements > mat.mElements; } inline bool operator>=(GMatrix const& mat) const { return mNumRows == mat.mNumRows && mNumCols == mat.mNumCols && mElements >= mat.mElements; } // Special matrices. // All components are 0. void MakeZero() { std::fill(mElements.begin(), mElements.end(), (Real)0); } // Component (r,c) is 1, all others zero. void MakeUnit(int32_t r, int32_t c) { if (0 <= r && r < mNumRows && 0 <= c && c < mNumCols) { MakeZero(); operator()(r, c) = (Real)1; return; } LogError("Invalid index."); } // Diagonal entries 1, others 0, even when nonsquare. void MakeIdentity() { MakeZero(); int32_t const numDiagonal = (mNumRows <= mNumCols ? mNumRows : mNumCols); for (int32_t i = 0; i < numDiagonal; ++i) { operator()(i, i) = (Real)1; } } static GMatrix Zero(int32_t numRows, int32_t numCols) { GMatrix<Real> M(numRows, numCols); M.MakeZero(); return M; } static GMatrix Unit(int32_t numRows, int32_t numCols, int32_t r, int32_t c) { GMatrix<Real> M(numRows, numCols); M.MakeUnit(r, c); return M; } static GMatrix Identity(int32_t numRows, int32_t numCols) { GMatrix<Real> M(numRows, numCols); M.MakeIdentity(); return M; } protected: // The matrix is stored as a 1-dimensional array. The convention of // row-major or column-major is your choice. int32_t mNumRows, mNumCols; std::vector<Real> mElements; }; // Unary operations. template <typename Real> GMatrix<Real> operator+(GMatrix<Real> const& M) { return M; } template <typename Real> GMatrix<Real> operator-(GMatrix<Real> const& M) { GMatrix<Real> result(M.GetNumRows(), M.GetNumCols()); for (int32_t i = 0; i < M.GetNumElements(); ++i) { result[i] = -M[i]; } return result; } // Linear-algebraic operations. template <typename Real> GMatrix<Real> operator+(GMatrix<Real> const& M0, GMatrix<Real> const& M1) { GMatrix<Real> result = M0; return result += M1; } template <typename Real> GMatrix<Real> operator-(GMatrix<Real> const& M0, GMatrix<Real> const& M1) { GMatrix<Real> result = M0; return result -= M1; } template <typename Real> GMatrix<Real> operator*(GMatrix<Real> const& M, Real scalar) { GMatrix<Real> result = M; return result *= scalar; } template <typename Real> GMatrix<Real> operator*(Real scalar, GMatrix<Real> const& M) { GMatrix<Real> result = M; return result *= scalar; } template <typename Real> GMatrix<Real> operator/(GMatrix<Real> const& M, Real scalar) { GMatrix<Real> result = M; return result /= scalar; } template <typename Real> GMatrix<Real>& operator+=(GMatrix<Real>& M0, GMatrix<Real> const& M1) { if (M0.GetNumRows() == M1.GetNumRows() && M0.GetNumCols() == M1.GetNumCols()) { for (int32_t i = 0; i < M0.GetNumElements(); ++i) { M0[i] += M1[i]; } return M0; } LogError("Mismatched sizes"); } template <typename Real> GMatrix<Real>& operator-=(GMatrix<Real>& M0, GMatrix<Real> const& M1) { if (M0.GetNumRows() == M1.GetNumRows() && M0.GetNumCols() == M1.GetNumCols()) { for (int32_t i = 0; i < M0.GetNumElements(); ++i) { M0[i] -= M1[i]; } return M0; } LogError("Mismatched sizes"); } template <typename Real> GMatrix<Real>& operator*=(GMatrix<Real>& M, Real scalar) { for (int32_t i = 0; i < M.GetNumElements(); ++i) { M[i] *= scalar; } return M; } template <typename Real> GMatrix<Real>& operator/=(GMatrix<Real>& M, Real scalar) { if (scalar != (Real)0) { Real invScalar = ((Real)1) / scalar; for (int32_t i = 0; i < M.GetNumElements(); ++i) { M[i] *= invScalar; } return M; } LogError("Division by zero."); } // Geometric operations. template <typename Real> Real L1Norm(GMatrix<Real> const& M) { Real sum(0); for (int32_t i = 0; i < M.GetNumElements(); ++i) { sum += std::fabs(M[i]); } return sum; } template <typename Real> Real L2Norm(GMatrix<Real> const& M) { Real sum(0); for (int32_t i = 0; i < M.GetNumElements(); ++i) { sum += M[i] * M[i]; } return std::sqrt(sum); } template <typename Real> Real LInfinityNorm(GMatrix<Real> const& M) { Real maxAbsElement(0); for (int32_t i = 0; i < M.GetNumElements(); ++i) { Real absElement = std::fabs(M[i]); if (absElement > maxAbsElement) { maxAbsElement = absElement; } } return maxAbsElement; } template <typename Real> GMatrix<Real> Inverse(GMatrix<Real> const& M, bool* reportInvertibility = nullptr) { if (M.GetNumRows() == M.GetNumCols()) { GMatrix<Real> invM(M.GetNumRows(), M.GetNumCols()); Real determinant; bool invertible = GaussianElimination<Real>()(M.GetNumRows(), &M[0], &invM[0], determinant, nullptr, nullptr, nullptr, 0, nullptr); if (reportInvertibility) { *reportInvertibility = invertible; } return invM; } LogError("Matrix must be square."); } template <typename Real> Real Determinant(GMatrix<Real> const& M) { if (M.GetNumRows() == M.GetNumCols()) { Real determinant; GaussianElimination<Real>()(M.GetNumRows(), &M[0], nullptr, determinant, nullptr, nullptr, nullptr, 0, nullptr); return determinant; } LogError("Matrix must be square."); } // M^T template <typename Real> GMatrix<Real> Transpose(GMatrix<Real> const& M) { GMatrix<Real> result(M.GetNumCols(), M.GetNumRows()); for (int32_t r = 0; r < M.GetNumRows(); ++r) { for (int32_t c = 0; c < M.GetNumCols(); ++c) { result(c, r) = M(r, c); } } return result; } // M*V template <typename Real> GVector<Real> operator*(GMatrix<Real> const& M, GVector<Real> const& V) { if (V.GetSize() == M.GetNumCols()) { GVector<Real> result(M.GetNumRows()); for (int32_t r = 0; r < M.GetNumRows(); ++r) { result[r] = (Real)0; for (int32_t c = 0; c < M.GetNumCols(); ++c) { result[r] += M(r, c) * V[c]; } } return result; } LogError("Mismatched sizes."); } // V^T*M template <typename Real> GVector<Real> operator*(GVector<Real> const& V, GMatrix<Real> const& M) { if (V.GetSize() == M.GetNumRows()) { GVector<Real> result(M.GetNumCols()); for (int32_t c = 0; c < M.GetNumCols(); ++c) { result[c] = (Real)0; for (int32_t r = 0; r < M.GetNumRows(); ++r) { result[c] += V[r] * M(r, c); } } return result; } LogError("Mismatched sizes."); } // A*B template <typename Real> GMatrix<Real> operator*(GMatrix<Real> const& A, GMatrix<Real> const& B) { return MultiplyAB(A, B); } template <typename Real> GMatrix<Real> MultiplyAB(GMatrix<Real> const& A, GMatrix<Real> const& B) { if (A.GetNumCols() == B.GetNumRows()) { GMatrix<Real> result(A.GetNumRows(), B.GetNumCols()); int32_t const numCommon = A.GetNumCols(); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = (Real)0; for (int32_t i = 0; i < numCommon; ++i) { result(r, c) += A(r, i) * B(i, c); } } } return result; } LogError("Mismatched sizes."); } // A*B^T template <typename Real> GMatrix<Real> MultiplyABT(GMatrix<Real> const& A, GMatrix<Real> const& B) { if (A.GetNumCols() == B.GetNumCols()) { GMatrix<Real> result(A.GetNumRows(), B.GetNumRows()); int32_t const numCommon = A.GetNumCols(); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = (Real)0; for (int32_t i = 0; i < numCommon; ++i) { result(r, c) += A(r, i) * B(c, i); } } } return result; } LogError("Mismatched sizes."); } // A^T*B template <typename Real> GMatrix<Real> MultiplyATB(GMatrix<Real> const& A, GMatrix<Real> const& B) { if (A.GetNumRows() == B.GetNumRows()) { GMatrix<Real> result(A.GetNumCols(), B.GetNumCols()); int32_t const numCommon = A.GetNumRows(); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = (Real)0; for (int32_t i = 0; i < numCommon; ++i) { result(r, c) += A(i, r) * B(i, c); } } } return result; } LogError("Mismatched sizes."); } // A^T*B^T template <typename Real> GMatrix<Real> MultiplyATBT(GMatrix<Real> const& A, GMatrix<Real> const& B) { if (A.GetNumRows() == B.GetNumCols()) { GMatrix<Real> result(A.GetNumCols(), B.GetNumRows()); int32_t const numCommon = A.GetNumRows(); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = (Real)0; for (int32_t i = 0; i < numCommon; ++i) { result(r, c) += A(i, r) * B(c, i); } } } return result; } LogError("Mismatched sizes."); } // M*D, D is square diagonal (stored as vector) template <typename Real> GMatrix<Real> MultiplyMD(GMatrix<Real> const& M, GVector<Real> const& D) { if (D.GetSize() == M.GetNumCols()) { GMatrix<Real> result(M.GetNumRows(), M.GetNumCols()); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = M(r, c) * D[c]; } } return result; } LogError("Mismatched sizes."); } // D*M, D is square diagonal (stored as vector) template <typename Real> GMatrix<Real> MultiplyDM(GVector<Real> const& D, GMatrix<Real> const& M) { if (D.GetSize() == M.GetNumRows()) { GMatrix<Real> result(M.GetNumRows(), M.GetNumCols()); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = D[r] * M(r, c); } } return result; } LogError("Mismatched sizes."); } // U*V^T, U is N-by-1, V is M-by-1, result is N-by-M. template <typename Real> GMatrix<Real> OuterProduct(GVector<Real> const& U, GVector<Real> const& V) { GMatrix<Real> result(U.GetSize(), V.GetSize()); for (int32_t r = 0; r < result.GetNumRows(); ++r) { for (int32_t c = 0; c < result.GetNumCols(); ++c) { result(r, c) = U[r] * V[c]; } } return result; } // Initialization to a diagonal matrix whose diagonal entries are the // components of D, even when nonsquare. template <typename Real> void MakeDiagonal(GVector<Real> const& D, GMatrix<Real>& M) { int32_t const numRows = M.GetNumRows(); int32_t const numCols = M.GetNumCols(); int32_t const numDiagonal = (numRows <= numCols ? numRows : numCols); M.MakeZero(); for (int32_t i = 0; i < numDiagonal; ++i) { M(i, i) = D[i]; } } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SymmetricEigensolver2x2.h
.h
2,822
87
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> #include <algorithm> #include <array> namespace gte { template <typename Real> class SymmetricEigensolver2x2 { public: // The input matrix must be symmetric, so only the unique elements // must be specified: a00, a01, and a11. // // The order of the eigenvalues is specified by sortType: // -1 (decreasing), 0 (no sorting) or +1 (increasing). When sorted, // the eigenvectors are ordered accordingly, and {evec[0], evec[1]} // is guaranteed to be a right-handed orthonormal set. void operator()(Real a00, Real a01, Real a11, int32_t sortType, std::array<Real, 2>& eval, std::array<std::array<Real, 2>, 2>& evec) const { // Normalize (c2,s2) robustly, avoiding floating-point overflow // in the sqrt call. Real const zero = (Real)0, one = (Real)1, half = (Real)0.5; Real c2 = half * (a00 - a11), s2 = a01; Real maxAbsComp = std::max(std::fabs(c2), std::fabs(s2)); if (maxAbsComp > zero) { c2 /= maxAbsComp; // in [-1,1] s2 /= maxAbsComp; // in [-1,1] Real length = std::sqrt(c2 * c2 + s2 * s2); c2 /= length; s2 /= length; if (c2 > zero) { c2 = -c2; s2 = -s2; } } else { c2 = -one; s2 = zero; } Real s = std::sqrt(half * (one - c2)); // >= 1/sqrt(2) Real c = half * s2 / s; Real csqr = c * c, ssqr = s * s, mid = s2 * a01; std::array<Real, 2> diagonal { csqr * a00 + mid + ssqr * a11, csqr * a11 - mid + ssqr * a00 }; if (sortType == 0 || static_cast<Real>(sortType) * diagonal[0] <= static_cast<Real>(sortType) * diagonal[1]) { eval[0] = diagonal[0]; eval[1] = diagonal[1]; evec[0][0] = c; evec[0][1] = s; evec[1][0] = -s; evec[1][1] = c; } else { eval[0] = diagonal[1]; eval[1] = diagonal[0]; evec[0][0] = s; evec[0][1] = -c; evec[1][0] = c; evec[1][1] = s; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrTriangle3Triangle3.h
.h
49,754
1,345
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.20 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/FIQuery.h> #include <Mathematics/Vector3.h> #include <Mathematics/IntrTriangle2Triangle2.h> #include <Mathematics/IntrSegment2Triangle2.h> // The queries consider the triangles to be solids. // // The test-intersection query (TIQuery) uses the method of separating axes // to determine whether or not the triangles intersect. See // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // Section 5 describes the finite set of potential separating axes. // // The find-intersection query (FIQuery) determines how the two triangles // are positioned and oriented to each other. The algorithm uses the sign of // the projections of the vertices of triangle1 onto a normal line that is // perpendicular to the plane of triangle0. The table of possibilities is // listed next with n = numNegative, p = numPositive and z = numZero. // // n p z intersection // ------------------------------------ // 0 3 0 none // 0 2 1 vertex // 0 1 2 edge // 0 0 3 coplanar triangles or a triangle is degenerate // 1 2 0 segment (2 edges clipped) // 1 1 1 segment (1 edge clipped) // 1 0 2 edge // 2 1 0 segment (2 edges clipped) // 2 0 1 vertex // 3 0 0 none namespace gte { template <typename T> class TIQuery<T, Triangle3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false), contactTime(static_cast<T>(0)) { } // The contact time is 0 for stationary triangles. It is // nonnegative for moving triangles. bool intersect; T contactTime; }; // The query is for stationary triangles. Result operator()(Triangle3<T> const& inTriangle0, Triangle3<T> const& inTriangle1) { Result result{}; // Translate the triangles so that triangle0.v[0] becomes (0,0,0). T const zero = static_cast<T>(0); Vector3<T> const& origin = inTriangle0.v[0]; Triangle3<T> triangle0( Vector3<T>{ zero, zero, zero }, inTriangle0.v[1] - origin, inTriangle0.v[2] - origin); Triangle3<T> triangle1( inTriangle1.v[0] - origin, inTriangle1.v[1] - origin, inTriangle1.v[2] - origin); // Get edge directions and a normal vector for triangle0. std::array<Vector3<T>, 3> E0 { triangle0.v[1] - triangle0.v[0], triangle0.v[2] - triangle0.v[1], triangle0.v[0] - triangle0.v[2] }; Vector3<T> N0 = Cross(E0[0], E0[1]); // Scale-project triangle1 onto the normal line of triangle0 and // test for separation. The translation performed initially // ensures that triangle0 projects onto its normal line at t = 0. std::array<T, 2> tExtreme0{ zero, zero }; std::array<T, 2> tExtreme1 = ScaleProjectOntoLine(triangle1, N0); if (tExtreme0[1] < tExtreme1[0] || tExtreme1[1] < tExtreme0[0]) { return result; } // Get edge directions and a normal vector for triangle1. std::array<Vector3<T>, 3> E1 { triangle1.v[1] - triangle1.v[0], triangle1.v[2] - triangle1.v[1], triangle1.v[0] - triangle1.v[2] }; Vector3<T> N1 = Cross(E1[0], E1[1]); // Scale-project triangle0 onto the normal line of triangle1 and // test for separation. T const projT0V0 = Dot(N1, triangle1.v[0] - triangle0.v[0]); tExtreme0 = { projT0V0, projT0V0 }; tExtreme1 = ScaleProjectOntoLine(triangle0, N1); if (tExtreme0[1] < tExtreme1[0] || tExtreme1[1] < tExtreme0[0]) { return result; } // At this time, neither normal line is a separation axis for the // triangles. If Cross(N0,N1) != (0,0,0), the planes of the // triangles are not parallel and must intersect in a line. If // Cross(N0,N1) = (0,0,0), the planes are parallel. In fact they // are coplanar; for if they were not coplanar, one of the two // previous separating axis tests would have determined this and // returned from the function call. // The potential separating axes are origin+t*direction, where // origin is inTriangle.v[0]. In the translated configuration, // the potential separating axes are t*direction. Vector3<T> direction{ zero, zero, zero }; Vector3<T> N0xN1 = Cross(N0, N1); T sqrLengthN0xN1 = Dot(N0xN1, N0xN1); if (sqrLengthN0xN1 > zero) { // The triangles are not parallel. Test for separation by // using directions that are cross products of a pair of // triangle edges, one edge from triangle0 and one edge from // triangle1. for (size_t i1 = 0; i1 < 3; ++i1) { for (size_t i0 = 0; i0 < 3; ++i0) { direction = Cross(E0[i0], E1[i1]); tExtreme0 = ScaleProjectOntoLine(triangle0, direction); tExtreme1 = ScaleProjectOntoLine(triangle1, direction); if (tExtreme0[1] < tExtreme1[0] || tExtreme1[1] < tExtreme0[0]) { return result; } } } } else { // The triangles are coplanar. Test for separation by using // directions that are cross products of a pair of vectors, // one vector a normal of a triangle and the other vector an // edge from the other triangle. // Directions N0xE0[i0]. for (size_t i0 = 0; i0 < 3; ++i0) { direction = Cross(N0, E0[i0]); tExtreme0 = ScaleProjectOntoLine(triangle0, direction); tExtreme1 = ScaleProjectOntoLine(triangle1, direction); if (tExtreme0[1] < tExtreme1[0] || tExtreme1[1] < tExtreme0[0]) { return result; } } // Directions N1xE1[i1]. for (size_t i1 = 0; i1 < 3; ++i1) { direction = Cross(N1, E1[i1]); tExtreme0 = ScaleProjectOntoLine(triangle0, direction); tExtreme1 = ScaleProjectOntoLine(triangle1, direction); if (tExtreme0[1] < tExtreme1[0] || tExtreme1[1] < tExtreme0[0]) { return result; } } } result.intersect = true; return result; } // The query is for triangles moving with constant linear velocity // during the time interval [0,tMax]. Result operator()(T const& tMax, Triangle3<T> const& inTriangle0, Vector3<T> const& velocity0, Triangle3<T> const& inTriangle1, Vector3<T> const& velocity1) { Result result{}; // The query determines the interval [tFirst,tLast] over which // the triangle are intersecting. Start with time interval // [0,+infinity). T tFirst = static_cast<T>(0); T tLast = std::numeric_limits<T>::max(); // Compute the velocity of inTriangle1 relative to inTriangle0. Vector3<T> relVelocity = velocity1 - velocity0; // Translate the triangles so that triangle0.v[0] becomes (0,0,0). T const zero = static_cast<T>(0); Vector3<T> const& origin = inTriangle0.v[0]; Triangle3<T> triangle0( Vector3<T>{ zero, zero, zero }, inTriangle0.v[1] - origin, inTriangle0.v[2] - origin); Triangle3<T> triangle1( inTriangle1.v[0] - origin, inTriangle1.v[1] - origin, inTriangle1.v[2] - origin); // Get edge directions and a normal vector for triangle0. std::array<Vector3<T>, 3> E0 { triangle0.v[1] - triangle0.v[0], triangle0.v[2] - triangle0.v[1], triangle0.v[0] - triangle0.v[2] }; Vector3<T> N0 = Cross(E0[0], E0[1]); // Test for overlap using the separating axis test in the N0 // direction. if (!TestOverlap(triangle0, triangle1, N0, tMax, relVelocity, tFirst, tLast)) { return result; } // Get edge directions and a normal vector for triangle1. std::array<Vector3<T>, 3> E1 { triangle1.v[1] - triangle1.v[0], triangle1.v[2] - triangle1.v[1], triangle1.v[0] - triangle1.v[2] }; Vector3<T> N1 = Cross(E1[0], E1[1]); if (std::fabs(Dot(N0, N1)) < static_cast<T>(1)) { // The triangles are not parallel. // Test for overlap using the separating axis test in the // N1 direction. if (!TestOverlap(triangle0, triangle1, N1, tMax, relVelocity, tFirst, tLast)) { return result; } // Test for overlap using the separating axis test in the // directions E0[i0]xE1[i1]. for (size_t i1 = 0; i1 < 3; ++i1) { for (size_t i0 = 0; i0 < 3; ++i0) { Vector3<T> direction = UnitCross(E0[i0], E1[i1]); if (!TestOverlap(triangle0, triangle1, direction, tMax, relVelocity, tFirst, tLast)) { return result; } } } } else { // The triangles are coplanar. // Test for overlap using the separating axis test in the // directions N0xE0[i0]. for (size_t i0 = 0; i0 < 3; ++i0) { Vector3<T> direction = UnitCross(N0, E0[i0]); if (!TestOverlap(triangle0, triangle1, direction, tMax, relVelocity, tFirst, tLast)) { return result; } } // Test for overlap using the separating axis test in the // directions N1xE1[i1]. for (size_t i1 = 0; i1 < 3; ++i1) { Vector3<T> direction = UnitCross(N1, E1[i1]); if (!TestOverlap(triangle0, triangle1, direction, tMax, relVelocity, tFirst, tLast)) { return result; } } } result.intersect = true; result.contactTime = tFirst; return result; } private: // The triangle is <V[0],V[1],V[2]>. The line is t*direction, where // the origin is (0,0,0) and the 'direction' is not zero but not // necessarily unit length. The projections of the triangle vertices // onto the line are t[i] = Dot(direction, V[i]). Return the extremes // tmin = min(t[0],t[1],t[2]) and tmax = max(t[0],t[1],t[2]) as // elements of a std::array<T,2>. static std::array<T, 2> ScaleProjectOntoLine(Triangle3<T> const& triangle, Vector3<T> const& direction) { T t = Dot(direction, triangle.v[0]); std::array<T, 2> tExtreme{ t, t }; for (size_t i = 1; i < 3; ++i) { t = Dot(direction, triangle.v[i]); if (t < tExtreme[0]) { tExtreme[0] = t; } else if (t > tExtreme[1]) { tExtreme[1] = t; } } return tExtreme; } // This is the constant velocity separating axis test. static bool TestOverlap(T const& tMax, T const& speed, std::array<T, 2> const& extreme0, std::array<T, 2> const& extreme1, T& tFirst, T& tLast) { T const zero = static_cast<T>(0); if (extreme1[1] < extreme0[0]) { // The interval extreme1 is on the left of the interval // extreme0. if (speed <= zero) { // The interval extreme1 is moving away from the interval // extreme0. return false; } // Compute the first time of contact on this axis. T t = (extreme0[0] - extreme1[1]) / speed; if (t > tFirst) { tFirst = t; } if (tFirst > tMax) { // The intersection occurs after the specified maximum // time. return false; } // Compute the last time of contact on this axis. t = (extreme0[1] - extreme1[0]) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are not // intersecting. return false; } } else if (extreme0[1] < extreme1[0]) { // The interval extreme1 is on the right of the interval // extreme0. if (speed >= zero) { // The interval extreme1 is moving away from the interval // extreme0. return false; } // Compute the first time of contact on this axis. T t = (extreme0[1] - extreme1[0]) / speed; if (t > tFirst) { tFirst = t; } if (tFirst > tMax) { // The intersection occurs after the specified maximum // time. return false; } // Compute the last time of contact on this axis. t = (extreme0[0] - extreme1[1]) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are not // intersecting. return false; } } else { // The intervals extreme0 and extreme1 are currently // overlapping. if (speed > zero) { // Compute the last time of contact on this axis. T t = (extreme0[1] - extreme1[0]) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } else if (speed < zero) { // Compute the last time of contact on this axis. T t = (extreme0[0] - extreme1[1]) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } } return true; } // A projection wrapper to set up for the separating axis test. static bool TestOverlap(Triangle3<T> const& triangle0, Triangle3<T> const& triangle1, Vector3<T> const& direction, T const& tMax, Vector3<T> const& velocity, T& tFirst, T& tLast) { auto extreme0 = ScaleProjectOntoLine(triangle0, direction); auto extreme1 = ScaleProjectOntoLine(triangle1, direction); T speed = Dot(direction, velocity); return TestOverlap(tMax, speed, extreme0, extreme1, tFirst, tLast); } }; template <typename T> class FIQuery<T, Triangle3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false), contactTime(static_cast<T>(0)), intersection{} { } // The contact time is 0 for stationary triangles. It is // nonnegative for moving triangles. bool intersect; T contactTime; std::vector<Vector3<T>> intersection; }; // The query is for stationary triangles. Result operator()(Triangle3<T> const& inTriangle0, Triangle3<T> const& inTriangle1) { Result result{}; // Translate the triangles so that triangle0.v[0] becomes (0,0,0). T const zero = static_cast<T>(0); Vector3<T> const& origin = inTriangle0.v[0]; Triangle3<T> triangle0( Vector3<T>{ zero, zero, zero }, inTriangle0.v[1] - origin, inTriangle0.v[2] - origin); Triangle3<T> triangle1( inTriangle1.v[0] - origin, inTriangle1.v[1] - origin, inTriangle1.v[2] - origin); // Compute a normal vector for the plane containing triangle0. Vector3<T> normal = Cross(triangle0.v[1], triangle0.v[2]); // Determine where the vertices of triangle1 live relative to the // plane of triangle0. The 'distance' values are actually signed // and scaled distances, the latter because 'normal' is not // necessarily unit length. size_t numPositive = 0, numNegative = 0, numZero = 0; std::array<T, 3> distance{}; std::array<int32_t, 3> sign{}; for (size_t i = 0; i < 3; ++i) { distance[i] = Dot(normal, triangle1.v[i]); if (distance[i] > zero) { sign[i] = 1; ++numPositive; } else if (distance[i] < zero) { sign[i] = -1; ++numNegative; } else { sign[i] = 0; ++numZero; } } if (numZero == 0 ) { if (numPositive > 0 && numNegative > 0) { // (n,p,z) is (1,2,0) or (2,1,0). int32_t signCompare = (numPositive == 1 ? 1 : -1); for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (sign[i2] == signCompare) { Segment3<T> segment{}; Vector3<T> const& Vi2 = triangle1.v[i2]; T t0 = distance[i2] / (distance[i2] - distance[i0]); Vector3<T> diffVi0Vi2 = triangle1.v[i0] - triangle1.v[i2]; segment.p[0] = Vi2 + t0 * diffVi0Vi2; Vector3<T> diffVi1Vi2 = triangle1.v[i1] - triangle1.v[i2]; T t1 = distance[i2] / (distance[i2] - distance[i1]); segment.p[1] = Vi2 + t1 * diffVi1Vi2; IntersectsSegment(normal, triangle0, segment, result); break; } } } // else: (n,p,z) is (0,3,0) or (3,0,0) and triangle1 is // strictly on one side of the plane of triangle0, so no // intersection. } else if (numZero == 1) { if (numPositive == 1) { // (n,p,z) is (1,1,1). A single vertex of triangle1 is // in the plane of triangle0 and the opposing edge of // triangle1 intersects the plane transversely. for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (sign[i2] == 0) { Segment3<T> segment{}; segment.p[0] = triangle1.v[i2]; Vector3<T> const& Vi1 = triangle1.v[i1]; T t = distance[i1] / (distance[i1] - distance[i0]); Vector3<T> diffVi0Vi1 = triangle1.v[i0] - triangle1.v[i1]; segment.p[1] = Vi1 + t * diffVi0Vi1; IntersectsSegment(normal, triangle0, segment, result); break; } } } else { // (n,p,z) is (2,0,1) or (0,2,1). A single vertex of // triangle1 is in the plane of triangle0. for (size_t i = 0; i < 3; ++i) { if (sign[i] == 0) { ContainsPoint(normal, triangle0, triangle1.v[i], result); break; } } } } else if (numZero == 2) { // (n,p,z) is (0,1,2) or (1,0,2). Two vertices are on the // plane of triangle0, so the segment connecting the vertices // is on the plane. for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (sign[i2] != 0) { Segment3<T> segment(triangle1.v[i0], triangle1.v[i1]); IntersectsSegment(normal, triangle0, segment, result); break; } } } else // numZero == 3 { // (n,p,z) is (0,0,3). Triangle1 is contained in the plane of // triangle0. GetCoplanarIntersection(normal, triangle0, triangle1, result); } if (result.intersect) { // Translate the intersection set back to the original // coordinate system. for (auto& point : result.intersection) { point += origin; } } return result; } // The query is for triangles moving with constant linear velocity // during the time interval [0,tMax]. Result operator()(T const& tMax, Triangle3<T> const& inTriangle0, Vector3<T> const& velocity0, Triangle3<T> const& inTriangle1, Vector3<T> const& velocity1) { Result result{}; // The query determines the interval [tFirst,tLast] over which // the triangle are intersecting. Start with time interval // [0,+infinity). T tFirst = static_cast<T>(0); T tLast = std::numeric_limits<T>::max(); // Compute the velocity of inTriangle1 relative to inTriangle0. Vector3<T> relVelocity = velocity1 - velocity0; // Translate the triangles so that triangle0.v[0] becomes (0,0,0). T const zero = static_cast<T>(0); Vector3<T> const& origin = inTriangle0.v[0]; Triangle3<T> triangle0( Vector3<T>{ zero, zero, zero }, inTriangle0.v[1] - origin, inTriangle0.v[2] - origin); Triangle3<T> triangle1( inTriangle1.v[0] - origin, inTriangle1.v[1] - origin, inTriangle1.v[2] - origin); // Get edge directions and a normal vector for triangle0. std::array<Vector3<T>, 3> E0 { triangle0.v[1] - triangle0.v[0], triangle0.v[2] - triangle0.v[1], triangle0.v[0] - triangle0.v[2] }; Vector3<T> N0 = Cross(E0[0], E0[1]); // Find overlap using the separating axis test in the N0 // direction. ContactSide side = ContactSide::CS_NONE; Configuration tcfg0{}, tcfg1{}; if (!FindOverlap(triangle0, triangle1, N0, tMax, relVelocity, side, tcfg0, tcfg1, tFirst, tLast)) { return result; } // Get edge directions and a normal vector for triangle1. std::array<Vector3<T>, 3> E1 { triangle1.v[1] - triangle1.v[0], triangle1.v[2] - triangle1.v[1], triangle1.v[0] - triangle1.v[2] }; Vector3<T> N1 = Cross(E1[0], E1[1]); if (std::fabs(Dot(N0, N1)) < static_cast<T>(1)) { // The triangles are not parallel. // Test for overlap using the separating axis test in the // N1 direction. if (!FindOverlap(triangle0, triangle1, N1, tMax, relVelocity, side, tcfg0, tcfg1, tFirst, tLast)) { return result; } // Test for overlap using the separating axis test in the // directions E0[i0]xE1[i1]. for (size_t i1 = 0; i1 < 3; ++i1) { for (size_t i0 = 0; i0 < 3; ++i0) { Vector3<T> direction = UnitCross(E0[i0], E1[i1]); if (!FindOverlap(triangle0, triangle1, direction, tMax, relVelocity, side, tcfg0, tcfg1, tFirst, tLast)) { return result; } } } } else { // The triangles are coplanar. // Test for overlap using the separating axis test in the // directions N0xE0[i0]. for (size_t i0 = 0; i0 < 3; ++i0) { Vector3<T> direction = UnitCross(N0, E0[i0]); if (!FindOverlap(triangle0, triangle1, direction, tMax, relVelocity, side, tcfg0, tcfg1, tFirst, tLast)) { return result; } } // Test for overlap using the separating axis test in the // directions N1xE1[i1]. for (size_t i1 = 0; i1 < 3; ++i1) { Vector3<T> direction = UnitCross(N1, E1[i1]); if (!FindOverlap(triangle0, triangle1, direction, tMax, relVelocity, side, tcfg0, tcfg1, tFirst, tLast)) { return result; } } } // Move the triangles to the first contact before computing // the contact set. for (size_t i = 0; i < 3; ++i) { triangle0.v[i] = inTriangle0.v[i] + tFirst * velocity0; triangle1.v[i] = inTriangle1.v[i] + tFirst * velocity1; } auto stationary = this->operator()(triangle0, triangle1); result.intersect = true; result.contactTime = tFirst; result.intersection = std::move(stationary.intersection); return result; } private: // Compute the point, segment or polygon of intersection of coplanar // triangles. The intersection is computed by projecting the triangles // onto the plane and using a find-intersection query for two // triangles in 2D. The intersection can be empty. static void GetCoplanarIntersection(Vector3<T> const& normal, Triangle3<T> const& triangle0, Triangle3<T> const& triangle1, Result& result) { // Project the triangles onto the coordinate plane most aligned // with the plane normal. int32_t maxIndex = 0; T cmax = std::fabs(normal[0]); T cvalue = std::fabs(normal[1]); if (cvalue > cmax) { maxIndex = 1; cmax = cvalue; } cvalue = std::fabs(normal[2]); if (cvalue > cmax) { maxIndex = 2; } std::array<int32_t, 3> lookup{}; if (maxIndex == 0) { // Project onto the yz-plane. lookup = { 1, 2, 0 }; } else if (maxIndex == 1) { // Project onto the xz-plane. lookup = { 0, 2, 1 }; } else // maxIndex = 2 { // Project onto the xy-plane. lookup = { 0, 1, 2 }; } Triangle2<T> projTriangle0{}, projTriangle1{}; for (size_t i = 0; i < 3; ++i) { projTriangle0.v[i][0] = triangle0.v[i][lookup[0]]; projTriangle0.v[i][1] = triangle0.v[i][lookup[1]]; projTriangle1.v[i][0] = triangle1.v[i][lookup[0]]; projTriangle1.v[i][1] = triangle1.v[i][lookup[1]]; } // 2D triangle intersection queries require counterclockwise // ordering of vertices. T const zero = static_cast<T>(0); if (normal[maxIndex] < zero) { // Triangle0 is clockwise; reorder it. std::swap(projTriangle0.v[1], projTriangle0.v[2]); } Vector2<T> edge0 = projTriangle1.v[1] - projTriangle1.v[0]; Vector2<T> edge1 = projTriangle1.v[2] - projTriangle1.v[0]; if (DotPerp(edge0, edge1) < zero) { // Triangle1 is clockwise; reorder it. std::swap(projTriangle1.v[1], projTriangle1.v[2]); } FIQuery<T, Triangle2<T>, Triangle2<T>> ttQuery{}; auto ttResult = ttQuery(projTriangle0, projTriangle1); size_t const numVertices = ttResult.intersection.size(); if (numVertices == 0) { result.intersect = false; result.intersection.clear(); return; } // Lift the 2D polygon of intersection to the 3D triangle space. result.intersect = true; result.intersection.resize(numVertices); auto const& src = ttResult.intersection; auto& trg = result.intersection; for (size_t i = 0; i < trg.size(); ++i) { trg[i][lookup[0]] = src[i][0]; trg[i][lookup[1]] = src[i][1]; trg[i][lookup[2]] = -(normal[lookup[0]] * trg[i][lookup[0]] + normal[lookup[1]] * trg[i][lookup[1]]) / normal[lookup[2]]; } } // Compute the point or segment of intersection of the 'triangle' with // 'normal' vector. The input segment is an edge of the other triangle. // The intersection can be empty. static void IntersectsSegment(Vector3<T> const& normal, Triangle3<T> const& triangle, Segment3<T> const& segment, Result& result) { // Project the triangle and segment onto the coordinate plane most // aligned with the plane normal. int32_t maxIndex = 0; T cmax = std::fabs(normal[0]); T cvalue = std::fabs(normal[1]); if (cvalue > cmax) { maxIndex = 1; cmax = cvalue; } cvalue = std::fabs(normal[2]); if (cvalue > cmax) { maxIndex = 2; } std::array<int32_t, 3> lookup{}; if (maxIndex == 0) { // Project onto the yz-plane. lookup = { 1, 2, 0 }; } else if (maxIndex == 1) { // Project onto the xz-plane. lookup = { 0, 2, 1 }; } else // maxIndex = 2 { // Project onto the xy-plane. lookup = { 0, 1, 2 }; } Triangle2<T> projTriangle{}; for (size_t i = 0; i < 3; ++i) { projTriangle.v[i][0] = triangle.v[i][lookup[0]]; projTriangle.v[i][1] = triangle.v[i][lookup[1]]; } Segment2<T> projSegment{}; for (size_t i = 0; i < 2; ++i) { projSegment.p[i][0] = segment.p[i][lookup[0]]; projSegment.p[i][1] = segment.p[i][lookup[1]]; } // Compute the intersection with the coincident edge and the // triangle. FIQuery<T, Segment2<T>, Triangle2<T>> stQuery{}; auto stResult = stQuery(projSegment, projTriangle); if (stResult.intersect) { result.intersect = true; result.intersection.resize(stResult.numIntersections); // Lift the 2D intersection points to the 3D triangle space. auto const& src = stResult.point; auto& trg = result.intersection; for (size_t i = 0; i < trg.size(); ++i) { trg[i][lookup[0]] = src[i][0]; trg[i][lookup[1]] = src[i][1]; trg[i][lookup[2]] = -(normal[lookup[0]] * trg[i][lookup[0]] + normal[lookup[1]] * trg[i][lookup[1]]) / normal[lookup[2]]; } } } // Determine whether the point is inside or strictly outside the // triangle. static void ContainsPoint(Vector3<T> const& normal, Triangle3<T> const& triangle, Vector3<T> const& point, Result& result) { // Project the triangle and point onto the coordinate plane most // aligned with the plane normal. int32_t maxIndex = 0; T cmax = std::fabs(normal[0]); T cvalue = std::fabs(normal[1]); if (cvalue > cmax) { maxIndex = 1; cmax = cvalue; } cvalue = std::fabs(normal[2]); if (cvalue > cmax) { maxIndex = 2; } std::array<int32_t, 3> lookup{}; if (maxIndex == 0) { // Project onto the yz-plane. lookup = { 1, 2, 0 }; } else if (maxIndex == 1) { // Project onto the xz-plane. lookup = { 0, 2, 1 }; } else // maxIndex = 2 { // Project onto the xy-plane. lookup = { 0, 1, 2 }; } Triangle2<T> projTriangle{}; for (size_t i = 0; i < 3; ++i) { projTriangle.v[i][0] = triangle.v[i][lookup[0]]; projTriangle.v[i][1] = triangle.v[i][lookup[1]]; } Vector2<T> projPoint{ point[lookup[0]], point[lookup[1]] }; // Determine whether the point is inside or strictly outside the // triangle. The triangle is counterclockwise ordered when sign // is +1 or clockwise ordered when sign is -1. T const zero = static_cast<T>(0); T const sign = (normal[maxIndex] > zero ? static_cast<T>(1) : static_cast<T>(-1)); for (size_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { Vector2<T> diffPV0 = projPoint - projTriangle.v[i0]; Vector2<T> diffV1V0 = projTriangle.v[i1] - projTriangle.v[i0]; if (sign * DotPerp(diffPV0, diffV1V0) > zero) { // The point is strictly outside edge <V[i0],V[i1]>. result.intersect = false; result.intersection.clear(); return; } } // Lift the 2D point of intersection to the 3D triangle space. result.intersect = true; result.intersection.resize(1); auto const& src = projPoint; auto& trg = result.intersection[0]; trg[lookup[0]] = src[0]; trg[lookup[1]] = src[1]; trg[lookup[2]] = -(normal[lookup[0]] * trg[lookup[0]] + normal[lookup[1]] * trg[lookup[1]]) / normal[lookup[2]]; } // Support for the query for moving triangles. enum class ProjectionMap { // Initial value for construction of Configuration. PM_INVALID, // 3 vertices project to the same point (min = max). PM_3, // 2 vertices project to a point (min) and 1 vertex projects to // a point (max). PM_21, // 1 vertex projects to a point (min) and 2 vertices project to // a point (max). PM_12, // 1 vertex projects to a point (min), 1 vertex projects to a // point (max) and 1 vertex projects to a point strictly between // the min and max points. PM_111 }; struct Configuration { Configuration() : map(ProjectionMap::PM_INVALID), index{ 0, 0, 0, 0, 0, 0, 0, 0 }, min(static_cast<T>(0)), max(static_cast<T>(0)) { } // This is how the vertices map to the projection interval. ProjectionMap map; // The sorted indices of the vertices. std::array<int32_t, 8> index; // The projection interval [min,max]. T min, max; }; enum class ContactSide { CS_LEFT, CS_RIGHT, CS_NONE }; // The triangle is <V[0],V[1],V[2]>. The line is t*direction, where // the origin is (0,0,0) and the 'direction' is not zero but not // necessarily unit length. The projections of the triangle vertices // onto the line are t[i] = Dot(direction, V[i]). Return the // configuration of the triangle that lead to the extreme interval. static void ScaleProjectOntoLine(Triangle3<T> const& triangle, Vector3<T> const& direction, Configuration& cfg) { // Find the projections of the triangle vertices onto the // potential separating axis. T d0 = Dot(direction, triangle.v[0]); T d1 = Dot(direction, triangle.v[1]); T d2 = Dot(direction, triangle.v[2]); // Explicit sort of vertices to construct a Configuration object. if (d0 <= d1) { if (d1 <= d2) // d0 <= d1 <= d2 { if (d0 != d1) { if (d1 != d2) { cfg.map = ProjectionMap::PM_111; } else { cfg.map = ProjectionMap::PM_12; } } else // d0 = d1 { if (d1 != d2) { cfg.map = ProjectionMap::PM_21; } else { cfg.map = ProjectionMap::PM_3; } } cfg.index[0] = 0; cfg.index[1] = 1; cfg.index[2] = 2; cfg.min = d0; cfg.max = d2; } else if (d0 <= d2) // d0 <= d2 < d1 { if (d0 != d2) { cfg.map = ProjectionMap::PM_111; cfg.index[0] = 0; cfg.index[1] = 2; cfg.index[2] = 1; } else { cfg.map = ProjectionMap::PM_21; cfg.index[0] = 2; cfg.index[1] = 0; cfg.index[2] = 1; } cfg.min = d0; cfg.max = d1; } else // d2 < d0 <= d1 { if (d0 != d1) { cfg.map = ProjectionMap::PM_111; } else { cfg.map = ProjectionMap::PM_12; } cfg.index[0] = 2; cfg.index[1] = 0; cfg.index[2] = 1; cfg.min = d2; cfg.max = d1; } } else if (d2 <= d1) // d2 <= d1 < d0 { if (d2 != d1) { cfg.map = ProjectionMap::PM_111; cfg.index[0] = 2; cfg.index[1] = 1; cfg.index[2] = 0; } else { cfg.map = ProjectionMap::PM_21; cfg.index[0] = 1; cfg.index[1] = 2; cfg.index[2] = 0; } cfg.min = d2; cfg.max = d0; } else if (d2 <= d0) // d1 < d2 <= d0 { if (d2 != d0) { cfg.map = ProjectionMap::PM_111; } else { cfg.map = ProjectionMap::PM_12; } cfg.index[0] = 1; cfg.index[1] = 2; cfg.index[2] = 0; cfg.min = d1; cfg.max = d0; } else // d1 < d0 < d2 { cfg.map = ProjectionMap::PM_111; cfg.index[0] = 1; cfg.index[1] = 0; cfg.index[2] = 2; cfg.min = d1; cfg.max = d2; } } // This is the constant velocity separating axis test. The cfg0 and // cfg1 inputs are the configurations for the triangles at time 0. // The tcfg0 and tcfg1 are the configurations at contact time. static bool FindOverlap(T const& tMax, T const& speed, Configuration const& cfg0, Configuration const& cfg1, ContactSide& side, Configuration& tcfg0, Configuration& tcfg1, T& tFirst, T& tLast) { T const zero = static_cast<T>(0); if (cfg1.max < cfg0.min) { // The cfg1 interval is on the left of the cfg0 interval. if (speed <= zero) { // The cfg1 interval is moving away from the cfg0 // interval. return false; } // Compute the first time of contact on this axis. T t = (cfg0.min - cfg1.max) / speed; if (t > tFirst) { // Time t is the new maximum first time of contact. tFirst = t; side = ContactSide::CS_LEFT; tcfg0 = cfg0; tcfg1 = cfg1; } if (tFirst > tMax) { // The intersection occurs after the specified maximum // time. return false; } // Compute the last time of contact on this axis. t = (cfg0.max - cfg1.min) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } else if (cfg0.max < cfg1.min) { // The cfg1 interval is on the right of the cfg0 interval. if (speed >= zero) { // The cfg1 interval is moving away from the cfg0 // interval. return false; } // Compute the first time of contact on this axis. T t = (cfg0.max - cfg1.min) / speed; if (t > tFirst) { // Time t is the new maximum first time of contact. tFirst = t; side = ContactSide::CS_RIGHT; tcfg0 = cfg0; tcfg1 = cfg1; } if (tFirst > tMax) { // The intersection occurs after the specified maximum // time. return false; } // Compute the last time of contact on this axis. t = (cfg0.min - cfg1.max) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } else { // The intervals for cfg0 and cfg1 are currently // overlapping. if (speed > zero) { // Compute the last time of contact on this axis. T t = (cfg0.max - cfg1.min) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } else if (speed < zero) { // Compute the last time of contact on this axis. T t = (cfg0.min - cfg1.max) / speed; if (t < tLast) { tLast = t; } if (tFirst > tLast) { // The time interval is invalid, so the objects are // not intersecting. return false; } } } return true; } // A projection wrapper to set up for the separating axis test. static bool FindOverlap(Triangle3<T> const& triangle0, Triangle3<T> const& triangle1, Vector3<T> const& direction, T const& tMax, Vector3<T> const& velocity, ContactSide& side, Configuration& tcfg0, Configuration& tcfg1, T& tFirst, T& tLast) { Configuration cfg0{}, cfg1{}; ScaleProjectOntoLine(triangle0, direction, cfg0); ScaleProjectOntoLine(triangle1, direction, cfg1); T speed = Dot(direction, velocity); return FindOverlap(tMax, speed, cfg0, cfg1, side, tcfg0, tcfg1, tFirst, tLast); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/VertexAttribute.h
.h
1,502
43
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <string> namespace gte { struct VertexAttribute { VertexAttribute(std::string inSemantic = "", void* inSource = nullptr, size_t inStride = 0) : semantic(inSemantic), source(inSource), stride(inStride) { } // The 'semantic' string allows you to query for a specific vertex // attribute and use the 'source' and 'stride' to access the data // of the attribute. For example, you might use the semantics // "position" (px,py,pz), "normal" (nx,ny,nz), "tcoord" (texture // coordinates (u,v)), "dpdu" (derivative of position with respect // to u), or "dpdv" (derivative of position with respect to v) for // mesh vertices. // // The source pointer must be 4-byte aligned. The stride must be // positive and a multiple of 4. The pointer alignment constraint is // guaranteed on 32-bit and 64-bit architectures. The stride constraint // is reasonable given that (usually) geometric attributes are usually // arrays of 'float' or 'double'. std::string semantic; void* source; size_t stride; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContEllipsoid3MinCR.h
.h
10,300
299
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix3x3.h> #include <random> // Compute the minimum-volume ellipsoid, (X-C)^T R D R^T (X-C) = 1, given the // center C and orientation matrix R. The columns of R are the axes of the // ellipsoid. The algorithm computes the diagonal matrix D. The minimum // volume is (4*pi/3)/sqrt(D[0]*D[1]*D[2]), where D = diag(D[0],D[1],D[2]). // The problem is equivalent to maximizing the product D[0]*D[1]*D[2] for a // given C and R, and subject to the constraints // (P[i]-C)^T R D R^T (P[i]-C) <= 1 // for all input points P[i] with 0 <= i < N. Each constraint has the form // A[0]*D[0] + A[1]*D[1] + A[2]*D[2] <= 1 // where A[0] >= 0, A[1] >= 0, and A[2] >= 0. namespace gte { template <typename Real> class ContEllipsoid3MinCR { public: void operator()(int32_t numPoints, Vector3<Real> const* points, Vector3<Real> const& C, Matrix3x3<Real> const& R, Real D[3]) const { // Compute the constraint coefficients, of the form (A[0],A[1]) // for each i. std::vector<Vector3<Real>> A(numPoints); for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - C; // P[i] - C Vector3<Real> prod = diff * R; // R^T*(P[i] - C) = (u,v,w) A[i] = prod * prod; // (u^2, v^2, w^2) } // TODO: Sort the constraints to eliminate redundant ones. It // is clear how to do this in ContEllipse2MinCR. How to do this // in 3D? MaxProduct(A, D); } private: void FindEdgeMax(std::vector<Vector3<Real>>& A, int32_t& plane0, int32_t& plane1, Real D[3]) const { // Compute direction to local maximum point on line of // intersection. Real xDir = A[plane0][1] * A[plane1][2] - A[plane1][1] * A[plane0][2]; Real yDir = A[plane0][2] * A[plane1][0] - A[plane1][2] * A[plane0][0]; Real zDir = A[plane0][0] * A[plane1][1] - A[plane1][0] * A[plane0][1]; // Build quadratic Q'(t) = (d/dt)(x(t)y(t)z(t)) = a0+a1*t+a2*t^2. Real a0 = D[0] * D[1] * zDir + D[0] * D[2] * yDir + D[1] * D[2] * xDir; Real a1 = (Real)2 * (D[2] * xDir * yDir + D[1] * xDir * zDir + D[0] * yDir * zDir); Real a2 = (Real)3 * (xDir * yDir * zDir); // Find root to Q'(t) = 0 corresponding to maximum. Real tFinal; if (a2 != (Real)0) { Real invA2 = (Real)1 / a2; Real discr = a1 * a1 - (Real)4 * a0 * a2; discr = std::sqrt(std::max(discr, (Real)0)); tFinal = (Real)-0.5 * (a1 + discr) * invA2; if (a1 + (Real)2 * a2 * tFinal > (Real)0) { tFinal = (Real)0.5 * (-a1 + discr) * invA2; } } else if (a1 != (Real)0) { tFinal = -a0 / a1; } else if (a0 != (Real)0) { Real fmax = std::numeric_limits<Real>::max(); tFinal = (a0 >= (Real)0 ? fmax : -fmax); } else { return; } if (tFinal < (Real)0) { // Make (xDir,yDir,zDir) point in direction of increase of Q. tFinal = -tFinal; xDir = -xDir; yDir = -yDir; zDir = -zDir; } // Sort remaining planes along line from current point to local // maximum. Real tMax = tFinal; int32_t plane2 = -1; int32_t numPoints = static_cast<int32_t>(A.size()); for (int32_t i = 0; i < numPoints; ++i) { if (i == plane0 || i == plane1) { continue; } Real norDotDir = A[i][0] * xDir + A[i][1] * yDir + A[i][2] * zDir; if (norDotDir <= (Real)0) { continue; } // Theoretically the numerator must be nonnegative since an // invariant in the algorithm is that (x0,y0,z0) is on the // convex hull of the constraints. However, some numerical // error may make this a small negative number. In that case // set tmax = 0 (no change in position). Real numer = (Real)1 - A[i][0] * D[0] - A[i][1] * D[1] - A[i][2] * D[2]; LogAssert(numer >= (Real)0, "Unexpected condition."); Real t = numer / norDotDir; if (0 <= t && t < tMax) { plane2 = i; tMax = t; } } D[0] += tMax * xDir; D[1] += tMax * yDir; D[2] += tMax * zDir; if (tMax == tFinal) { return; } if (tMax > (Real)0) { plane0 = plane2; FindFacetMax(A, plane0, D); return; } // tmax == 0, so return with D[0], D[1], and D[2] unchanged. } void FindFacetMax(std::vector<Vector3<Real>>& A, int32_t& plane0, Real D[3]) const { Real tFinal, xDir, yDir, zDir; if (A[plane0][0] > (Real)0 && A[plane0][1] > (Real)0 && A[plane0][2] > (Real)0) { // Compute local maximum point on plane. Real oneThird = (Real)1 / (Real)3; Real xMax = oneThird / A[plane0][0]; Real yMax = oneThird / A[plane0][1]; Real zMax = oneThird / A[plane0][2]; // Compute direction to local maximum point on plane. tFinal = (Real)1; xDir = xMax - D[0]; yDir = yMax - D[1]; zDir = zMax - D[2]; } else { tFinal = std::numeric_limits<Real>::max(); if (A[plane0][0] > (Real)0) { xDir = (Real)0; } else { xDir = (Real)1; } if (A[plane0][1] > (Real)0) { yDir = (Real)0; } else { yDir = (Real)1; } if (A[plane0][2] > (Real)0) { zDir = (Real)0; } else { zDir = (Real)1; } } // Sort remaining planes along line from current point. Real tMax = tFinal; int32_t plane1 = -1; int32_t numPoints = static_cast<int32_t>(A.size()); for (int32_t i = 0; i < numPoints; ++i) { if (i == plane0) { continue; } Real norDotDir = A[i][0] * xDir + A[i][1] * yDir + A[i][2] * zDir; if (norDotDir <= (Real)0) { continue; } // Theoretically the numerator must be nonnegative because an // invariant in the algorithm is that (x0,y0,z0) is on the // convex hull of the constraints. However, some numerical // error may make this a small negative number. In that case, // set tmax = 0 (no change in position). Real numer = (Real)1 - A[i][0] * D[0] - A[i][1] * D[1] - A[i][2] * D[2]; LogAssert(numer >= (Real)0, "Unexpected condition."); Real t = numer / norDotDir; if (0 <= t && t < tMax) { plane1 = i; tMax = t; } } D[0] += tMax * xDir; D[1] += tMax * yDir; D[2] += tMax * zDir; if (tMax == (Real)1) { return; } if (tMax > (Real)0) { plane0 = plane1; FindFacetMax(A, plane0, D); return; } FindEdgeMax(A, plane0, plane1, D); } void MaxProduct(std::vector<Vector3<Real>>& A, Real D[3]) const { // Maximize x*y*z subject to x >= 0, y >= 0, z >= 0, and // A[i]*x+B[i]*y+C[i]*z <= 1 for 0 <= i < N where A[i] >= 0, // B[i] >= 0, and C[i] >= 0. // Jitter the lines to avoid cases where more than three planes // intersect at the same point. Should also break parallelism // and planes parallel to the coordinate planes. std::mt19937 mte; std::uniform_real_distribution<Real> rnd((Real)0, (Real)1); Real maxJitter = (Real)1e-12; int32_t numPoints = static_cast<int32_t>(A.size()); int32_t i; for (i = 0; i < numPoints; ++i) { A[i][0] += maxJitter * rnd(mte); A[i][1] += maxJitter * rnd(mte); A[i][2] += maxJitter * rnd(mte); } // Sort lines along the z-axis (x = 0 and y = 0). int32_t plane = -1; Real zmax = (Real)0; for (i = 0; i < numPoints; ++i) { if (A[i][2] > zmax) { zmax = A[i][2]; plane = i; } } LogAssert(plane != -1, "Unexpected condition."); // Walk along convex hull searching for maximum. D[0] = (Real)0; D[1] = (Real)0; D[2] = (Real)1 / zmax; FindFacetMax(A, plane, D); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FIQuery.h
.h
1,111
34
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> namespace gte { // Find-intersection queries. template <typename Real, typename Type0, typename Type1> class FIQuery { public: struct Result { // A FIQuery-base class B must define a B::Result struct with // member 'bool intersect'. A FIQuery-derived class D must also // derive a D::Result from B:Result but may have no members. The // member 'intersect' is 'true' iff the primitives intersect. The // operator() is const for conceptual constness, but derived // classes can use internal data to support the queries and tag // that data with the mutable modifier. }; Result operator()(Type0 const& primitive0, Type1 const& primitive1) const; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay3AlignedBox3.h
.h
5,379
153
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine3AlignedBox3.h> #include <Mathematics/Ray.h> // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the six // faces of the box. The find-intersection queries use Liang-Barsky // clipping. The queries consider the box to be a solid. The algorithms // are described in // https://www.geometrictools.com/Documentation/IntersectionLineBox.pdf namespace gte { template <typename T> class TIQuery<T, Ray3<T>, AlignedBox3<T>> : public TIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public TIQuery<T, Line3<T>, AlignedBox3<T>>::Result { Result() : TIQuery<T, Line3<T>, AlignedBox3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray3<T> const& ray, AlignedBox3<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly axis[d] = Vector3<T>::Unit(d). Vector3<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the ray to the aligned-box coordinate system. Vector3<T> rayOrigin = ray.origin - boxCenter; Result result{}; DoQuery(rayOrigin, ray.direction, boxExtent, result); return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& rayOrigin, Vector3<T> const& rayDirection, Vector3<T> const& boxExtent, Result& result) { T const zero = static_cast<T>(0); for (int32_t i = 0; i < 3; ++i) { if (std::fabs(rayOrigin[i]) > boxExtent[i] && rayOrigin[i] * rayDirection[i] >= zero) { result.intersect = false; return; } } TIQuery<T, Line3<T>, AlignedBox3<T>>::DoQuery( rayOrigin, rayDirection, boxExtent, result); } }; template <typename T> class FIQuery<T, Ray3<T>, AlignedBox3<T>> : public FIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public FIQuery<T, Line3<T>, AlignedBox3<T>>::Result { Result() : FIQuery<T, Line3<T>, AlignedBox3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray3<T> const& ray, AlignedBox3<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly axis[d] = Vector3<T>::Unit(d). Vector3<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the ray to the aligned-box coordinate system. Vector3<T> rayOrigin = ray.origin - boxCenter; Result result{}; DoQuery(rayOrigin, ray.direction, boxExtent, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& rayOrigin, Vector3<T> const& rayDirection, Vector3<T> const& boxExtent, Result& result) { FIQuery<T, Line3<T>, AlignedBox3<T>>::DoQuery( rayOrigin, rayDirection, boxExtent, result); if (result.intersect) { // The line containing the ray intersects the box; the // t-interval is [t0,t1]. The ray intersects the box as long // as [t0,t1] overlaps the ray t-interval (0,+infinity). FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery; auto iiResult = iiQuery(result.parameter, static_cast<T>(0), true); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { // The line containing the ray does not intersect the box. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine3Triangle3.h
.h
6,635
157
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLineSegment.h> #include <Mathematics/Triangle.h> #include <Mathematics/Vector3.h> // Compute the distance between a line and a solid triangle in 3D. // // The line is P + t * D, where D is not required to be unit length. // // The triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The closest point on the line is stored in closest[0] with parameter t. The // closest point on the triangle is closest[1] with barycentric coordinates // (b[0],b[1],b[2]). When there are infinitely many choices for the pair of // closest points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Line3<T>, Triangle3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter(static_cast<T>(0)), barycentric{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; T parameter; std::array<T, 3> barycentric; std::array<Vector3<T>, 2> closest; }; Result operator()(Line3<T> const& line, Triangle3<T> const& triangle) { // The line points are X = P + t * D and the triangle points // are Y = b[0] * V[0] + b[1] * V[1] + b[2] * V[2], where the // barycentric coordinates satisfy b[i] in [0,1] and // b[0] + b[1] + b[2 = 1. Define the triangle edge directions by // E[1] = V[1] - V[0] and E[2] = V[2] - V[0]; then // Y = V[0] + b1 * E[1] + b2 * E[2]. If Y is specified the // barycentric coordinates are the solution to // // +- -+ +- -+ +- -+ // | Dot(E1, E1) Dot(E1, E2) | | b[1] | = | Dot(E1, Y - V[0]) | // | Dot(E1, E2) Dot(E2, E2) | | b[2] | | Dot(E2, Y - V[0]) | // +- -+ +- -+ +- -+ // // and b[0] = 1 - b[1] - b[2]. Result result{}; // Test whether the line intersects triangle. If so, the squared // distance is zero. The normal of the plane of the triangle does // not have to be normalized to unit length. T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> E1 = triangle.v[1] - triangle.v[0]; Vector3<T> E2 = triangle.v[2] - triangle.v[0]; Vector3<T> N = Cross(E1, E2); T NdD = Dot(N, line.direction); if (std::fabs(NdD) > zero) { // The line and triangle are not parallel, so the line // intersects the plane of the triangle at a point Y. // Determine whether Y is contained by the triangle. Vector3<T> PmV0 = line.origin - triangle.v[0]; T NdDiff = Dot(N, PmV0); T tIntersect = -NdDiff / NdD; Vector3<T> Y = line.origin + tIntersect * line.direction; Vector3<T> YmV0 = Y - triangle.v[0]; // Compute the barycentric coordinates of the intersection. T E1dE1 = Dot(E1, E1); T E1dE2 = Dot(E1, E2); T E2dE2 = Dot(E2, E2); T E1dYmV0 = Dot(E1, YmV0); T E2dYmV0 = Dot(E2, YmV0); T det = E1dE1 * E2dE2 - E1dE2 * E1dE2; T b1 = (E2dE2 * E1dYmV0 - E1dE2 * E2dYmV0) / det; T b2 = (E1dE1 * E2dYmV0 - E1dE2 * E1dYmV0) / det; T b0 = one - b1 - b2; if (b0 >= zero && b1 >= zero && b2 >= zero) { // The point Y is contained by the triangle. result.sqrDistance = zero; result.distance = zero; result.parameter = tIntersect; result.barycentric[0] = b0; result.barycentric[1] = b1; result.barycentric[2] = b2; result.closest[0] = Y; result.closest[1] = Y; return result; } } // Either (1) the line is not parallel to the triangle and the // point of intersection of the line and the plane of the triangle // is outside the triangle or (2) the line and triangle are // parallel. Regardless, the closest point on the triangle is on // an edge of the triangle. Compare the line to all three edges // of the triangle. To allow for arbitrary precision arithmetic, // the initial distance and sqrDistance are initialized to a // negative number rather than a floating-point maximum value. // Tracking the minimum requires a small amount of extra logic. T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; using LSQuery = DCPQuery<T, Line3<T>, Segment3<T>>; LSQuery lsQuery{}; typename LSQuery::Result lsResult{}; Segment3<T> segment{}; for (size_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { segment.p[0] = triangle.v[i0]; segment.p[1] = triangle.v[i1]; lsResult = lsQuery(line, segment); if (result.sqrDistance == invalid || lsResult.sqrDistance < result.sqrDistance) { result.sqrDistance = lsResult.sqrDistance; result.distance = lsResult.distance; result.parameter = lsResult.parameter[0]; result.barycentric[i0] = one - lsResult.parameter[1]; result.barycentric[i1] = lsResult.parameter[1]; result.barycentric[i2] = zero; result.closest = lsResult.closest; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrAlignedBox3Cone3.h
.h
36,576
1,017
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/AlignedBox.h> #include <Mathematics/Cone.h> #include <Mathematics/IntrRay3AlignedBox3.h> #include <Mathematics/IntrSegment3AlignedBox3.h> // Test for intersection of a box and a cone. The cone can be infinite // 0 <= minHeight < maxHeight = std::numeric_limits<T>::max() // or finite (cone frustum) // 0 <= minHeight < maxHeight < std::numeric_limits<T>::max(). // The algorithm is described in // https://www.geometrictools.com/Documentation/IntersectionBoxCone.pdf // and reports an intersection only when the intersection set has positive // volume. For example, let the box be outside the cone. If the box is // below the minHeight plane at the cone vertex and just touches the cone // vertex, no intersection is reported. If the box is above the maxHeight // plane and just touches the disk capping the cone, either at a single // point, a line segment of points or a polygon of points, no intersection // is reported. // TODO: These queries were designed when an infinite cone was defined // by choosing maxHeight of std::numeric_limits<T>::max(). The Cone<N,T> // class has been redesigned not to use std::numeric_limits to allow for // arithmetic systems that do not have representations for infinities // (such as BSNumber and BSRational). The intersection queries need to be // rewritten for the new class design. FOR NOW, the queries will work with // float/double when you create a cone using the cone-frustum constructor // Cone(ray, angle, minHeight, std::numeric_limits<T>::max()). namespace gte { template <typename T> class TIQuery<T, AlignedBox3<T>, Cone3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; TIQuery() : mVertices{}, mEdges{}, mFaces{}, mProjectionMin{}, mProjectionMax{}, mNumCandidateEdges(0), mCandidateEdges{}, mAdjacencyMatrix{}, mConfiguration{} { // An edge is { v0, v1 }, where v0 and v1 are relative to mVertices // with v0 < v1. mEdges[0] = { 0, 1 }; mEdges[1] = { 1, 3 }; mEdges[2] = { 2, 3 }; mEdges[3] = { 0, 2 }; mEdges[4] = { 4, 5 }; mEdges[5] = { 5, 7 }; mEdges[6] = { 6, 7 }; mEdges[7] = { 4, 6 }; mEdges[8] = { 0, 4 }; mEdges[9] = { 1, 5 }; mEdges[10] = { 3, 7 }; mEdges[11] = { 2, 6 }; // A face is { { v0, v1, v2, v3 }, { e0, e1, e2, e3 } }, where // { v0, v1, v2, v3 } are relative to mVertices with // v0 = min(v0,v1,v2,v3) and where { e0, e1, e2, e3 } are relative // to mEdges. For example, mFaces[0] has vertices { 0, 4, 6, 2 }. // The edge { 0, 4 } is mEdges[8], the edge { 4, 6 } is mEdges[7], // the edge { 6, 2 } is mEdges[11] and the edge { 2, 0 } is // mEdges[3]; thus, the edge indices are { 8, 7, 11, 3 }. mFaces[0] = { { 0, 4, 6, 2 }, { 8, 7, 11, 3 } }; mFaces[1] = { { 1, 3, 7, 5 }, { 1, 10, 5, 9 } }; mFaces[2] = { { 0, 1, 5, 4 }, { 0, 9, 4, 8 } }; mFaces[3] = { { 2, 6, 7, 3 }, { 11, 6, 10, 2 } }; mFaces[4] = { { 0, 2, 3, 1 }, { 3, 2, 1, 0 } }; mFaces[5] = { { 4, 5, 7, 6 }, { 4, 5, 6, 7 } }; // Clear the edges. for (size_t r = 0; r < MAX_CANDIDATE_EDGES; ++r) { for (size_t c = 0; c < 2; ++c) { mCandidateEdges[r][c] = 0; } } for (size_t r = 0; r < MAX_VERTICES; ++r) { for (size_t c = 0; c < MAX_VERTICES; ++c) { mAdjacencyMatrix[r][c] = 0; } } mConfiguration[0] = &TIQuery::NNNN_0; mConfiguration[1] = &TIQuery::NNNZ_1; mConfiguration[2] = &TIQuery::NNNP_2; mConfiguration[3] = &TIQuery::NNZN_3; mConfiguration[4] = &TIQuery::NNZZ_4; mConfiguration[5] = &TIQuery::NNZP_5; mConfiguration[6] = &TIQuery::NNPN_6; mConfiguration[7] = &TIQuery::NNPZ_7; mConfiguration[8] = &TIQuery::NNPP_8; mConfiguration[9] = &TIQuery::NZNN_9; mConfiguration[10] = &TIQuery::NZNZ_10; mConfiguration[11] = &TIQuery::NZNP_11; mConfiguration[12] = &TIQuery::NZZN_12; mConfiguration[13] = &TIQuery::NZZZ_13; mConfiguration[14] = &TIQuery::NZZP_14; mConfiguration[15] = &TIQuery::NZPN_15; mConfiguration[16] = &TIQuery::NZPZ_16; mConfiguration[17] = &TIQuery::NZPP_17; mConfiguration[18] = &TIQuery::NPNN_18; mConfiguration[19] = &TIQuery::NPNZ_19; mConfiguration[20] = &TIQuery::NPNP_20; mConfiguration[21] = &TIQuery::NPZN_21; mConfiguration[22] = &TIQuery::NPZZ_22; mConfiguration[23] = &TIQuery::NPZP_23; mConfiguration[24] = &TIQuery::NPPN_24; mConfiguration[25] = &TIQuery::NPPZ_25; mConfiguration[26] = &TIQuery::NPPP_26; mConfiguration[27] = &TIQuery::ZNNN_27; mConfiguration[28] = &TIQuery::ZNNZ_28; mConfiguration[29] = &TIQuery::ZNNP_29; mConfiguration[30] = &TIQuery::ZNZN_30; mConfiguration[31] = &TIQuery::ZNZZ_31; mConfiguration[32] = &TIQuery::ZNZP_32; mConfiguration[33] = &TIQuery::ZNPN_33; mConfiguration[34] = &TIQuery::ZNPZ_34; mConfiguration[35] = &TIQuery::ZNPP_35; mConfiguration[36] = &TIQuery::ZZNN_36; mConfiguration[37] = &TIQuery::ZZNZ_37; mConfiguration[38] = &TIQuery::ZZNP_38; mConfiguration[39] = &TIQuery::ZZZN_39; mConfiguration[40] = &TIQuery::ZZZZ_40; mConfiguration[41] = &TIQuery::ZZZP_41; mConfiguration[42] = &TIQuery::ZZPN_42; mConfiguration[43] = &TIQuery::ZZPZ_43; mConfiguration[44] = &TIQuery::ZZPP_44; mConfiguration[45] = &TIQuery::ZPNN_45; mConfiguration[46] = &TIQuery::ZPNZ_46; mConfiguration[47] = &TIQuery::ZPNP_47; mConfiguration[48] = &TIQuery::ZPZN_48; mConfiguration[49] = &TIQuery::ZPZZ_49; mConfiguration[50] = &TIQuery::ZPZP_50; mConfiguration[51] = &TIQuery::ZPPN_51; mConfiguration[52] = &TIQuery::ZPPZ_52; mConfiguration[53] = &TIQuery::ZPPP_53; mConfiguration[54] = &TIQuery::PNNN_54; mConfiguration[55] = &TIQuery::PNNZ_55; mConfiguration[56] = &TIQuery::PNNP_56; mConfiguration[57] = &TIQuery::PNZN_57; mConfiguration[58] = &TIQuery::PNZZ_58; mConfiguration[59] = &TIQuery::PNZP_59; mConfiguration[60] = &TIQuery::PNPN_60; mConfiguration[61] = &TIQuery::PNPZ_61; mConfiguration[62] = &TIQuery::PNPP_62; mConfiguration[63] = &TIQuery::PZNN_63; mConfiguration[64] = &TIQuery::PZNZ_64; mConfiguration[65] = &TIQuery::PZNP_65; mConfiguration[66] = &TIQuery::PZZN_66; mConfiguration[67] = &TIQuery::PZZZ_67; mConfiguration[68] = &TIQuery::PZZP_68; mConfiguration[69] = &TIQuery::PZPN_69; mConfiguration[70] = &TIQuery::PZPZ_70; mConfiguration[71] = &TIQuery::PZPP_71; mConfiguration[72] = &TIQuery::PPNN_72; mConfiguration[73] = &TIQuery::PPNZ_73; mConfiguration[74] = &TIQuery::PPNP_74; mConfiguration[75] = &TIQuery::PPZN_75; mConfiguration[76] = &TIQuery::PPZZ_76; mConfiguration[77] = &TIQuery::PPZP_77; mConfiguration[78] = &TIQuery::PPPN_78; mConfiguration[79] = &TIQuery::PPPZ_79; mConfiguration[80] = &TIQuery::PPPP_80; } Result operator()(AlignedBox3<T> const& box, Cone3<T> const& cone) { Result result{}; // Quick-rejectance test. Determine whether the box is outside // the slab bounded by the minimum and maximum height planes. // When outside the slab, the box vertices are not required by the // cone-box intersection query, so the vertices are not yet // computed. T boxMinHeight = (T)0, boxMaxHeight = (T)0; ComputeBoxHeightInterval(box, cone, boxMinHeight, boxMaxHeight); // TODO: See the comments at the beginning of this file. T coneMaxHeight = (cone.IsFinite() ? cone.GetMaxHeight() : std::numeric_limits<T>::max()); if (boxMaxHeight <= cone.GetMinHeight() || boxMinHeight >= coneMaxHeight) { // There is no volumetric overlap of the box and the cone. The // box is clipped entirely. result.intersect = false; return result; } // Quick-acceptance test. Determine whether the cone axis // intersects the box. if (ConeAxisIntersectsBox(box, cone)) { result.intersect = true; return result; } // Test for box fully inside the slab. When inside the slab, the // box vertices are required by the cone-box intersection query, // so they are computed here; they are also required in the // remaining cases. Also when inside the slab, the box edges are // the candidates, so they are copied to mCandidateEdges. if (BoxFullyInConeSlab(box, boxMinHeight, boxMaxHeight, cone)) { result.intersect = CandidatesHavePointInsideCone(cone); return result; } // Clear the candidates array and adjacency matrix. ClearCandidates(); // The box intersects at least one plane. Compute the box-plane // edge-interior intersection points. Insert the box subedges into // the array of candidate edges. ComputeCandidatesOnBoxEdges(cone); // Insert any relevant box face-interior clipped edges into the array // of candidate edges. ComputeCandidatesOnBoxFaces(); result.intersect = CandidatesHavePointInsideCone(cone); return result; } protected: // The constants here are described in the comments below. static size_t constexpr NUM_BOX_VERTICES = 8; static size_t constexpr NUM_BOX_EDGES = 12; static size_t constexpr NUM_BOX_FACES = 6; static size_t constexpr MAX_VERTICES = 32; static size_t constexpr VERTEX_MIN_BASE = 8; static size_t constexpr VERTEX_MAX_BASE = 20; static size_t constexpr MAX_CANDIDATE_EDGES = 496; static size_t constexpr NUM_CONFIGURATIONS = 81; // The box topology is that of a cube whose vertices have components // in {0,1}. The cube vertices are indexed by // 0: (0,0,0), 1: (1,0,0), 2: (1,1,0), 3: (0,1,0) // 4: (0,0,1), 5: (1,0,1), 6: (1,1,1), 7: (0,1,1) // The first 8 vertices are the box corners, the next 12 vertices are // reserved for hmin-edge points and the final 12 vertices are reserved // for the hmax-edge points. The conservative upper bound of the number // of vertices is 8 + 12 + 12 = 32. std::array<Vector3<T>, MAX_VERTICES> mVertices; // The box has 12 edges stored in mEdges. An edge is mEdges[i] = // { v0, v1 }, where the indices v0 and v1 are relative to mVertices // with v0 < v1. std::array<std::array<size_t, 2>, NUM_BOX_EDGES> mEdges; // The box has 6 faces stored in mFaces. A face is mFaces[i] = // { { v0, v1, v2, v3 }, { e0, e1, e2, e3 } }, where the face corner // vertices are { v0, v1, v2, v3 }. These indices are relative to // mVertices. The indices { e0, e1, e2, e3 } are relative to mEdges. // The index e0 refers to edge { v0, v1 }, the index e1 refers to edge // { v1, v2 }, the index e2 refers to edge { v2, v3 } and the index e3 // refers to edge { v3, v0 }. The ordering of vertices for the faces // is/ counterclockwise when viewed from outside the box. The choice // of initial vertex affects how you implement the graph data // structure. In this implementation, the initial vertex has minimum // index for all vertices of that face. The faces themselves are // listed as -x face, +x face, -y face, +y face, -z face and +z face. struct Face { std::array<size_t, 4> v, e; }; std::array<Face, NUM_BOX_FACES> mFaces; // Store the signed distances from the minimum and maximum height // planes for the cone to the projection of the box vertices onto the // cone axis. std::array<T, NUM_BOX_VERTICES> mProjectionMin, mProjectionMax; // The mCandidateEdges array stores the edges of the clipped box that // are candidates for containing the optimizing point. The maximum // number of candidate edges is 1 + 2 + ... + 31 = 496, which is a // conservative bound because not all pairs of vertices form edges on // box faces. The candidate edges are stored as (v0,v1) with v0 < v1. // The implementation is designed so that during a single query, the // number of candidate edges can only grow. size_t mNumCandidateEdges; std::array<std::array<size_t, 2>, MAX_CANDIDATE_EDGES> mCandidateEdges; // The mAdjancencyMatrix is a simple representation of edges in the // graph G = (V,E) that represents the (wireframe) clipped box. An // edge (r,c) does not exist when mAdjancencyMatrix[r][c] = 0. If an // edge (r,c) does exist, it is appended to mCandidateEdges at index k // and the adjacency matrix is set to mAdjacencyMatrix[r][c] = 1. // This allows for a fast edge-in-graph test and a fast and efficient // clear of mCandidateEdges and mAdjacencyMatrix. std::array<std::array<size_t, MAX_VERTICES>, MAX_VERTICES> mAdjacencyMatrix; typedef void (TIQuery::* ConfigurationFunction)(size_t, Face const&); std::array<ConfigurationFunction, NUM_CONFIGURATIONS> mConfiguration; static void ComputeBoxHeightInterval(AlignedBox3<T> const& box, Cone3<T> const& cone, T& boxMinHeight, T& boxMaxHeight) { Vector3<T> C, e; box.GetCenteredForm(C, e); Vector3<T> const& V = cone.ray.origin; Vector3<T> const& U = cone.ray.direction; Vector3<T> CmV = C - V; T DdCmV = Dot(U, CmV); T radius = e[0] * std::abs(U[0]) + e[1] * std::abs(U[1]) + e[2] * std::abs(U[2]); boxMinHeight = DdCmV - radius; boxMaxHeight = DdCmV + radius; } static bool ConeAxisIntersectsBox(AlignedBox3<T> const& box, Cone3<T> const& cone) { if (cone.IsFinite()) { Segment3<T> segment; segment.p[0] = cone.ray.origin + cone.GetMinHeight() * cone.ray.direction; segment.p[1] = cone.ray.origin + cone.GetMaxHeight() * cone.ray.direction; auto sbResult = TIQuery<T, Segment3<T>, AlignedBox3<T>>()(segment, box); if (sbResult.intersect) { return true; } } else { Ray3<T> ray; ray.origin = cone.ray.origin + cone.GetMinHeight() * cone.ray.direction; ray.direction = cone.ray.direction; auto rbResult = TIQuery<T, Ray3<T>, AlignedBox3<T>>()(ray, box); if (rbResult.intersect) { return true; } } return false; } bool BoxFullyInConeSlab(AlignedBox3<T> const& box, T boxMinHeight, T boxMaxHeight, Cone3<T> const& cone) { // Compute the box vertices relative to cone vertex as origin. mVertices[0] = { box.min[0], box.min[1], box.min[2] }; mVertices[1] = { box.max[0], box.min[1], box.min[2] }; mVertices[2] = { box.min[0], box.max[1], box.min[2] }; mVertices[3] = { box.max[0], box.max[1], box.min[2] }; mVertices[4] = { box.min[0], box.min[1], box.max[2] }; mVertices[5] = { box.max[0], box.min[1], box.max[2] }; mVertices[6] = { box.min[0], box.max[1], box.max[2] }; mVertices[7] = { box.max[0], box.max[1], box.max[2] }; for (size_t i = 0; i < NUM_BOX_VERTICES; ++i) { mVertices[i] -= cone.ray.origin; } T coneMaxHeight = (cone.IsFinite() ? cone.GetMaxHeight() : std::numeric_limits<T>::max()); if (cone.GetMinHeight() <= boxMinHeight && boxMaxHeight <= coneMaxHeight) { // The box is fully inside, so no clipping is necessary. std::copy(mEdges.begin(), mEdges.end(), mCandidateEdges.begin()); mNumCandidateEdges = 12; return true; } return false; } static bool HasPointInsideCone(Vector3<T> const& P0, Vector3<T> const& P1, Cone3<T> const& cone) { // Define F(X) = Dot(U,X - V)/|X - V|, where U is the unit-length // cone axis direction and V is the cone vertex. The incoming // points P0 and P1 are relative to V; that is, the original // points are X0 = P0 + V and X1 = P1 + V. The segment <P0,P1> // and cone intersect when a segment point X is inside the cone; // that is, when F(X) > cosAngle. The comparison is converted to // an equivalent one that does not involve divisions in order to // avoid a division by zero if a vertex or edge contain (0,0,0). // The function is G(X) = Dot(U,X-V) - cosAngle*Length(X-V). Vector3<T> const& U = cone.ray.direction; // Test whether P0 or P1 is inside the cone. T g = Dot(U, P0) - cone.cosAngle * Length(P0); if (g > (T)0) { // X0 = P0 + V is inside the cone. return true; } g = Dot(U, P1) - cone.cosAngle * Length(P1); if (g > (T)0) { // X1 = P1 + V is inside the cone. return true; } // Test whether an interior segment point is inside the cone. Vector3<T> E = P1 - P0; Vector3<T> crossP0U = Cross(P0, U); Vector3<T> crossP0E = Cross(P0, E); T dphi0 = Dot(crossP0E, crossP0U); if (dphi0 > (T)0) { Vector3<T> crossP1U = Cross(P1, U); T dphi1 = Dot(crossP0E, crossP1U); if (dphi1 < (T)0) { T t = dphi0 / (dphi0 - dphi1); Vector3<T> PMax = P0 + t * E; g = Dot(U, PMax) - cone.cosAngle * Length(PMax); if (g > (T)0) { // The edge point XMax = Pmax + V is inside the cone. return true; } } } return false; } bool CandidatesHavePointInsideCone(Cone3<T> const& cone) const { for (size_t i = 0; i < mNumCandidateEdges; ++i) { auto const& edge = mCandidateEdges[i]; Vector3<T> const& P0 = mVertices[edge[0]]; Vector3<T> const& P1 = mVertices[edge[1]]; if (HasPointInsideCone(P0, P1, cone)) { return true; } } return false; } void ComputeCandidatesOnBoxEdges(Cone3<T> const& cone) { for (size_t i = 0; i < NUM_BOX_VERTICES; ++i) { T h = Dot(cone.ray.direction, mVertices[i]); T coneMaxHeight = (cone.IsFinite() ? cone.GetMaxHeight() : std::numeric_limits<T>::max()); mProjectionMin[i] = cone.GetMinHeight() - h; mProjectionMax[i] = h - coneMaxHeight; } size_t v0 = VERTEX_MIN_BASE, v1 = VERTEX_MAX_BASE; for (size_t i = 0; i < NUM_BOX_EDGES; ++i, ++v0, ++v1) { auto const& edge = mEdges[i]; // In the next blocks, the sign comparisons can be expressed // instead as "s0 * s1 < 0". The multiplication could lead to // floating-point underflow where the product becomes 0, so I // avoid that approach. // Process the hmin-plane. T p0Min = mProjectionMin[edge[0]]; T p1Min = mProjectionMin[edge[1]]; bool clipMin = (p0Min < (T)0 && p1Min >(T)0) || (p0Min > (T)0 && p1Min < (T)0); if (clipMin) { mVertices[v0] = (p1Min * mVertices[edge[0]] - p0Min * mVertices[edge[1]]) / (p1Min - p0Min); } // Process the hmax-plane. T p0Max = mProjectionMax[edge[0]]; T p1Max = mProjectionMax[edge[1]]; bool clipMax = (p0Max < (T)0 && p1Max >(T)0) || (p0Max > (T)0 && p1Max < (T)0); if (clipMax) { mVertices[v1] = (p1Max * mVertices[edge[0]] - p0Max * mVertices[edge[1]]) / (p1Max - p0Max); } // Get the candidate edges that are contained by the box edges. if (clipMin) { if (clipMax) { InsertEdge(v0, v1); } else { if (p0Min < (T)0) { InsertEdge(edge[0], v0); } else // p1Min < 0 { InsertEdge(edge[1], v0); } } } else if (clipMax) { if (p0Max < (T)0) { InsertEdge(edge[0], v1); } else // p1Max < 0 { InsertEdge(edge[1], v1); } } else { // No clipping has occurred. If the edge is inside the box, // it is a candidate edge. To be inside the box, the p*min // and p*max values must be nonpositive. if (p0Min <= (T)0 && p1Min <= (T)0 && p0Max <= (T)0 && p1Max <= (T)0) { InsertEdge(edge[0], edge[1]); } } } } void ComputeCandidatesOnBoxFaces() { T p0, p1, p2, p3; size_t b0, b1, b2, b3, index; for (size_t i = 0; i < NUM_BOX_FACES; ++i) { auto const& face = mFaces[i]; // Process the hmin-plane. p0 = mProjectionMin[face.v[0]]; p1 = mProjectionMin[face.v[1]]; p2 = mProjectionMin[face.v[2]]; p3 = mProjectionMin[face.v[3]]; b0 = (p0 < (T)0 ? 0 : (p0 > (T)0 ? 2 : 1)); b1 = (p1 < (T)0 ? 0 : (p1 > (T)0 ? 2 : 1)); b2 = (p2 < (T)0 ? 0 : (p2 > (T)0 ? 2 : 1)); b3 = (p3 < (T)0 ? 0 : (p3 > (T)0 ? 2 : 1)); index = b3 + 3 * (b2 + 3 * (b1 + 3 * b0)); (this->*mConfiguration[index])(VERTEX_MIN_BASE, face); // Process the hmax-plane. p0 = mProjectionMax[face.v[0]]; p1 = mProjectionMax[face.v[1]]; p2 = mProjectionMax[face.v[2]]; p3 = mProjectionMax[face.v[3]]; b0 = (p0 < (T)0 ? 0 : (p0 > (T)0 ? 2 : 1)); b1 = (p1 < (T)0 ? 0 : (p1 > (T)0 ? 2 : 1)); b2 = (p2 < (T)0 ? 0 : (p2 > (T)0 ? 2 : 1)); b3 = (p3 < (T)0 ? 0 : (p3 > (T)0 ? 2 : 1)); index = b3 + 3 * (b2 + 3 * (b1 + 3 * b0)); (this->*mConfiguration[index])(VERTEX_MAX_BASE, face); } } void ClearCandidates() { for (size_t i = 0; i < mNumCandidateEdges; ++i) { auto const& edge = mCandidateEdges[i]; mAdjacencyMatrix[edge[0]][edge[1]] = 0; mAdjacencyMatrix[edge[1]][edge[0]] = 0; } mNumCandidateEdges = 0; } void InsertEdge(size_t v0, size_t v1) { if (mAdjacencyMatrix[v0][v1] == 0) { mAdjacencyMatrix[v0][v1] = 1; mAdjacencyMatrix[v1][v0] = 1; mCandidateEdges[mNumCandidateEdges] = { v0, v1 }; ++mNumCandidateEdges; } } // The 81 possible configurations for a box face. The N stands for a // '-', the Z stands for '0' and the P stands for '+'. These are // listed in the order that maps to the array mConfiguration. Thus, // NNNN maps to mConfiguration[0], NNNZ maps to mConfiguration[1], and // so on. void NNNN_0(size_t, Face const&) { } void NNNZ_1(size_t, Face const&) { } void NNNP_2(size_t base, Face const& face) { InsertEdge(base + face.e[2], base + face.e[3]); } void NNZN_3(size_t, Face const&) { } void NNZZ_4(size_t, Face const&) { } void NNZP_5(size_t base, Face const& face) { InsertEdge(face.v[2], base + face.e[3]); } void NNPN_6(size_t base, Face const& face) { InsertEdge(base + face.e[1], base + face.e[2]); } void NNPZ_7(size_t base, Face const& face) { InsertEdge(base + face.e[1], face.v[3]); } void NNPP_8(size_t base, Face const& face) { InsertEdge(base + face.e[1], base + face.e[3]); } void NZNN_9(size_t, Face const&) { } void NZNZ_10(size_t, Face const&) { } void NZNP_11(size_t base, Face const& face) { InsertEdge(base + face.e[2], face.v[3]); InsertEdge(base + face.e[3], face.v[3]); } void NZZN_12(size_t, Face const&) { } void NZZZ_13(size_t, Face const&) { } void NZZP_14(size_t base, Face const& face) { InsertEdge(face.v[2], face.v[3]); InsertEdge(base + face.e[3], face.v[3]); } void NZPN_15(size_t base, Face const& face) { InsertEdge(base + face.e[2], face.v[1]); } void NZPZ_16(size_t, Face const& face) { InsertEdge(face.v[1], face.v[3]); } void NZPP_17(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[1]); } void NPNN_18(size_t base, Face const& face) { InsertEdge(base + face.e[0], base + face.e[1]); } void NPNZ_19(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[1]); InsertEdge(base + face.e[1], face.v[1]); } void NPNP_20(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[1]); InsertEdge(base + face.e[1], face.v[1]); InsertEdge(base + face.e[2], face.v[3]); InsertEdge(base + face.e[3], face.v[3]); } void NPZN_21(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[2]); } void NPZZ_22(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[1]); InsertEdge(face.v[1], face.v[2]); } void NPZP_23(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[1]); InsertEdge(face.v[1], face.v[2]); InsertEdge(base + face.e[3], face.v[2]); InsertEdge(face.v[2], face.v[3]); } void NPPN_24(size_t base, Face const& face) { InsertEdge(base + face.e[0], base + face.e[2]); } void NPPZ_25(size_t base, Face const& face) { InsertEdge(base + face.e[0], face.v[3]); } void NPPP_26(size_t base, Face const& face) { InsertEdge(base + face.e[0], base + face.e[3]); } void ZNNN_27(size_t, Face const&) { } void ZNNZ_28(size_t, Face const&) { } void ZNNP_29(size_t base, Face const& face) { InsertEdge(base + face.e[2], face.v[0]); } void ZNZN_30(size_t, Face const&) { } void ZNZZ_31(size_t, Face const&) { } void ZNZP_32(size_t, Face const& face) { InsertEdge(face.v[0], face.v[2]); } void ZNPN_33(size_t base, Face const& face) { InsertEdge(base + face.e[1], face.v[2]); InsertEdge(base + face.e[2], face.v[2]); } void ZNPZ_34(size_t base, Face const& face) { InsertEdge(base + face.e[1], face.v[2]); InsertEdge(face.v[2], face.v[3]); } void ZNPP_35(size_t base, Face const& face) { InsertEdge(face.v[0], base + face.e[1]); } void ZZNN_36(size_t, Face const&) { } void ZZNZ_37(size_t, Face const&) { } void ZZNP_38(size_t base, Face const& face) { InsertEdge(face.v[0], face.v[3]); InsertEdge(face.v[3], base + face.e[2]); } void ZZZN_39(size_t, Face const&) { } void ZZZZ_40(size_t, Face const&) { } void ZZZP_41(size_t, Face const& face) { InsertEdge(face.v[0], face.v[3]); InsertEdge(face.v[3], face.v[2]); } void ZZPN_42(size_t base, Face const& face) { InsertEdge(face.v[1], face.v[2]); InsertEdge(face.v[2], base + face.e[2]); } void ZZPZ_43(size_t, Face const& face) { InsertEdge(face.v[1], face.v[2]); InsertEdge(face.v[2], face.v[3]); } void ZZPP_44(size_t, Face const&) { } void ZPNN_45(size_t base, Face const& face) { InsertEdge(face.v[0], base + face.e[1]); } void ZPNZ_46(size_t base, Face const& face) { InsertEdge(face.v[0], face.v[1]); InsertEdge(face.v[1], base + face.e[1]); } void ZPNP_47(size_t base, Face const& face) { InsertEdge(face.v[0], face.v[1]); InsertEdge(face.v[1], base + face.e[1]); InsertEdge(base + face.e[2], face.v[3]); InsertEdge(face.v[3], face.v[0]); } void ZPZN_48(size_t, Face const& face) { InsertEdge(face.v[0], face.v[2]); } void ZPZZ_49(size_t, Face const& face) { InsertEdge(face.v[0], face.v[1]); InsertEdge(face.v[1], face.v[2]); } void ZPZP_50(size_t, Face const&) { } void ZPPN_51(size_t base, Face const& face) { InsertEdge(face.v[0], base + face.e[2]); } void ZPPZ_52(size_t, Face const&) { } void ZPPP_53(size_t, Face const&) { } void PNNN_54(size_t base, Face const& face) { InsertEdge(base + face.e[3], base + face.e[0]); } void PNNZ_55(size_t base, Face const& face) { InsertEdge(face.v[3], base + face.e[0]); } void PNNP_56(size_t base, Face const& face) { InsertEdge(base + face.e[2], base + face.e[0]); } void PNZN_57(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[0]); InsertEdge(face.v[0], base + face.e[0]); } void PNZZ_58(size_t base, Face const& face) { InsertEdge(face.v[3], face.v[0]); InsertEdge(face.v[0], base + face.e[0]); } void PNZP_59(size_t base, Face const& face) { InsertEdge(face.v[2], base + face.e[0]); } void PNPN_60(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[0]); InsertEdge(face.v[0], base + face.e[0]); InsertEdge(base + face.e[1], face.v[2]); InsertEdge(face.v[2], base + face.e[2]); } void PNPZ_61(size_t base, Face const& face) { InsertEdge(face.v[3], face.v[0]); InsertEdge(face.v[0], base + face.e[0]); InsertEdge(base + face.e[1], face.v[2]); InsertEdge(face.v[2], face.v[3]); } void PNPP_62(size_t base, Face const& face) { InsertEdge(base + face.e[0], base + face.e[1]); } void PZNN_63(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[1]); } void PZNZ_64(size_t, Face const& face) { InsertEdge(face.v[3], face.v[1]); } void PZNP_65(size_t base, Face const& face) { InsertEdge(base + face.e[2], face.v[1]); } void PZZN_66(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[0]); InsertEdge(face.v[0], face.v[1]); } void PZZZ_67(size_t, Face const&) { } void PZZP_68(size_t, Face const&) { } void PZPN_69(size_t base, Face const& face) { InsertEdge(base + face.e[3], face.v[0]); InsertEdge(face.v[0], face.v[1]); InsertEdge(face.v[1], face.v[2]); InsertEdge(face.v[2], base + face.e[2]); } void PZPZ_70(size_t, Face const&) { } void PZPP_71(size_t, Face const&) { } void PPNN_72(size_t base, Face const& face) { InsertEdge(base + face.e[3], base + face.e[1]); } void PPNZ_73(size_t base, Face const& face) { InsertEdge(face.v[3], base + face.e[1]); } void PPNP_74(size_t base, Face const& face) { InsertEdge(base + face.e[2], base + face.e[1]); } void PPZN_75(size_t base, Face const& face) { InsertEdge(base + face.e[2], face.v[2]); } void PPZZ_76(size_t, Face const&) { } void PPZP_77(size_t, Face const&) { } void PPPN_78(size_t base, Face const& face) { InsertEdge(base + face.e[3], base + face.e[2]); } void PPPZ_79(size_t, Face const&) { } void PPPP_80(size_t, Face const&) { } }; // Template alias for convenience. template <typename T> using TIAlignedBox3Cone3 = TIQuery<T, AlignedBox3<T>, Cone3<T>>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomial3.h
.h
8,734
236
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/Array2.h> #include <Mathematics/GMatrix.h> #include <array> // The samples are (x[i],y[i],w[i]) for 0 <= i < S. Think of w as a function // of x and y, say w = f(x,y). The function fits the samples with a // polynomial of degree d0 in x and degree d1 in y, say // w = sum_{i=0}^{d0} sum_{j=0}^{d1} c[i][j]*x^i*y^j // The method is a least-squares fitting algorithm. The mParameters stores // c[i][j] = mParameters[i+(d0+1)*j] for a total of (d0+1)*(d1+1) // coefficients. The observation type is std::array<Real,3>, which represents // a triple (x,y,w). // // WARNING. The fitting algorithm for polynomial terms // (1,x,x^2,...,x^d0), (1,y,y^2,...,y^d1) // is known to be nonrobust for large degrees and for large magnitude data. // One alternative is to use orthogonal polynomials // (f[0](x),...,f[d0](x)), (g[0](y),...,g[d1](y)) // and apply the least-squares algorithm to these. Another alternative is to // transform // (x',y',w') = ((x-xcen)/rng, (y-ycen)/rng, w/rng) // where xmin = min(x[i]), xmax = max(x[i]), xcen = (xmin+xmax)/2, // ymin = min(y[i]), ymax = max(y[i]), ycen = (ymin+ymax)/2, and // rng = max(xmax-xmin,ymax-ymin). Fit the (x',y',w') points, // w' = sum_{i=0}^{d0} sum_{j=0}^{d1} c'[i][j]*(x')^i*(y')^j // The original polynomial is evaluated as // w = rng * sum_{i=0}^{d0} sum_{j=0}^{d1} c'[i][j] * // ((x-xcen)/rng)^i * ((y-ycen)/rng)^j namespace gte { template <typename Real> class ApprPolynomial3 : public ApprQuery<Real, std::array<Real, 3>> { public: // Initialize the model parameters to zero. ApprPolynomial3(int32_t xDegree, int32_t yDegree) : mXDegree(xDegree), mYDegree(yDegree), mXDegreeP1(xDegree + 1), mYDegreeP1(yDegree + 1), mSize(mXDegreeP1 * mYDegreeP1), mParameters(mSize, (Real)0), mYCoefficient(mYDegreeP1, (Real)0) { mXDomain[0] = std::numeric_limits<Real>::max(); mXDomain[1] = -mXDomain[0]; mYDomain[0] = std::numeric_limits<Real>::max(); mYDomain[1] = -mYDomain[0]; } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numObservations, std::array<Real, 3> const* observations, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numObservations, observations, numIndices, indices)) { int32_t s, i0, j0, k0, i1, j1, k1; // Compute the powers of x and y. int32_t numSamples = static_cast<int32_t>(numIndices); int32_t twoXDegree = 2 * mXDegree; int32_t twoYDegree = 2 * mYDegree; Array2<Real> xPower(static_cast<size_t>(twoXDegree) + 1, numSamples); Array2<Real> yPower(static_cast<size_t>(twoYDegree) + 1, numSamples); for (s = 0; s < numSamples; ++s) { Real x = observations[indices[s]][0]; Real y = observations[indices[s]][1]; mXDomain[0] = std::min(x, mXDomain[0]); mXDomain[1] = std::max(x, mXDomain[1]); mYDomain[0] = std::min(y, mYDomain[0]); mYDomain[1] = std::max(y, mYDomain[1]); xPower[s][0] = (Real)1; for (i0 = 1; i0 <= twoXDegree; ++i0) { xPower[s][i0] = x * xPower[s][i0 - 1]; } yPower[s][0] = (Real)1; for (j0 = 1; j0 <= twoYDegree; ++j0) { yPower[s][j0] = y * yPower[s][j0 - 1]; } } // Matrix A is the Vandermonde matrix and vector B is the // right-hand side of the linear system A*X = B. GMatrix<Real> A(mSize, mSize); GVector<Real> B(mSize); for (j0 = 0; j0 <= mYDegree; ++j0) { for (i0 = 0; i0 <= mXDegree; ++i0) { Real sum = (Real)0; k0 = i0 + mXDegreeP1 * j0; for (s = 0; s < numSamples; ++s) { Real w = observations[indices[s]][2]; sum += w * xPower[s][i0] * yPower[s][j0]; } B[k0] = sum; for (j1 = 0; j1 <= mYDegree; ++j1) { for (i1 = 0; i1 <= mXDegree; ++i1) { sum = (Real)0; k1 = i1 + mXDegreeP1 * j1; for (s = 0; s < numSamples; ++s) { sum += xPower[s][i0 + i1] * yPower[s][j0 + j1]; } A(k0, k1) = sum; } } } } // Solve for the polynomial coefficients. GVector<Real> coefficients = Inverse(A) * B; bool hasNonzero = false; for (int32_t i = 0; i < mSize; ++i) { mParameters[i] = coefficients[i]; if (coefficients[i] != (Real)0) { hasNonzero = true; } } return hasNonzero; } std::fill(mParameters.begin(), mParameters.end(), (Real)0); return false; } // Get the parameters for the best fit. std::vector<Real> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return static_cast<size_t>(mSize); } // Compute the model error for the specified observation for the // current model parameters. The returned value for observation // (x0,y0,w0) is |w(x0,y0) - w0|, where w(x,y) is the fitted // polynomial. virtual Real Error(std::array<Real, 3> const& observation) const override { Real w = Evaluate(observation[0], observation[1]); Real error = std::fabs(w - observation[2]); return error; } virtual void CopyParameters(ApprQuery<Real, std::array<Real, 3>> const* input) override { auto source = dynamic_cast<ApprPolynomial3 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain intervals are provided so you // can interpolate ((x,y) in domain) or extrapolate ((x,y) not in // domain). std::array<Real, 2> const& GetXDomain() const { return mXDomain; } std::array<Real, 2> const& GetYDomain() const { return mYDomain; } Real Evaluate(Real x, Real y) const { int32_t i0, i1; Real w; for (i1 = 0; i1 <= mYDegree; ++i1) { i0 = mXDegree; w = mParameters[i0 + static_cast<size_t>(mXDegreeP1) * i1]; while (--i0 >= 0) { w = mParameters[i0 + static_cast<size_t>(mXDegreeP1) * i1] + w * x; } mYCoefficient[i1] = w; } i1 = mYDegree; w = mYCoefficient[i1]; while (--i1 >= 0) { w = mYCoefficient[i1] + w * y; } return w; } private: int32_t mXDegree, mYDegree, mXDegreeP1, mYDegreeP1, mSize; std::array<Real, 2> mXDomain, mYDomain; std::vector<Real> mParameters; // This array is used by Evaluate() to avoid reallocation of the // 'vector' for each call. The member is mutable because, to the // user, the call to Evaluate does not modify the polynomial. mutable std::vector<Real> mYCoefficient; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DarbouxFrame.h
.h
6,087
149
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix2x2.h> #include <Mathematics/ParametricSurface.h> #include <Mathematics/Vector3.h> #include <memory> namespace gte { template <typename Real> class DarbouxFrame3 { public: // Construction. The curve must persist as long as the DarbouxFrame3 // object does. DarbouxFrame3(std::shared_ptr<ParametricSurface<3, Real>> const& surface) : mSurface(surface) { } // Get a coordinate frame, {T0, T1, N}. At a nondegenerate surface // points, dX/du and dX/dv are linearly independent tangent vectors. // The frame is constructed as // T0 = (dX/du)/|dX/du| // N = Cross(dX/du,dX/dv)/|Cross(dX/du,dX/dv)| // T1 = Cross(N, T0) // so that {T0, T1, N} is a right-handed orthonormal set. void operator()(Real u, Real v, Vector3<Real>& position, Vector3<Real>& tangent0, Vector3<Real>& tangent1, Vector3<Real>& normal) const { std::array<Vector3<Real>, 3> jet; mSurface->Evaluate(u, v, 1, jet.data()); position = jet[0]; tangent0 = jet[1]; Normalize(tangent0); tangent1 = jet[2]; Normalize(tangent1); normal = UnitCross(tangent0, tangent1); tangent1 = Cross(normal, tangent0); } // Compute the principal curvatures and principal directions. void GetPrincipalInformation(Real u, Real v, Real& curvature0, Real& curvature1, Vector3<Real>& direction0, Vector3<Real>& direction1) const { // Tangents: T0 = (x_u,y_u,z_u), T1 = (x_v,y_v,z_v) // Normal: N = Cross(T0,T1)/Length(Cross(T0,T1)) // Metric Tensor: G = +- -+ // | Dot(T0,T0) Dot(T0,T1) | // | Dot(T1,T0) Dot(T1,T1) | // +- -+ // // Curvature Tensor: B = +- -+ // | -Dot(N,T0_u) -Dot(N,T0_v) | // | -Dot(N,T1_u) -Dot(N,T1_v) | // +- -+ // // Principal curvatures k are the generalized eigenvalues of // // Bw = kGw // // If k is a curvature and w=(a,b) is the corresponding solution // to Bw = kGw, then the principal direction as a 3D vector is // d = a*U+b*V. // // Let k1 and k2 be the principal curvatures. The mean curvature // is (k1+k2)/2 and the Gaussian curvature is k1*k2. // Compute derivatives. std::array<Vector3<Real>, 6> jet; mSurface->Evaluate(u, v, 2, jet.data()); Vector3<Real> derU = jet[1]; Vector3<Real> derV = jet[2]; Vector3<Real> derUU = jet[3]; Vector3<Real> derUV = jet[4]; Vector3<Real> derVV = jet[5]; // Compute the metric tensor. Matrix2x2<Real> metricTensor; metricTensor(0, 0) = Dot(jet[1], jet[1]); metricTensor(0, 1) = Dot(jet[1], jet[2]); metricTensor(1, 0) = metricTensor(0, 1); metricTensor(1, 1) = Dot(jet[2], jet[2]); // Compute the curvature tensor. Vector3<Real> normal = UnitCross(jet[1], jet[2]); Matrix2x2<Real> curvatureTensor; curvatureTensor(0, 0) = -Dot(normal, derUU); curvatureTensor(0, 1) = -Dot(normal, derUV); curvatureTensor(1, 0) = curvatureTensor(0, 1); curvatureTensor(1, 1) = -Dot(normal, derVV); // Characteristic polynomial is 0 = det(B-kG) = c2*k^2+c1*k+c0. Real c0 = Determinant(curvatureTensor); Real c1 = (Real)2 * curvatureTensor(0, 1) * metricTensor(0, 1) - curvatureTensor(0, 0) * metricTensor(1, 1) - curvatureTensor(1, 1) * metricTensor(0, 0); Real c2 = Determinant(metricTensor); // Principal curvatures are roots of characteristic polynomial. Real temp = std::sqrt(std::max(c1 * c1 - (Real)4 * c0 * c2, (Real)0)); Real mult = (Real)0.5 / c2; curvature0 = -mult * (c1 + temp); curvature1 = -mult * (c1 - temp); // Principal directions are solutions to (B-kG)w = 0, // w1 = (b12-k1*g12,-(b11-k1*g11)) OR (b22-k1*g22,-(b12-k1*g12)). Real a0 = curvatureTensor(0, 1) - curvature0 * metricTensor(0, 1); Real a1 = curvature0 * metricTensor(0, 0) - curvatureTensor(0, 0); Real length = std::sqrt(a0 * a0 + a1 * a1); if (length > (Real)0) { direction0 = a0 * derU + a1 * derV; } else { a0 = curvatureTensor(1, 1) - curvature0 * metricTensor(1, 1); a1 = curvature0 * metricTensor(0, 1) - curvatureTensor(0, 1); length = std::sqrt(a0 * a0 + a1 * a1); if (length > (Real)0) { direction0 = a0 * derU + a1 * derV; } else { // Umbilic (surface is locally sphere, any direction // principal). direction0 = derU; } } Normalize(direction0); // Second tangent is cross product of first tangent and normal. direction1 = Cross(direction0, normal); } private: std::shared_ptr<ParametricSurface<3, Real>> mSurface; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RectangleManager.h
.h
11,335
265
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.05.16 #pragma once #include <Mathematics/IntrAlignedBox2AlignedBox2.h> #include <Mathematics/EdgeKey.h> #include <set> #include <vector> namespace gte { template <typename Real> class RectangleManager { public: // Construction. RectangleManager(std::vector<AlignedBox2<Real>>& rectangles) : mRectangles(rectangles) { Initialize(); } // No default construction, copy construction, or assignment are // allowed. RectangleManager() = delete; RectangleManager(RectangleManager const&) = delete; RectangleManager& operator=(RectangleManager const&) = delete; // This function is called by the constructor and does the // sort-and-sweep to initialize the update system. However, if you // add or remove items from the array of rectangles after the // constructor call, you will need to call this function once before // you start the multiple calls of the update function. void Initialize() { // Get the rectangle endpoints. int32_t intrSize = static_cast<int32_t>(mRectangles.size()), endpSize = 2 * intrSize; mXEndpoints.resize(endpSize); mYEndpoints.resize(endpSize); for (int32_t i = 0, j = 0; i < intrSize; ++i) { mXEndpoints[j].type = 0; mXEndpoints[j].value = mRectangles[i].min[0]; mXEndpoints[j].index = i; mYEndpoints[j].type = 0; mYEndpoints[j].value = mRectangles[i].min[1]; mYEndpoints[j].index = i; ++j; mXEndpoints[j].type = 1; mXEndpoints[j].value = mRectangles[i].max[0]; mXEndpoints[j].index = i; mYEndpoints[j].type = 1; mYEndpoints[j].value = mRectangles[i].max[1]; mYEndpoints[j].index = i; ++j; } // Sort the rectangle endpoints. std::sort(mXEndpoints.begin(), mXEndpoints.end()); std::sort(mYEndpoints.begin(), mYEndpoints.end()); // Create the interval-to-endpoint lookup tables. mXLookup.resize(endpSize); mYLookup.resize(endpSize); for (int32_t j = 0; j < endpSize; ++j) { mXLookup[2 * static_cast<size_t>(mXEndpoints[j].index) + static_cast<size_t>(mXEndpoints[j].type)] = j; mYLookup[2 * static_cast<size_t>(mYEndpoints[j].index) + static_cast<size_t>(mYEndpoints[j].type)] = j; } // Active set of rectangles (stored by index in array). std::set<int32_t> active; // Set of overlapping rectangles (stored by pairs of indices in // array). mOverlap.clear(); // Sweep through the endpoints to determine overlapping // x-intervals. for (int32_t i = 0; i < endpSize; ++i) { Endpoint const& endpoint = mXEndpoints[i]; int32_t index = endpoint.index; if (endpoint.type == 0) // an interval 'begin' value { // In the 1D problem, the current interval overlaps with // all the active intervals. In 2D we also need to check // for y-overlap. for (auto activeIndex : active) { // Rectangles activeIndex and index overlap in the // x-dimension. Test for overlap in the y-dimension. AlignedBox2<Real> const& r0 = mRectangles[activeIndex]; AlignedBox2<Real> const& r1 = mRectangles[index]; if (r0.max[1] >= r1.min[1] && r0.min[1] <= r1.max[1]) { if (activeIndex < index) { mOverlap.insert(EdgeKey<false>(activeIndex, index)); } else { mOverlap.insert(EdgeKey<false>(index, activeIndex)); } } } active.insert(index); } else // an interval 'end' value { active.erase(index); } } } // After the system is initialized, you can move the rectangles using // this function. It is not enough to modify the input array of // rectangles because the endpoint values stored internally by this // class must also change. You can also retrieve the current // rectangles information. void SetRectangle(int32_t i, AlignedBox2<Real> const& rectangle) { size_t szI = static_cast<size_t>(i); mRectangles[szI] = rectangle; mXEndpoints[mXLookup[2 * szI]].value = rectangle.min[0]; mXEndpoints[mXLookup[2 * szI + 1]].value = rectangle.max[0]; mYEndpoints[mYLookup[2 * szI]].value = rectangle.min[1]; mYEndpoints[mYLookup[2 * szI + 1]].value = rectangle.max[1]; } inline void GetRectangle(int32_t i, AlignedBox2<Real>& rectangle) const { rectangle = mRectangles[i]; } // When you are finished moving rectangles, call this function to // determine the overlapping rectangles. An incremental update is // applied to determine the new set of overlapping rectangles. void Update() { InsertionSort(mXEndpoints, mXLookup); InsertionSort(mYEndpoints, mYLookup); } // If (i,j) is in the overlap set, then rectangle i and rectangle j // are overlapping. The indices are those for the the input array. // The set elements (i,j) are stored so that i < j. inline std::set<EdgeKey<false>> const& GetOverlap() const { return mOverlap; } private: class Endpoint { public: Real value; // endpoint value int32_t type; // '0' if interval min, '1' if interval max. int32_t index; // index of interval containing this endpoint // Support for sorting of endpoints. bool operator<(Endpoint const& endpoint) const { if (value < endpoint.value) { return true; } if (value > endpoint.value) { return false; } return type < endpoint.type; } }; void InsertionSort(std::vector<Endpoint>& endpoint, std::vector<int32_t>& lookup) { // Apply an insertion sort. Under the assumption that the // rectangles have not changed much since the last call, the // endpoints are nearly sorted. The insertion sort should be very // fast in this case. TIQuery<Real, AlignedBox2<Real>, AlignedBox2<Real>> query; int32_t endpSize = static_cast<int32_t>(endpoint.size()); for (int32_t j = 1; j < endpSize; ++j) { Endpoint key = endpoint[j]; int32_t i = j - 1; while (i >= 0 && key < endpoint[i]) { Endpoint e0 = endpoint[i]; Endpoint e1 = endpoint[static_cast<size_t>(i) + 1]; // Update the overlap status. if (e0.type == 0) { if (e1.type == 1) { // The 'b' of interval E0.index was smaller than // the 'e' of interval E1.index, and the intervals // *might have been* overlapping. Now 'b' and 'e' // are swapped, and the intervals cannot overlap. // Remove the pair from the overlap set. The // removal operation needs to find the pair and // erase it if it exists. Finding the pair is the // expensive part of the operation, so there is no // real time savings in testing for existence // first, then deleting if it does. mOverlap.erase(EdgeKey<false>(e0.index, e1.index)); } } else { if (e1.type == 0) { // The 'b' of interval E1.index was larger than // the 'e' of interval E0.index, and the intervals // were not overlapping. Now 'b' and 'e' are // swapped, and the intervals *might be* // overlapping. Determine if they are overlapping // and then insert. if (query(mRectangles[e0.index], mRectangles[e1.index]).intersect) { mOverlap.insert(EdgeKey<false>(e0.index, e1.index)); } } } // Reorder the items to maintain the sorted list. endpoint[i] = e1; endpoint[static_cast<size_t>(i) + 1] = e0; lookup[2 * static_cast<size_t>(e1.index) + static_cast<size_t>(e1.type)] = i; lookup[2 * static_cast<size_t>(e0.index) + static_cast<size_t>(e0.type)] = i + 1; --i; } endpoint[static_cast<size_t>(i) + 1] = key; lookup[2 * static_cast<size_t>(key.index) + static_cast<size_t>(key.type)] = i + 1; } } std::vector<AlignedBox2<Real>>& mRectangles; std::vector<Endpoint> mXEndpoints, mYEndpoints; std::set<EdgeKey<false>> mOverlap; // The intervals are indexed 0 <= i < n. The endpoint array has 2*n // entries. The original 2*n interval values are ordered as // b[0], e[0], b[1], e[1], ..., b[n-1], e[n-1] // When the endpoint array is sorted, the mapping between interval // values and endpoints is lost. In order to modify interval values // that are stored in the endpoint array, we need to maintain the // mapping. This is done by the following lookup table of 2*n // entries. The value mLookup[2*i] is the index of b[i] in the // endpoint array. The value mLookup[2*i+1] is the index of e[i] // in the endpoint array. std::vector<int32_t> mXLookup, mYLookup; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OdeMidpoint.h
.h
1,714
50
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/OdeSolver.h> // The TVector template parameter allows you to create solvers with // Vector<N,Real> when the dimension N is known at compile time or // GVector<Real> when the dimension N is known at run time. Both classes // have 'int32_t GetSize() const' that allow OdeSolver-derived classes to query // for the dimension. namespace gte { template <typename Real, typename TVector> class OdeMidpoint : public OdeSolver<Real, TVector> { public: // Construction and destruction. virtual ~OdeMidpoint() = default; OdeMidpoint(Real tDelta, std::function<TVector(Real, TVector const&)> const& F) : OdeSolver<Real, TVector>(tDelta, F) { } // Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may // allow xIn and xOut to be the same object. virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) override { // Compute the first step. Real halfTDelta = (Real)0.5 * this->mTDelta; TVector fVector = this->mFunction(tIn, xIn); TVector xTemp = xIn + halfTDelta * fVector; // Compute the second step. Real halfT = tIn + halfTDelta; fVector = this->mFunction(halfT, xTemp); tOut = tIn + this->mTDelta; xOut = xIn + this->mTDelta * fVector; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay3Capsule3.h
.h
3,428
111
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistRaySegment.h> #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine3Capsule3.h> // The queries consider the capsule to be a solid. // // The test-intersection queries are based on distance computations. namespace gte { template <typename T> class TIQuery<T, Ray3<T>, Capsule3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Ray3<T> const& ray, Capsule3<T> const& capsule) { Result result{}; DCPQuery<T, Ray3<T>, Segment3<T>> rsQuery{}; auto rsResult = rsQuery(ray, capsule.segment); result.intersect = (rsResult.distance <= capsule.radius); return result; } }; template <typename T> class FIQuery<T, Ray3<T>, Capsule3<T>> : public FIQuery<T, Line3<T>, Capsule3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Capsule3<T>>::Result { Result() : FIQuery<T, Line3<T>, Capsule3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray3<T> const& ray, Capsule3<T> const& capsule) { Result result{}; DoQuery(ray.origin, ray.direction, capsule, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& rayOrigin, Vector3<T> const& rayDirection, Capsule3<T> const& capsule, Result& result) { FIQuery<T, Line3<T>, Capsule3<T>>::DoQuery( rayOrigin, rayDirection, capsule, result); if (result.intersect) { // The line containing the ray intersects the capsule; the // t-interval is [t0,t1]. The ray intersects the capsule as // long as [t0,t1] overlaps the ray t-interval [0,+infinity). FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery; auto iiResult = iiQuery(result.parameter, static_cast<T>(0), true); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { // The line containing the ray does not intersect the // capsule. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Image.h
.h
5,272
195
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> #include <vector> namespace gte { template <typename PixelType> class Image { public: // Construction and destruction. virtual ~Image() { } Image() { } Image(std::vector<int32_t> const& dimensions) { Reconstruct(dimensions); } // Support for copy semantics. Image(Image const& image) { *this = image; } Image& operator=(Image const& image) { mDimensions = image.mDimensions; mOffsets = image.mOffsets; mPixels = image.mPixels; return *this; } // Support for move semantics. Image(Image&& image) noexcept { *this = std::move(image); } Image& operator=(Image&& image) noexcept { mDimensions = std::move(image.mDimensions); mOffsets = std::move(image.mOffsets); mPixels = std::move(image.mPixels); return *this; } // Support for changing the image dimensions. All pixel data is lost // by this operation. void Reconstruct(std::vector<int32_t> const& dimensions) { mDimensions.clear(); mOffsets.clear(); mPixels.clear(); if (dimensions.size() > 0) { for (auto dim : dimensions) { if (dim <= 0) { return; } } mDimensions = dimensions; mOffsets.resize(dimensions.size()); size_t numPixels = 1; for (size_t d = 0; d < dimensions.size(); ++d) { numPixels *= static_cast<size_t>(mDimensions[d]); } mOffsets[0] = 1; for (size_t d = 1; d < dimensions.size(); ++d) { mOffsets[d] = static_cast<size_t>(mDimensions[d - 1]) * mOffsets[d - 1]; } mPixels.resize(numPixels); } } // Access to image data. inline std::vector<int32_t> const& GetDimensions() const { return mDimensions; } inline int32_t GetNumDimensions() const { return static_cast<int32_t>(mDimensions.size()); } inline int32_t GetDimension(int32_t d) const { return mDimensions[d]; } inline std::vector<size_t> const& GetOffsets() const { return mOffsets; } inline size_t GetOffset(int32_t d) const { return mOffsets[d]; } inline std::vector<PixelType> const& GetPixels() const { return mPixels; } inline std::vector<PixelType>& GetPixels() { return mPixels; } inline size_t GetNumPixels() const { return mPixels.size(); } // Conversions between n-dim and 1-dim structures. The 'coord' arrays // must have GetNumDimensions() elements. size_t GetIndex(int32_t const* coord) const { // assert: coord is array of mNumDimensions elements int32_t const numDimensions = static_cast<int32_t>(mDimensions.size()); size_t index = coord[0]; for (int32_t d = 1; d < numDimensions; ++d) { index += mOffsets[d] * coord[d]; } return index; } void GetCoordinates(size_t index, int32_t* coord) const { // assert: coord is array of numDimensions elements int32_t const numDimensions = static_cast<int32_t>(mDimensions.size()); for (int32_t d = 0; d < numDimensions; ++d) { coord[d] = index % mDimensions[d]; index /= mDimensions[d]; } } // Access the data as a 1-dimensional array. The operator[] functions // test for valid i when iterator checking is enabled and assert on // invalid i. The Get() functions test for valid i and clamp when // invalid; these functions cannot fail. inline PixelType& operator[] (size_t i) { return mPixels[i]; } inline PixelType const& operator[] (size_t i) const { return mPixels[i]; } PixelType& Get(size_t i) { return (i < mPixels.size() ? mPixels[i] : mPixels.front()); } PixelType const& Get(size_t i) const { return (i < mPixels.size() ? mPixels[i] : mPixels.front()); } protected: std::vector<int32_t> mDimensions; std::vector<size_t> mOffsets; std::vector<PixelType> mPixels; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment2AlignedBox2.h
.h
2,802
78
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine2AlignedBox2.h> #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/Segment.h> // Compute the distance between a segment and a solid aligned box in 2D. // // The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0 // is generally not unit length. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the segment is stored in closest[0] with parameter t. // The closest point on the box is stored in closest[1]. When there are // infinitely many choices for the pair of closest points, only one of them is // returned. namespace gte { template <typename T> class DCPQuery<T, Segment2<T>, AlignedBox2<T>> { public: using AlignedQuery = DCPQuery<T, Line2<T>, AlignedBox2<T>>; using Result = typename AlignedQuery::Result; Result operator()(Segment2<T> const& segment, AlignedBox2<T> const& box) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector2<T> direction = segment.p[1] - segment.p[0]; Line2<T> line(segment.p[0], direction); DCPQuery<T, Line2<T>, AlignedBox2<T>> lbQuery{}; auto lbResult = lbQuery(line, box); if (lbResult.parameter >= zero) { if (lbResult.parameter <= one) { result = lbResult; } else { DCPQuery<T, Vector2<T>, AlignedBox2<T>> pbQuery{}; auto pbResult = pbQuery(segment.p[1], box); result.sqrDistance = pbResult.sqrDistance; result.distance = pbResult.distance; result.parameter = one; result.closest[0] = segment.p[1]; result.closest[1] = pbResult.closest[1]; } } else { DCPQuery<T, Vector2<T>, AlignedBox2<T>> pbQuery{}; auto pbResult = pbQuery(segment.p[0], box); result.distance = pbResult.distance; result.sqrDistance = pbResult.sqrDistance; result.parameter = zero; result.closest[0] = segment.p[0]; result.closest[1] = pbResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprQuadratic3.h
.h
11,033
314
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/Vector3.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/SymmetricEigensolver.h> namespace gte { // The quadratic fit is // 0 = C[0] + C[1]*x + C[2]*y + C[3]*z + C[4]*x^2 + C[5]*x*y // + C[6]*x*z + C[7]*y^2 + C[8]*y*z + C[9]*z^2 // which has one degree of freedom in the coefficients. Eliminate the // degree of freedom by minimizing the quadratic form E(C) = C^T M C // subject to Length(C) = 1 with M = (sum_i V_i)(sum_i V_i)^t where // V = (1, x, y, z, x^2, x*y, x*z, y^2, y*z, z^2) // The minimum value is the smallest eigenvalue of M and C is a // corresponding unit length eigenvector. // // Input: // n = number of points to fit // P[0..n-1] = array of points to fit // // Output: // C[0..9] = coefficients of quadratic fit (the eigenvector) // return value of function is nonnegative and a measure of the fit // (the minimum eigenvalue; 0 = exact fit, positive otherwise) // // Canonical forms. The quadratic equation can be factored into // P^T A P + B^T P + K = 0 where P = (x,y,z), K = C[0], // B = (C[1],C[2],C[3]) and A is a 3x3 symmetric matrix with // A00 = C[4], A01 = C[5]/2, A02 = C[6]/2, A11 = C[7], A12 = C[8]/2 and // A22 = C[9]. Using an eigendecomposition, matrix A = R^T D R where // R is orthogonal and D is diagonal. Define V = R*P = (v0,v1,v2), // E = R*B = (e0,e1,e2), D = diag(d0,d1,d2) and f = K to obtain // d0 v0^2 + d1 v1^2 + d2 v^2 + e0 v0 + e1 v1 + e2 v2 + f = 0 // The classification depends on the signs of the d_i. See the file // QuadricSurface.h for determining the type of quadric surface. template <typename Real> class ApprQuadratic3 { public: Real operator()(int32_t numPoints, Vector3<Real> const* points, std::array<Real, 10>& coefficients) { Matrix<10, 10, Real> M{}; // constructor sets M to zero for (int32_t i = 0; i < numPoints; ++i) { Real x = points[i][0]; Real y = points[i][1]; Real z = points[i][2]; Real x2 = x * x; Real y2 = y * y; Real z2 = z * z; Real xy = x * y; Real xz = x * z; Real yz = y * z; Real x3 = x * x2; Real xy2 = x * y2; Real xz2 = x * z2; Real x2y = x * xy; Real x2z = x * xz; Real xyz = x * yz; Real y3 = y * y2; Real yz2 = y * z2; Real y2z = y * yz; Real z3 = z * z2; Real x4 = x * x3; Real x2y2 = x * xy2; Real x2z2 = x * xz2; Real x3y = x * x2y; Real x3z = x * x2z; Real x2yz = x * xyz; Real y4 = y * y3; Real y2z2 = y * yz2; Real xy3 = x * y3; Real xy2z = x * y2z; Real y3z = y * y2z; Real z4 = z * z3; Real xyz2 = x * yz2; Real xz3 = x * z3; Real yz3 = y * z3; // M(0, 0) += 1 M(0, 1) += x; M(0, 2) += y; M(0, 3) += z; M(0, 4) += x2; M(0, 5) += xy; M(0, 6) += xz; M(0, 7) += y2; M(0, 8) += yz; M(0, 9) += z2; // M(1, 1) += x2 [M(0,4)] // M(1, 2) += xy [M(0,5)] // M(1, 3) += xz [M(0,6)] M(1, 4) += x3; M(1, 5) += x2y; M(1, 6) += x2z; M(1, 7) += xy2; M(1, 8) += xyz; M(1, 9) += xz2; // M(2, 2) += y2 [M(0,7)] // M(2, 3) += yz [M(0,8)] // M(2, 4) += x2y [M(1,5)] M(2, 5) += xy2; // M(2, 6) += xyz [M(1,8)] M(2, 7) += y3; M(2, 8) += y2z; M(2, 9) += yz2; // M(3, 3) += z2 [M(0,9)] // M(3, 4) += x2z [M(1,6)] // M(3, 5) += xyz [M(1,8)] // M(3, 6) += xz2 [M(1,9)] // M(3, 7) += y2z [M(2,8)] // M(3, 8) += yz2 [M(2,9)] M(3, 9) += z3; M(4, 4) += x4; M(4, 5) += x3y; M(4, 6) += x3z; M(4, 7) += x2y2; M(4, 8) += x2yz; M(4, 9) += x2z2; // M(5, 5) += x2y2 [M(4,7)] // M(5, 6) += x2yz [M(4,8)] M(5, 7) += xy3; M(5, 8) += xy2z; M(5, 9) += xyz2; // M(6, 6) += x2z2 [M(4,9)] // M(6, 7) += xy2z [M(5,8)] // M(6, 8) += xyz2 [M(5,9)] M(6, 9) += xz3; M(7, 7) += y4; M(7, 8) += y3z; M(7, 9) += y2z2; // M(8, 8) += y2z2 [M(7,9)] M(8, 9) += yz3; M(9, 9) += z4; } Real const rNumPoints = static_cast<Real>(numPoints); M(0, 0) = rNumPoints; M(1, 1) = M(0, 4); // x2 M(1, 2) = M(0, 5); // xy M(1, 3) = M(0, 6); // xz M(2, 2) = M(0, 7); // y2 M(2, 3) = M(0, 8); // yz M(2, 4) = M(1, 5); // x2y M(2, 6) = M(1, 8); // xyz M(3, 3) = M(0, 9); // z2 M(3, 4) = M(1, 6); // x2z M(3, 5) = M(1, 8); // xyz M(3, 6) = M(1, 9); // xz2 M(3, 7) = M(2, 8); // y2z M(3, 8) = M(2, 9); // yz2 M(5, 5) = M(4, 7); // x2y2 M(5, 6) = M(4, 8); // x2yz M(6, 6) = M(4, 9); // x2z2 M(6, 7) = M(5, 8); // xy2z M(6, 8) = M(5, 9); // xyz2 M(8, 8) = M(7, 9); // y2z2 for (int32_t row = 0; row < 10; ++row) { for (int32_t col = 0; col < row; ++col) { M(row, col) = M(col, row); } } for (int32_t row = 0; row < 10; ++row) { for (int32_t col = 0; col < 10; ++col) { M(row, col) /= rNumPoints; } } SymmetricEigensolver<Real> es(10, 1024); es.Solve(&M[0], +1); es.GetEigenvector(0, coefficients.data()); // For an exact fit, numeric round-off errors might make the // minimum eigenvalue just slightly negative. Return the clamped // value because the application might rely on the return value // being nonnegative. return std::max(es.GetEigenvalue(0), static_cast<Real>(0)); } }; // If you believe your points are nearly spherical, use this. The sphere // is of the form // C'[0] + C'[1]*x + C'[2]*y + C'[3]*z + C'[4]*(x^2 + y^2 + z^2) = 0 // where Length(C') = 1. The function returns // C = (C'[0] / C'[4], C'[1] / C'[4], C'[2] / C'[4], C'[3] / C'[4]) // = (C[0], C[1], C[2], C[3]) // so the fitted sphere is // C[0] + C[1]*x + C[2]*y + C[3]*z + x^2 + y^2 + z^2 = 0 // The center is (xc,yc,zc) = -0.5*(C[1],C[2],C[3]) and the radius is // r = sqrt(xc * xc + yc * yc + zc * zc - C[0]). template <typename Real> class ApprQuadraticSphere3 { public: Real operator()(int32_t numPoints, Vector3<Real> const* points, Sphere3<Real>& sphere) { Matrix<5, 5, Real> M{}; // constructor sets M to zero for (int32_t i = 0; i < numPoints; ++i) { Real x = points[i][0]; Real y = points[i][1]; Real z = points[i][2]; Real x2 = x * x; Real y2 = y * y; Real z2 = z * z; Real xy = x * y; Real xz = x * z; Real yz = y * z; Real r2 = x2 + y2 + z2; Real xr2 = x * r2; Real yr2 = y * r2; Real zr2 = z * r2; Real r4 = r2 * r2; // M(0, 0) += 1 M(0, 1) += x; M(0, 2) += y; M(0, 3) += z; M(0, 4) += r2; M(1, 1) += x2; M(1, 2) += xy; M(1, 3) += xz; M(1, 4) += xr2; M(2, 2) += y2; M(2, 3) += yz; M(2, 4) += yr2; M(3, 3) += z2; M(3, 4) += zr2; M(4, 4) += r4; } Real const rNumPoints = static_cast<Real>(numPoints); M(0, 0) = rNumPoints; for (int32_t row = 0; row < 5; ++row) { for (int32_t col = 0; col < row; ++col) { M(row, col) = M(col, row); } } for (int32_t row = 0; row < 5; ++row) { for (int32_t col = 0; col < 5; ++col) { M(row, col) /= rNumPoints; } } M(0, 0) = static_cast<Real>(1); SymmetricEigensolver<Real> es(5, 1024); es.Solve(&M[0], +1); Vector<5, Real> evector{}; es.GetEigenvector(0, &evector[0]); std::array<Real, 4> coefficients{}; for (int32_t row = 0; row < 4; ++row) { coefficients[row] = evector[row] / evector[4]; } // Clamp the radius to nonnegative values in case rounding errors // cause sqrRadius to be slightly negative. Real const negHalf = static_cast<Real>(-0.5); sphere.center[0] = negHalf * coefficients[1]; sphere.center[1] = negHalf * coefficients[2]; sphere.center[2] = negHalf * coefficients[3]; Real sqrRadius = Dot(sphere.center, sphere.center) - coefficients[0]; sphere.radius = std::sqrt(std::max(sqrRadius, static_cast<Real>(0))); // For an exact fit, numeric round-off errors might make the // minimum eigenvalue just slightly negative. Return the clamped // value because the application might rely on the return value // being nonnegative. return std::max(es.GetEigenvalue(0), static_cast<Real>(0)); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay3OrientedBox3.h
.h
2,099
61
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3OrientedBox3.h> #include <Mathematics/DistPointOrientedBox.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a solid orienteded box in 3D. // // The ray is P + t * D for t >= 0, where D is not required to be unit length. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where // |y[i]| <= e[i] for all i. // // The closest point on the ray is stored in closest[0] with parameter t. The // closest point on the box is stored in closest[1]. When there are infinitely // many choices for the pair of closest points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Ray3<T>, OrientedBox3<T>> { public: using OrientedQuery = DCPQuery<T, Line3<T>, OrientedBox3<T>>; using Result = typename OrientedQuery::Result; Result operator()(Ray3<T> const& ray, OrientedBox3<T> const& box) { Result result{}; Line3<T> line(ray.origin, ray.direction); OrientedQuery lbQuery{}; auto lbOutput = lbQuery(line, box); T const zero = static_cast<T>(0); if (lbOutput.parameter >= zero) { result = lbOutput; } else { DCPQuery<T, Vector3<T>, OrientedBox3<T>> pbQuery{}; auto pbOutput = pbQuery(ray.origin, box); result.distance = pbOutput.distance; result.sqrDistance = pbOutput.sqrDistance; result.parameter = zero; result.closest[0] = ray.origin; result.closest[1] = pbOutput.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Transform.h
.h
31,195
826
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/Matrix4x4.h> #include <Mathematics/Rotation.h> // Transforms when GTE_USE_MAT_VEC is defined in the preprocessor symbols. // // The transform is Y = M*X+T, where M is a 3-by-3 matrix and T is a 3x1 // translation. In most cases, M = R, a rotation matrix, or M = R*S, // where R is a rotation matrix and S is a diagonal matrix whose diagonal // entries are positive scales. To support modeling packages that allow // general affine transforms, M can be any invertible 3x3 matrix. The vector // X is transformed in the "forward" direction to Y. The "inverse" direction // transforms Y to X, namely X = M^{-1}*(Y-T) in the general case. In the // special case of M = R*S, the inverse direction is X = S^{-1}*R^t*(Y-T), // where S^{-1} is the diagonal matrix whose diagonal entries are the // reciprocoals of those of S and where R^t is the transpose of R. For SIMD // support of matrix-vector and matrix-matrix multiplications, a homogeneous // matrix H = {{M,T},{0,1}} is stored by this class. The forward transform is // {Y,1} = H*{X,1} and the inverse transform is {X,1} = H^{-1}*{Y,1}. // Transforms when GTE_USE_MAT_VEC is NOT defined in the preprocessor symbols. // // The transform is Y = T + X*M, where M is a 3-by-3 matrix and T is a 1x3 // translation. In most cases, M = R, a rotation matrix, or M = S*R, // where R is a rotation matrix and S is a diagonal matrix whose diagonal // entries are positive scales. To support modeling packages that allow // general affine transforms, M can be any invertible 3x3 matrix. The vector // X is transformed in the "forward" direction to Y. The "inverse" direction // transforms Y to X, namely X = (Y-T)*M^{-1} in the general case. In the // special case of M = S*R, the inverse direction is X = (Y-T)*R^t*S^{-1}, // where S^{-1} is the diagonal matrix whose diagonal entries are the // reciprocoals of those of S and where R^t is the transpose of R. For SIMD // support of matrix-vector and matrix-matrix multiplications, a homogeneous // matrix H = {{M,0},{T,1}} is stored by this class. The forward transform is // {Y,1} = {X,1}*H and the inverse transform is {X,1} = {Y,1}*H^{-1}. // With either multiplication convention, a matrix M = R*S (GTE_USE_MAT_VEC) // or a matrix M = S*R (!GTE_USE_VEC_MAT) is referred to as an "RS-matrix". // The class does not provide a member function to compute the inverse of a // transform: 'Transform GetInverse() const'. If one were to add this, // be aware that the inverse of an RS-matrix is not generally an RS-matrix; // that is, the inverse of R*S is S^{-1}*R^t which cannot always be factored // as S^{-1} * R^t = R' * S'. You would need to SetMatrix using S^{-1}*R^t // as the input. namespace gte { template <typename Real> class Transform { public: // The default constructor produces the identity transformation. The // default copy constructor and assignment operator are generated by // the compiler. Transform() : mHMatrix{}, mInvHMatrix{}, mMatrix{}, mTranslate{ (Real)0, (Real)0, (Real)0, (Real)1 }, mScale{ (Real)1, (Real)1, (Real)1, (Real)1 }, mIsIdentity(true), mIsRSMatrix(true), mIsUniformScale(true), mInverseNeedsUpdate(false) { mHMatrix.MakeIdentity(); mInvHMatrix.MakeIdentity(); mMatrix.MakeIdentity(); } // Implicit conversion. inline operator Matrix4x4<Real> const& () const { return GetHMatrix(); } // Set the transformation to the identity matrix. void MakeIdentity() { mMatrix.MakeIdentity(); mTranslate = { (Real)0, (Real)0, (Real)0, (Real)1 }; mScale = { (Real)1, (Real)1, (Real)1, (Real)1 }; mIsIdentity = true; mIsRSMatrix = true; mIsUniformScale = true; UpdateHMatrix(); } // Set the transformation to have scales of 1. void MakeUnitScale() { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); mScale = { (Real)1, (Real)1, (Real)1, (Real)1 }; mIsUniformScale = true; UpdateHMatrix(); } // Hints about the structure of the transformation. // M = I inline bool IsIdentity() const { return mIsIdentity; } // R*S (GTE_USE_MAT_VEC defined) or S*R (GTE_USE_MAT_VEC not defined) inline bool IsRSMatrix() const { return mIsRSMatrix; } // RS-matrix with S = c*I inline bool IsUniformScale() const { return mIsRSMatrix && mIsUniformScale; } // Member access. // (1) The Set* functions set the is-identity hint to false. // (2) The SetRotate function sets the is-rsmatrix hint to true. If this // hint is false, GetRotate triggers an assertion in debug mode. // (3) The SetMatrix function sets the is-rsmatrix and is-uniform-scale // hints to false. // (4) The SetScale function sets the is-uniform-scale hint to false. // The SetUniformScale function sets the is-uniform-scale hint to // true. If this hint is false, GetUniformScale triggers an assertion // in debug mode. // (5) All Set* functions set the inverse-needs-update to true. When // GetHInverse is called, the inverse must be computed in this case // and the inverse-needs-update is reset to false. // {{R,0},{0,1}} void SetRotation(Matrix4x4<Real> const& rotate) { mMatrix = rotate; mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } // {{M,0},{0,1}} void SetMatrix(Matrix4x4<Real> const& matrix) { mMatrix = matrix; mIsIdentity = false; mIsRSMatrix = false; mIsUniformScale = false; UpdateHMatrix(); } void SetTranslation(Real x0, Real x1, Real x2) { mTranslate = Vector4<Real>{ x0, x1, x2, (Real)1 }; mIsIdentity = false; UpdateHMatrix(); } inline void SetTranslation(Vector3<Real> const& translate) { SetTranslation(translate[0], translate[1], translate[2]); } inline void SetTranslation(Vector4<Real> const& translate) { SetTranslation(translate[0], translate[1], translate[2]); } void SetScale(Real s0, Real s1, Real s2) { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); LogAssert(s0 != (Real)0 && s1 != (Real)0 && s2 != (Real)0, "Scales must be nonzero."); mScale = { s0, s1, s2, (Real)1 }; mIsIdentity = false; mIsUniformScale = false; UpdateHMatrix(); } inline void SetScale(Vector3<Real> const& scale) { SetScale(scale[0], scale[1], scale[2]); } inline void SetScale(Vector4<Real> const& scale) { SetScale(scale[0], scale[1], scale[2]); } void SetUniformScale(Real scale) { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); LogAssert(scale != (Real)0, "Scale must be nonzero."); mScale = { scale, scale, scale, (Real)1 }; mIsIdentity = false; mIsUniformScale = true; UpdateHMatrix(); } // {{R,0},{0,1}} Matrix4x4<Real> const& GetRotation() const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); return mMatrix; } // {{M,0},{0,1}} inline Matrix4x4<Real> const& GetMatrix() const { return mMatrix; } // (x,y,z) inline Vector3<Real> GetTranslation() const { return Vector3<Real>{ mTranslate[0], mTranslate[1], mTranslate[2] }; } // (x,y,z,0) inline Vector4<Real> GetTranslationW0() const { return Vector4<Real>{ mTranslate[0], mTranslate[1], mTranslate[2], (Real)0 }; } // (x,y,z,1) inline Vector4<Real> GetTranslationW1() const { return Vector4<Real>{ mTranslate[0], mTranslate[1], mTranslate[2], (Real)1 }; } // (s0,s1,s2) Vector3<Real> GetScale() const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); return Vector3<Real>{ mScale[0], mScale[1], mScale[2] }; } // (s0,s1,s2,1) Vector4<Real> GetScaleW1() const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); return Vector4<Real>{ mScale[0], mScale[1], mScale[2], (Real)1 }; } Real GetUniformScale() const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); LogAssert(mIsUniformScale, "Transform is not uniform scale."); return mScale[0]; } // Alternate representations to set/get the rotation. // Set/get from 3x3 matrices. void SetRotation(Matrix3x3<Real> const& rotate) { mMatrix.MakeIdentity(); for (int32_t r = 0; r < 3; ++r) { for (int32_t c = 0; c < 3; ++c) { mMatrix(r, c) = rotate(r, c); } } mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } void GetRotation(Matrix3x3<Real>& rotate) const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); for (int32_t r = 0; r < 3; ++r) { for (int32_t c = 0; c < 3; ++c) { rotate(r, c) = mMatrix(r, c); } } } // The quaternion is unit length. void SetRotation(Quaternion<Real> const& q) { mMatrix = Rotation<4, Real>(q); mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } void GetRotation(Quaternion<Real>& q) const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); q = Rotation<4, Real>(mMatrix); } // The axis is unit length and the angle is in radians. void SetRotation(AxisAngle<3, Real> const& axisAngle) { AxisAngle<4, Real> aa4(HLift(axisAngle.axis, (Real)1), axisAngle.angle); mMatrix = Rotation<4, Real>(aa4); mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } void GetRotation(AxisAngle<3, Real>& axisAngle) const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); AxisAngle<4, Real> aa4 = Rotation<4, Real>(mMatrix); axisAngle.axis = HProject(aa4.axis); axisAngle.angle = aa4.angle; } void SetRotation(AxisAngle<4, Real> const& axisAngle) { mMatrix = Rotation<4, Real>(axisAngle); mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } void GetRotation(AxisAngle<4, Real>& axisAngle) const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); axisAngle = Rotation<4, Real>(mMatrix); } // The Euler angles are in radians. The GetEulerAngles function // expects the eulerAngles.axis[] values to be set to the axis order // you want. void SetRotation(EulerAngles<Real> const& eulerAngles) { mMatrix = Rotation<4, Real>(eulerAngles); mIsIdentity = false; mIsRSMatrix = true; UpdateHMatrix(); } void GetRotation(EulerAngles<Real>& eulerAngles) const { LogAssert(mIsRSMatrix, "Transform is not rotation-scale."); eulerAngles = Rotation<4, Real>(mMatrix)(eulerAngles.axis[0], eulerAngles.axis[1], eulerAngles.axis[2]); } // For M = R*S or M = S*R, the largest value of S in absolute value is // returned. For general M, the max-row-sum norm is returned when // GTE_USE_MAT_VEC is defined or the max-col-sum norm is returned when // the GTE_USE_MAT_VEC is not defined, which is a reasonable measure // of maximum scale of the transformation. Real GetNorm() const { Real sum0, sum1, sum2; if (mIsRSMatrix) { // A RS matrix (GTE_USE_MAT_VEC defined) or an SR matrix // (GTE_USE_MAT_VEC is not defined). sum0 = std::fabs(mScale[0]); sum1 = std::fabs(mScale[1]); sum2 = std::fabs(mScale[2]); } else { // The spectral norm (the maximum absolute value of the // eigenvalues) is smaller or equal to this norm. Therefore, // this function returns an approximation to the maximum // scale. #if defined(GTE_USE_MAT_VEC) // Use the max-row-sum matrix norm. sum0 = std::fabs(mMatrix(0, 0)) + std::fabs(mMatrix(0, 1)) + std::fabs(mMatrix(0, 2)); sum1 = std::fabs(mMatrix(1, 0)) + std::fabs(mMatrix(1, 1)) + std::fabs(mMatrix(1, 2)); sum2 = std::fabs(mMatrix(2, 0)) + std::fabs(mMatrix(2, 1)) + std::fabs(mMatrix(2, 2)); #else // Use the max-col-sum matrix norm. sum0 = std::fabs(mMatrix(0, 0)) + std::fabs(mMatrix(1, 0)) + std::fabs(mMatrix(2, 0)); sum1 = std::fabs(mMatrix(0, 1)) + std::fabs(mMatrix(1, 1)) + std::fabs(mMatrix(2, 1)); sum2 = std::fabs(mMatrix(0, 2)) + std::fabs(mMatrix(1, 2)) + std::fabs(mMatrix(2, 2)); #endif } return std::max(std::max(sum0, sum1), sum2); } // Get the homogeneous matrix (composite of all channels). inline Matrix4x4<Real> const& GetHMatrix() const { return mHMatrix; } // Get the inverse homogeneous matrix, recomputing it when necessary. // GTE_USE_MAT_VEC // H = {{M,T},{0,1}}, then H^{-1} = {{M^{-1},-M^{-1}*T},{0,1}} // GTE_USE_VEC_MAT // H = {{M,0},{T,1}}, then H^{-1} = {{M^{-1},0},{-M^{-1}*T,1}} Matrix4x4<Real> const& GetHInverse() const { if (mInverseNeedsUpdate) { if (mIsIdentity) { mInvHMatrix.MakeIdentity(); } else { if (mIsRSMatrix) { if (mIsUniformScale) { Real invScale = (Real)1 / mScale[0]; #if defined(GTE_USE_MAT_VEC) mInvHMatrix(0, 0) = invScale * mMatrix(0, 0); mInvHMatrix(0, 1) = invScale * mMatrix(1, 0); mInvHMatrix(0, 2) = invScale * mMatrix(2, 0); mInvHMatrix(1, 0) = invScale * mMatrix(0, 1); mInvHMatrix(1, 1) = invScale * mMatrix(1, 1); mInvHMatrix(1, 2) = invScale * mMatrix(2, 1); mInvHMatrix(2, 0) = invScale * mMatrix(0, 2); mInvHMatrix(2, 1) = invScale * mMatrix(1, 2); mInvHMatrix(2, 2) = invScale * mMatrix(2, 2); #else mInvHMatrix(0, 0) = mMatrix(0, 0) * invScale; mInvHMatrix(0, 1) = mMatrix(1, 0) * invScale; mInvHMatrix(0, 2) = mMatrix(2, 0) * invScale; mInvHMatrix(1, 0) = mMatrix(0, 1) * invScale; mInvHMatrix(1, 1) = mMatrix(1, 1) * invScale; mInvHMatrix(1, 2) = mMatrix(2, 1) * invScale; mInvHMatrix(2, 0) = mMatrix(0, 2) * invScale; mInvHMatrix(2, 1) = mMatrix(1, 2) * invScale; mInvHMatrix(2, 2) = mMatrix(2, 2) * invScale; #endif } else { // Replace 3 reciprocals by 6 multiplies and // 1 reciprocal. Real s01 = mScale[0] * mScale[1]; Real s02 = mScale[0] * mScale[2]; Real s12 = mScale[1] * mScale[2]; Real invs012 = (Real)1 / (s01 * mScale[2]); Real invS0 = s12 * invs012; Real invS1 = s02 * invs012; Real invS2 = s01 * invs012; #if defined(GTE_USE_MAT_VEC) mInvHMatrix(0, 0) = invS0 * mMatrix(0, 0); mInvHMatrix(0, 1) = invS0 * mMatrix(1, 0); mInvHMatrix(0, 2) = invS0 * mMatrix(2, 0); mInvHMatrix(1, 0) = invS1 * mMatrix(0, 1); mInvHMatrix(1, 1) = invS1 * mMatrix(1, 1); mInvHMatrix(1, 2) = invS1 * mMatrix(2, 1); mInvHMatrix(2, 0) = invS2 * mMatrix(0, 2); mInvHMatrix(2, 1) = invS2 * mMatrix(1, 2); mInvHMatrix(2, 2) = invS2 * mMatrix(2, 2); #else mInvHMatrix(0, 0) = mMatrix(0, 0) * invS0; mInvHMatrix(0, 1) = mMatrix(1, 0) * invS1; mInvHMatrix(0, 2) = mMatrix(2, 0) * invS2; mInvHMatrix(1, 0) = mMatrix(0, 1) * invS0; mInvHMatrix(1, 1) = mMatrix(1, 1) * invS1; mInvHMatrix(1, 2) = mMatrix(2, 1) * invS2; mInvHMatrix(2, 0) = mMatrix(0, 2) * invS0; mInvHMatrix(2, 1) = mMatrix(1, 2) * invS1; mInvHMatrix(2, 2) = mMatrix(2, 2) * invS2; #endif } } else { mInvHMatrix = gte::Inverse(mHMatrix); } #if defined(GTE_USE_MAT_VEC) mInvHMatrix(0, 3) = -( mInvHMatrix(0, 0) * mTranslate[0] + mInvHMatrix(0, 1) * mTranslate[1] + mInvHMatrix(0, 2) * mTranslate[2] ); mInvHMatrix(1, 3) = -( mInvHMatrix(1, 0) * mTranslate[0] + mInvHMatrix(1, 1) * mTranslate[1] + mInvHMatrix(1, 2) * mTranslate[2] ); mInvHMatrix(2, 3) = -( mInvHMatrix(2, 0) * mTranslate[0] + mInvHMatrix(2, 1) * mTranslate[1] + mInvHMatrix(2, 2) * mTranslate[2] ); // The last row of mHMatrix is always (0,0,0,1) for an // affine transformation, so it is set once in the // constructor. It is not necessary to reset it here. #else mInvHMatrix(3, 0) = -( mInvHMatrix(0, 0) * mTranslate[0] + mInvHMatrix(1, 0) * mTranslate[1] + mInvHMatrix(2, 0) * mTranslate[2] ); mInvHMatrix(3, 1) = -( mInvHMatrix(0, 1) * mTranslate[0] + mInvHMatrix(1, 1) * mTranslate[1] + mInvHMatrix(2, 1) * mTranslate[2] ); mInvHMatrix(3, 2) = -( mInvHMatrix(0, 2) * mTranslate[0] + mInvHMatrix(1, 2) * mTranslate[1] + mInvHMatrix(2, 2) * mTranslate[2] ); // The last column of mHMatrix is always (0,0,0,1) for an // affine transformation, so it is set once in the // constructor. It is not necessary to reset it here. #endif } mInverseNeedsUpdate = false; } return mInvHMatrix; } // Invert the transform. If possible, the channels are properly // assigned. For example, if the input has mIsRSMatrix equal to // 'true', then the inverse also has mIsRSMatrix equal to 'true' // and the inverse's mMatrix is a rotation matrix and mScale is // set accordingly. Transform Inverse() const { Transform inverse{}; // = the identity if (!mIsIdentity) { if (mIsRSMatrix && mIsUniformScale) { Matrix4x4<Real> invRotate = Transpose(GetRotation()); Real invScale = static_cast<Real>(1) / GetUniformScale(); Vector4<Real> invTranslate = -invScale * (invRotate * GetTranslationW1()); inverse.SetRotation(invRotate); inverse.SetUniformScale(invScale); inverse.SetTranslation(invTranslate); } else { Matrix4x4<Real> invMatrix = gte::Inverse(GetHMatrix()); Vector4<Real> invTranslate = invMatrix.GetCol(3); inverse.SetMatrix(invMatrix); inverse.SetTranslation(invTranslate); } } return inverse; } // The identity transformation. static Transform Identity() { static Transform identity; return identity; } private: // Fill in the entries of mHMatrix whenever one of the components // mMatrix, mTranslate, or mScale changes. void UpdateHMatrix() { if (mIsIdentity) { mHMatrix.MakeIdentity(); } else { if (mIsRSMatrix) { #if defined(GTE_USE_MAT_VEC) mHMatrix(0, 0) = mMatrix(0, 0) * mScale[0]; mHMatrix(0, 1) = mMatrix(0, 1) * mScale[1]; mHMatrix(0, 2) = mMatrix(0, 2) * mScale[2]; mHMatrix(1, 0) = mMatrix(1, 0) * mScale[0]; mHMatrix(1, 1) = mMatrix(1, 1) * mScale[1]; mHMatrix(1, 2) = mMatrix(1, 2) * mScale[2]; mHMatrix(2, 0) = mMatrix(2, 0) * mScale[0]; mHMatrix(2, 1) = mMatrix(2, 1) * mScale[1]; mHMatrix(2, 2) = mMatrix(2, 2) * mScale[2]; #else mHMatrix(0, 0) = mScale[0] * mMatrix(0, 0); mHMatrix(0, 1) = mScale[0] * mMatrix(0, 1); mHMatrix(0, 2) = mScale[0] * mMatrix(0, 2); mHMatrix(1, 0) = mScale[1] * mMatrix(1, 0); mHMatrix(1, 1) = mScale[1] * mMatrix(1, 1); mHMatrix(1, 2) = mScale[1] * mMatrix(1, 2); mHMatrix(2, 0) = mScale[2] * mMatrix(2, 0); mHMatrix(2, 1) = mScale[2] * mMatrix(2, 1); mHMatrix(2, 2) = mScale[2] * mMatrix(2, 2); #endif } else { mHMatrix(0, 0) = mMatrix(0, 0); mHMatrix(0, 1) = mMatrix(0, 1); mHMatrix(0, 2) = mMatrix(0, 2); mHMatrix(1, 0) = mMatrix(1, 0); mHMatrix(1, 1) = mMatrix(1, 1); mHMatrix(1, 2) = mMatrix(1, 2); mHMatrix(2, 0) = mMatrix(2, 0); mHMatrix(2, 1) = mMatrix(2, 1); mHMatrix(2, 2) = mMatrix(2, 2); } #if defined(GTE_USE_MAT_VEC) mHMatrix(0, 3) = mTranslate[0]; mHMatrix(1, 3) = mTranslate[1]; mHMatrix(2, 3) = mTranslate[2]; // The last row of mHMatrix is always (0,0,0,1) for an affine // transformation, so it is set once in the constructor. It // is not necessary to reset it here. #else mHMatrix(3, 0) = mTranslate[0]; mHMatrix(3, 1) = mTranslate[1]; mHMatrix(3, 2) = mTranslate[2]; // The last column of mHMatrix is always (0,0,0,1) for an // affine transformation, so it is set once in the // constructor. It is not necessary to reset it here. #endif } mInverseNeedsUpdate = true; } // Invert the 3x3 upper-left block of the input matrix. static void Invert3x3(Matrix4x4<Real> const& mat, Matrix4x4<Real>& invMat) { // Compute the adjoint of M (3x3). invMat(0, 0) = mat(1, 1) * mat(2, 2) - mat(1, 2) * mat(2, 1); invMat(0, 1) = mat(0, 2) * mat(2, 1) - mat(0, 1) * mat(2, 2); invMat(0, 2) = mat(0, 1) * mat(1, 2) - mat(0, 2) * mat(1, 1); invMat(0, 3) = 0.0f; invMat(1, 0) = mat(1, 2) * mat(2, 0) - mat(1, 0) * mat(2, 2); invMat(1, 1) = mat(0, 0) * mat(2, 2) - mat(0, 2) * mat(2, 0); invMat(1, 2) = mat(0, 2) * mat(1, 0) - mat(0, 0) * mat(1, 2); invMat(1, 3) = 0.0f; invMat(2, 0) = mat(1, 0) * mat(2, 1) - mat(1, 1) * mat(2, 0); invMat(2, 1) = mat(0, 1) * mat(2, 0) - mat(0, 0) * mat(2, 1); invMat(2, 2) = mat(0, 0) * mat(1, 1) - mat(0, 1) * mat(1, 0); invMat(2, 3) = 0.0f; invMat(3, 0) = 0.0f; invMat(3, 1) = 0.0f; invMat(3, 2) = 0.0f; invMat(3, 3) = 1.0f; // Compute the reciprocal of the determinant of M. Real invDet = (Real)1 / ( mat(0, 0) * invMat(0, 0) + mat(0, 1) * invMat(1, 0) + mat(0, 2) * invMat(2, 0) ); // inverse(M) = adjoint(M)/determinant(M). invMat(0, 0) *= invDet; invMat(0, 1) *= invDet; invMat(0, 2) *= invDet; invMat(1, 0) *= invDet; invMat(1, 1) *= invDet; invMat(1, 2) *= invDet; invMat(2, 0) *= invDet; invMat(2, 1) *= invDet; invMat(2, 2) *= invDet; } // The full 4x4 homogeneous matrix H and its inverse H^{-1}, stored // according to the conventions (see GetHInverse description). The // inverse is computed only on demand. Matrix4x4<Real> mHMatrix; mutable Matrix4x4<Real> mInvHMatrix; Matrix4x4<Real> mMatrix; // M (general) or R (rotation) Vector4<Real> mTranslate; // T Vector4<Real> mScale; // S bool mIsIdentity, mIsRSMatrix, mIsUniformScale; mutable bool mInverseNeedsUpdate; }; // Compute M*V. template <typename Real> Vector4<Real> operator*(Transform<Real> const& M, Vector4<Real> const& V) { return M.GetHMatrix() * V; } // Compute V^T*M. template <typename Real> Vector4<Real> operator*(Vector4<Real> const& V, Transform<Real> const& M) { return V * M.GetHMatrix(); } // Compute A*B. template <typename Real> Transform<Real> operator*(Transform<Real> const& A, Transform<Real> const& B) { if (A.IsIdentity()) { return B; } if (B.IsIdentity()) { return A; } Transform<Real> product; if (A.IsRSMatrix() && B.IsRSMatrix()) { #if defined(GTE_USE_MAT_VEC) if (A.IsUniformScale()) { product.SetRotation(A.GetRotation() * B.GetRotation()); product.SetTranslation(A.GetUniformScale() * ( A.GetRotation() * B.GetTranslationW0()) + A.GetTranslationW1()); if (B.IsUniformScale()) { product.SetUniformScale(A.GetUniformScale() * B.GetUniformScale()); } else { product.SetScale(A.GetUniformScale() * B.GetScale()); } return product; } #else if (B.IsUniformScale()) { product.SetRotation(A.GetRotation() * B.GetRotation()); product.SetTranslation(B.GetUniformScale() * ( A.GetTranslationW0() * B.GetRotation()) + B.GetTranslationW1()); if (A.IsUniformScale()) { product.SetUniformScale(A.GetUniformScale() * B.GetUniformScale()); } else { product.SetScale(A.GetScale() * B.GetUniformScale()); } return product; } #endif } // In all remaining cases, the matrix cannot be written as R*S*X+T. Matrix4x4<Real> matMA; if (A.IsRSMatrix()) { #if defined(GTE_USE_MAT_VEC) matMA = MultiplyMD(A.GetRotation(), A.GetScaleW1()); #else matMA = MultiplyDM(A.GetScaleW1(), A.GetRotation()); #endif } else { matMA = A.GetMatrix(); } Matrix4x4<Real> matMB; if (B.IsRSMatrix()) { #if defined(GTE_USE_MAT_VEC) matMB = MultiplyMD(B.GetRotation(), B.GetScaleW1()); #else matMB = MultiplyDM(B.GetScaleW1(), B.GetRotation()); #endif } else { matMB = B.GetMatrix(); } product.SetMatrix(matMA * matMB); #if defined(GTE_USE_MAT_VEC) product.SetTranslation(matMA * B.GetTranslationW0() + A.GetTranslationW1()); #else product.SetTranslation(A.GetTranslationW0() * matMB + B.GetTranslationW1()); #endif return product; } template <typename Real> inline Matrix4x4<Real> operator*(Matrix4x4<Real> const& A, Transform<Real> const& B) { return A * B.GetHMatrix(); } template <typename Real> inline Matrix4x4<Real> operator*(Transform<Real> const& A, Matrix4x4<Real> const& B) { return A.GetHMatrix()* B; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistTriangle3Triangle3.h
.h
4,086
106
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.02.01 #pragma once #include <Mathematics/DistSegment3Triangle3.h> // Compute the distance between two solid triangles in 3D. // // Each triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The closest point on triangle0 is stored in closest[0] with barycentric // coordinates relative to its vertices. The closest point on triangle1 is // stored in closest[1] with barycentric coordinates relative to its vertices. // When there are infinitely many choices for the pair of closest points, only // one pair is returned. namespace gte { template <typename T> class DCPQuery<T, Triangle3<T>, Triangle3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), barycentric0{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, barycentric1{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<T, 3> barycentric0; std::array<T, 3> barycentric1; std::array<Vector3<T>, 2> closest; }; Result operator()(Triangle3<T> const& triangle0, Triangle3<T> const& triangle1) { Result result{}; DCPQuery<T, Segment3<T>, Triangle3<T>> stQuery{}; typename DCPQuery<T, Segment3<T>, Triangle3<T>>::Result stResult; Segment3<T> segment{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; // Compare edges of triangle0 to the interior of triangle1. for (size_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { segment.p[0] = triangle0.v[i0]; segment.p[1] = triangle0.v[i1]; stResult = stQuery(segment, triangle1); if (result.sqrDistance == invalid || stResult.sqrDistance < result.sqrDistance) { result.distance = stResult.distance; result.sqrDistance = stResult.sqrDistance; result.barycentric0[i0] = one - stResult.parameter; result.barycentric0[i1] = stResult.parameter; result.barycentric0[i2] = zero; result.barycentric1 = stResult.barycentric; result.closest = stResult.closest; } } // Compare edges of triangle1 to the interior of triangle0. for (size_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { segment.p[0] = triangle1.v[i0]; segment.p[1] = triangle1.v[i1]; stResult = stQuery(segment, triangle0); if (result.sqrDistance == invalid || stResult.sqrDistance < result.sqrDistance) { result.distance = stResult.distance; result.sqrDistance = stResult.sqrDistance; result.barycentric0 = stResult.barycentric; result.barycentric1[i0] = one - stResult.parameter; result.barycentric1[i1] = stResult.parameter; result.barycentric1[i2] = zero; result.closest[0] = stResult.closest[1]; result.closest[1] = stResult.closest[0]; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/LogEstimate.h
.h
1,544
45
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.08 #pragma once #include <Mathematics/Log2Estimate.h> // Minimax polynomial approximations to log2(x). The polynomial p(x) of // degree D minimizes the quantity maximum{|log2(x) - p(x)| : x in [1,2]} // over all polynomials of degree D. The natural logarithm is computed // using log(x) = log2(x)/log2(e) = log2(x)*log(2). namespace gte { template <typename Real> class LogEstimate { public: // The input constraint is x in [1,2]. For example, // float x; // in [1,2] // float result = LogEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return Log2Estimate<Real>::template Degree<D>(x) * (Real)GTE_C_LN_2; } // The input constraint is x > 0. Range reduction is used to generate // a value y in (0,1], call Degree(y), and add the exponent for the // power of two in the binary scientific representation of x. For // example, // float x; // x > 0 // float result = LogEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { return Log2Estimate<Real>::template DegreeRR<D>(x) * (Real)GTE_C_LN_2; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/PrimalQuery2.h
.h
13,374
401
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector2.h> // Queries about the relation of a point to various geometric objects. The // choices for N when using UIntegerFP32<N> for either BSNumber of BSRational // are determined in GeometricTools/GTEngine/Tools/PrecisionCalculator. These // N-values are worst case scenarios. Your specific input data might require // much smaller N, in which case you can modify PrecisionCalculator to use the // BSPrecision(int32_t,int32_t,int32_t,bool) constructors. namespace gte { template <typename Real> class PrimalQuery2 { public: // The caller is responsible for ensuring that the array is not empty // before calling queries and that the indices passed to the queries // are valid. The class does no range checking. PrimalQuery2() : mNumVertices(0), mVertices(nullptr) { } PrimalQuery2(int32_t numVertices, Vector2<Real> const* vertices) : mNumVertices(numVertices), mVertices(vertices) { } // Member access. inline void Set(int32_t numVertices, Vector2<Real> const* vertices) { mNumVertices = numVertices; mVertices = vertices; } inline int32_t GetNumVertices() const { return mNumVertices; } inline Vector2<Real> const* GetVertices() const { return mVertices; } // In the following, point P refers to vertices[i] or 'test' and Vi // refers to vertices[vi]. // For a line with origin V0 and direction <V0,V1>, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+---- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 35 // double | BSRational | 263 int32_t ToLine(int32_t i, int32_t v0, int32_t v1) const { return ToLine(mVertices[i], v0, v1); } int32_t ToLine(Vector2<Real> const& test, int32_t v0, int32_t v1) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Real x0 = test[0] - vec0[0]; Real y0 = test[1] - vec0[1]; Real x1 = vec1[0] - vec0[0]; Real y1 = vec1[1] - vec0[1]; Real x0y1 = x0 * y1; Real x1y0 = x1 * y0; Real det = x0y1 - x1y0; Real const zero(0); return (det > zero ? +1 : (det < zero ? -1 : 0)); } // For a line with origin V0 and direction <V0,V1>, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line // The 'order' parameter is // -3, points not collinear, P on left of line // -2, P strictly left of V0 on the line // -1, P = V0 // 0, P interior to line segment [V0,V1] // +1, P = V1 // +2, P strictly right of V0 on the line // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+---- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 35 // double | BSRational | 263 // This is the same as the first-listed ToLine calls because the // worst-case path has the same computational complexity. int32_t ToLine(int32_t i, int32_t v0, int32_t v1, int32_t& order) const { return ToLine(mVertices[i], v0, v1, order); } int32_t ToLine(Vector2<Real> const& test, int32_t v0, int32_t v1, int32_t& order) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Real x0 = test[0] - vec0[0]; Real y0 = test[1] - vec0[1]; Real x1 = vec1[0] - vec0[0]; Real y1 = vec1[1] - vec0[1]; Real x0y1 = x0 * y1; Real x1y0 = x1 * y0; Real det = x0y1 - x1y0; Real const zero(0); if (det > zero) { order = +3; return +1; } if (det < zero) { order = -3; return -1; } Real x0x1 = x0 * x1; Real y0y1 = y0 * y1; Real dot = x0x1 + y0y1; if (dot == zero) { order = -1; } else if (dot < zero) { order = -2; } else { Real x0x0 = x0 * x0; Real y0y0 = y0 * y0; Real sqrLength = x0x0 + y0y0; if (dot == sqrLength) { order = +1; } else if (dot > sqrLength) { order = +2; } else { order = 0; } } return 0; } // For a triangle with counterclockwise vertices V0, V1, and V2, // ToTriangle returns // +1, P outside triangle // -1, P inside triangle // 0, P on triangle // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+----- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 35 // double | BSRational | 263 // The query involves three calls to ToLine, so the numbers match // those of ToLine. int32_t ToTriangle(int32_t i, int32_t v0, int32_t v1, int32_t v2) const { return ToTriangle(mVertices[i], v0, v1, v2); } int32_t ToTriangle(Vector2<Real> const& test, int32_t v0, int32_t v1, int32_t v2) const { int32_t sign0 = ToLine(test, v1, v2); if (sign0 > 0) { return +1; } int32_t sign1 = ToLine(test, v0, v2); if (sign1 < 0) { return +1; } int32_t sign2 = ToLine(test, v0, v1); if (sign2 > 0) { return +1; } return ((sign0 && sign1 && sign2) ? -1 : 0); } // For a triangle with counterclockwise vertices V0, V1, and V2, // ToCircumcircle returns // +1, P outside circumcircle of triangle // -1, P inside circumcircle of triangle // 0, P on circumcircle of triangle // // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+---- // float | BSNumber | 35 // double | BSNumber | 263 // float | BSRational | 105 // double | BSRational | 788 // The query involves three calls of ToLine, so the numbers match // those of ToLine. int32_t ToCircumcircle(int32_t i, int32_t v0, int32_t v1, int32_t v2) const { return ToCircumcircle(mVertices[i], v0, v1, v2); } int32_t ToCircumcircle(Vector2<Real> const& test, int32_t v0, int32_t v1, int32_t v2) const { Vector2<Real> const& vec0 = mVertices[v0]; Vector2<Real> const& vec1 = mVertices[v1]; Vector2<Real> const& vec2 = mVertices[v2]; Real x0 = vec0[0] - test[0]; Real y0 = vec0[1] - test[1]; Real s00 = vec0[0] + test[0]; Real s01 = vec0[1] + test[1]; Real t00 = s00 * x0; Real t01 = s01 * y0; Real z0 = t00 + t01; Real x1 = vec1[0] - test[0]; Real y1 = vec1[1] - test[1]; Real s10 = vec1[0] + test[0]; Real s11 = vec1[1] + test[1]; Real t10 = s10 * x1; Real t11 = s11 * y1; Real z1 = t10 + t11; Real x2 = vec2[0] - test[0]; Real y2 = vec2[1] - test[1]; Real s20 = vec2[0] + test[0]; Real s21 = vec2[1] + test[1]; Real t20 = s20 * x2; Real t21 = s21 * y2; Real z2 = t20 + t21; Real y0z1 = y0 * z1; Real y0z2 = y0 * z2; Real y1z0 = y1 * z0; Real y1z2 = y1 * z2; Real y2z0 = y2 * z0; Real y2z1 = y2 * z1; Real c0 = y1z2 - y2z1; Real c1 = y2z0 - y0z2; Real c2 = y0z1 - y1z0; Real x0c0 = x0 * c0; Real x1c1 = x1 * c1; Real x2c2 = x2 * c2; Real term = x0c0 + x1c1; Real det = term + x2c2; Real const zero(0); return (det < zero ? 1 : (det > zero ? -1 : 0)); } // An extended classification of the relationship of a point to a line // segment. For noncollinear points, the return value is // OrderType::POSITIVE when <P,Q0,Q1> is a counterclockwise triangle // OrderType::NEGATIVE when <P,Q0,Q1> is a clockwise triangle // For collinear points, the line direction is Q1-Q0. The return // value is // OrderType::COLLINEAR_LEFT when the line ordering is <P,Q0,Q1> // OrderType::COLLINEAR_RIGHT when the line ordering is <Q0,Q1,P> // OrderType::COLLINEAR_CONTAIN when the line ordering is <Q0,P,Q1> enum class OrderType { Q0_EQUALS_Q1, P_EQUALS_Q0, P_EQUALS_Q1, POSITIVE, NEGATIVE, COLLINEAR_LEFT, COLLINEAR_RIGHT, COLLINEAR_CONTAIN }; // Choice of N for UIntegerFP32<N>. // input type | compute type | N // -----------+--------------+---- // float | BSNumber | 18 // double | BSNumber | 132 // float | BSRational | 35 // double | BSRational | 263 // This is the same as the first-listed ToLine calls because the // worst-case path has the same computational complexity. OrderType ToLineExtended(Vector2<Real> const& P, Vector2<Real> const& Q0, Vector2<Real> const& Q1) const { Real const zero(0); Real x0 = Q1[0] - Q0[0]; Real y0 = Q1[1] - Q0[1]; if (x0 == zero && y0 == zero) { return OrderType::Q0_EQUALS_Q1; } Real x1 = P[0] - Q0[0]; Real y1 = P[1] - Q0[1]; if (x1 == zero && y1 == zero) { return OrderType::P_EQUALS_Q0; } Real x2 = P[0] - Q1[0]; Real y2 = P[1] - Q1[1]; if (x2 == zero && y2 == zero) { return OrderType::P_EQUALS_Q1; } // The theoretical classification relies on computing exactly the // sign of the determinant. Numerical roundoff errors can cause // misclassification. Real x0y1 = x0 * y1; Real x1y0 = x1 * y0; Real det = x0y1 - x1y0; if (det != zero) { if (det > zero) { // The points form a counterclockwise triangle <P,Q0,Q1>. return OrderType::POSITIVE; } else { // The points form a clockwise triangle <P,Q1,Q0>. return OrderType::NEGATIVE; } } else { // The points are collinear; P is on the line through // Q0 and Q1. Real x0x1 = x0 * x1; Real y0y1 = y0 * y1; Real dot = x0x1 + y0y1; if (dot < zero) { // The line ordering is <P,Q0,Q1>. return OrderType::COLLINEAR_LEFT; } Real x0x0 = x0 * x0; Real y0y0 = y0 * y0; Real sqrLength = x0x0 + y0y0; if (dot > sqrLength) { // The line ordering is <Q0,Q1,P>. return OrderType::COLLINEAR_RIGHT; } // The line ordering is <Q0,P,Q1> with P strictly between // Q0 and Q1. return OrderType::COLLINEAR_CONTAIN; } } private: int32_t mNumVertices; Vector2<Real> const* mVertices; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ImplicitSurface3.h
.h
5,198
141
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.3.2022.06.29 #pragma once // The surface is defined by F(x,y,z) = 0. In all member functions it is // the application's responsibility to ensure that (x,y,z) is a solution // to F = 0. The class is abstract, so you must derive from it and // implement the function and derivative evaluations. // // The computation of principal curvature and principal directions is based // on the document // https://www.geometrictools.com/Documentation/PrincipalCurvature.pdf #include <Mathematics/Matrix2x2.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/SymmetricEigensolver2x2.h> namespace gte { template <typename T> class ImplicitSurface3 { public: // Abstract base class. virtual ~ImplicitSurface3() = default; // Evaluate the implicit function. virtual T F(Vector3<T> const& position) const = 0; // Evaluate the first-order partial derivatives. virtual T FX(Vector3<T> const& position) const = 0; virtual T FY(Vector3<T> const& position) const = 0; virtual T FZ(Vector3<T> const& position) const = 0; // Evaluate the second-order partial derivatives. virtual T FXX(Vector3<T> const& position) const = 0; virtual T FXY(Vector3<T> const& position) const = 0; virtual T FXZ(Vector3<T> const& position) const = 0; virtual T FYY(Vector3<T> const& position) const = 0; virtual T FYZ(Vector3<T> const& position) const = 0; virtual T FZZ(Vector3<T> const& position) const = 0; // Verify the point is on the surface within the tolerance specified // by epsilon. bool IsOnSurface(Vector3<T> const& position, T const& epsilon) const { return std::fabs(F(position)) <= epsilon; } // Compute all first-order derivatives. Vector3<T> GetGradient(Vector3<T> const& position) const { T fx = FX(position); T fy = FY(position); T fz = FZ(position); return Vector3<T>{ fx, fy, fz }; } // Compute all second-order derivatives. Matrix3x3<T> GetHessian(Vector3<T> const& position) const { T fxx = FXX(position); T fxy = FXY(position); T fxz = FXZ(position); T fyy = FYY(position); T fyz = FYZ(position); T fzz = FZZ(position); return Matrix3x3<T>{ fxx, fxy, fxz, fxy, fyy, fyz, fxz, fyz, fzz }; } // Compute a coordinate frame. The set {T0,T1,N} is a right-handed // orthonormal basis. void GetFrame(Vector3<T> const& position, Vector3<T>& tangent0, Vector3<T>& tangent1, Vector3<T>& normal) const { std::array<Vector3<T>, 3> basis{}; basis[0] = GetGradient(position); ComputeOrthogonalComplement(1, basis.data()); tangent0 = basis[1]; tangent1 = basis[2]; normal = basis[0]; } // Differential geometric quantities. The returned scalars are the // principal curvatures and the returned vectors are the corresponding // principal directions. bool GetPrincipalInformation(Vector3<T> const& position, T& curvature0, T& curvature1, Vector3<T>& direction0, Vector3<T>& direction1) const { // Compute the normal N. T const zero = static_cast<T>(0); Vector3<T> normal = GetGradient(position); T gradientLength = Normalize(normal); if (gradientLength == zero) { curvature0 = zero; curvature1 = zero; direction0.MakeZero(); direction1.MakeZero(); return false; } // Compute the matrix A. Matrix3x3<T> A = GetHessian(position) / gradientLength; // Solve for the eigensystem of equation (8) of the PDF referenced // at the top of this file. std::array<Vector3<T>, 3> basis{}; basis[0] = normal; ComputeOrthogonalComplement(1, basis.data()); // basis[1] = tangent0 // basis[2] = tangent1 Matrix<3, 2, T> J{}; J.SetCol(0, basis[1]); J.SetCol(1, basis[2]); Matrix2x2<T> barA = MultiplyATB(J, A * J); SymmetricEigensolver2x2<T> eigensolver{}; std::array<T, 2> eval{}; std::array<std::array<T, 2>, 2> evec{}; eigensolver(barA(0, 0), barA(0, 1), barA(1, 1), +1, eval, evec); curvature0 = eval[0]; curvature1 = eval[1]; Vector2<T> v0 = { evec[0][0], evec[0][1] }; Vector2<T> v1 = { evec[1][0], evec[1][1] }; direction0 = J * v0; direction1 = J * v1; return true; } protected: ImplicitSurface3() = default; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BoxManager.h
.h
11,987
281
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.05.16 #pragma once #include <Mathematics/IntrAlignedBox3AlignedBox3.h> #include <Mathematics/EdgeKey.h> #include <set> #include <vector> namespace gte { template <typename Real> class BoxManager { public: // Construction. BoxManager(std::vector<AlignedBox3<Real>>& boxes) : mBoxes(boxes) { Initialize(); } // No default construction, copy construction, or assignment are // allowed. BoxManager() = delete; BoxManager(BoxManager const&) = delete; BoxManager& operator=(BoxManager const&) = delete; // This function is called by the constructor and does the // sort-and-sweep to initialize the update system. However, if you // add or remove items from the array of boxes after the constructor // call, you will need to call this function once before you start the // multiple calls of the update function. void Initialize() { // Get the box endpoints. int32_t intrSize = static_cast<int32_t>(mBoxes.size()), endpSize = 2 * intrSize; mXEndpoints.resize(endpSize); mYEndpoints.resize(endpSize); mZEndpoints.resize(endpSize); for (int32_t i = 0, j = 0; i < intrSize; ++i) { mXEndpoints[j].type = 0; mXEndpoints[j].value = mBoxes[i].min[0]; mXEndpoints[j].index = i; mYEndpoints[j].type = 0; mYEndpoints[j].value = mBoxes[i].min[1]; mYEndpoints[j].index = i; mZEndpoints[j].type = 0; mZEndpoints[j].value = mBoxes[i].min[2]; mZEndpoints[j].index = i; ++j; mXEndpoints[j].type = 1; mXEndpoints[j].value = mBoxes[i].max[0]; mXEndpoints[j].index = i; mYEndpoints[j].type = 1; mYEndpoints[j].value = mBoxes[i].max[1]; mYEndpoints[j].index = i; mZEndpoints[j].type = 1; mZEndpoints[j].value = mBoxes[i].max[2]; mZEndpoints[j].index = i; ++j; } // Sort the box endpoints. std::sort(mXEndpoints.begin(), mXEndpoints.end()); std::sort(mYEndpoints.begin(), mYEndpoints.end()); std::sort(mZEndpoints.begin(), mZEndpoints.end()); // Create the interval-to-endpoint lookup tables. mXLookup.resize(endpSize); mYLookup.resize(endpSize); mZLookup.resize(endpSize); for (int32_t j = 0; j < endpSize; ++j) { mXLookup[2 * static_cast<size_t>(mXEndpoints[j].index) + static_cast<size_t>(mXEndpoints[j].type)] = j; mYLookup[2 * static_cast<size_t>(mYEndpoints[j].index) + static_cast<size_t>(mYEndpoints[j].type)] = j; mZLookup[2 * static_cast<size_t>(mZEndpoints[j].index) + static_cast<size_t>(mZEndpoints[j].type)] = j; } // Active set of boxes (stored by index in array). std::set<int32_t> active; // Set of overlapping boxes (stored by pairs of indices in // array). mOverlap.clear(); // Sweep through the endpoints to determine overlapping // x-intervals. for (int32_t i = 0; i < endpSize; ++i) { Endpoint const& endpoint = mXEndpoints[i]; int32_t index = endpoint.index; if (endpoint.type == 0) // an interval 'begin' value { // In the 1D problem, the current interval overlaps with // all the active intervals. In 3D we also need to check // for y-overlap and z-overlap. for (auto activeIndex : active) { // Rectangles activeIndex and index overlap in the // x-dimension. Test for overlap in the y-dimension // and z-dimension. AlignedBox3<Real> const& b0 = mBoxes[activeIndex]; AlignedBox3<Real> const& b1 = mBoxes[index]; if (b0.max[1] >= b1.min[1] && b0.min[1] <= b1.max[1] && b0.max[2] >= b1.min[2] && b0.min[2] <= b1.max[2]) { if (activeIndex < index) { mOverlap.insert(EdgeKey<false>(activeIndex, index)); } else { mOverlap.insert(EdgeKey<false>(index, activeIndex)); } } } active.insert(index); } else // an interval 'end' value { active.erase(index); } } } // After the system is initialized, you can move the boxes using this // function. It is not enough to modify the input array of boxes // because the endpoint values stored internally by this class must // also change. You can also retrieve the current boxes // information. void SetBox(int32_t i, AlignedBox3<Real> const& box) { mBoxes[i] = box; size_t twoI = 2 * static_cast<size_t>(i); mXEndpoints[mXLookup[twoI]].value = box.min[0]; mXEndpoints[mXLookup[twoI + 1]].value = box.max[0]; mYEndpoints[mYLookup[twoI]].value = box.min[1]; mYEndpoints[mYLookup[twoI + 1]].value = box.max[1]; mZEndpoints[mZLookup[twoI]].value = box.min[2]; mZEndpoints[mZLookup[twoI + 1]].value = box.max[2]; } inline void GetBox(int32_t i, AlignedBox3<Real>& box) const { box = mBoxes[i]; } // When you are finished moving boxes, call this function to determine // the overlapping boxes. An incremental update is applied to // determine the new set of overlapping boxes. void Update() { InsertionSort(mXEndpoints, mXLookup); InsertionSort(mYEndpoints, mYLookup); InsertionSort(mZEndpoints, mZLookup); } // If (i,j) is in the overlap set, then box i and box j are // overlapping. The indices are those for the the input array. The // set elements (i,j) are stored so that i < j. inline std::set<EdgeKey<false>> const& GetOverlap() const { return mOverlap; } private: class Endpoint { public: Real value; // endpoint value int32_t type; // '0' if interval min, '1' if interval max. int32_t index; // index of interval containing this endpoint // Support for sorting of endpoints. bool operator<(Endpoint const& endpoint) const { if (value < endpoint.value) { return true; } if (value > endpoint.value) { return false; } return type < endpoint.type; } }; void InsertionSort(std::vector<Endpoint>& endpoint, std::vector<int32_t>& lookup) { // Apply an insertion sort. Under the assumption that the // boxes have not changed much since the last call, the // endpoints are nearly sorted. The insertion sort should be very // fast in this case. TIQuery<Real, AlignedBox3<Real>, AlignedBox3<Real>> query; int32_t endpSize = static_cast<int32_t>(endpoint.size()); for (int32_t j = 1; j < endpSize; ++j) { Endpoint key = endpoint[j]; int32_t i = j - 1; while (i >= 0 && key < endpoint[i]) { Endpoint e0 = endpoint[i]; Endpoint e1 = endpoint[static_cast<size_t>(i) + 1]; // Update the overlap status. if (e0.type == 0) { if (e1.type == 1) { // The 'b' of interval E0.mIndex was smaller than // the 'e' of interval E1.mIndex, and the // intervals *might have been* overlapping. Now // 'b' and 'e' are swapped, and the intervals // cannot overlap. Remove the pair from the // overlap set. The removal operation needs to // find the pair and erase it if it exists. // Finding the pair is the expensive part of the // operation, so there is no real time savings in // testing for existence first, then deleting if // it does. mOverlap.erase(EdgeKey<false>(e0.index, e1.index)); } } else { if (e1.type == 0) { // The 'b' of interval E1.index was larger than // the 'e' of interval E0.index, and the intervals // were not overlapping. Now 'b' and 'e' are // swapped, and the intervals *might be* // overlapping. Determine if they are overlapping // and then insert. if (query(mBoxes[e0.index], mBoxes[e1.index]).intersect) { mOverlap.insert(EdgeKey<false>(e0.index, e1.index)); } } } // Reorder the items to maintain the sorted list. endpoint[i] = e1; endpoint[static_cast<size_t>(i) + 1] = e0; lookup[2 * static_cast<size_t>(e1.index) + static_cast<size_t>(e1.type)] = i; lookup[2 * static_cast<size_t>(e0.index) + static_cast<size_t>(e0.type)] = i + 1; --i; } endpoint[static_cast<size_t>(i) + 1] = key; lookup[2 * static_cast<size_t>(key.index) + static_cast<size_t>(key.type)] = i + 1; } } std::vector<AlignedBox3<Real>>& mBoxes; std::vector<Endpoint> mXEndpoints, mYEndpoints, mZEndpoints; std::set<EdgeKey<false>> mOverlap; // The intervals are indexed 0 <= i < n. The endpoint array has 2*n // entries. The original 2*n interval values are ordered as // b[0], e[0], b[1], e[1], ..., b[n-1], e[n-1] // When the endpoint array is sorted, the mapping between interval // values and endpoints is lost. In order to modify interval values // that are stored in the endpoint array, we need to maintain the // mapping. This is done by the following lookup table of 2*n // entries. The value mLookup[2*i] is the index of b[i] in the // endpoint array. The value mLookup[2*i+1] is the index of e[i] // in the endpoint array. std::vector<int32_t> mXLookup, mYLookup, mZLookup; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Rotation.h
.h
33,991
842
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/AxisAngle.h> #include <Mathematics/EulerAngles.h> #include <Mathematics/Matrix.h> #include <Mathematics/Quaternion.h> namespace gte { // Conversions among various representations of rotations. The value of // N must be 3 or 4. The latter case supports affine algebra when you use // 4-tuple vectors (w-component is 1 for points and 0 for vector) and 4x4 // matrices for affine transformations. Rotation axes must be unit // length. The angles are in radians. The Euler angles are in world // coordinates; we have not yet added support for body coordinates. template <int32_t N, typename Real> class Rotation { public: // Create rotations from various representations. Rotation(Matrix<N, N, Real> const& matrix) : mType(Type::IS_MATRIX), mMatrix(matrix), mQuaternion{}, mAxisAngle{}, mEulerAngles{} { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); } Rotation(Quaternion<Real> const& quaternion) : mType(Type::IS_QUATERNION), mMatrix{}, mQuaternion(quaternion), mAxisAngle{}, mEulerAngles{} { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); } Rotation(AxisAngle<N, Real> const& axisAngle) : mType(Type::IS_AXIS_ANGLE), mMatrix{}, mQuaternion{}, mAxisAngle(axisAngle), mEulerAngles{} { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); } Rotation(EulerAngles<Real> const& eulerAngles) : mType(Type::IS_EULER_ANGLES), mMatrix{}, mQuaternion{}, mAxisAngle{}, mEulerAngles(eulerAngles) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); } // Convert one representation to another. operator Matrix<N, N, Real>() const { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); switch (mType) { case Type::IS_MATRIX: break; case Type::IS_QUATERNION: Convert(mQuaternion, mMatrix); break; case Type::IS_AXIS_ANGLE: Convert(mAxisAngle, mMatrix); break; case Type::IS_EULER_ANGLES: Convert(mEulerAngles, mMatrix); break; } return mMatrix; } operator Quaternion<Real>() const { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); switch (mType) { case Type::IS_MATRIX: Convert(mMatrix, mQuaternion); break; case Type::IS_QUATERNION: break; case Type::IS_AXIS_ANGLE: Convert(mAxisAngle, mQuaternion); break; case Type::IS_EULER_ANGLES: Convert(mEulerAngles, mQuaternion); break; } return mQuaternion; } operator AxisAngle<N, Real>() const { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); switch (mType) { case Type::IS_MATRIX: Convert(mMatrix, mAxisAngle); break; case Type::IS_QUATERNION: Convert(mQuaternion, mAxisAngle); break; case Type::IS_AXIS_ANGLE: break; case Type::IS_EULER_ANGLES: Convert(mEulerAngles, mAxisAngle); break; } return mAxisAngle; } EulerAngles<Real> const& operator()(int32_t i0, int32_t i1, int32_t i2) const { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); mEulerAngles.axis[0] = i0; mEulerAngles.axis[1] = i1; mEulerAngles.axis[2] = i2; switch (mType) { case Type::IS_MATRIX: Convert(mMatrix, mEulerAngles); break; case Type::IS_QUATERNION: Convert(mQuaternion, mEulerAngles); break; case Type::IS_AXIS_ANGLE: Convert(mAxisAngle, mEulerAngles); break; case Type::IS_EULER_ANGLES: break; } return mEulerAngles; } private: enum class Type { IS_MATRIX, IS_QUATERNION, IS_AXIS_ANGLE, IS_EULER_ANGLES }; Type mType; mutable Matrix<N, N, Real> mMatrix; mutable Quaternion<Real> mQuaternion; mutable AxisAngle<N, Real> mAxisAngle; mutable EulerAngles<Real> mEulerAngles; // Convert a rotation matrix to a quaternion. // // x^2 = (+r00 - r11 - r22 + 1)/4 // y^2 = (-r00 + r11 - r22 + 1)/4 // z^2 = (-r00 - r11 + r22 + 1)/4 // w^2 = (+r00 + r11 + r22 + 1)/4 // x^2 + y^2 = (1 - r22)/2 // z^2 + w^2 = (1 + r22)/2 // y^2 - x^2 = (r11 - r00)/2 // w^2 - z^2 = (r11 + r00)/2 // x*y = (r01 + r10)/4 // x*z = (r02 + r20)/4 // y*z = (r12 + r21)/4 // [GTE_USE_MAT_VEC] // x*w = (r21 - r12)/4 // y*w = (r02 - r20)/4 // z*w = (r10 - r01)/4 // [GTE_USE_VEC_MAT] // x*w = (r12 - r21)/4 // y*w = (r20 - r02)/4 // z*w = (r01 - r10)/4 // // If Q is the 4x1 column vector (x,y,z,w), the previous equations // give us // +- -+ // | x*x x*y x*z x*w | // Q*Q^T = | y*x y*y y*z y*w | // | z*x z*y z*z z*w | // | w*x w*y w*z w*w | // +- -+ // The code extracts the row of maximum length, normalizing it to // obtain the result q. static void Convert(Matrix<N, N, Real> const& r, Quaternion<Real>& q) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Real r22 = r(2, 2); if (r22 <= (Real)0) // x^2 + y^2 >= z^2 + w^2 { Real dif10 = r(1, 1) - r(0, 0); Real omr22 = (Real)1 - r22; if (dif10 <= (Real)0) // x^2 >= y^2 { Real fourXSqr = omr22 - dif10; Real inv4x = ((Real)0.5) / std::sqrt(fourXSqr); q[0] = fourXSqr * inv4x; q[1] = (r(0, 1) + r(1, 0)) * inv4x; q[2] = (r(0, 2) + r(2, 0)) * inv4x; #if defined(GTE_USE_MAT_VEC) q[3] = (r(2, 1) - r(1, 2)) * inv4x; #else q[3] = (r(1, 2) - r(2, 1)) * inv4x; #endif } else // y^2 >= x^2 { Real fourYSqr = omr22 + dif10; Real inv4y = ((Real)0.5) / std::sqrt(fourYSqr); q[0] = (r(0, 1) + r(1, 0)) * inv4y; q[1] = fourYSqr * inv4y; q[2] = (r(1, 2) + r(2, 1)) * inv4y; #if defined(GTE_USE_MAT_VEC) q[3] = (r(0, 2) - r(2, 0)) * inv4y; #else q[3] = (r(2, 0) - r(0, 2)) * inv4y; #endif } } else // z^2 + w^2 >= x^2 + y^2 { Real sum10 = r(1, 1) + r(0, 0); Real opr22 = (Real)1 + r22; if (sum10 <= (Real)0) // z^2 >= w^2 { Real fourZSqr = opr22 - sum10; Real inv4z = ((Real)0.5) / std::sqrt(fourZSqr); q[0] = (r(0, 2) + r(2, 0)) * inv4z; q[1] = (r(1, 2) + r(2, 1)) * inv4z; q[2] = fourZSqr * inv4z; #if defined(GTE_USE_MAT_VEC) q[3] = (r(1, 0) - r(0, 1)) * inv4z; #else q[3] = (r(0, 1) - r(1, 0)) * inv4z; #endif } else // w^2 >= z^2 { Real fourWSqr = opr22 + sum10; Real inv4w = ((Real)0.5) / std::sqrt(fourWSqr); #if defined(GTE_USE_MAT_VEC) q[0] = (r(2, 1) - r(1, 2)) * inv4w; q[1] = (r(0, 2) - r(2, 0)) * inv4w; q[2] = (r(1, 0) - r(0, 1)) * inv4w; #else q[0] = (r(1, 2) - r(2, 1)) * inv4w; q[1] = (r(2, 0) - r(0, 2)) * inv4w; q[2] = (r(0, 1) - r(1, 0)) * inv4w; #endif q[3] = fourWSqr * inv4w; } } } // Convert a quaterion q = x*i + y*j + z*k + w to a rotation matrix. // [GTE_USE_MAT_VEC] // +- -+ +- -+ // R = | r00 r01 r02 | = | 1-2y^2-2z^2 2(xy-zw) 2(xz+yw) | // | r10 r11 r12 | | 2(xy+zw) 1-2x^2-2z^2 2(yz-xw) | // | r20 r21 r22 | | 2(xz-yw) 2(yz+xw) 1-2x^2-2y^2 | // +- -+ +- -+ // [GTE_USE_VEC_MAT] // +- -+ +- -+ // R = | r00 r01 r02 | = | 1-2y^2-2z^2 2(xy+zw) 2(xz-yw) | // | r10 r11 r12 | | 2(xy-zw) 1-2x^2-2z^2 2(yz+xw) | // | r20 r21 r22 | | 2(xz+yw) 2(yz-xw) 1-2x^2-2y^2 | // +- -+ +- -+ static void Convert(Quaternion<Real> const& q, Matrix<N, N, Real>& r) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); r.MakeIdentity(); Real twoX = ((Real)2) * q[0]; Real twoY = ((Real)2) * q[1]; Real twoZ = ((Real)2) * q[2]; Real twoXX = twoX * q[0]; Real twoXY = twoX * q[1]; Real twoXZ = twoX * q[2]; Real twoXW = twoX * q[3]; Real twoYY = twoY * q[1]; Real twoYZ = twoY * q[2]; Real twoYW = twoY * q[3]; Real twoZZ = twoZ * q[2]; Real twoZW = twoZ * q[3]; #if defined(GTE_USE_MAT_VEC) r(0, 0) = (Real)1 - twoYY - twoZZ; r(0, 1) = twoXY - twoZW; r(0, 2) = twoXZ + twoYW; r(1, 0) = twoXY + twoZW; r(1, 1) = (Real)1 - twoXX - twoZZ; r(1, 2) = twoYZ - twoXW; r(2, 0) = twoXZ - twoYW; r(2, 1) = twoYZ + twoXW; r(2, 2) = (Real)1 - twoXX - twoYY; #else r(0, 0) = (Real)1 - twoYY - twoZZ; r(1, 0) = twoXY - twoZW; r(2, 0) = twoXZ + twoYW; r(0, 1) = twoXY + twoZW; r(1, 1) = (Real)1 - twoXX - twoZZ; r(2, 1) = twoYZ - twoXW; r(0, 2) = twoXZ - twoYW; r(1, 2) = twoYZ + twoXW; r(2, 2) = (Real)1 - twoXX - twoYY; #endif } // Convert a rotation matrix to an axis-angle pair. Let (x0,x1,x2) be // the axis let t be an angle of rotation. The rotation matrix is // [GTE_USE_MAT_VEC] // R = I + sin(t)*S + (1-cos(t))*S^2 // or // [GTE_USE_VEC_MAT] // R = I - sin(t)*S + (1-cos(t))*S^2 // where I is the identity and S = {{0,-x2,x1},{x2,0,-x0},{-x1,x0,0}} // where the inner-brace triples are the rows of the matrix. If // t > 0, R represents a counterclockwise rotation; see the comments // for the constructor Matrix3x3(axis,angle). It may be shown that // cos(t) = (trace(R)-1)/2 and R - Transpose(R) = 2*sin(t)*S. As long // as sin(t) is not zero, we may solve for S in the second equation, // which produces the axis direction U = (S21,S02,S10). When t = 0, // the rotation is the identity, in which case any axis direction is // valid; we choose (1,0,0). When t = pi, it must be that // R - Transpose(R) = 0, which prevents us from extracting the axis. // Instead, note that (R+I)/2 = I+S^2 = U*U^T, where U is a // unit-length axis direction. static void Convert(Matrix<N, N, Real> const& r, AxisAngle<N, Real>& a) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Real trace = r(0, 0) + r(1, 1) + r(2, 2); Real half = (Real)0.5; Real cs = half * (trace - (Real)1); cs = std::max(std::min(cs, (Real)1), (Real)-1); a.angle = std::acos(cs); // The angle is in [0,pi]. a.axis.MakeZero(); if (a.angle > (Real)0) { if (a.angle < (Real)GTE_C_PI) { // The angle is in (0,pi). #if defined(GTE_USE_MAT_VEC) a.axis[0] = r(2, 1) - r(1, 2); a.axis[1] = r(0, 2) - r(2, 0); a.axis[2] = r(1, 0) - r(0, 1); Normalize(a.axis); #else a.axis[0] = r(1, 2) - r(2, 1); a.axis[1] = r(2, 0) - r(0, 2); a.axis[2] = r(0, 1) - r(1, 0); Normalize(a.axis); #endif } else { // The angle is pi, in which case R is symmetric and // R+I = 2*(I+S^2) = 2*U*U^T, where U = (u0,u1,u2) is the // unit-length direction of the rotation axis. Determine // the largest diagonal entry of R+I and normalize the // corresponding row to produce U. It does not matter the // sign on u[d] for chosen diagonal d, because // R(U,pi) = R(-U,pi). Real one = (Real)1; if (r(0, 0) >= r(1, 1)) { if (r(0, 0) >= r(2, 2)) { // r00 is maximum diagonal term a.axis[0] = r(0, 0) + one; a.axis[1] = half * (r(0, 1) + r(1, 0)); a.axis[2] = half * (r(0, 2) + r(2, 0)); } else { // r22 is maximum diagonal term a.axis[0] = half * (r(2, 0) + r(0, 2)); a.axis[1] = half * (r(2, 1) + r(1, 2)); a.axis[2] = r(2, 2) + one; } } else { if (r(1, 1) >= r(2, 2)) { // r11 is maximum diagonal term a.axis[0] = half * (r(1, 0) + r(0, 1)); a.axis[1] = r(1, 1) + one; a.axis[2] = half * (r(1, 2) + r(2, 1)); } else { // r22 is maximum diagonal term a.axis[0] = half * (r(2, 0) + r(0, 2)); a.axis[1] = half * (r(2, 1) + r(1, 2)); a.axis[2] = r(2, 2) + one; } } Normalize(a.axis); } } else { // The angle is 0 and the matrix is the identity. Any axis // will work, so choose the Unit(0) axis. a.axis[0] = (Real)1; } } // Convert an axis-angle pair to a rotation matrix. Assuming // (x0,x1,x2) is for a right-handed world (x0 to right, x1 up, x2 out // of plane of page), a positive angle corresponds to a // counterclockwise rotation from the perspective of an observer // looking at the origin of the plane of rotation and having view // direction the negative of the axis direction. The coordinate-axis // rotations are the following, where unit(0) = (1,0,0), // unit(1) = (0,1,0), unit(2) = (0,0,1), // [GTE_USE_MAT_VEC] // R(unit(0),t) = {{ 1, 0, 0}, { 0, c,-s}, { 0, s, c}} // R(unit(1),t) = {{ c, 0, s}, { 0, 1, 0}, {-s, 0, c}} // R(unit(2),t) = {{ c,-s, 0}, { s, c, 0}, { 0, 0, 1}} // or // [GTE_USE_VEC_MAT] // R(unit(0),t) = {{ 1, 0, 0}, { 0, c, s}, { 0,-s, c}} // R(unit(1),t) = {{ c, 0,-s}, { 0, 1, 0}, { s, 0, c}} // R(unit(2),t) = {{ c, s, 0}, {-s, c, 0}, { 0, 0, 1}} // where c = cos(t), s = sin(t), and the inner-brace triples are rows // of the matrix. The general matrix is // [GTE_USE_MAT_VEC] // +- -+ // R = | (1-c)*x0^2 + c (1-c)*x0*x1 - s*x2 (1-c)*x0*x2 + s*x1 | // | (1-c)*x0*x1 + s*x2 (1-c)*x1^2 + c (1-c)*x1*x2 - s*x0 | // | (1-c)*x0*x2 - s*x1 (1-c)*x1*x2 + s*x0 (1-c)*x2^2 + c | // +- -+ // [GTE_USE_VEC_MAT] // +- -+ // R = | (1-c)*x0^2 + c (1-c)*x0*x1 + s*x2 (1-c)*x0*x2 - s*x1 | // | (1-c)*x0*x1 - s*x2 (1-c)*x1^2 + c (1-c)*x1*x2 + s*x0 | // | (1-c)*x0*x2 + s*x1 (1-c)*x1*x2 - s*x0 (1-c)*x2^2 + c | // +- -+ static void Convert(AxisAngle<N, Real> const& a, Matrix<N, N, Real>& r) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); r.MakeIdentity(); Real cs = std::cos(a.angle); Real sn = std::sin(a.angle); Real oneMinusCos = ((Real)1) - cs; Real x0sqr = a.axis[0] * a.axis[0]; Real x1sqr = a.axis[1] * a.axis[1]; Real x2sqr = a.axis[2] * a.axis[2]; Real x0x1m = a.axis[0] * a.axis[1] * oneMinusCos; Real x0x2m = a.axis[0] * a.axis[2] * oneMinusCos; Real x1x2m = a.axis[1] * a.axis[2] * oneMinusCos; Real x0Sin = a.axis[0] * sn; Real x1Sin = a.axis[1] * sn; Real x2Sin = a.axis[2] * sn; #if defined(GTE_USE_MAT_VEC) r(0, 0) = x0sqr * oneMinusCos + cs; r(0, 1) = x0x1m - x2Sin; r(0, 2) = x0x2m + x1Sin; r(1, 0) = x0x1m + x2Sin; r(1, 1) = x1sqr * oneMinusCos + cs; r(1, 2) = x1x2m - x0Sin; r(2, 0) = x0x2m - x1Sin; r(2, 1) = x1x2m + x0Sin; r(2, 2) = x2sqr * oneMinusCos + cs; #else r(0, 0) = x0sqr * oneMinusCos + cs; r(1, 0) = x0x1m - x2Sin; r(2, 0) = x0x2m + x1Sin; r(0, 1) = x0x1m + x2Sin; r(1, 1) = x1sqr * oneMinusCos + cs; r(2, 1) = x1x2m - x0Sin; r(0, 2) = x0x2m - x1Sin; r(1, 2) = x1x2m + x0Sin; r(2, 2) = x2sqr * oneMinusCos + cs; #endif } // Convert a rotation matrix to Euler angles. Factorization into // Euler angles is not necessarily unique. If the result is // NOT_UNIQUE_SUM, then the multiple solutions occur because // angleN2+angleN0 is constant. If the result is NOT_UNIQUE_DIF, // then the multiple solutions occur because angleN2-angleN0 is // constant. In either type of nonuniqueness, the function returns // angleN0=0. static void Convert(Matrix<N, N, Real> const& r, EulerAngles<Real>& e) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); if (0 <= e.axis[0] && e.axis[0] < 3 && 0 <= e.axis[1] && e.axis[1] < 3 && 0 <= e.axis[2] && e.axis[2] < 3 && e.axis[1] != e.axis[0] && e.axis[1] != e.axis[2]) { if (e.axis[0] != e.axis[2]) { #if defined(GTE_USE_MAT_VEC) // Map (0,1,2), (1,2,0), and (2,0,1) to +1. // Map (0,2,1), (2,1,0), and (1,0,2) to -1. int32_t parity = (((e.axis[2] | (e.axis[1] << 2)) >> e.axis[0]) & 1); Real const sgn = (parity & 1 ? (Real)-1 : (Real)+1); if (r(e.axis[2], e.axis[0]) < (Real)1) { if (r(e.axis[2], e.axis[0]) > (Real)-1) { e.angle[2] = std::atan2(sgn * r(e.axis[1], e.axis[0]), r(e.axis[0], e.axis[0])); e.angle[1] = std::asin(-sgn * r(e.axis[2], e.axis[0])); e.angle[0] = std::atan2(sgn * r(e.axis[2], e.axis[1]), r(e.axis[2], e.axis[2])); e.result = EulerResult::UNIQUE; } else { e.angle[2] = (Real)0; e.angle[1] = sgn * (Real)GTE_C_HALF_PI; e.angle[0] = std::atan2(-sgn * r(e.axis[1], e.axis[2]), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_DIF; } } else { e.angle[2] = (Real)0; e.angle[1] = -sgn * (Real)GTE_C_HALF_PI; e.angle[0] = std::atan2(-sgn * r(e.axis[1], e.axis[2]), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_SUM; } #else // Map (0,1,2), (1,2,0), and (2,0,1) to +1. // Map (0,2,1), (2,1,0), and (1,0,2) to -1. int32_t parity = (((e.axis[0] | (e.axis[1] << 2)) >> e.axis[2]) & 1); Real const sgn = (parity & 1 ? (Real)+1 : (Real)-1); if (r(e.axis[0], e.axis[2]) < (Real)1) { if (r(e.axis[0], e.axis[2]) > (Real)-1) { e.angle[0] = std::atan2(sgn * r(e.axis[1], e.axis[2]), r(e.axis[2], e.axis[2])); e.angle[1] = std::asin(-sgn * r(e.axis[0], e.axis[2])); e.angle[2] = std::atan2(sgn * r(e.axis[0], e.axis[1]), r(e.axis[0], e.axis[0])); e.result = EulerResult::UNIQUE; } else { e.angle[0] = (Real)0; e.angle[1] = sgn * (Real)GTE_C_HALF_PI; e.angle[2] = std::atan2(-sgn * r(e.axis[1], e.axis[0]), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_DIF; } } else { e.angle[0] = (Real)0; e.angle[1] = -sgn * (Real)GTE_C_HALF_PI; e.angle[2] = std::atan2(-sgn * r(e.axis[1], e.axis[0]), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_SUM; } #endif } else { #if defined(GTE_USE_MAT_VEC) // Map (0,2,0), (1,0,1), and (2,1,2) to +1. // Map (0,1,0), (1,2,1), and (2,0,2) to -1. int32_t b0 = 3 - e.axis[1] - e.axis[2]; int32_t parity = (((b0 | (e.axis[1] << 2)) >> e.axis[2]) & 1); Real const sgn = (parity & 1 ? (Real)+1 : (Real)-1); if (r(e.axis[2], e.axis[2]) < (Real)1) { if (r(e.axis[2], e.axis[2]) > (Real)-1) { e.angle[2] = std::atan2(r(e.axis[1], e.axis[2]), sgn * r(b0, e.axis[2])); e.angle[1] = std::acos(r(e.axis[2], e.axis[2])); e.angle[0] = std::atan2(r(e.axis[2], e.axis[1]), -sgn * r(e.axis[2], b0)); e.result = EulerResult::UNIQUE; } else { e.angle[2] = (Real)0; e.angle[1] = (Real)GTE_C_PI; e.angle[0] = std::atan2(sgn * r(e.axis[1], b0), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_DIF; } } else { e.angle[2] = (Real)0; e.angle[1] = (Real)0; e.angle[0] = std::atan2(sgn * r(e.axis[1], b0), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_SUM; } #else // Map (0,2,0), (1,0,1), and (2,1,2) to -1. // Map (0,1,0), (1,2,1), and (2,0,2) to +1. int32_t b2 = 3 - e.axis[0] - e.axis[1]; int32_t parity = (((b2 | (e.axis[1] << 2)) >> e.axis[0]) & 1); Real const sgn = (parity & 1 ? (Real)-1 : (Real)+1); if (r(e.axis[0], e.axis[0]) < (Real)1) { if (r(e.axis[0], e.axis[0]) > (Real)-1) { e.angle[0] = std::atan2(r(e.axis[1], e.axis[0]), sgn * r(b2, e.axis[0])); e.angle[1] = std::acos(r(e.axis[0], e.axis[0])); e.angle[2] = std::atan2(r(e.axis[0], e.axis[1]), -sgn * r(e.axis[0], b2)); e.result = EulerResult::UNIQUE; } else { e.angle[0] = (Real)0; e.angle[1] = (Real)GTE_C_PI; e.angle[2] = std::atan2(sgn * r(e.axis[1], b2), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_DIF; } } else { e.angle[0] = (Real)0; e.angle[1] = (Real)0; e.angle[2] = std::atan2(sgn * r(e.axis[1], b2), r(e.axis[1], e.axis[1])); e.result = EulerResult::NOT_UNIQUE_SUM; } #endif } } else { // Invalid angles. e.angle[0] = (Real)0; e.angle[1] = (Real)0; e.angle[2] = (Real)0; e.result = EulerResult::INVALID; } } // Convert Euler angles to a rotation matrix. The three integer // inputs are in {0,1,2} and correspond to world directions // unit(0) = (1,0,0), unit(1) = (0,1,0), or unit(2) = (0,0,1). The // triples (N0,N1,N2) must be in the following set, // {(0,1,2),(0,2,1),(1,0,2),(1,2,0),(2,0,1),(2,1,0), // (0,1,0),(0,2,0),(1,0,1),(1,2,1),(2,0,2),(2,1,2)} // The rotation matrix is // [GTE_USE_MAT_VEC] // R(unit(N2),angleN2)*R(unit(N1),angleN1)*R(unit(N0),angleN0) // or // [GTE_USE_VEC_MAT] // R(unit(N0),angleN0)*R(unit(N1),angleN1)*R(unit(N2),angleN2) // The conventions of constructor Matrix3(axis,angle) apply here as // well. // // NOTE: The reversal of order is chosen so that a rotation matrix // built with one multiplication convention is the transpose of the // rotation matrix built with the other multiplication convention. // Thus, // [GTE_USE_MAT_VEC] // Matrix3x3<Real> R_mvconvention(N0,N1,N2,angleN0,angleN1,angleN2); // Vector3<Real> V(...); // Vector3<Real> U = R_mvconvention*V; // (u0,u1,u2) = R2*R1*R0*V // [GTE_USE_VEC_MAT] // Matrix3x3<Real> R_vmconvention(N0,N1,N2,angleN0,angleN1,angleN2); // Vector3<Real> V(...); // Vector3<Real> U = R_mvconvention*V; // (u0,u1,u2) = V*R0*R1*R2 // In either convention, you get the same 3-tuple U. static void Convert(EulerAngles<Real> const& e, Matrix<N, N, Real>& r) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); if (0 <= e.axis[0] && e.axis[0] < 3 && 0 <= e.axis[1] && e.axis[1] < 3 && 0 <= e.axis[2] && e.axis[2] < 3 && e.axis[1] != e.axis[0] && e.axis[1] != e.axis[2]) { Matrix<N, N, Real> r0, r1, r2; Convert(AxisAngle<N, Real>(Vector<N, Real>::Unit(e.axis[0]), e.angle[0]), r0); Convert(AxisAngle<N, Real>(Vector<N, Real>::Unit(e.axis[1]), e.angle[1]), r1); Convert(AxisAngle<N, Real>(Vector<N, Real>::Unit(e.axis[2]), e.angle[2]), r2); #if defined(GTE_USE_MAT_VEC) r = r2 * r1 * r0; #else r = r0 * r1 * r2; #endif } else { // Invalid angles. r.MakeIdentity(); } } // Convert a quaternion to an axis-angle pair, where // q = sin(angle/2)*(axis[0]*i+axis[1]*j+axis[2]*k)+cos(angle/2) static void Convert(Quaternion<Real> const& q, AxisAngle<N, Real>& a) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); a.axis.MakeZero(); Real axisSqrLen = q[0] * q[0] + q[1] * q[1] + q[2] * q[2]; if (axisSqrLen > (Real)0) { #if defined(GTE_USE_MAT_VEC) Real adjust = ((Real)1) / std::sqrt(axisSqrLen); #else Real adjust = ((Real)-1) / std::sqrt(axisSqrLen); #endif a.axis[0] = q[0] * adjust; a.axis[1] = q[1] * adjust; a.axis[2] = q[2] * adjust; Real cs = std::max(std::min(q[3], (Real)1), (Real)-1); a.angle = (Real)2 * std::acos(cs); } else { // The angle is 0 (modulo 2*pi). Any axis will work, so choose // the Unit(0) axis. a.axis[0] = (Real)1; a.angle = (Real)0; } } // Convert an axis-angle pair to a quaternion, where // q = sin(angle/2)*(axis[0]*i+axis[1]*j+axis[2]*k)+cos(angle/2) static void Convert(AxisAngle<N, Real> const& a, Quaternion<Real>& q) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); #if defined(GTE_USE_MAT_VEC) Real halfAngle = (Real)0.5 * a.angle; #else Real halfAngle = (Real)-0.5 * a.angle; #endif Real sn = std::sin(halfAngle); q[0] = sn * a.axis[0]; q[1] = sn * a.axis[1]; q[2] = sn * a.axis[2]; q[3] = std::cos(halfAngle); } // Convert a quaternion to Euler angles. The quaternion is converted // to a matrix which is then converted to Euler angles. static void Convert(Quaternion<Real> const& q, EulerAngles<Real>& e) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Matrix<N, N, Real> r; Convert(q, r); Convert(r, e); } // Convert Euler angles to a quaternion. The Euler angles are // converted to a matrix which is then converted to a quaternion. static void Convert(EulerAngles<Real> const& e, Quaternion<Real>& q) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Matrix<N, N, Real> r; Convert(e, r); Convert(r, q); } // Convert an axis-angle pair to Euler angles. The axis-angle pair // is converted to a quaternion which is then converted to Euler // angles. static void Convert(AxisAngle<N, Real> const& a, EulerAngles<Real>& e) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Quaternion<Real> q; Convert(a, q); Convert(q, e); } // Convert Euler angles to an axis-angle pair. The Euler angles are // converted to a quaternion which is then converted to an axis-angle // pair. static void Convert(EulerAngles<Real> const& e, AxisAngle<N, Real>& a) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Quaternion<Real> q; Convert(e, q); Convert(q, a); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OdeEuler.h
.h
1,416
43
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/OdeSolver.h> // The TVector template parameter allows you to create solvers with // Vector<N,Real> when the dimension N is known at compile time or // GVector<Real> when the dimension N is known at run time. Both classes // have 'int32_t GetSize() const' that allow OdeSolver-derived classes to query // for the dimension. namespace gte { template <typename Real, typename TVector> class OdeEuler : public OdeSolver<Real, TVector> { public: // Construction and destruction. virtual ~OdeEuler() = default; OdeEuler(Real tDelta, std::function<TVector(Real, TVector const&)> const& F) : OdeSolver<Real, TVector>(tDelta, F) { } // Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may // allow xIn and xOut to be the same object. virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) override { TVector fVector = this->mFunction(tIn, xIn); tOut = tIn + this->mTDelta; xOut = xIn + this->mTDelta * fVector; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Image2.h
.h
17,332
513
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Image.h> #include <array> #include <string> //#define GTE_THROW_ON_IMAGE2_ERRORS namespace gte { template <typename PixelType> class Image2 : public Image<PixelType> { public: // Construction and destruction. The last constructor must have // positive dimensions; otherwise, the image is empty. virtual ~Image2() { } Image2() { } Image2(int32_t dimension0, int32_t dimension1) : Image<PixelType>(std::vector<int32_t>{ dimension0, dimension1 }) { } // Support for copy semantics. Image2(Image2 const& image) : Image<PixelType>(image) { } Image2& operator=(Image2 const& image) { Image<PixelType>::operator=(image); return *this; } // Support for move semantics. Image2(Image2&& image) noexcept { *this = std::move(image); } Image2& operator=(Image2&& image) noexcept { Image<PixelType>::operator=(image); return *this; } // Support for changing the image dimensions. All pixel data is lost // by this operation. void Reconstruct(int32_t dimension0, int32_t dimension1) { Image<PixelType>::Reconstruct(std::vector<int32_t>{ dimension0, dimension1 }); } // Conversion between 1-dimensional indices and 2-dimensional // coordinates. inline size_t GetIndex(int32_t x, int32_t y) const { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1]) { return static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * static_cast<size_t>(y); } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + ")."); } #else return static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * static_cast<size_t>(y); #endif } inline size_t GetIndex(std::array<int32_t, 2> const& coord) const { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1]) { return static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * static_cast<size_t>(coord[1]); } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + ")."); } #else return static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * static_cast<size_t>(coord[1]); #endif } inline void GetCoordinates(size_t index, int32_t& x, int32_t& y) const { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (index < this->mPixels.size()) { x = static_cast<int32_t>(index % this->mDimensions[0]); y = static_cast<int32_t>(index / this->mDimensions[0]); } else { LogError( "Invalid index " + std::to_string(index) + "."); } #else x = static_cast<int32_t>(index % this->mDimensions[0]); y = static_cast<int32_t>(index / this->mDimensions[0]); #endif } inline std::array<int32_t, 2> GetCoordinates(size_t index) const { std::array<int32_t, 2> coord; #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (index < this->mPixels.size()) { coord[0] = static_cast<int32_t>(index % this->mDimensions[0]); coord[1] = static_cast<int32_t>(index / this->mDimensions[0]); return coord; } else { LogError( "Invalid index " + std::to_string(index) + "."); } #else coord[0] = static_cast<int32_t>(index % this->mDimensions[0]); coord[1] = static_cast<int32_t>(index / this->mDimensions[0]); return coord; #endif } // Access the data as a 2-dimensional array. The operator() functions // test for valid (x,y) when iterator checking is enabled and throw // on invalid (x,y). The Get() functions test for valid (x,y) and // clamp when invalid; these functions cannot fail. inline PixelType& operator() (int32_t x, int32_t y) { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1]) { return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + ")."); } #else return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; #endif } inline PixelType const& operator() (int32_t x, int32_t y) const { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1]) { return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + ")."); } #else return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; #endif } inline PixelType& operator() (std::array<int32_t, 2> const& coord) { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1]) { return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + ")."); } #else return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; #endif } inline PixelType const& operator() (std::array<int32_t, 2> const& coord) const { #if defined(GTE_THROW_ON_IMAGE2_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1]) { return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + ")."); } #else return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; #endif } inline PixelType& Get(int32_t x, int32_t y) { // Clamp to valid (x,y). if (x < 0) { x = 0; } else if (x >= this->mDimensions[0]) { x = this->mDimensions[0] - 1; } if (y < 0) { y = 0; } else if (y >= this->mDimensions[1]) { y = this->mDimensions[1] - 1; } return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; } inline PixelType const& Get(int32_t x, int32_t y) const { // Clamp to valid (x,y). if (x < 0) { x = 0; } else if (x >= this->mDimensions[0]) { x = this->mDimensions[0] - 1; } if (y < 0) { y = 0; } else if (y >= this->mDimensions[1]) { y = this->mDimensions[1] - 1; } return this->mPixels[x + static_cast<size_t>(this->mDimensions[0]) * y]; } inline PixelType& Get(std::array<int32_t, 2> coord) { // Clamp to valid (x,y). for (int32_t i = 0; i < 2; ++i) { if (coord[i] < 0) { coord[i] = 0; } else if (coord[i] >= this->mDimensions[i]) { coord[i] = this->mDimensions[i] - 1; } } return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; } inline PixelType const& Get(std::array<int32_t, 2> coord) const { // Clamp to valid (x,y). for (int32_t i = 0; i < 2; ++i) { if (coord[i] < 0) { coord[i] = 0; } else if (coord[i] >= this->mDimensions[i]) { coord[i] = this->mDimensions[i] - 1; } } return this->mPixels[coord[0] + static_cast<size_t>(this->mDimensions[0]) * coord[1]]; } // In the following discussion, u and v are in {-1,1}. Given a pixel // (x,y), the 4-connected neighbors have relative offsets (u,0) and // (0,v). The 8-connected neighbors include the 4-connected neighbors // and have additional relative offsets (u,v). The corner neighbors // have relative offsets (0,0), (1,0), (0,1), and (1,1) in that order. // The full neighborhood is the set of 3x3 pixels centered at (x,y). // The neighborhoods can be accessed as 1-dimensional indices using // these functions. The first four functions provide 1-dimensional // indices relative to any pixel location; these depend only on the // image dimensions. The last four functions provide 1-dimensional // indices for the actual pixels in the neighborhood; no clamping is // used when (x,y) is on the boundary. void GetNeighborhood(std::array<int32_t, 4>& nbr) const { int32_t dim0 = this->mDimensions[0]; nbr[0] = -1; // (x-1,y) nbr[1] = +1; // (x+1,y) nbr[2] = -dim0; // (x,y-1) nbr[3] = +dim0; // (x,y+1) } void GetNeighborhood(std::array<int32_t, 8>& nbr) const { int32_t dim0 = this->mDimensions[0]; nbr[0] = -1; // (x-1,y) nbr[1] = +1; // (x+1,y) nbr[2] = -dim0; // (x,y-1) nbr[3] = +dim0; // (x,y+1) nbr[4] = -1 - dim0; // (x-1,y-1) nbr[5] = +1 - dim0; // (x+1,y-1) nbr[6] = -1 + dim0; // (x-1,y+1) nbr[7] = +1 + dim0; // (x+1,y+1) } void GetCorners(std::array<int32_t, 4>& nbr) const { int32_t dim0 = this->mDimensions[0]; nbr[0] = 0; // (x,y) nbr[1] = 1; // (x+1,y) nbr[2] = dim0; // (x,y+1) nbr[3] = dim0 + 1; // (x+1,y+1) } void GetFull(std::array<int32_t, 9>& nbr) const { int32_t dim0 = this->mDimensions[0]; nbr[0] = -1 - dim0; // (x-1,y-1) nbr[1] = -dim0; // (x,y-1) nbr[2] = +1 - dim0; // (x+1,y-1) nbr[3] = -1; // (x-1,y) nbr[4] = 0; // (x,y) nbr[5] = +1; // (x+1,y) nbr[6] = -1 + dim0; // (x-1,y+1) nbr[7] = +dim0; // (x,y+1) nbr[8] = +1 + dim0; // (x+1,y+1) } void GetNeighborhood(int32_t x, int32_t y, std::array<size_t, 4>& nbr) const { size_t index = GetIndex(x, y); std::array<int32_t, 4> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 4; ++i) { nbr[i] = index + inbr[i]; } } void GetNeighborhood(int32_t x, int32_t y, std::array<size_t, 8>& nbr) const { size_t index = GetIndex(x, y); std::array<int32_t, 8> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 8; ++i) { nbr[i] = index + inbr[i]; } } void GetCorners(int32_t x, int32_t y, std::array<size_t, 4>& nbr) const { size_t index = GetIndex(x, y); std::array<int32_t, 4> inbr; GetCorners(inbr); for (int32_t i = 0; i < 4; ++i) { nbr[i] = index + inbr[i]; } } void GetFull(int32_t x, int32_t y, std::array<size_t, 9>& nbr) const { size_t index = GetIndex(x, y); std::array<int32_t, 9> inbr; GetFull(inbr); for (int32_t i = 0; i < 9; ++i) { nbr[i] = index + inbr[i]; } } // The neighborhoods can be accessed as 2-tuples using these // functions. The first four functions provide 2-tuples relative to // any pixel location; these depend only on the image dimensions. The // last four functions provide 2-tuples for the actual pixels in the // neighborhood; no clamping is used when (x,y) is on the boundary. void GetNeighborhood(std::array<std::array<int32_t, 2>, 4>& nbr) const { nbr[0] = { { -1, 0 } }; nbr[1] = { { +1, 0 } }; nbr[2] = { { 0, -1 } }; nbr[3] = { { 0, +1 } }; } void GetNeighborhood(std::array<std::array<int32_t, 2>, 8>& nbr) const { nbr[0] = { { -1, -1 } }; nbr[1] = { { 0, -1 } }; nbr[2] = { { +1, -1 } }; nbr[3] = { { -1, 0 } }; nbr[4] = { { +1, 0 } }; nbr[5] = { { -1, +1 } }; nbr[6] = { { 0, +1 } }; nbr[7] = { { +1, +1 } }; } void GetCorners(std::array<std::array<int32_t, 2>, 4>& nbr) const { nbr[0] = { { 0, 0 } }; nbr[1] = { { 1, 0 } }; nbr[2] = { { 0, 1 } }; nbr[3] = { { 1, 1 } }; } void GetFull(std::array<std::array<int32_t, 2>, 9>& nbr) const { nbr[0] = { { -1, -1 } }; nbr[1] = { { 0, -1 } }; nbr[2] = { { +1, -1 } }; nbr[3] = { { -1, 0 } }; nbr[4] = { { 0, 0 } }; nbr[5] = { { +1, 0 } }; nbr[6] = { { -1, +1 } }; nbr[7] = { { 0, +1 } }; nbr[8] = { { +1, +1 } }; } void GetNeighborhood(int32_t x, int32_t y, std::array<std::array<size_t, 2>, 4>& nbr) const { std::array<std::array<int32_t, 2>, 4> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 4; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; } } void GetNeighborhood(int32_t x, int32_t y, std::array<std::array<size_t, 2>, 8>& nbr) const { std::array<std::array<int32_t, 2>, 8> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 8; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; } } void GetCorners(int32_t x, int32_t y, std::array<std::array<size_t, 2>, 4>& nbr) const { std::array<std::array<int32_t, 2>, 4> inbr; GetCorners(inbr); for (int32_t i = 0; i < 4; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; } } void GetFull(int32_t x, int32_t y, std::array<std::array<size_t, 2>, 9>& nbr) const { std::array<std::array<int32_t, 2>, 9> inbr; GetFull(inbr); for (int32_t i = 0; i < 9; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FastMarch.h
.h
5,955
194
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/MinHeap.h> #include <limits> // The topic of fast marching methods are discussed in the book // Level Set Methods and Fast Marching Methods: // Evolving Interfaces in Computational Geometry, Fluid Mechanics, // Computer Vision, and Materials Science // J.A. Sethian, // Cambridge University Press, 1999 namespace gte { template <typename Real> class FastMarch { // Abstract base class. public: virtual ~FastMarch() { } protected: // The seed points have a crossing time of 0. As the iterations // occur, some of the non-seed points are visited by the moving // front. Define maxReal to be std::numeric_limits<Real>::max(). // The valid crossing times are 0 <= t < maxReal. A value of // maxReal indicates the pixel has not yet been reached by the // moving front. If the speed value at a pixel is 0, the pixel // is marked with a time of -maxReal. Such pixels can never be // visited; the minus sign distinguishes these from pixels not yet // reached during iteration. // // Trial pixels are identified by having min-heap records // associated with them. Known or far pixels have no associated // record. // // The speeds must be nonnegative and are inverted because the // reciprocals are all that are needed in the numerical method. FastMarch(size_t quantity, std::vector<size_t> const& seeds, std::vector<Real> const& speeds) : mQuantity(quantity), mTimes(quantity, std::numeric_limits<Real>::max()), mInvSpeeds(quantity), mHeap(static_cast<int32_t>(quantity)), mTrials(quantity, nullptr) { for (auto seed : seeds) { mTimes[seed] = (Real)0; } for (size_t i = 0; i < mQuantity; ++i) { if (speeds[i] > (Real)0) { mInvSpeeds[i] = (Real)1 / speeds[i]; } else { mInvSpeeds[i] = std::numeric_limits<Real>::max(); mTimes[i] = -std::numeric_limits<Real>::max(); } } } FastMarch(size_t quantity, std::vector<size_t> const& seeds, Real speed) : mQuantity(quantity), mTimes(quantity, std::numeric_limits<Real>::max()), mInvSpeeds(quantity, (Real)1 / speed), mHeap(static_cast<int32_t>(quantity)), mTrials(quantity, nullptr) { for (auto seed : seeds) { mTimes[seed] = (Real)0; } } public: // Member access. inline size_t GetQuantity() const { return mQuantity; } inline void SetTime(size_t i, Real time) { mTimes[i] = time; } inline Real GetTime(size_t i) const { return mTimes[i]; } void GetTimeExtremes(Real& minValue, Real& maxValue) const { minValue = std::numeric_limits<Real>::max(); maxValue = -std::numeric_limits<Real>::max(); size_t i; for (i = 0; i < mQuantity; ++i) { if (IsValid(i)) { minValue = mTimes[i]; maxValue = minValue; break; } } // Assert: At least one time must be valid, in which case // i < mQuantity at this point. If all times are invalid, // minValue = +maxReal and maxValue = -maxReal on exit. for (/**/; i < mQuantity; ++i) { if (IsValid(i)) { if (mTimes[i] < minValue) { minValue = mTimes[i]; } else if (mTimes[i] > maxValue) { maxValue = mTimes[i]; } } } } // Image element classification. inline bool IsValid(size_t i) const { return (Real)0 <= mTimes[i] && mTimes[i] < std::numeric_limits<Real>::max(); } inline bool IsTrial(size_t i) const { return mTrials[i] != nullptr; } inline bool IsFar(size_t i) const { return mTimes[i] == std::numeric_limits<Real>::max(); } inline bool IsZeroSpeed(size_t i) const { return mTimes[i] == -std::numeric_limits<Real>::max(); } inline bool IsInterior(size_t i) const { return IsValid(i) && !IsTrial(i); } void GetInterior(std::vector<size_t>& interior) const { interior.clear(); for (size_t i = 0; i < mQuantity; ++i) { if (IsValid(i) && !IsTrial(i)) { interior.push_back(i); } } } virtual void GetBoundary(std::vector<size_t>& boundary) const = 0; virtual bool IsBoundary(size_t i) const = 0; // Run one step of the fast marching algorithm. virtual void Iterate() = 0; protected: size_t mQuantity; std::vector<Real> mTimes; std::vector<Real> mInvSpeeds; MinHeap<size_t, Real> mHeap; std::vector<typename MinHeap<size_t, Real>::Record*> mTrials; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Delaunay2.h
.h
70,737
1,838
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once // Remove includes of <Mathematics/PrimalQuery2.h> and <set> once // Delaunay2<InputType, ComputeType> is removed. #include <Mathematics/Logger.h> #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/HashCombine.h> #include <Mathematics/Line.h> #include <Mathematics/PrimalQuery2.h> #include <Mathematics/SWInterval.h> #include <Mathematics/Vector2.h> #include <Mathematics/VETManifoldMesh.h> #include <numeric> #include <set> // Delaunay triangulation of points (intrinsic dimensionality 2). // VQ = number of vertices // V = array of vertices // TQ = number of triangles // I = Array of 3-tuples of indices into V that represent the triangles // (3*TQ total elements). Access via GetIndices(*). // A = Array of 3-tuples of indices into I that represent the adjacent // triangles (3*TQ total elements). Access via GetAdjacencies(*). // The i-th triangle has vertices // vertex[0] = V[I[3*i+0]] // vertex[1] = V[I[3*i+1]] // vertex[2] = V[I[3*i+2]] // and edge index pairs // edge[0] = <I[3*i+0],I[3*i+1]> // edge[1] = <I[3*i+1],I[3*i+2]> // edge[2] = <I[3*i+2],I[3*i+0]> // The triangles adjacent to these edges have indices // adjacent[0] = A[3*i+0] is the triangle sharing edge[0] // adjacent[1] = A[3*i+1] is the triangle sharing edge[1] // adjacent[2] = A[3*i+2] is the triangle sharing edge[2] // If there is no adjacent triangle, the A[*] value is set to -1. The // triangle adjacent to edge[j] has vertices // adjvertex[0] = V[I[3*adjacent[j]+0]] // adjvertex[1] = V[I[3*adjacent[j]+1]] // adjvertex[2] = V[I[3*adjacent[j]+2]] // The only way to ensure a correct result for the input vertices (assumed to // be exact) is to choose ComputeType for exact rational arithmetic. You may // use BSNumber. No divisions are performed in this computation, so you do // not have to use BSRational. namespace gte { // The variadic template declaration supports the class // Delaunay2<InputType, ComputeType>, which is deprecated and will be // removed in a future release. The declaration also supports the // replacement class Delaunay2<InputType>. The new class uses a blend of // interval arithmetic and rational arithmetic. It also uses unordered // sets (hash tables). The replacement performs much better than the // deprecated class. template <typename T, typename...> class Delaunay2 {}; } namespace gte { // This class requires you to specify the ComputeType yourself. If it // is BSNumber<> or BSRational<>, the worst-case choices of N for the // chosen InputType are listed in the next table. The numerical // computations are encapsulated in PrimalQuery2<ComputeType>::ToLine and // PrimalQuery2<ComputeType>::ToCircumcircle, the latter query the // dominant one in determining N. We recommend using only BSNumber, // because no divisions are performed in the triangulation computations. // // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 35 // double | BSNumber | 263 // float | BSRational | 573 // double | BSRational | 4329 template <typename InputType, typename ComputeType> class // [[deprecated("Use Delaunay2<T> instead.")]] Delaunay2<InputType, ComputeType> { public: virtual ~Delaunay2() = default; Delaunay2() : mEpsilon((InputType)0), mDimension(0), mLine(Vector2<InputType>::Zero(), Vector2<InputType>::Zero()), mNumVertices(0), mNumUniqueVertices(0), mNumTriangles(0), mVertices(nullptr), mIndex{ { { 0, 1 }, { 1, 2 }, { 2, 0 } } } { } // The input is the array of vertices whose Delaunay triangulation is // required. The epsilon value is used to determine the intrinsic // dimensionality of the vertices (d = 0, 1, or 2). When epsilon is // positive, the determination is fuzzy--vertices approximately the // same point, approximately on a line, or planar. The return value // is 'true' if and only if the hull construction is successful. bool operator()(int32_t numVertices, Vector2<InputType> const* vertices, InputType epsilon) { mEpsilon = std::max(epsilon, (InputType)0); mDimension = 0; mLine.origin = Vector2<InputType>::Zero(); mLine.direction = Vector2<InputType>::Zero(); mNumVertices = numVertices; mNumUniqueVertices = 0; mNumTriangles = 0; mVertices = vertices; mGraph.Clear(); mIndices.clear(); mAdjacencies.clear(); mDuplicates.resize(std::max(numVertices, 3)); int32_t i, j; if (mNumVertices < 3) { // Delaunay2 should be called with at least three points. return false; } IntrinsicsVector2<InputType> info(mNumVertices, vertices, mEpsilon); if (info.dimension == 0) { // mDimension is 0; mGraph, mIndices, and mAdjacencies are empty return false; } if (info.dimension == 1) { // The set is (nearly) collinear. mDimension = 1; mLine = Line2<InputType>(info.origin, info.direction[0]); return false; } mDimension = 2; // Compute the vertices for the queries. mComputeVertices.resize(mNumVertices); mQuery.Set(mNumVertices, &mComputeVertices[0]); for (i = 0; i < mNumVertices; ++i) { for (j = 0; j < 2; ++j) { mComputeVertices[i][j] = vertices[i][j]; } } // Insert the (nondegenerate) triangle constructed by the call to // GetInformation. This is necessary for the circumcircle-visibility // algorithm to work correctly. if (!info.extremeCCW) { std::swap(info.extreme[1], info.extreme[2]); } if (!mGraph.Insert(info.extreme[0], info.extreme[1], info.extreme[2])) { return false; } // Incrementally update the triangulation. The set of processed // points is maintained to eliminate duplicates, either in the // original input points or in the points obtained by snap rounding. std::set<ProcessedVertex> processed; for (i = 0; i < 3; ++i) { j = info.extreme[i]; processed.insert(ProcessedVertex(vertices[j], j)); mDuplicates[j] = j; } for (i = 0; i < mNumVertices; ++i) { ProcessedVertex v(vertices[i], i); auto iter = processed.find(v); if (iter == processed.end()) { if (!Update(i)) { // A failure can occur if ComputeType is not an exact // arithmetic type. return false; } processed.insert(v); mDuplicates[i] = i; } else { mDuplicates[i] = iter->location; } } mNumUniqueVertices = static_cast<int32_t>(processed.size()); // Assign integer values to the triangles for use by the caller // and copy the triangle information to compact arrays mIndices // and mAdjacencies. UpdateIndicesAdjacencies(); return true; } // Dimensional information. If GetDimension() returns 1, the points // lie on a line P+t*D (fuzzy comparison when epsilon > 0). You can // sort these if you need a polyline output by projecting onto the // line each vertex X = P+t*D, where t = Dot(D,X-P). inline InputType GetEpsilon() const { return mEpsilon; } inline int32_t GetDimension() const { return mDimension; } inline Line2<InputType> const& GetLine() const { return mLine; } // Member access. inline int32_t GetNumVertices() const { return mNumVertices; } inline int32_t GetNumUniqueVertices() const { return mNumUniqueVertices; } inline int32_t GetNumTriangles() const { return mNumTriangles; } inline Vector2<InputType> const* GetVertices() const { return mVertices; } inline PrimalQuery2<ComputeType> const& GetQuery() const { return mQuery; } inline ETManifoldMesh const& GetGraph() const { return mGraph; } inline std::vector<int32_t> const& GetIndices() const { return mIndices; } inline std::vector<int32_t> const& GetAdjacencies() const { return mAdjacencies; } // If 'vertices' has no duplicates, GetDuplicates()[i] = i for all i. // If vertices[i] is the first occurrence of a vertex and if // vertices[j] is found later, then GetDuplicates()[j] = i. inline std::vector<int32_t> const& GetDuplicates() const { return mDuplicates; } // Locate those triangle edges that do not share other triangles. The // returned array has hull.size() = 2*numEdges, each pair representing // an edge. The edges are not ordered, but the pair of vertices for // an edge is ordered so that they conform to a counterclockwise // traversal of the hull. The return value is 'true' if and only if // the dimension is 2. bool GetHull(std::vector<int32_t>& hull) const { if (mDimension == 2) { // Count the number of edges that are not shared by two // triangles. int32_t numEdges = 0; for (auto adj : mAdjacencies) { if (adj == -1) { ++numEdges; } } if (numEdges > 0) { // Enumerate the edges. hull.resize(2 * static_cast<size_t>(numEdges)); size_t current = 0, i = 0; for (auto adj : mAdjacencies) { if (adj == -1) { size_t tri = i / 3, j = i % 3; hull[current++] = mIndices[3 * tri + j]; hull[current++] = mIndices[3 * tri + ((j + 1) % 3)]; } ++i; } return true; } else { LogError("Unexpected. There must be at least one triangle."); } } else { LogError("The dimension must be 2."); } } // Copy Delaunay triangles to compact arrays mIndices and // mAdjacencies. The array information is accessible via the // functions GetIndices(int32_t, std::array<int32_t, 3>&) and // GetAdjacencies(int32_t, std::array<int32_t, 3>&). void UpdateIndicesAdjacencies() { // Assign integer values to the triangles. auto const& tmap = mGraph.GetTriangles(); std::map<Triangle*, int32_t> permute; int32_t i = -1; permute[nullptr] = i++; for (auto const& element : tmap) { permute[element.second.get()] = i++; } mNumTriangles = static_cast<int32_t>(tmap.size()); int32_t numindices = 3 * mNumTriangles; if (numindices > 0) { mIndices.resize(numindices); mAdjacencies.resize(numindices); i = 0; for (auto const& element : tmap) { Triangle* tri = element.second.get(); for (size_t j = 0; j < 3; ++j, ++i) { mIndices[i] = tri->V[j]; mAdjacencies[i] = permute[tri->T[j]]; } } } } // Get the vertex indices for triangle i. The function returns 'true' // when the dimension is 2 and i is a valid triangle index, in which // case the vertices are valid; otherwise, the function returns // 'false' and the vertices are invalid. bool GetIndices(int32_t i, std::array<int32_t, 3>& indices) const { if (mDimension == 2) { int32_t numTriangles = static_cast<int32_t>(mIndices.size() / 3); if (0 <= i && i < numTriangles) { size_t threeI = 3 * static_cast<size_t>(i); indices[0] = mIndices[threeI]; indices[1] = mIndices[threeI + 1]; indices[2] = mIndices[threeI + 2]; return true; } } else { LogError("The dimension must be 2."); } return false; } // Get the indices for triangles adjacent to triangle i. The function // returns 'true' when the dimension is 2 and if i is a valid triangle // index, in which case the adjacencies are valid; otherwise, the // function returns 'false' and the adjacencies are invalid. bool GetAdjacencies(int32_t i, std::array<int32_t, 3>& adjacencies) const { if (mDimension == 2) { int32_t numTriangles = static_cast<int32_t>(mIndices.size() / 3); if (0 <= i && i < numTriangles) { size_t threeI = 3 * static_cast<size_t>(i); adjacencies[0] = mAdjacencies[threeI]; adjacencies[1] = mAdjacencies[threeI + 1]; adjacencies[2] = mAdjacencies[threeI + 2]; return true; } } else { LogError("The dimension must be 2."); } return false; } // Support for searching the triangulation for a triangle that // contains a point. If there is a containing triangle, the returned // value is a triangle index i with 0 <= i < GetNumTriangles(). If // there is not a containing triangle, -1 is returned. The // computations are performed using exact rational arithmetic. // // The SearchInfo input stores information about the triangle search // when looking for the triangle (if any) that contains p. The first // triangle searched is 'initialTriangle'. On return 'path' stores // those (ordered) triangle indices visited during the search. The // last visited triangle has index 'finalTriangle and vertex indices // 'finalV[0,1,2]', stored in counterclockwise order. The last edge // of the search is <finalV[0],finalV[1]>. For spatially coherent // inputs p for numerous calls to this function, you will want to // specify 'finalTriangle' from the previous call as 'initialTriangle' // for the next call, which should reduce search times. static int32_t constexpr negOne = -1; struct SearchInfo { SearchInfo() : initialTriangle(negOne), numPath(0), path{}, finalTriangle(0), finalV{ 0, 0, 0 } { } int32_t initialTriangle; int32_t numPath; std::vector<int32_t> path; int32_t finalTriangle; std::array<int32_t, 3> finalV; }; int32_t GetContainingTriangle(Vector2<InputType> const& p, SearchInfo& info) const { if (mDimension == 2) { Vector2<ComputeType> test{ p[0], p[1] }; int32_t numTriangles = static_cast<int32_t>(mIndices.size() / 3); info.path.resize(numTriangles); info.numPath = 0; int32_t triangle; if (0 <= info.initialTriangle && info.initialTriangle < numTriangles) { triangle = info.initialTriangle; } else { info.initialTriangle = 0; triangle = 0; } // Use triangle edges as binary separating lines. for (int32_t i = 0; i < numTriangles; ++i) { int32_t ibase = 3 * triangle; int32_t const* v = &mIndices[ibase]; info.path[info.numPath++] = triangle; info.finalTriangle = triangle; info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; if (mQuery.ToLine(test, v[0], v[1]) > 0) { triangle = mAdjacencies[ibase]; if (triangle == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; return -1; } continue; } if (mQuery.ToLine(test, v[1], v[2]) > 0) { triangle = mAdjacencies[static_cast<size_t>(ibase) + 1]; if (triangle == -1) { info.finalV[0] = v[1]; info.finalV[1] = v[2]; info.finalV[2] = v[0]; return -1; } continue; } if (mQuery.ToLine(test, v[2], v[0]) > 0) { triangle = mAdjacencies[static_cast<size_t>(ibase) + 2]; if (triangle == -1) { info.finalV[0] = v[2]; info.finalV[1] = v[0]; info.finalV[2] = v[1]; return -1; } continue; } return triangle; } } else { LogError("The dimension must be 2."); } return -1; } protected: // Support for incremental Delaunay triangulation. typedef ETManifoldMesh::Triangle Triangle; bool GetContainingTriangle(int32_t i, Triangle*& tri) const { int32_t numTriangles = static_cast<int32_t>(mGraph.GetTriangles().size()); for (int32_t t = 0; t < numTriangles; ++t) { int32_t j; for (j = 0; j < 3; ++j) { int32_t v0 = tri->V[mIndex[j][0]]; int32_t v1 = tri->V[mIndex[j][1]]; if (mQuery.ToLine(i, v0, v1) > 0) { // Point i sees edge <v0,v1> from outside the triangle. auto adjTri = tri->T[j]; if (adjTri) { // Traverse to the triangle sharing the face. tri = adjTri; break; } else { // We reached a hull edge, so the point is outside // the hull. return false; } } } if (j == 3) { // The point is inside all four edges, so the point is inside // a triangle. return true; } } LogError("Unexpected termination of loop."); } bool GetAndRemoveInsertionPolygon(int32_t i, std::set<Triangle*>& candidates, std::set<EdgeKey<true>>& boundary) { // Locate the triangles that make up the insertion polygon. ETManifoldMesh polygon; while (candidates.size() > 0) { Triangle* tri = *candidates.begin(); candidates.erase(candidates.begin()); for (int32_t j = 0; j < 3; ++j) { auto adj = tri->T[j]; if (adj && candidates.find(adj) == candidates.end()) { int32_t a0 = adj->V[0]; int32_t a1 = adj->V[1]; int32_t a2 = adj->V[2]; if (mQuery.ToCircumcircle(i, a0, a1, a2) <= 0) { // Point i is in the circumcircle. candidates.insert(adj); } } } if (!polygon.Insert(tri->V[0], tri->V[1], tri->V[2])) { return false; } if (!mGraph.Remove(tri->V[0], tri->V[1], tri->V[2])) { return false; } } // Get the boundary edges of the insertion polygon. for (auto const& element : polygon.GetTriangles()) { Triangle* tri = element.second.get(); for (int32_t j = 0; j < 3; ++j) { if (!tri->T[j]) { boundary.insert(EdgeKey<true>(tri->V[mIndex[j][0]], tri->V[mIndex[j][1]])); } } } return true; } bool Update(int32_t i) { // The return value of mGraph.Insert(...) is nullptr if there was // a failure to insert. The Update function will return 'false' // when the insertion fails. auto const& tmap = mGraph.GetTriangles(); Triangle* tri = tmap.begin()->second.get(); if (GetContainingTriangle(i, tri)) { // The point is inside the convex hull. The insertion polygon // contains only triangles in the current triangulation; the // hull does not change. // Use a depth-first search for those triangles whose // circumcircles contain point i. std::set<Triangle*> candidates; candidates.insert(tri); // Get the boundary of the insertion polygon C that contains // the triangles whose circumcircles contain point i. Polygon // C contains the point i. std::set<EdgeKey<true>> boundary; if (!GetAndRemoveInsertionPolygon(i, candidates, boundary)) { return false; } // The insertion polygon consists of the triangles formed by // point i and the faces of C. for (auto const& key : boundary) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; if (mQuery.ToLine(i, v0, v1) < 0) { if (!mGraph.Insert(i, v0, v1)) { return false; } } // else: Point i is on an edge of 'tri', so the // subdivision has degenerate triangles. Ignore these. } } else { // The point is outside the convex hull. The insertion // polygon is formed by point i and any triangles in the // current triangulation whose circumcircles contain point i. // Locate the convex hull of the triangles. std::set<EdgeKey<true>> hull; for (auto const& element : tmap) { Triangle* t = element.second.get(); for (int32_t j = 0; j < 3; ++j) { if (!t->T[j]) { hull.insert(EdgeKey<true>(t->V[mIndex[j][0]], t->V[mIndex[j][1]])); } } } // Iterate over all the hull edges and use the ones visible to // point i to locate the insertion polygon. auto const& emap = mGraph.GetEdges(); std::set<Triangle*> candidates; std::set<EdgeKey<true>> visible; for (auto const& key : hull) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; if (mQuery.ToLine(i, v0, v1) > 0) { auto iter = emap.find(EdgeKey<false>(v0, v1)); if (iter != emap.end() && iter->second->T[1] == nullptr) { auto adj = iter->second->T[0]; if (adj && candidates.find(adj) == candidates.end()) { int32_t a0 = adj->V[0]; int32_t a1 = adj->V[1]; int32_t a2 = adj->V[2]; if (mQuery.ToCircumcircle(i, a0, a1, a2) <= 0) { // Point i is in the circumcircle. candidates.insert(adj); } else { // Point i is not in the circumcircle but // the hull edge is visible. visible.insert(key); } } } else { // This should be exposed, but because the class is // deprecated, it is not exposed to preserve current // behavior in client applications. // LogError("Unexpected condition (ComputeType not exact?)"); return false; } } } // Get the boundary of the insertion subpolygon C that // contains the triangles whose circumcircles contain point i. std::set<EdgeKey<true>> boundary; if (!GetAndRemoveInsertionPolygon(i, candidates, boundary)) { return false; } // The insertion polygon P consists of the triangles formed by // point i and the back edges of C *and* the visible edges of // mGraph-C. for (auto const& key : boundary) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; if (mQuery.ToLine(i, v0, v1) < 0) { // This is a back edge of the boundary. if (!mGraph.Insert(i, v0, v1)) { return false; } } } for (auto const& key : visible) { if (!mGraph.Insert(i, key.V[1], key.V[0])) { return false; } } } return true; } // The epsilon value is used for fuzzy determination of intrinsic // dimensionality. If the dimension is 0 or 1, the constructor // returns early. The caller is responsible for retrieving the // dimension and taking an alternate path should the dimension be // smaller than 2. If the dimension is 0, the caller may as well // treat all vertices[] as a single point, say, vertices[0]. If the // dimension is 1, the caller can query for the approximating line and // project vertices[] onto it for further processing. InputType mEpsilon; int32_t mDimension; Line2<InputType> mLine; // The array of vertices used for geometric queries. If you want to // be certain of a correct result, choose ComputeType to be BSNumber. std::vector<Vector2<ComputeType>> mComputeVertices; PrimalQuery2<ComputeType> mQuery; // The graph information. int32_t mNumVertices; int32_t mNumUniqueVertices; int32_t mNumTriangles; Vector2<InputType> const* mVertices; VETManifoldMesh mGraph; std::vector<int32_t> mIndices; std::vector<int32_t> mAdjacencies; // If a vertex occurs multiple times in the 'vertices' input to the // constructor, the first processed occurrence of that vertex has an // index stored in this array. If there are no duplicates, then // mDuplicates[i] = i for all i. struct ProcessedVertex { ProcessedVertex() = default; ProcessedVertex(Vector2<InputType> const& inVertex, int32_t inLocation) : vertex(inVertex), location(inLocation) { } bool operator<(ProcessedVertex const& v) const { return vertex < v.vertex; } Vector2<InputType> vertex; int32_t location; }; std::vector<int32_t> mDuplicates; // Indexing for the vertices of the triangle adjacent to a vertex. // The edge adjacent to vertex j is <mIndex[j][0], mIndex[j][1]> and // is listed so that the triangle interior is to your left as you walk // around the edges. std::array<std::array<int32_t, 2>, 3> mIndex; }; } namespace gte { // The input type must be 'float' or 'double'. The user no longer has // the responsibility to specify the compute type. template <typename T> class Delaunay2<T> { public: virtual ~Delaunay2() = default; Delaunay2() : mNumVertices(0), mVertices(nullptr), mIRVertices{}, mGraph(), mDuplicates{}, mNumUniqueVertices(0), mDimension(0), mLine(Vector2<T>::Zero(), Vector2<T>::Zero()), mNumTriangles(0), mIndices{}, mAdjacencies{}, mIndex{ { { 0, 1 }, { 1, 2 }, { 2, 0 } } }, mQueryPoint(Vector2<T>::Zero()), mIRQueryPoint(Vector2<InputRational>::Zero()), mCRPool(maxNumCRPool) { static_assert(std::is_floating_point<T>::value, "The input type must be float or double."); } // The input is the array of vertices whose Delaunay triangulation is // required. The return value is 'true' if and only if the intrinsic // dimension of the points is 2. If the intrinsic dimension is 1, the // points lie exactly on a line which is then accessible via the // accessor GetLine(). If the intrinsic dimension is 0, the points are // all the same point. bool operator()(std::vector<Vector2<T>> const& vertices) { return operator()(vertices.size(), vertices.data()); } bool operator()(size_t numVertices, Vector2<T> const* vertices) { // Initialize values in case they were set by a previous call // to operator()(...). LogAssert(numVertices > 0 && vertices != nullptr, "Invalid argument."); mNumVertices = numVertices; mVertices = vertices; mIRVertices.clear(); mDuplicates.clear(); mLine.origin = Vector2<T>::Zero(); mLine.direction = Vector2<T>::Zero(); mNumUniqueVertices = 0; mNumTriangles = 0; mGraph.Clear(); mIndices.clear(); mAdjacencies.clear(); mQueryPoint = Vector2<T>::Zero(); mIRQueryPoint = Vector2<InputRational>::Zero(); // Compute the intrinsic dimension and return early if that // dimension is 0 or 1. IntrinsicsVector2<T> info(static_cast<int32_t>(mNumVertices), mVertices, static_cast<T>(0)); if (info.dimension == 0) { // The vertices are the same point. mDimension = 0; mLine.origin = info.origin; return false; } if (info.dimension == 1) { // The vertices are collinear. mDimension = 1; mLine.origin = info.origin; mLine.direction = info.direction[0]; return false; } // The vertices necessarily will have a triangulation. mDimension = 2; // Convert the floating-point inputs to rational type. mIRVertices.resize(mNumVertices); for (size_t i = 0; i < mNumVertices; ++i) { mIRVertices[i][0] = mVertices[i][0]; mIRVertices[i][1] = mVertices[i][1]; } // Assume initially the vertices are unique. If duplicates are // found during the Delaunay update, mDuplicates[] will be // modified accordingly. mDuplicates.resize(mNumVertices); std::iota(mDuplicates.begin(), mDuplicates.end(), 0); // Insert the nondegenerate triangle constructed by the call to // GetInformation. This is necessary for the circumcircle // visibility algorithm to work correctly. if (!info.extremeCCW) { std::swap(info.extreme[1], info.extreme[2]); } auto inserted = mGraph.Insert(info.extreme[0], info.extreme[1], info.extreme[2]); LogAssert(inserted != nullptr, "The triangle should not be degenerate."); // Incrementally update the triangulation. The set of processed // points is maintained to eliminate duplicates. ProcessedVertexSet processed; for (size_t i = 0; i < 3; ++i) { int32_t j = info.extreme[i]; processed.insert(ProcessedVertex(mVertices[j], j)); mDuplicates[j] = j; } for (size_t i = 0; i < mNumVertices; ++i) { ProcessedVertex v(mVertices[i], i); auto iter = processed.find(v); if (iter == processed.end()) { Update(i); processed.insert(v); mDuplicates[i] = i; } else { mDuplicates[i] = iter->location; } } mNumUniqueVertices = processed.size(); // Assign integer values to the triangles for use by the caller // and copy the triangle information to compact arrays mIndices // and mAdjacencies. UpdateIndicesAdjacencies(); return true; } // Dimensional information. If GetDimension() returns 1, the points // lie on a line P+t*D. You can sort these if you need a polyline // output by projecting onto the line each vertex X = P+t*D, where // t = Dot(D,X-P). inline size_t GetDimension() const { return mDimension; } inline Line2<T> const& GetLine() const { return mLine; } // Member access. inline size_t GetNumVertices() const { return mIRVertices.size(); } inline Vector2<T> const* GetVertices() const { return mVertices; } inline size_t GetNumUniqueVertices() const { return mNumUniqueVertices; } // If 'vertices' has no duplicates, GetDuplicates()[i] = i for all i. // If vertices[i] is the first occurrence of a vertex and if // vertices[j] is found later, then GetDuplicates()[j] = i. inline std::vector<size_t> const& GetDuplicates() const { return mDuplicates; } inline size_t GetNumTriangles() const { return mNumTriangles; } inline ETManifoldMesh const& GetGraph() const { return mGraph; } inline std::vector<int32_t> const& GetIndices() const { return mIndices; } inline std::vector<int32_t> const& GetAdjacencies() const { return mAdjacencies; } // Locate those triangle edges that do not share other triangles. The // returned array has hull.size() = 2*numEdges, each pair representing // an edge. The edges are not ordered, but the pair of vertices for // an edge is ordered so that they conform to a counterclockwise // traversal of the hull. The return value is 'true' if and only if // the dimension is 2. bool GetHull(std::vector<size_t>& hull) const { if (mDimension == 2) { // Count the number of edges that are not shared by two // triangles. size_t numEdges = 0; for (auto adj : mAdjacencies) { if (adj == -1) { ++numEdges; } } if (numEdges > 0) { // Enumerate the edges. hull.resize(2 * numEdges); size_t current = 0, i = 0; for (auto adj : mAdjacencies) { if (adj == -1) { size_t tri = i / 3, j = i % 3; hull[current++] = mIndices[3 * tri + j]; hull[current++] = mIndices[3 * tri + ((j + 1) % 3)]; } ++i; } return true; } else { LogError("Unexpected condition. There must be at least one triangle."); } } else { LogError("The dimension must be 2."); } } // Copy Delaunay triangles to compact arrays mIndices and // mAdjacencies. The array information is accessible via the // functions GetIndices(int32_t, std::array<int32_t, 3>&) and // GetAdjacencies(int32_t, std::array<int32_t, 3>&). void UpdateIndicesAdjacencies() { // Assign integer values to the triangles. auto const& tmap = mGraph.GetTriangles(); std::unordered_map<Triangle*, int32_t> permute; int32_t i = -1; permute[nullptr] = i++; for (auto const& element : tmap) { permute[element.second.get()] = i++; } mNumTriangles = tmap.size(); size_t numindices = 3 * mNumTriangles; if (numindices > 0) { mIndices.resize(numindices); mAdjacencies.resize(numindices); i = 0; for (auto const& element : tmap) { Triangle* tri = element.second.get(); for (size_t j = 0; j < 3; ++j, ++i) { mIndices[i] = tri->V[j]; mAdjacencies[i] = permute[tri->T[j]]; } } } } // Get the vertex indices for triangle t. The function returns 'true' // when the dimension is 2 and t is a valid triangle index, in which // case the vertices are valid; otherwise, the function returns // 'false' and the vertices are invalid. bool GetIndices(size_t t, std::array<int32_t, 3>& indices) const { if (mDimension == 2) { size_t const numTriangles = mIndices.size() / 3; if (t < numTriangles) { indices[0] = mIndices[3 * t]; indices[1] = mIndices[3 * t + 1]; indices[2] = mIndices[3 * t + 2]; return true; } } return false; } // Get the indices for triangles adjacent to triangle t. The function // returns 'true' when the dimension is 2 and if t is a valid triangle // index, in which case the adjacencies are valid; otherwise, the // function returns 'false' and the adjacencies are invalid. bool GetAdjacencies(size_t t, std::array<int32_t, 3>& adjacencies) const { if (mDimension == 2) { size_t const numTriangles = mIndices.size() / 3; if (t < numTriangles) { adjacencies[0] = mAdjacencies[3 * t]; adjacencies[1] = mAdjacencies[3 * t + 1]; adjacencies[2] = mAdjacencies[3 * t + 2]; return true; } } return false; } // Support for searching the triangulation for a triangle that // contains a point. If there is a containing triangle, the returned // value is a triangle index t with 0 <= t < GetNumTriangles(). If // there is not a containing triangle, -1 is returned. The // computations are performed using exact rational arithmetic. // // The SearchInfo input stores information about the triangle search // when looking for the triangle (if any) that contains p. The first // triangle searched is 'initialTriangle'. On return 'path' stores // those (ordered) triangle indices visited during the search. The // last visited triangle has index 'finalTriangle and vertex indices // 'finalV[0,1,2]', stored in counterclockwise order. The last edge // of the search is <finalV[0],finalV[1]>. For spatially coherent // inputs p for numerous calls to this function, you will want to // specify 'finalTriangle' from the previous call as 'initialTriangle' // for the next call, which should reduce search times. static size_t constexpr negOne = std::numeric_limits<size_t>::max(); struct SearchInfo { SearchInfo() : initialTriangle(negOne), numPath(0), finalTriangle(0), finalV{ 0, 0, 0 }, path{} { } size_t initialTriangle; size_t numPath; size_t finalTriangle; std::array<int32_t, 3> finalV; std::vector<size_t> path; }; // If the point is in a triangle, the return value is the index of the // triangle. If the point is not in a triangle, the return value is // std::numeric_limits<size_t>::max(). size_t GetContainingTriangle(Vector2<T> const& inP, SearchInfo& info) const { LogAssert(mDimension == 2, "Invalid dimension for triangle search."); mQueryPoint = inP; mIRQueryPoint = { inP[0], inP[1] }; size_t const numTriangles = mIndices.size() / 3; info.path.resize(numTriangles); info.numPath = 0; size_t triangle; if (info.initialTriangle < numTriangles) { triangle = info.initialTriangle; } else { info.initialTriangle = 0; triangle = 0; } // Use triangle edges as binary separating lines. int32_t adjacent; for (size_t i = 0; i < numTriangles; ++i) { size_t ibase = 3 * triangle; int32_t const* v = &mIndices[ibase]; info.path[info.numPath++] = triangle; info.finalTriangle = triangle; info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; if (ToLine(negOne, v[0], v[1]) > 0) { adjacent = mAdjacencies[ibase]; if (adjacent == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; return negOne; } triangle = static_cast<size_t>(adjacent); continue; } if (ToLine(negOne, v[1], v[2]) > 0) { adjacent = mAdjacencies[ibase + 1]; if (adjacent == -1) { info.finalV[0] = v[1]; info.finalV[1] = v[2]; info.finalV[2] = v[0]; return negOne; } triangle = static_cast<size_t>(adjacent); continue; } if (ToLine(negOne, v[2], v[0]) > 0) { adjacent = mAdjacencies[ibase + 2]; if (adjacent == -1) { info.finalV[0] = v[2]; info.finalV[1] = v[0]; info.finalV[2] = v[1]; return negOne; } triangle = static_cast<size_t>(adjacent); continue; } return triangle; } LogError("Unexpected termination of loop while searching for a triangle."); } protected: // The type of the read-only input vertices[] when converted for // rational arithmetic. static int32_t constexpr InputNumWords = std::is_same<T, float>::value ? 2 : 4; using InputRational = BSNumber<UIntegerFP32<InputNumWords>>; // The vector of vertices used for geometric queries. The input // vertices are read-only, so we can represent them by the type // InputRational. size_t mNumVertices; Vector2<T> const* mVertices; std::vector<Vector2<InputRational>> mIRVertices; VETManifoldMesh mGraph; private: // The compute type used for exact sign classification. static int32_t constexpr ComputeNumWords = std::is_same<T, float>::value ? 36 : 264; using ComputeRational = BSNumber<UIntegerFP32<ComputeNumWords>>; // Convenient renaming. using Triangle = ETManifoldMesh::Triangle; struct ProcessedVertex { ProcessedVertex() = default; ProcessedVertex(Vector2<T> const& inVertex, size_t inLocation) : vertex(inVertex), location(inLocation) { } // Support for hashing in std::unordered_set<>. The first // operator() is the hash function. The second operator() is // the equality comparison used for elements in the same bucket. std::size_t operator()(ProcessedVertex const& v) const { return HashValue(v.vertex[0], v.vertex[1], v.location); } bool operator()(ProcessedVertex const& v0, ProcessedVertex const& v1) const { return v0.vertex == v1.vertex && v0.location == v1.location; } Vector2<T> vertex; size_t location; }; using ProcessedVertexSet = std::unordered_set< ProcessedVertex, ProcessedVertex, ProcessedVertex>; using DirectedEdgeKeySet = std::unordered_set< EdgeKey<true>, EdgeKey<true>, EdgeKey<true>>; using TrianglePtrSet = std::unordered_set<Triangle*>; static ComputeRational const& Copy(InputRational const& source, ComputeRational& target) { target.SetSign(source.GetSign()); target.SetBiasedExponent(source.GetBiasedExponent()); target.GetUInteger().CopyFrom(source.GetUInteger()); return target; } // Given a line with origin V0 and direction <V0,V1> and a query // point P, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line int32_t ToLine(size_t pIndex, size_t v0Index, size_t v1Index) const { // The expression tree has 13 nodes consisting of 6 input // leaves and 7 compute nodes. // Use interval arithmetic to determine the sign if possible. auto const& inP = (pIndex != negOne ? mVertices[pIndex] : mQueryPoint); Vector2<T> const& inV0 = mVertices[v0Index]; Vector2<T> const& inV1 = mVertices[v1Index]; auto x0 = SWInterval<T>::Sub(inP[0], inV0[0]); auto y0 = SWInterval<T>::Sub(inP[1], inV0[1]); auto x1 = SWInterval<T>::Sub(inV1[0], inV0[0]); auto y1 = SWInterval<T>::Sub(inV1[1], inV0[1]); auto x0y1 = x0 * y1; auto x1y0 = x1 * y0; auto det = x0y1 - x1y0; T constexpr zero = 0; if (det[0] > zero) { return +1; } else if (det[1] < zero) { return -1; } // The exact sign of the determinant is not known, so compute // the determinant using rational arithmetic. // Name the nodes of the expression tree. auto const& irP = (pIndex != negOne ? mIRVertices[pIndex] : mIRQueryPoint); Vector2<InputRational> const& irV0 = mIRVertices[v0Index]; Vector2<InputRational> const& irV1 = mIRVertices[v1Index]; auto const& crP0 = Copy(irP[0], mCRPool[0]); auto const& crP1 = Copy(irP[1], mCRPool[1]); auto const& crV00 = Copy(irV0[0], mCRPool[2]); auto const& crV01 = Copy(irV0[1], mCRPool[3]); auto const& crV10 = Copy(irV1[0], mCRPool[4]); auto const& crV11 = Copy(irV1[1], mCRPool[5]); auto& crX0 = mCRPool[6]; auto& crY0 = mCRPool[7]; auto& crX1 = mCRPool[8]; auto& crY1 = mCRPool[9]; auto& crX0Y1 = mCRPool[10]; auto& crX1Y0 = mCRPool[11]; auto& crDet = mCRPool[12]; // Evaluate the expression tree. crX0 = crP0 - crV00; crY0 = crP1 - crV01; crX1 = crV10 - crV00; crY1 = crV11 - crV01; crX0Y1 = crX0 * crY1; crX1Y0 = crX1 * crY0; crDet = crX0Y1 - crX1Y0; return crDet.GetSign(); } // For a triangle with counterclockwise vertices V0, V1 and V2 and a // query point P, ToCircumcircle returns // +1, P outside circumcircle of triangle // -1, P inside circumcircle of triangle // 0, P on circumcircle of triangle int32_t ToCircumcircle(size_t pIndex, size_t v0Index, size_t v1Index, size_t v2Index) const { // The expression tree has 43 nodes consisting of 8 input // leaves and 35 compute nodes. // Use interval arithmetic to determine the sign if possible. auto const& inP = (pIndex != negOne ? mVertices[pIndex] : mQueryPoint); Vector2<T> const& inV0 = mVertices[v0Index]; Vector2<T> const& inV1 = mVertices[v1Index]; Vector2<T> const& inV2 = mVertices[v2Index]; auto x0 = SWInterval<T>::Sub(inV0[0], inP[0]); auto y0 = SWInterval<T>::Sub(inV0[1], inP[1]); auto s00 = SWInterval<T>::Add(inV0[0], inP[0]); auto s01 = SWInterval<T>::Add(inV0[1], inP[1]); auto x1 = SWInterval<T>::Sub(inV1[0], inP[0]); auto y1 = SWInterval<T>::Sub(inV1[1], inP[1]); auto s10 = SWInterval<T>::Add(inV1[0], inP[0]); auto s11 = SWInterval<T>::Add(inV1[1], inP[1]); auto x2 = SWInterval<T>::Sub(inV2[0], inP[0]); auto y2 = SWInterval<T>::Sub(inV2[1], inP[1]); auto s20 = SWInterval<T>::Add(inV2[0], inP[0]); auto s21 = SWInterval<T>::Add(inV2[1], inP[1]); auto t00 = s00 * x0; auto t01 = s01 * y0; auto t10 = s10 * x1; auto t11 = s11 * y1; auto t20 = s20 * x2; auto t21 = s21 * y2; auto z0 = t00 + t01; auto z1 = t10 + t11; auto z2 = t20 + t21; auto y0z1 = y0 * z1; auto y0z2 = y0 * z2; auto y1z0 = y1 * z0; auto y1z2 = y1 * z2; auto y2z0 = y2 * z0; auto y2z1 = y2 * z1; auto c0 = y1z2 - y2z1; auto c1 = y2z0 - y0z2; auto c2 = y0z1 - y1z0; auto x0c0 = x0 * c0; auto x1c1 = x1 * c1; auto x2c2 = x2 * c2; auto det = x0c0 + x1c1 + x2c2; T constexpr zero = 0; if (det[0] > zero) { return -1; } else if (det[1] < zero) { return +1; } // The exact sign of the determinant is not known, so compute // the determinant using rational arithmetic. // Name the nodes of the expression tree. auto const& irP = (pIndex != negOne ? mIRVertices[pIndex] : mIRQueryPoint); Vector2<InputRational> const& irV0 = mIRVertices[v0Index]; Vector2<InputRational> const& irV1 = mIRVertices[v1Index]; Vector2<InputRational> const& irV2 = mIRVertices[v2Index]; auto const& crP0 = Copy(irP[0], mCRPool[0]); auto const& crP1 = Copy(irP[1], mCRPool[1]); auto const& crV00 = Copy(irV0[0], mCRPool[2]); auto const& crV01 = Copy(irV0[1], mCRPool[3]); auto const& crV10 = Copy(irV1[0], mCRPool[4]); auto const& crV11 = Copy(irV1[1], mCRPool[5]); auto const& crV20 = Copy(irV2[0], mCRPool[6]); auto const& crV21 = Copy(irV2[1], mCRPool[7]); auto& crX0 = mCRPool[8]; auto& crY0 = mCRPool[9]; auto& crS00 = mCRPool[10]; auto& crS01 = mCRPool[11]; auto& crT00 = mCRPool[12]; auto& crT01 = mCRPool[13]; auto& crZ0 = mCRPool[14]; auto& crX1 = mCRPool[15]; auto& crY1 = mCRPool[16]; auto& crS10 = mCRPool[17]; auto& crS11 = mCRPool[18]; auto& crT10 = mCRPool[19]; auto& crT11 = mCRPool[20]; auto& crZ1 = mCRPool[21]; auto& crX2 = mCRPool[22]; auto& crY2 = mCRPool[23]; auto& crS20 = mCRPool[24]; auto& crS21 = mCRPool[25]; auto& crT20 = mCRPool[26]; auto& crT21 = mCRPool[27]; auto& crZ2 = mCRPool[28]; auto& crY0Z1 = mCRPool[29]; auto& crY0Z2 = mCRPool[30]; auto& crY1Z0 = mCRPool[31]; auto& crY1Z2 = mCRPool[32]; auto& crY2Z0 = mCRPool[33]; auto& crY2Z1 = mCRPool[34]; auto& crC0 = mCRPool[35]; auto& crC1 = mCRPool[36]; auto& crC2 = mCRPool[37]; auto& crX0C0 = mCRPool[38]; auto& crX1C1 = mCRPool[39]; auto& crX2C2 = mCRPool[40]; auto& crTerm = mCRPool[41]; auto& crDet = mCRPool[42]; // Evaluate the expression tree. crX0 = crV00 - crP0; crY0 = crV01 - crP1; crS00 = crV00 + crP0; crS01 = crV01 + crP1; crT00 = crS00 * crX0; crT01 = crS01 * crY0; crZ0 = crT00 + crT01; crX1 = crV10 - crP0; crY1 = crV11 - crP1; crS10 = crV10 + crP0; crS11 = crV11 + crP1; crT10 = crS10 * crX1; crT11 = crS11 * crY1; crZ1 = crT10 + crT11; crX2 = crV20 - crP0; crY2 = crV21 - crP1; crS20 = crV20 + crP0; crS21 = crV21 + crP1; crT20 = crS20 * crX2; crT21 = crS21 * crY2; crZ2 = crT20 + crT21; crY0Z1 = crY0 * crZ1; crY0Z2 = crY0 * crZ2; crY1Z0 = crY1 * crZ0; crY1Z2 = crY1 * crZ2; crY2Z0 = crY2 * crZ0; crY2Z1 = crY2 * crZ1; crC0 = crY1Z2 - crY2Z1; crC1 = crY2Z0 - crY0Z2; crC2 = crY0Z1 - crY1Z0; crX0C0 = crX0 * crC0; crX1C1 = crX1 * crC1; crX2C2 = crX2 * crC2; crTerm = crX0C0 + crX1C1; crDet = crTerm + crX2C2; return -crDet.GetSign(); } bool GetContainingTriangle(size_t pIndex, Triangle*& tri) const { size_t const numTriangles = mGraph.GetTriangles().size(); for (size_t t = 0; t < numTriangles; ++t) { size_t j; for (j = 0; j < 3; ++j) { size_t v0Index = static_cast<size_t>(tri->V[mIndex[j][0]]); size_t v1Index = static_cast<size_t>(tri->V[mIndex[j][1]]); if (ToLine(pIndex, v0Index, v1Index) > 0) { // Point i sees edge <v0,v1> from outside the triangle. auto adjTri = tri->T[j]; if (adjTri) { // Traverse to the triangle sharing the face. tri = adjTri; break; } else { // We reached a hull edge, so the point is outside // the hull. return false; } } } if (j == 3) { // The point is inside all four edges, so the point is // inside a triangle. return true; } } LogError("Unexpected termination of loop while searching for a triangle."); } void GetAndRemoveInsertionPolygon(size_t pIndex, TrianglePtrSet& candidates, DirectedEdgeKeySet& boundary) { // Locate the triangles that make up the insertion polygon. ETManifoldMesh polygon; while (candidates.size() > 0) { Triangle* tri = *candidates.begin(); candidates.erase(candidates.begin()); for (size_t j = 0; j < 3; ++j) { auto adj = tri->T[j]; if (adj && candidates.find(adj) == candidates.end()) { size_t v0Index = adj->V[0]; size_t v1Index = adj->V[1]; size_t v2Index = adj->V[2]; if (ToCircumcircle(pIndex, v0Index, v1Index, v2Index) <= 0) { // Point P is in the circumcircle. candidates.insert(adj); } } } auto inserted = polygon.Insert(tri->V[0], tri->V[1], tri->V[2]); LogAssert(inserted != nullptr, "Unexpected insertion failure."); auto removed = mGraph.Remove(tri->V[0], tri->V[1], tri->V[2]); LogAssert(removed, "Unexpected removal failure."); } // Get the boundary edges of the insertion polygon. for (auto const& element : polygon.GetTriangles()) { Triangle* tri = element.second.get(); for (size_t j = 0; j < 3; ++j) { if (!tri->T[j]) { EdgeKey<true> ekey(tri->V[mIndex[j][0]], tri->V[mIndex[j][1]]); boundary.insert(ekey); } } } } void Update(size_t pIndex) { auto const& tmap = mGraph.GetTriangles(); Triangle* tri = tmap.begin()->second.get(); if (GetContainingTriangle(pIndex, tri)) { // The point is inside the convex hull. The insertion polygon // contains only triangles in the current triangulation; the // hull does not change. // Use a depth-first search for those triangles whose // circumcircles contain point P. TrianglePtrSet candidates; candidates.insert(tri); // Get the boundary of the insertion polygon C that contains // the triangles whose circumcircles contain point P. Polygon // Polygon C contains this point. DirectedEdgeKeySet boundary; GetAndRemoveInsertionPolygon(pIndex, candidates, boundary); // The insertion polygon consists of the triangles formed by // point P and the faces of C. for (auto const& key : boundary) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); if (ToLine(pIndex, v0Index, v1Index) < 0) { auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[0], key.V[1]); LogAssert(inserted != nullptr, "Unexpected insertion failure."); } } } else { // The point is outside the convex hull. The insertion // polygon is formed by point P and any triangles in the // current triangulation whose circumcircles contain point P. // Locate the convex hull of the triangles. DirectedEdgeKeySet hull; for (auto const& element : tmap) { Triangle* t = element.second.get(); for (size_t j = 0; j < 3; ++j) { if (!t->T[j]) { hull.insert(EdgeKey<true>(t->V[mIndex[j][0]], t->V[mIndex[j][1]])); } } } // Iterate over all the hull edges and use the ones visible to // point P to locate the insertion polygon. auto const& emap = mGraph.GetEdges(); TrianglePtrSet candidates; DirectedEdgeKeySet visible; for (auto const& key : hull) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); if (ToLine(pIndex, v0Index, v1Index) > 0) { auto iter = emap.find(EdgeKey<false>(key.V[0], key.V[1])); if (iter != emap.end() && iter->second->T[1] == nullptr) { auto adj = iter->second->T[0]; if (adj && candidates.find(adj) == candidates.end()) { size_t a0Index = static_cast<size_t>(adj->V[0]); size_t a1Index = static_cast<size_t>(adj->V[1]); size_t a2Index = static_cast<size_t>(adj->V[2]); if (ToCircumcircle(pIndex, a0Index, a1Index, a2Index) <= 0) { // Point P is in the circumcircle. candidates.insert(adj); } else { // Point P is not in the circumcircle but // the hull edge is visible. visible.insert(key); } } } else { LogError("This condition should not occur for rational arithmetic."); } } } // Get the boundary of the insertion subpolygon C that // contains the triangles whose circumcircles contain point P. DirectedEdgeKeySet boundary; GetAndRemoveInsertionPolygon(pIndex, candidates, boundary); // The insertion polygon P consists of the triangles formed by // point i and the back edges of C and by the visible edges of // mGraph-C. for (auto const& key : boundary) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); if (ToLine(pIndex, v0Index, v1Index) < 0) { // This is a back edge of the boundary. auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[0], key.V[1]); LogAssert(inserted != nullptr, "Unexpected insertion failure."); } } for (auto const& key : visible) { auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[1], key.V[0]); LogAssert(inserted != nullptr, "Unexpected insertion failure."); } } } // If a vertex occurs multiple times in the 'vertices' input to the // constructor, the first processed occurrence of that vertex has an // index stored in this array. If there are no duplicates, then // mDuplicates[i] = i for all i. std::vector<size_t> mDuplicates; size_t mNumUniqueVertices; // If the intrinsic dimension of the input vertices is 0 or 1, the // constructor returns early. The caller is responsible for retrieving // the dimension and taking an alternate path should the dimension be // smaller than 2. If the dimension is 0, all vertices are the same. // If the dimension is 1, the vertices lie on a line, in which case // the caller can project vertices[] onto the line for further // processing. size_t mDimension; Line2<T> mLine; // These are computed by UpdateIndicesAdjacencies(). They are used // for point-containment queries in the triangle mesh. size_t mNumTriangles; std::vector<int32_t> mIndices; std::vector<int32_t> mAdjacencies; private: // Indexing for the vertices of the triangle adjacent to a vertex. // The edge adjacent to vertex j is <mIndex[j][0], mIndex[j][1]> and // is listed so that the triangle interior is to your left as you walk // around the edges. std::array<std::array<size_t, 2>, 3> const mIndex; // The query point for Update, GetContainingTriangle and // GetAndRemoveInsertionPolygon when the point is not an input vertex // to the constructor. ToLine and ToCircumcircle are passed indices // into the vertex array. When the vertex is valid, mVertices[] and // mCRVertices[] are used for lookups. When the vertex is 'negOne', the // query point is used for lookups. mutable Vector2<T> mQueryPoint; mutable Vector2<InputRational> mIRQueryPoint; // Sufficient storage for the expression trees related to computing // the exact signs in ToLine(...) and ToCircumcircle(...). static size_t constexpr maxNumCRPool = 43; mutable std::vector<ComputeRational> mCRPool; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrPlane3Plane3.h
.h
5,453
157
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/Line.h> #include <Mathematics/Vector3.h> namespace gte { template <typename T> class TIQuery<T, Plane3<T>, Plane3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Plane3<T> const& plane0, Plane3<T> const& plane1) { // If Cross(N0,N1) is zero, then either planes are parallel and // separated or the same plane. In both cases, 'false' is // returned. Otherwise, the planes intersect. To avoid subtle // differences in reporting between Test() and Find(), the same // parallel test is used. Mathematically, // |Cross(N0,N1)|^2 = Dot(N0,N0)*Dot(N1,N1)-Dot(N0,N1)^2 // = 1 - Dot(N0,N1)^2 // The last equality is true since planes are required to have // unit-length normal vectors. The test |Cross(N0,N1)| = 0 is the // same as |Dot(N0,N1)| = 1. Result result{}; T dot = Dot(plane0.normal, plane1.normal); if (std::fabs(dot) < (T)1) { result.intersect = true; return result; } // The planes are parallel. Check whether they are coplanar. T cDiff; if (dot >= (T)0) { // Normals are in same direction, need to look at c0-c1. cDiff = plane0.constant - plane1.constant; } else { // Normals are in opposite directions, need to look at c0+c1. cDiff = plane0.constant + plane1.constant; } result.intersect = (std::fabs(cDiff) == (T)0); return result; } }; template <typename T> class FIQuery<T, Plane3<T>, Plane3<T>> { public: struct Result { Result() : intersect(false), isLine(false), line(Vector3<T>::Zero(), Vector3<T>::Zero()), plane(Vector3<T>::Zero(), (T)0) { } bool intersect; // If 'intersect' is true, the intersection is either a line or // the planes are the same. When a line, 'line' is valid. When // the same plane, 'plane' is set to one of the planes. bool isLine; Line3<T> line; Plane3<T> plane; }; Result operator()(Plane3<T> const& plane0, Plane3<T> const& plane1) { // If N0 and N1 are parallel, either the planes are parallel and // separated or the same plane. In both cases, 'false' is // returned. Otherwise, the intersection line is // L(t) = t*Cross(N0,N1)/|Cross(N0,N1)| + c0*N0 + c1*N1 // for some coefficients c0 and c1 and for t any real number (the // line parameter). Taking dot products with the normals, // d0 = Dot(N0,L) = c0*Dot(N0,N0) + c1*Dot(N0,N1) = c0 + c1*d // d1 = Dot(N1,L) = c0*Dot(N0,N1) + c1*Dot(N1,N1) = c0*d + c1 // where d = Dot(N0,N1). These are two equations in two unknowns. // The solution is // c0 = (d0 - d*d1)/det // c1 = (d1 - d*d0)/det // where det = 1 - d^2. Result result{}; T dot = Dot(plane0.normal, plane1.normal); if (std::fabs(dot) >= (T)1) { // The planes are parallel. Check if they are coplanar. T cDiff; if (dot >= (T)0) { // Normals are in same direction, need to look at c0-c1. cDiff = plane0.constant - plane1.constant; } else { // Normals are in opposite directions, need to look at // c0+c1. cDiff = plane0.constant + plane1.constant; } if (std::fabs(cDiff) == (T)0) { // The planes are coplanar. result.intersect = true; result.isLine = false; result.plane = plane0; return result; } // The planes are parallel but distinct. result.intersect = false; return result; } T invDet = (T)1 / ((T)1 - dot * dot); T c0 = (plane0.constant - dot * plane1.constant) * invDet; T c1 = (plane1.constant - dot * plane0.constant) * invDet; result.intersect = true; result.isLine = true; result.line.origin = c0 * plane0.normal + c1 * plane1.normal; result.line.direction = UnitCross(plane0.normal, plane1.normal); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GaussianBlur3.h
.h
1,675
52
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/PdeFilter3.h> namespace gte { template <typename Real> class GaussianBlur3 : public PdeFilter3<Real> { public: GaussianBlur3(int32_t xBound, int32_t yBound, int32_t zBound, Real xSpacing, Real ySpacing, Real zSpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType) : PdeFilter3<Real>(xBound, yBound, zBound, xSpacing, ySpacing, zSpacing, data, mask, borderValue, scaleType) { mMaximumTimeStep = (Real)0.5 / (this->mInvDxDx + this->mInvDyDy + this->mInvDzDz); } virtual ~GaussianBlur3() { } inline Real GetMaximumTimeStep() const { return mMaximumTimeStep; } protected: virtual void OnUpdateSingle(int32_t x, int32_t y, int32_t z) override { this->LookUp7(x, y, z); Real uxx = this->mInvDxDx * (this->mUpzz - (Real)2 * this->mUzzz + this->mUmzz); Real uyy = this->mInvDyDy * (this->mUzpz - (Real)2 * this->mUzzz + this->mUzmz); Real uzz = this->mInvDzDz * (this->mUzzp - (Real)2 * this->mUzzz + this->mUzzm); this->mBuffer[this->mDst][z][y][x] = this->mUzzz + this->mTimeStep * (uxx + uyy + uzz); } Real mMaximumTimeStep; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/VertexCollapseMesh.h
.h
20,654
526
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/MinHeap.h> #include <Mathematics/Polygon2.h> #include <Mathematics/TriangulateEC.h> #include <Mathematics/Vector3.h> #include <Mathematics/VETManifoldMesh.h> #include <set> namespace gte { template <typename Real> class VertexCollapseMesh { public: // Construction. VertexCollapseMesh(int32_t numPositions, Vector3<Real> const* positions, int32_t numIndices, int32_t const* indices) : mNumPositions(numPositions), mPositions(positions), mMesh(VCVertex::Create) { if (numPositions <= 0 || !positions || numIndices < 3 || !indices) { mNumPositions = 0; mPositions = nullptr; return; } // Build the manifold mesh from the inputs. int32_t numTriangles = numIndices / 3; int32_t const* current = indices; for (int32_t t = 0; t < numTriangles; ++t) { int32_t v0 = *current++; int32_t v1 = *current++; int32_t v2 = *current++; mMesh.Insert(v0, v1, v2); } // Locate the vertices (if any) on the mesh boundary. auto const& vmap = mMesh.GetVertices(); for (auto const& eelement : mMesh.GetEdges()) { auto edge = eelement.second.get(); if (!edge->T[1]) { for (int32_t i = 0; i < 2; ++i) { auto velement = vmap.find(edge->V[i]); auto vertex = static_cast<VCVertex*>(velement->second.get()); vertex->isBoundary = true; } } } // Build the priority queue of weights for the interior vertices. mMinHeap.Reset((int32_t)vmap.size()); for (auto const& velement : vmap) { auto vertex = static_cast<VCVertex*>(velement.second.get()); Real weight; if (vertex->isBoundary) { weight = std::numeric_limits<Real>::max(); } else { weight = vertex->ComputeWeight(mPositions); } auto record = mMinHeap.Insert(velement.first, weight); mHeapRecords.insert(std::make_pair(velement.first, record)); } } // Decimate the mesh using vertex collapses struct Record { Record() : vertex(0), removed{}, inserted{} { } // The index of the interior vertex that is removed from the mesh. // The triangles adjacent to the vertex are 'removed' from the // mesh. The polygon boundary of the adjacent triangles is // triangulated and the new triangles are 'inserted' into the // mesh. int32_t vertex; std::vector<TriangleKey<true>> removed; std::vector<TriangleKey<true>> inserted; }; // Return 'true' when a vertex collapse occurs. Once the function // returns 'false', no more vertex collapses are allowed so you may // then stop calling the function. The implementation has several // consistency tests that should not fail with a theoretically correct // implementation. If a test fails, the function returns 'false' and // the record.vertex is set to the invalid integer 0x80000000. When // the Logger system is enabled, the failed tests are reported to any // Logger listeners. bool DoCollapse(Record& record) { record.vertex = 0x80000000; record.removed.clear(); record.inserted.clear(); if (mNumPositions == 0) { // The constructor failed, so there is nothing to collapse. return false; } while (mMinHeap.GetNumElements() > 0) { int32_t v = -1; Real weight = std::numeric_limits<Real>::max(); mMinHeap.GetMinimum(v, weight); if (weight == std::numeric_limits<Real>::max()) { // There are no more interior vertices to collapse. return false; } auto const& vmap = mMesh.GetVertices(); auto velement = vmap.find(v); if (velement == vmap.end()) { // Unexpected condition. return false; } auto vertex = static_cast<VCVertex*>(velement->second.get()); std::vector<TriangleKey<true>> removed, inserted; std::vector<int32_t> linkVertices; int32_t result = TriangulateLink(vertex, removed, inserted, linkVertices); if (result == VCM_UNEXPECTED_ERROR) { return false; } if (result == VCM_ALLOWED) { result = Collapsed(removed, inserted, linkVertices); if (result == VCM_UNEXPECTED_ERROR) { return false; } if (result == VCM_ALLOWED) { // Remove the vertex and associated weight. mMinHeap.Remove(v, weight); mHeapRecords.erase(v); // Update the weights of the link vertices. for (auto vlink : linkVertices) { velement = vmap.find(vlink); if (velement == vmap.end()) { // Unexpected condition. return false; } vertex = static_cast<VCVertex*>(velement->second.get()); if (!vertex->isBoundary) { auto iter = mHeapRecords.find(vlink); if (iter == mHeapRecords.end()) { // Unexpected condition. return false; } weight = vertex->ComputeWeight(mPositions); mMinHeap.Update(iter->second, weight); } } record.vertex = v; record.removed = std::move(removed); record.inserted = std::move(inserted); return true; } // else: result == VCM_DEFERRED } // To get here, result must be VCM_DEFERRED. The vertex // collapse would cause mesh fold-over. Temporarily set the // edge weight to infinity. After removal of other triangles, // the vertex weight will be updated to a finite value and the // vertex possibly can be removed at that time. auto iter = mHeapRecords.find(v); if (iter == mHeapRecords.end()) { // Unexpected condition. return false; } mMinHeap.Update(iter->second, std::numeric_limits<Real>::max()); } // We do not expect to reach this line of code, even for a closed // mesh. However, the compiler does not know this, yet requires // a return value. return false; } // Access the current state of the mesh, whether the original built // in the constructor or a decimated mesh during DoCollapse calls. inline ETManifoldMesh const& GetMesh() const { return mMesh; } private: struct VCVertex : public VETManifoldMesh::Vertex { VCVertex(int32_t v) : VETManifoldMesh::Vertex(v), normal(Vector3<Real>::Zero()), isBoundary(false) { } static std::unique_ptr<Vertex> Create(int32_t v) { return std::make_unique<VCVertex>(v); } // The weight depends on the area of the triangles sharing the // vertex and the lengths of the projections of the adjacent // vertices onto the vertex normal line. A side effect of the // call is that the vertex normal is computed and stored. Real ComputeWeight(Vector3<Real> const* positions) { Real weight = (Real)0; normal = { (Real)0, (Real)0, (Real)0 }; for (auto const& tri : TAdjacent) { Vector3<Real> E0 = positions[tri->V[1]] - positions[tri->V[0]]; Vector3<Real> E1 = positions[tri->V[2]] - positions[tri->V[0]]; Vector3<Real> N = Cross(E0, E1); normal += N; weight += Length(N); } Normalize(normal); for (int32_t index : VAdjacent) { Vector3<Real> diff = positions[index] - positions[V]; weight += std::fabs(Dot(normal, diff)); } return weight; } Vector3<Real> normal; bool isBoundary; }; // The functions TriangulateLink and Collapsed return one of the // enumerates described next. // // VCM_NO_MORE_ALLOWED: // Either the mesh has no more interior vertices or a collapse // will lead to a mesh fold-over or to a nonmanifold mesh. The // returned value 'v' is invalid (0x80000000) and 'removed' and // 'inserted' are empty. // // VCM_ALLOWED: // An interior vertex v has been removed. This is allowed using // the following algorithm. The vertex normal is the weighted // average of non-unit-length normals of triangles sharing v. The // weights are the triangle areas. The adjacent vertices are // projected onto a plane containing v and having normal equal to // the vertex normal. If the projection is a simple polygon in // the plane, the collapse is allowed. The triangles sharing v // are 'removed', the polygon is triangulated, and the new // triangles are 'inserted' into the mesh. // // VCM_DEFERRED: // If the projection polygon described in the previous case is not // simple (at least one pair of edges overlaps at some // edge-interior point), the collapse would produce a fold-over in // the mesh. We do not collapse in this case. It is possible // that such a vertex occurs in a later collapse as its neighbors // are adjusted by collapses. When this case occurs, v is valid // (even though the collapse was not allowed) but 'removed' and // 'inserted' are empty. // // VCM_UNEXPECTED_ERROR: // The code has several tests for conditions that are not expected // to occur for a theoretically correct implementation. If you // receive this error, file a bug report and provide a data set // that caused the error. enum { VCM_NO_MORE_ALLOWED, VCM_ALLOWED, VCM_DEFERRED, VCM_UNEXPECTED_ERROR }; int32_t TriangulateLink(VCVertex* vertex, std::vector<TriangleKey<true>>& removed, std::vector<TriangleKey<true>>& inserted, std::vector<int32_t>& linkVertices) const { // Create the (CCW) polygon boundary of the link of the vertex. // The incoming vertex is interior, so the number of triangles // sharing the vertex is equal to the number of vertices of the // polygon. A precondition of the function call is that the // vertex normal has already been computed. // Get the edges of the link that are opposite the incoming // vertex. int32_t const numVertices = static_cast<int32_t>(vertex->TAdjacent.size()); removed.resize(numVertices); int32_t j = 0; std::map<int32_t, int32_t> edgeMap; for (auto tri : vertex->TAdjacent) { for (int32_t i = 0; i < 3; ++i) { if (tri->V[i] == vertex->V) { edgeMap.insert(std::make_pair(tri->V[(i + 1) % 3], tri->V[(i + 2) % 3])); break; } } removed[j++] = TriangleKey<true>(tri->V[0], tri->V[1], tri->V[2]); } if (edgeMap.size() != vertex->TAdjacent.size()) { return VCM_UNEXPECTED_ERROR; } // Connect the edges into a polygon. linkVertices.resize(numVertices); auto iter = edgeMap.begin(); for (int32_t i = 0; i < numVertices; ++i) { linkVertices[i] = iter->first; iter = edgeMap.find(iter->second); if (iter == edgeMap.end()) { return VCM_UNEXPECTED_ERROR; } } if (iter->first != linkVertices[0]) { return VCM_UNEXPECTED_ERROR; } // Project the polygon onto the plane containing the incoming // vertex and having the vertex normal. The projected polygon // is computed so that the incoming vertex is projected to (0,0). Vector3<Real> center = mPositions[vertex->V]; Vector3<Real> basis[3]; basis[0] = vertex->normal; ComputeOrthogonalComplement(1, basis); std::vector<Vector2<Real>> projected(numVertices); std::vector<int32_t> indices(numVertices); for (int32_t i = 0; i < numVertices; ++i) { Vector3<Real> diff = mPositions[linkVertices[i]] - center; projected[i][0] = Dot(basis[1], diff); projected[i][1] = Dot(basis[2], diff); indices[i] = i; } // The polygon must be simple in order to triangulate it. Polygon2<Real> polygon(projected.data(), numVertices, indices.data(), true); if (polygon.IsSimple()) { TriangulateEC<Real, Real> triangulator(numVertices, projected.data()); triangulator(); auto const& triangles = triangulator.GetTriangles(); if (triangles.size() == 0) { return VCM_UNEXPECTED_ERROR; } int32_t const numTriangles = static_cast<int32_t>(triangles.size()); inserted.resize(numTriangles); for (int32_t t = 0; t < numTriangles; ++t) { inserted[t] = TriangleKey<true>( linkVertices[triangles[t][0]], linkVertices[triangles[t][1]], linkVertices[triangles[t][2]]); } return VCM_ALLOWED; } else { return VCM_DEFERRED; } } int32_t Collapsed(std::vector<TriangleKey<true>> const& removed, std::vector<TriangleKey<true>> const& inserted, std::vector<int32_t> const& linkVertices) { // The triangles that were disconnected from the link edges are // guaranteed to allow manifold reconnection to 'inserted' // triangles. On the insertion, each diagonal of the link becomes // a mesh edge and shares two (link) triangles. It is possible // that the mesh already contains the (diagonal) edge, which will // lead to a nonmanifold connection, which we cannot allow. The // following code traps this condition and restores the mesh to // its state before the 'Remove(...)' call. bool isCollapsible = true; auto const& emap = mMesh.GetEdges(); std::set<EdgeKey<false>> edges; for (auto const& tri : inserted) { for (int32_t k0 = 2, k1 = 0; k1 < 3; k0 = k1++) { EdgeKey<false> edge(tri.V[k0], tri.V[k1]); if (edges.find(edge) == edges.end()) { edges.insert(edge); } else { // The edge has been visited twice, so it is a // diagonal of the link. auto eelement = emap.find(edge); if (eelement != emap.end()) { if (eelement->second->T[1]) { // The edge will not allow a manifold // connection. isCollapsible = false; break; } } edges.erase(edge); } }; if (!isCollapsible) { return VCM_DEFERRED; } } // Remove the old triangle neighborhood, which will lead to the // vertex itself being removed from the mesh. for (auto tri : removed) { mMesh.Remove(tri.V[0], tri.V[1], tri.V[2]); } // Insert the new triangulation. for (auto const& tri : inserted) { mMesh.Insert(tri.V[0], tri.V[1], tri.V[2]); } // If the Remove(...) calls remove a boundary vertex that is in // the link vertices, the Insert(...) calls will insert the // boundary vertex again. We must re-tag those boundary // vertices. auto const& vmap = mMesh.GetVertices(); size_t const numVertices = linkVertices.size(); for (size_t i0 = numVertices - 1, i1 = 0; i1 < numVertices; i0 = i1++) { EdgeKey<false> ekey(linkVertices[i0], linkVertices[i1]); auto eelement = emap.find(ekey); if (eelement == emap.end()) { return VCM_UNEXPECTED_ERROR; } auto edge = eelement->second.get(); if (!edge) { return VCM_UNEXPECTED_ERROR; } if (edge->T[0] && !edge->T[1]) { for (int32_t k = 0; k < 2; ++k) { auto velement = vmap.find(edge->V[k]); if (velement == vmap.end()) { return VCM_UNEXPECTED_ERROR; } auto vertex = static_cast<VCVertex*>(velement->second.get()); vertex->isBoundary = true; } } } return VCM_ALLOWED; } int32_t mNumPositions; Vector3<Real> const* mPositions; VETManifoldMesh mMesh; MinHeap<int32_t, Real> mMinHeap; std::map<int32_t, typename MinHeap<int32_t, Real>::Record*> mHeapRecords; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPoint3Frustum3.h
.h
16,945
438
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Frustum3.h> // The algorithm for computing the distance from a point to an orthogonal // frustum is described in // https://www.geometrictools.com/Documentation/DistancePointToFrustum.pdf namespace gte { template <typename T> class DCPQuery<T, Vector3<T>, Frustum3<T>> { public: // The input point is stored in the member closest[0]. The frustum // point closest to it is stored in the member closest[1]. struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<Vector3<T>, 2> closest; }; Result operator()(Vector3<T> const& point, Frustum3<T> const& frustum) { Result result{}; // Compute coordinates of point with respect to frustum coordinate // system. Vector3<T> diff = point - frustum.origin; Vector3<T> test = { Dot(diff, frustum.rVector), Dot(diff, frustum.uVector), Dot(diff, frustum.dVector) }; // Perform calculations in octant with nonnegative R and U // coordinates. bool rSignChange; if (test[0] < (T)0) { rSignChange = true; test[0] = -test[0]; } else { rSignChange = false; } bool uSignChange; if (test[1] < (T)0) { uSignChange = true; test[1] = -test[1]; } else { uSignChange = false; } // Frustum derived parameters. T rmin = frustum.rBound; T rmax = frustum.GetDRatio() * rmin; T umin = frustum.uBound; T umax = frustum.GetDRatio() * umin; T dmin = frustum.dMin; T dmax = frustum.dMax; T rminSqr = rmin * rmin; T uminSqr = umin * umin; T dminSqr = dmin * dmin; T minRDDot = rminSqr + dminSqr; T minUDDot = uminSqr + dminSqr; T minRUDDot = rminSqr + minUDDot; T maxRDDot = frustum.GetDRatio() * minRDDot; T maxUDDot = frustum.GetDRatio() * minUDDot; T maxRUDDot = frustum.GetDRatio() * minRUDDot; // Algorithm computes closest point in all cases by determining // in which Voronoi region of the vertices, edges, and faces of // the frustum that the test point lives. Vector3<T> closest{}; T rDot, uDot, rdDot, udDot, rudDot, rEdgeDot, uEdgeDot, t; if (test[2] >= dmax) { if (test[0] <= rmax) { if (test[1] <= umax) { // F-face closest[0] = test[0]; closest[1] = test[1]; closest[2] = dmax; } else { // UF-edge closest[0] = test[0]; closest[1] = umax; closest[2] = dmax; } } else { if (test[1] <= umax) { // LF-edge closest[0] = rmax; closest[1] = test[1]; closest[2] = dmax; } else { // LUF-vertex closest[0] = rmax; closest[1] = umax; closest[2] = dmax; } } } else if (test[2] <= dmin) { if (test[0] <= rmin) { if (test[1] <= umin) { // N-face closest[0] = test[0]; closest[1] = test[1]; closest[2] = dmin; } else { udDot = umin * test[1] + dmin * test[2]; if (udDot >= maxUDDot) { // UF-edge closest[0] = test[0]; closest[1] = umax; closest[2] = dmax; } else if (udDot >= minUDDot) { // U-face uDot = dmin * test[1] - umin * test[2]; t = uDot / minUDDot; closest[0] = test[0]; closest[1] = test[1] - t * dmin; closest[2] = test[2] + t * umin; } else { // UN-edge closest[0] = test[0]; closest[1] = umin; closest[2] = dmin; } } } else { if (test[1] <= umin) { rdDot = rmin * test[0] + dmin * test[2]; if (rdDot >= maxRDDot) { // LF-edge closest[0] = rmax; closest[1] = test[1]; closest[2] = dmax; } else if (rdDot >= minRDDot) { // L-face rDot = dmin * test[0] - rmin * test[2]; t = rDot / minRDDot; closest[0] = test[0] - t * dmin; closest[1] = test[1]; closest[2] = test[2] + t * rmin; } else { // LN-edge closest[0] = rmin; closest[1] = test[1]; closest[2] = dmin; } } else { rudDot = rmin * test[0] + umin * test[1] + dmin * test[2]; rEdgeDot = umin * rudDot - minRUDDot * test[1]; if (rEdgeDot >= (T)0) { rdDot = rmin * test[0] + dmin * test[2]; if (rdDot >= maxRDDot) { // LF-edge closest[0] = rmax; closest[1] = test[1]; closest[2] = dmax; } else if (rdDot >= minRDDot) { // L-face rDot = dmin * test[0] - rmin * test[2]; t = rDot / minRDDot; closest[0] = test[0] - t * dmin; closest[1] = test[1]; closest[2] = test[2] + t * rmin; } else { // LN-edge closest[0] = rmin; closest[1] = test[1]; closest[2] = dmin; } } else { uEdgeDot = rmin * rudDot - minRUDDot * test[0]; if (uEdgeDot >= (T)0) { udDot = umin * test[1] + dmin * test[2]; if (udDot >= maxUDDot) { // UF-edge closest[0] = test[0]; closest[1] = umax; closest[2] = dmax; } else if (udDot >= minUDDot) { // U-face uDot = dmin * test[1] - umin * test[2]; t = uDot / minUDDot; closest[0] = test[0]; closest[1] = test[1] - t * dmin; closest[2] = test[2] + t * umin; } else { // UN-edge closest[0] = test[0]; closest[1] = umin; closest[2] = dmin; } } else { if (rudDot >= maxRUDDot) { // LUF-vertex closest[0] = rmax; closest[1] = umax; closest[2] = dmax; } else if (rudDot >= minRUDDot) { // LU-edge t = rudDot / minRUDDot; closest[0] = t * rmin; closest[1] = t * umin; closest[2] = t * dmin; } else { // LUN-vertex closest[0] = rmin; closest[1] = umin; closest[2] = dmin; } } } } } } else { rDot = dmin * test[0] - rmin * test[2]; uDot = dmin * test[1] - umin * test[2]; if (rDot <= (T)0) { if (uDot <= (T)0) { // point inside frustum closest = test; } else { udDot = umin * test[1] + dmin * test[2]; if (udDot >= maxUDDot) { // UF-edge closest[0] = test[0]; closest[1] = umax; closest[2] = dmax; } else { // U-face t = uDot / minUDDot; closest[0] = test[0]; closest[1] = test[1] - t * dmin; closest[2] = test[2] + t * umin; } } } else { if (uDot <= (T)0) { rdDot = rmin * test[0] + dmin * test[2]; if (rdDot >= maxRDDot) { // LF-edge closest[0] = rmax; closest[1] = test[1]; closest[2] = dmax; } else { // L-face t = rDot / minRDDot; closest[0] = test[0] - t * dmin; closest[1] = test[1]; closest[2] = test[2] + t * rmin; } } else { rudDot = rmin * test[0] + umin * test[1] + dmin * test[2]; rEdgeDot = umin * rudDot - minRUDDot * test[1]; if (rEdgeDot >= (T)0) { rdDot = rmin * test[0] + dmin * test[2]; if (rdDot >= maxRDDot) { // LF-edge closest[0] = rmax; closest[1] = test[1]; closest[2] = dmax; } else // assert( rdDot >= minRDDot ) { // L-face t = rDot / minRDDot; closest[0] = test[0] - t * dmin; closest[1] = test[1]; closest[2] = test[2] + t * rmin; } } else { uEdgeDot = rmin * rudDot - minRUDDot * test[0]; if (uEdgeDot >= (T)0) { udDot = umin * test[1] + dmin * test[2]; if (udDot >= maxUDDot) { // UF-edge closest[0] = test[0]; closest[1] = umax; closest[2] = dmax; } else // assert( udDot >= minUDDot ) { // U-face t = uDot / minUDDot; closest[0] = test[0]; closest[1] = test[1] - t * dmin; closest[2] = test[2] + t * umin; } } else { if (rudDot >= maxRUDDot) { // LUF-vertex closest[0] = rmax; closest[1] = umax; closest[2] = dmax; } else // assert( rudDot >= minRUDDot ) { // LU-edge t = rudDot / minRUDDot; closest[0] = t * rmin; closest[1] = t * umin; closest[2] = t * dmin; } } } } } } diff = test - closest; // Convert back to original quadrant. if (rSignChange) { closest[0] = -closest[0]; } if (uSignChange) { closest[1] = -closest[1]; } // Convert back to original coordinates. result.closest[0] = point; result.closest[1] = frustum.origin + closest[0] * frustum.rVector + closest[1] * frustum.uVector + closest[2] * frustum.dVector; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Vector2.h
.h
9,733
255
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.31 #pragma once #include <Mathematics/Vector.h> #include <array> namespace gte { // Template alias for convenience. template <typename Real> using Vector2 = Vector<2, Real>; // Compute the perpendicular using the formal determinant, // perp = det{{e0,e1},{x0,x1}} = (x1,-x0) // where e0 = (1,0), e1 = (0,1), and v = (x0,x1). template <typename Real> Vector2<Real> Perp(Vector2<Real> const& v) { return Vector2<Real>{ v[1], -v[0] }; } // Compute the normalized perpendicular. template <typename Real> Vector2<Real> UnitPerp(Vector2<Real> const& v, bool robust = false) { Vector2<Real> unitPerp{ v[1], -v[0] }; Normalize(unitPerp, robust); return unitPerp; } // Compute Dot((x0,x1),Perp(y0,y1)) = x0*y1 - x1*y0, where v0 = (x0,x1) // and v1 = (y0,y1). template <typename Real> Real DotPerp(Vector2<Real> const& v0, Vector2<Real> const& v1) { return Dot(v0, Perp(v1)); } // Compute a right-handed orthonormal basis for the orthogonal complement // of the input vectors. The function returns the smallest length of the // unnormalized vectors computed during the process. If this value is // nearly zero, it is possible that the inputs are linearly dependent // (within numerical round-off errors). On input, numInputs must be 1 and // v[0] must be initialized. On output, the vectors v[0] and v[1] form an // orthonormal set. template <typename Real> Real ComputeOrthogonalComplement(int32_t numInputs, Vector2<Real>* v, bool robust = false) { if (numInputs == 1) { v[1] = -Perp(v[0]); return Orthonormalize<2, Real>(2, v, robust); } return (Real)0; } // Compute the barycentric coordinates of the point P with respect to the // triangle <V0,V1,V2>, P = b0*V0 + b1*V1 + b2*V2, where b0 + b1 + b2 = 1. // The return value is 'true' iff {V0,V1,V2} is a linearly independent // set. Numerically, this is measured by |det[V0 V1 V2]| <= epsilon. The // values bary[] are valid only when the return value is 'true' but set to // zero when the return value is 'false'. template <typename Real> bool ComputeBarycentrics(Vector2<Real> const& p, Vector2<Real> const& v0, Vector2<Real> const& v1, Vector2<Real> const& v2, std::array<Real, 3>& bary, Real epsilon = static_cast<Real>(0)) { // Compute the vectors relative to V2 of the triangle. std::array<Vector2<Real>, 3> diff = { v0 - v2, v1 - v2, p - v2 }; Real det = DotPerp(diff[0], diff[1]); if (det < -epsilon || det > epsilon) { bary[0] = DotPerp(diff[2], diff[1]) / det; bary[1] = DotPerp(diff[0], diff[2]) / det; bary[2] = static_cast<Real>(1) - bary[0] - bary[1]; return true; } bary.fill(static_cast<Real>(0)); return false; } // Get intrinsic information about the input array of vectors. The return // value is 'true' iff the inputs are valid (numVectors > 0, v is not // null, and epsilon >= 0), in which case the class members are valid. template <typename Real> class IntrinsicsVector2 { public: // The constructor sets the class members based on the input set. IntrinsicsVector2(int32_t numVectors, Vector2<Real> const* v, Real inEpsilon) : epsilon(inEpsilon), dimension(0), maxRange((Real)0), origin{ (Real)0, (Real)0 }, extremeCCW(false) { min[0] = (Real)0; min[1] = (Real)0; max[0] = (Real)0; max[1] = (Real)0; direction[0] = { (Real)0, (Real)0 }; direction[1] = { (Real)0, (Real)0 }; extreme[0] = 0; extreme[1] = 0; extreme[2] = 0; if (numVectors > 0 && v && epsilon >= (Real)0) { // Compute the axis-aligned bounding box for the input // vectors. Keep track of the indices into 'vectors' for the // current min and max. int32_t j{}; std::array<int32_t, 2> indexMin{}, indexMax{}; for (j = 0; j < 2; ++j) { min[j] = v[0][j]; max[j] = min[j]; indexMin[j] = 0; indexMax[j] = 0; } int32_t i; for (i = 1; i < numVectors; ++i) { for (j = 0; j < 2; ++j) { if (v[i][j] < min[j]) { min[j] = v[i][j]; indexMin[j] = i; } else if (v[i][j] > max[j]) { max[j] = v[i][j]; indexMax[j] = i; } } } // Determine the maximum range for the bounding box. maxRange = max[0] - min[0]; extreme[0] = indexMin[0]; extreme[1] = indexMax[0]; Real range = max[1] - min[1]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[1]; extreme[1] = indexMax[1]; } // The origin is either the vector of minimum x0-value or // vector of minimum x1-value. origin = v[extreme[0]]; // Test whether the vector set is (nearly) a vector. if (maxRange <= epsilon) { dimension = 0; for (j = 0; j < 2; ++j) { extreme[j + 1] = extreme[0]; } return; } // Test whether the vector set is (nearly) a line segment. We // need direction[1] to span the orthogonal complement of // direction[0]. direction[0] = v[extreme[1]] - origin; Normalize(direction[0], false); direction[1] = -Perp(direction[0]); // Compute the maximum distance of the points from the line // origin+t*direction[0]. Real maxDistance = (Real)0; Real maxSign = (Real)0; extreme[2] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector2<Real> diff = v[i] - origin; Real distance = Dot(direction[1], diff); Real sign = (distance > (Real)0 ? (Real)1 : (distance < (Real)0 ? (Real)-1 : (Real)0)); distance = std::fabs(distance); if (distance > maxDistance) { maxDistance = distance; maxSign = sign; extreme[2] = i; } } if (maxDistance <= epsilon * maxRange) { // The points are (nearly) on the line // origin + t * direction[0]. dimension = 1; extreme[2] = extreme[1]; return; } dimension = 2; extremeCCW = (maxSign > (Real)0); return; } } // A nonnegative tolerance that is used to determine the intrinsic // dimension of the set. Real epsilon; // The intrinsic dimension of the input set, computed based on the // nonnegative tolerance mEpsilon. int32_t dimension; // Axis-aligned bounding box of the input set. The maximum range is // the larger of max[0]-min[0] and max[1]-min[1]. Real min[2], max[2]; Real maxRange; // Coordinate system. The origin is valid for any dimension d. The // unit-length direction vector is valid only for 0 <= i < d. The // extreme index is relative to the array of input points, and is also // valid only for 0 <= i < d. If d = 0, all points are effectively // the same, but the use of an epsilon may lead to an extreme index // that is not zero. If d = 1, all points effectively lie on a line // segment. If d = 2, the points are not collinear. Vector2<Real> origin; Vector2<Real> direction[2]; // The indices that define the maximum dimensional extents. The // values extreme[0] and extreme[1] are the indices for the points // that define the largest extent in one of the coordinate axis // directions. If the dimension is 2, then extreme[2] is the index // for the point that generates the largest extent in the direction // perpendicular to the line through the points corresponding to // extreme[0] and extreme[1]. The triangle formed by the points // V[extreme[0]], V[extreme[1]], and V[extreme[2]] is clockwise or // counterclockwise, the condition stored in extremeCCW. int32_t extreme[3]; bool extremeCCW; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine3Rectangle3.h
.h
6,280
157
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLineSegment.h> #include <Mathematics/Rectangle.h> #include <Mathematics/Vector3.h> // Compute the distance between a line and a solid rectangle in 3D. // // The line is P + t * D, where D is not required to be unit length. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The closest point on the line is stored in closest[0] with parameter t. The // closest point on the rectangle is stored in closest[1] with W-coordinates // (s[0],s[1]). When there are infinitely many choices for the pair of closest // points, only one of them is returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Line3<T>, Rectangle3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter(static_cast<T>(0)), cartesian{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; T parameter; std::array<T, 2> cartesian; std::array<Vector3<T>, 2> closest; }; Result operator()(Line3<T> const& line, Rectangle3<T> const& rectangle) { Result result{}; // Test whether the line intersects rectangle. If so, the squared // distance is zero. The normal of the plane of the rectangle does // not have to be normalized to unit length. T const zero = static_cast<T>(0); Vector3<T> N = Cross(rectangle.axis[0], rectangle.axis[1]); T NdD = Dot(N, line.direction); if (std::fabs(NdD) > zero) { // The line and rectangle are not parallel, so the line // intersects the plane of the rectangle at a point Y. // Determine whether Y is contained by the rectangle. Vector3<T> PmC = line.origin - rectangle.center; T NdDiff = Dot(N, PmC); T tIntersect = -NdDiff / NdD; Vector3<T> Y = line.origin + tIntersect * line.direction; Vector3<T> YmC = Y - rectangle.center; // Compute the rectangle coordinates of the intersection. T s0 = Dot(rectangle.axis[0], YmC); T s1 = Dot(rectangle.axis[1], YmC); if (std::fabs(s0) <= rectangle.extent[0] && std::fabs(s1) <= rectangle.extent[1]) { // The point Y is contained by the rectangle. result.sqrDistance = zero; result.distance = zero; result.parameter = tIntersect; result.cartesian[0] = s0; result.cartesian[1] = s1; result.closest[0] = Y; result.closest[1] = Y; return result; } } // Either (1) the line is not parallel to the rectangle and the // point of intersection of the line and the plane of the // rectangle is outside the rectangle or (2) the line and // rectangle are parallel. Regardless, the closest point on the // rectangle is on an edge of the rectangle. Compare the line to // all four edges of the rectangle. To allow for arbitrary // precision arithmetic, the initial distance and sqrDistance are // initialized to a negative number rather than a floating-point // maximum value. Tracking the minimum requires a small amount of // extra logic. using LSQuery = DCPQuery<T, Line3<T>, Segment3<T>>; LSQuery lsQuery{}; typename LSQuery::Result lsResult{}; Segment3<T> segment{}; T const one = static_cast<T>(1); T const negOne = static_cast<T>(-1); T const two = static_cast<T>(2); T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; std::array<T, 4> const sign{ negOne, one, negOne, one }; std::array<int32_t, 4> j0{ 0, 0, 1, 1 }; std::array<int32_t, 4> j1{ 1, 1, 0, 0 }; std::array<std::array<size_t, 2>, 4> const edges {{ // horizontal edges (y = +e1 or -e1) { 0, 1 }, { 2, 3 }, // vertical edges (x = +e0 or -e0) { 0, 2 }, { 1, 3 } }}; std::array<Vector3<T>, 4> vertices{}; rectangle.GetVertices(vertices); for (size_t i = 0; i < 4; ++i) { auto const& edge = edges[i]; segment.p[0] = vertices[edge[0]]; segment.p[1] = vertices[edge[1]]; lsResult = lsQuery(line, segment); if (result.sqrDistance == invalid || lsResult.sqrDistance < result.sqrDistance) { result.sqrDistance = lsResult.sqrDistance; result.distance = lsResult.distance; result.parameter = lsResult.parameter[0]; result.closest = lsResult.closest; T const scale = two * lsResult.parameter[1] - one; result.cartesian[j0[i]] = scale * rectangle.extent[j0[i]]; result.cartesian[j1[i]] = sign[i] * rectangle.extent[j1[i]]; } } return result; } }; // Template alias for convenience. template <typename T> using DCPLine3Rectangle3 = DCPQuery<T, Line3<T>, Rectangle3<T>>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OrientedBox.h
.h
4,057
144
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> // A box has center C, axis directions U[i], and extents e[i]. The set // {U[0],...,U[N-1]} is orthonormal, which means the vectors are // unit-length and mutually perpendicular. The extents are nonnegative; // zero is allowed, meaning the box is degenerate in the corresponding // direction. A point X is represented in box coordinates by // X = C + y[0]*U[0] + y[1]*U[1]. This point is inside or on the // box whenever |y[i]| <= e[i] for all i. namespace gte { template <int32_t N, typename T> class OrientedBox { public: // Construction and destruction. The default constructor sets the // center to (0,...,0), axis d to Vector<N,T>::Unit(d) and // extent d to +1. OrientedBox() { center.MakeZero(); for (int32_t i = 0; i < N; ++i) { axis[i].MakeUnit(i); extent[i] = (T)1; } } OrientedBox(Vector<N, T> const& inCenter, std::array<Vector<N, T>, N> const& inAxis, Vector<N, T> const& inExtent) : center(inCenter), axis(inAxis), extent(inExtent) { } // Compute the vertices of the box. If index i has the bit pattern // i = b[N-1]...b[0], then // vertex[i] = center + sum_{d=0}^{N-1} sign[d] * extent[d] * axis[d] // where sign[d] = 2*b[d] - 1. void GetVertices(std::array<Vector<N, T>, (1 << N)>& vertex) const { std::array<Vector<N, T>, N> product; for (int32_t d = 0; d < N; ++d) { product[d] = extent[d] * axis[d]; } int32_t const imax = (1 << N); for (int32_t i = 0; i < imax; ++i) { vertex[i] = center; for (int32_t d = 0, mask = 1; d < N; ++d, mask <<= 1) { if ((i & mask) > 0) { vertex[i] += product[d]; } else { vertex[i] -= product[d]; } } } } // Public member access. It is required that extent[i] >= 0. Vector<N, T> center; std::array<Vector<N, T>, N> axis; Vector<N, T> extent; public: // Comparisons to support sorted containers. bool operator==(OrientedBox const& box) const { return center == box.center && axis == box.axis && extent == box.extent; } bool operator!=(OrientedBox const& box) const { return !operator==(box); } bool operator< (OrientedBox const& box) const { if (center < box.center) { return true; } if (center > box.center) { return false; } if (axis < box.axis) { return true; } if (axis > box.axis) { return false; } return extent < box.extent; } bool operator<=(OrientedBox const& box) const { return !box.operator<(*this); } bool operator> (OrientedBox const& box) const { return box.operator<(*this); } bool operator>=(OrientedBox const& box) const { return !operator<(box); } }; // Template aliases for convenience. template <typename T> using OrientedBox2 = OrientedBox<2, T>; template <typename T> using OrientedBox3 = OrientedBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/APConversion.h
.h
20,982
503
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/QFNumber.h> // The conversion functions here are used to obtain arbitrary-precision // approximations to rational numbers and to quadratic field numbers. // The arbitrary-precision arithmetic is described in // https://www.geometrictools.com/Documentation/ArbitraryPrecision.pdf // The quadratic field numbers and conversions are described in // https://www.geometrictools.com/Documentation/QuadraticFields.pdf namespace gte { template <typename Rational> class APConversion { public: using QFN1 = QFNumber<Rational, 1>; using QFN2 = QFNumber<Rational, 2>; // Construction and destruction. APConversion(int32_t precision, uint32_t maxIterations) : mZero(0), mOne(1), mThree(3), mFive(5), mPrecision(precision), mMaxIterations(maxIterations), mThreshold(std::ldexp(mOne, -mPrecision)) { LogAssert(precision > 0, "Invalid precision."); LogAssert(maxIterations > 0, "Invalid maximum iterations."); } ~APConversion() { } // Member access. void SetPrecision(int32_t precision) { LogAssert(precision > 0, "Invalid precision."); mPrecision = precision; mThreshold = std::ldexp(mOne, -mPrecision); } void SetMaxIterations(uint32_t maxIterations) { LogAssert(maxIterations > 0, "Invalid maximum iterations."); mMaxIterations = maxIterations; } inline int32_t GetPrecision() const { return mPrecision; } inline uint32_t GetMaxIterations() const { return mMaxIterations; } // Disallow copying and moving. APConversion(APConversion const&) = delete; APConversion(APConversion&&) = delete; APConversion& operator=(APConversion const&) = delete; APConversion& operator=(APConversion&&) = delete; // The input a^2 is rational, but a itself is usually irrational, // although a rational value is allowed. Compute a bounding interval // for the root, aMin <= a <= aMax, where the endpoints are both // within the specified precision. uint32_t EstimateSqrt(Rational const& aSqr, Rational& aMin, Rational& aMax) { // Factor a^2 = r^2 * 2^e, where r^2 in [1/2,1). Compute s^2 and // the exponent used to generate the estimate of sqrt(a^2). Rational sSqr; int32_t exponentA; PreprocessSqr(aSqr, sSqr, exponentA); // Use the FPU to estimate s = sqrt(sSqr) to 53-bit precision with // rounding up. Multiply by the appropriate exponent to obtain // upper bound aMax > a. aMax = GetMaxOfSqrt(sSqr, exponentA); // Compute a lower bound aMin < a. aMin = aSqr / aMax; // Compute Newton iterates until convergence. The estimate closest // to a is aMin with aMin <= a <= aMax and a - aMin <= aMax - a. uint32_t iterate; for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (aMax - aMin < mThreshold) { break; } // Compute the average aMax = (aMin + aMax) / 2. Round up // to twice the precision to avoid quadratic growth in the // number of bits and to ensure that aMin can increase. aMax = std::ldexp(aMin + aMax, -1); Convert(aMax, 2 * mPrecision, FE_UPWARD, aMax); aMin = aSqr / aMax; } return iterate; } // Compute an estimate of the root when you do not need a bounding // interval. uint32_t EstimateSqrt(Rational const& aSqr, Rational& a) { // Compute a bounding interval aMin <= a <= aMax. Rational aMin, aMax; uint32_t numIterates = EstimateSqrt(aSqr, aMin, aMax); // Use the average of the interval endpoints as the estimate. a = std::ldexp(aMin + aMax, -1); return numIterates; } uint32_t EstimateApB(Rational const& aSqr, Rational const& bSqr, Rational& tMin, Rational& tMax) { // Factor a^2 = r^2 * 2^e, where r^2 in [1/2,1). Compute u^2 and // the exponent used to generate the estimate of sqrt(a^2). Rational uSqr; int32_t exponentA; PreprocessSqr(aSqr, uSqr, exponentA); // Factor b^2 = s^2 * 2^e, where s^2 in [1/2,1). Compute v^2 and // the exponent used to generate the estimate of sqrt(b^2). Rational vSqr; int32_t exponentB; PreprocessSqr(bSqr, vSqr, exponentB); // Use the FPU to estimate u = sqrt(u^2) and v = sqrt(v^2) to // 53 bits of precision with rounding up. Multiply by the // appropriate exponents to obtain upper bounds aMax > a and // bMax > b. This ensures tMax = aMax + bMax > a + b. Rational aMax = GetMaxOfSqrt(uSqr, exponentA); Rational bMax = GetMaxOfSqrt(vSqr, exponentB); tMax = aMax + bMax; // Compute a lower bound tMin < a + b. Rational a2pb2 = aSqr + bSqr; Rational a2mb2 = aSqr - bSqr; Rational a2mb2Sqr = a2mb2 * a2mb2; Rational tMaxSqr = tMax * tMax; tMin = (a2pb2 * tMaxSqr - a2mb2Sqr) / (tMax * (tMaxSqr - a2pb2)); // Compute Newton iterates until convergence. The estimate closest // to a + b is tMin with tMin < a + b < tMax and // (a + b) - tMin < tMax - (a + b). uint32_t iterate; for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (tMax - tMin < mThreshold) { break; } // Compute the weighted average tMax = (3*tMin + tMax) / 4. // Round up to twice the precision to avoid quadratic growth // in the number of bits and to ensure that tMin can increase. tMax = std::ldexp(mThree * tMax + tMin, -2); Convert(tMax, 2 * mPrecision, FE_UPWARD, tMax); tMaxSqr = tMax * tMax; tMin = (a2pb2 * tMaxSqr - a2mb2Sqr) / (tMax * (tMaxSqr - a2pb2)); } return iterate; } uint32_t EstimateAmB(Rational const& aSqr, Rational const& bSqr, Rational& tMin, Rational& tMax) { // The return value of the function. uint32_t iterate = 0; // Compute various quantities that are used later in the code. Rational a2tb2 = aSqr * bSqr; // a^2 * b^2 Rational a2pb2 = aSqr + bSqr; // a^2 + b^2 Rational a2mb2 = aSqr - bSqr; // a^2 - b^2 Rational a2mb2Sqr = a2mb2 * a2mb2; // (a^2 - b^2)^2 Rational twoa2pb2 = std::ldexp(a2pb2, 1); // 2 * (a^2 + b^2) // Factor a^2 = r^2 * 2^e, where r^2 in [1/2,1). Compute u^2 and // the exponent used to generate the estimate of sqrt(a^2). Rational uSqr; int32_t exponentA; PreprocessSqr(aSqr, uSqr, exponentA); // Factor b^2 = s^2 * 2^e, where s^2 in [1/2,1). Compute v^2 and // the exponent used to generate the estimate of sqrt(b^2). Rational vSqr; int32_t exponentB; PreprocessSqr(bSqr, vSqr, exponentB); // Compute the sign of f''(a-b)/8 = a^2 - 3*a*b + b^2. It can be // shown that Sign(a^2-3*a*b+b^2) = Sign(a^4-7*a^2*b^2+b^4) = // Sign((a^2-b^2)^2-5*a^2*b^2). Rational signSecDer = a2mb2Sqr - mFive * a2tb2; // Local variables shared by the two main blocks of code. Rational aMin, aMax, bMin, bMax, tMinSqr, tMaxSqr, tMid, tMidSqr, f; if (signSecDer > mZero) { // Choose an initial guess tMin < a-b. Use the FPU to // estimate u = sqrt(u^2) and v = sqrt(v^2) to 53 bits of // precision with specified rounding. Multiply by the // appropriate exponents to obtain tMin = aMin - bMax < a-b. aMin = GetMinOfSqrt(uSqr, exponentA); bMax = GetMaxOfSqrt(vSqr, exponentB); tMin = aMin - bMax; // When a-b is nearly zero, it is possible the lower bound is // negative. Clamp tMin to zero to stay on the nonnegative // t-axis where the f"-positive basin is. if (tMin < mZero) { tMin = mZero; } // Test whether tMin is in the positive f"(t) basin containing // a-b. If it is not, compute a tMin that is in the basis. The // sign test is applied to f"(t)/4 = 3*t^2 - (a^2+b^2). tMinSqr = tMin * tMin; signSecDer = mThree * tMinSqr - a2pb2; if (signSecDer < mZero) { // The initial guess satisfies f"(tMin) < 0. Compute an // upper bound tMax > a-b and bisect [tMin,tMax] until // either the t-value is an estimate to a-b within the // specified precision or until f"(t) >= 0 and f(t) >= 0. // In the latter case, continue on to Newton's method, // which is then guaranteed to converge. aMax = GetMaxOfSqrt(uSqr, exponentA); bMin = GetMinOfSqrt(vSqr, exponentB); tMax = aMax - bMin; for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (tMax - tMin < mThreshold) { return iterate; } tMid = std::ldexp(tMin + tMax, -1); tMidSqr = tMid * tMid; signSecDer = mThree * tMidSqr - a2pb2; if (signSecDer >= mZero) { f = tMidSqr * (tMidSqr - twoa2pb2) + a2mb2Sqr; if (f >= mZero) { tMin = tMid; tMinSqr = tMidSqr; break; } else { // Round up to twice the precision to avoid // quadratic growth in the number of bits. tMax = tMid; Convert(tMax, 2 * mPrecision, FE_UPWARD, tMax); } } else { // Round down to twice the precision to avoid // quadratic growth in the number of bits. tMin = tMid; Convert(tMin, 2 * mPrecision, FE_DOWNWARD, tMin); } } } // Compute an upper bound tMax > a-b. tMax = (a2pb2 * tMinSqr - a2mb2Sqr) / (tMin * (tMinSqr - a2pb2)); // Compute Newton iterates until convergence. The estimate // closest to a-b is tMax with tMin < a-b < tMax and // tMax - (a-b) < (a-b) - tMin. for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (tMax - tMin < mThreshold) { break; } // Compute the weighted average tMin = (3*tMin+tMax)/4. // Round down to twice the precision to avoid quadratic // growth in the number of bits and to ensure that tMax // can decrease. tMin = std::ldexp(mThree * tMin + tMax, -2); Convert(tMin, 2 * mPrecision, FE_DOWNWARD, tMin); tMinSqr = tMin * tMin; tMax = (a2pb2 * tMinSqr - a2mb2Sqr) / (tMin * (tMinSqr - a2pb2)); } return iterate; } if (signSecDer < mZero) { // Choose an initial guess tMax > a-b. Use the FPU to // estimate u = sqrt(u^2) and v = sqrt(v^2) to 53 bits of // precision with specified rounding. Multiply by the // appropriate exponents to obtain tMax = aMax - bMin > a-b. aMax = GetMaxOfSqrt(uSqr, exponentA); bMin = GetMinOfSqrt(vSqr, exponentB); tMax = aMax - bMin; // Test whether tMax is in the negative f"(t) basin containing // a-b. If it is not, compute a tMax that is in the basis. The // sign test is applied to f"(t)/4 = 3*t^2 - (a^2+b^2). tMaxSqr = tMax * tMax; signSecDer = mThree * tMaxSqr - a2pb2; if (signSecDer > mZero) { // The initial guess satisfies f"(tMax) > 0. Compute a // lower bound tMin < a-b and bisect [tMin,tMax] until // either the t-value is an estimate to a-b within the // specified precision or until f"(t) <= 0 and f(t) <= 0. // In the latter case, continue on to Newton's method, // which is then guaranteed to converge. aMin = GetMinOfSqrt(uSqr, exponentA); bMax = GetMaxOfSqrt(vSqr, exponentB); tMin = aMin - bMax; for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (tMax - tMin < mThreshold) { return iterate; } tMid = std::ldexp(tMin + tMax, -1); tMidSqr = tMid * tMid; signSecDer = mThree * tMidSqr - a2pb2; if (signSecDer <= mZero) { f = tMidSqr * (tMidSqr - twoa2pb2) + a2mb2Sqr; if (f <= mZero) { tMax = tMid; tMaxSqr = tMidSqr; break; } else { // Round down to twice the precision to avoid // quadratic growth in the number of bits. tMin = tMid; Convert(tMin, 2 * mPrecision, FE_DOWNWARD, tMin); } } else { // Round up to twice the precision to avoid // quadratic growth in the number of bits. tMax = tMid; Convert(tMax, 2 * mPrecision, FE_UPWARD, tMax); } } } // Compute a lower bound tMin < a-b. tMin = (a2pb2 * tMaxSqr - a2mb2Sqr) / (tMax * (tMaxSqr - a2pb2)); // Compute Newton iterates until convergence. The estimate // closest to a-b is tMin with tMin < a - b < tMax and // (a-b) - tMin < tMax - (a-b). for (iterate = 1; iterate <= mMaxIterations; ++iterate) { if (tMax - tMin < mThreshold) { break; } // Compute the weighted average tMax = (3*tMax+tMin)/4. // Round up to twice the precision to avoid quadratic // growth in the number of bits and to ensure that tMin // can increase. tMax = std::ldexp(mThree * tMax + tMin, -2); Convert(tMax, 2 * mPrecision, FE_UPWARD, tMax); tMaxSqr = tMax * tMax; tMin = (a2pb2 * tMaxSqr - a2mb2Sqr) / (tMax * (tMaxSqr - a2pb2)); } return iterate; } // The sign of the second derivative is Sign(a^4-7*a^2*b^2+b^4) // and cannot be zero. Define rational r = a^2/b^2 so that // a^4-7*a^2*b^2+b^4 = 0. This implies r^2 - 7*r^2 + 1 = 0. The // irrational roots are r = (7 +- sqrt(45))/2, which is a // contradiction. LogError("This second derivative cannot be zero at a-b."); } // Compute a bounding interval for the root, qMin <= q <= qMax, where // the endpoints are both within the specified precision. uint32_t Estimate(QFN1 const& q, Rational& qMin, Rational& qMax) { Rational const& x = q.x[0]; Rational const& y = q.x[1]; Rational const& d = q.d; uint32_t numIterates; if (d != mZero && y != mZero) { Rational aSqr = y * y * d; numIterates = EstimateSqrt(aSqr, qMin, qMax); if (y > mZero) { qMin = x + qMin; qMax = x + qMax; } else { Rational diff = x - qMax; qMax = x - qMin; qMin = diff; } } else { numIterates = 0; qMin = x; qMax = x; } return numIterates; } // Compute an estimate of the root when you do not need a bounding // interval. uint32_t Estimate(QFN1 const& q, Rational& qEstimate) { // Compute a bounding interval qMin <= q <= qMax. Rational qMin, qMax; uint32_t numIterates = Estimate(q, qMin, qMax); // Use the average of the interval endpoints as the estimate. qEstimate = std::ldexp(qMin + qMax, -1); return numIterates; } private: void PreprocessSqr(Rational const& aSqr, Rational& rSqr, int32_t& exponentA) { // Factor a^2 = r^2 * 2^e, where r^2 in [1/2,1). int32_t exponentASqr; rSqr = std::frexp(aSqr, &exponentASqr); if (exponentASqr & 1) // odd exponent { // a = sqrt(2*r^2) * 2^{(e-1)/2} exponentA = (exponentASqr - 1) / 2; rSqr = std::ldexp(rSqr, 1); // = 2*rSqr // rSqr in [1,2) } else // even exponent { // a = sqrt(r^2) * 2^{e/2} exponentA = exponentASqr / 2; // rSqr in [1/2,1) } } Rational GetMinOfSqrt(Rational const& rSqr, int32_t exponent) { // Compute a lower bound on the square root of r^2. double lowerRSqr = 0.0; Convert(rSqr, FE_DOWNWARD, lowerRSqr); double sqrtLowerRSqr = std::sqrt(lowerRSqr); Rational aMin = std::nextafter(sqrtLowerRSqr, -std::numeric_limits<double>::max()); aMin = std::ldexp(aMin, exponent); return aMin; } Rational GetMaxOfSqrt(Rational const& rSqr, int32_t exponent) { // Compute an upper bound on the square root of r^2. double upperRSqr = 0.0; Convert(rSqr, FE_UPWARD, upperRSqr); double sqrtUpperRSqr = std::sqrt(upperRSqr); Rational aMax = std::nextafter(sqrtUpperRSqr, +std::numeric_limits<double>::max()); aMax = std::ldexp(aMax, exponent); return aMax; } Rational const mZero, mOne, mThree, mFive; int32_t mPrecision; uint32_t mMaxIterations; Rational mThreshold; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine3AlignedBox3.h
.h
2,315
65
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3CanonicalBox3.h> #include <Mathematics/AlignedBox.h> // Compute the distance between a line and a solid aligned box in 3D. // // The line is P + t * D, where D is not required to be unit length. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the line is stored in closest[0] with parameter t. The // closest point on the box is stored in closest[1]. When there are infinitely // many choices for the pair of closest points, only one of them is returned. // // The DoQueryND functions are described in Section 10.9.4 Linear Component // to Oriented Bounding Box of // Geometric Tools for Computer Graphics, // Philip J. Schneider and David H. Eberly, // Morgan Kaufmnn, San Francisco CA, 2002 namespace gte { template <typename T> class DCPQuery<T, Line3<T>, AlignedBox3<T>> { public: using LBQuery = DCPQuery<T, Line3<T>, CanonicalBox3<T>>; using Result = typename LBQuery::Result; Result operator()(Line3<T> const& line, AlignedBox3<T> const& box) { Result result{}; // Translate the line and box so that the box has center at the // origin. Vector3<T> boxCenter{}; CanonicalBox3<T> cbox{}; box.GetCenteredForm(boxCenter, cbox.extent); Vector3<T> xfrmOrigin = line.origin - boxCenter; // The query computes 'output' relative to the box with center // at the origin. Line3<T> xfrmLine(xfrmOrigin, line.direction); LBQuery lbQuery{}; result = lbQuery(xfrmLine, cbox); // Compute the closest point on the line. result.closest[0] = line.origin + result.parameter * line.direction; // Translate the closest box point to the original coordinates. result.closest[1] += boxCenter; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpLinearNonuniform3.h
.h
2,602
73
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Vector3.h> // Linear interpolation of a network of triangles whose vertices are of the // form (x,y,z,f(x,y,z)). The function samples are F[i] and represent // f(x[i],y[i],z[i]), where i is the index of the input vertex // (x[i],y[i],z[i]) to Delaunay3. // // The TetrahedronMesh interface must support the following: // int32_t GetContainingTetrahedron(Vector3<Real> const&) const; // bool GetIndices(int32_t, std::array<int32_t, 4>&) const; // bool GetBarycentrics(int32_t, Vector3<Real> const&, Real[4]) const; namespace gte { template <typename Real, typename TetrahedronMesh> class IntpLinearNonuniform3 { public: // Construction. IntpLinearNonuniform3(TetrahedronMesh const& mesh, Real const* F) : mMesh(&mesh), mF(F) { LogAssert(mF != nullptr, "Invalid input."); } // Linear interpolation. The return value is 'true' if and only if // the input point is in the convex hull of the input vertices, in // which case the interpolation is valid. bool operator()(Vector3<Real> const& P, Real& F) const { int32_t t = mMesh->GetContainingTetrahedron(P); if (t == -1) { // The point is outside the tetrahedralization. return false; } // Get the barycentric coordinates of P with respect to the tetrahedron, // P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where b0 + b1 + b2 + b3 = 1. std::array<Real, 4> bary; if (!mMesh->GetBarycentrics(t, P, bary)) { // TODO: Throw an exception or allow this as valid behavior? // P is in a needle-like, flat, or degenerate tetrahedron. return false; } // The result is a barycentric combination of function values. std::array<int32_t, 4> indices{ 0, 0, 0, 0 }; mMesh->GetIndices(t, indices); F = bary[0] * mF[indices[0]] + bary[1] * mF[indices[1]] + bary[2] * mF[indices[2]] + bary[3] * mF[indices[3]]; return true; } private: TetrahedronMesh const* mMesh; Real const* mF; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Triangle3.h
.h
5,829
179
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Line.h> #include <Mathematics/Triangle.h> #include <Mathematics/Vector3.h> namespace gte { template <typename T> class TIQuery<T, Line3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line3<T> const& line, Triangle3<T> const& triangle) { Result result{}; // Compute the offset origin, edges, and normal. Vector3<T> diff = line.origin - triangle.v[0]; Vector3<T> edge1 = triangle.v[1] - triangle.v[0]; Vector3<T> edge2 = triangle.v[2] - triangle.v[0]; Vector3<T> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = line direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) T DdN = Dot(line.direction, normal); T sign; if (DdN > (T)0) { sign = (T)1; } else if (DdN < (T)0) { sign = (T)-1; DdN = -DdN; } else { // Line and triangle are parallel, call it a "no intersection" // even if the line and triangle are coplanar and // intersecting. result.intersect = false; return result; } T DdQxE2 = sign * DotCross(line.direction, diff, edge2); if (DdQxE2 >= (T)0) { T DdE1xQ = sign * DotCross(line.direction, edge1, diff); if (DdE1xQ >= (T)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle. result.intersect = true; return result; } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; template <typename T> class FIQuery<T, Line3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false), parameter((T)0), triangleBary{ (T)0, (T)0, (T)0 }, point{ (T)0, (T)0, (T)0 } { } bool intersect; T parameter; std::array<T, 3> triangleBary; Vector3<T> point; }; Result operator()(Line3<T> const& line, Triangle3<T> const& triangle) { Result result{}; // Compute the offset origin, edges, and normal. Vector3<T> diff = line.origin - triangle.v[0]; Vector3<T> edge1 = triangle.v[1] - triangle.v[0]; Vector3<T> edge2 = triangle.v[2] - triangle.v[0]; Vector3<T> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = line direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) T DdN = Dot(line.direction, normal); T sign; if (DdN > (T)0) { sign = (T)1; } else if (DdN < (T)0) { sign = (T)-1; DdN = -DdN; } else { // Line and triangle are parallel, call it a "no intersection" // even if the line and triangle are coplanar and // intersecting. result.intersect = false; return result; } T DdQxE2 = sign * DotCross(line.direction, diff, edge2); if (DdQxE2 >= (T)0) { T DdE1xQ = sign * DotCross(line.direction, edge1, diff); if (DdE1xQ >= (T)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle. T QdN = -sign * Dot(diff, normal); T inv = (T)1 / DdN; result.intersect = true; result.parameter = QdN * inv; result.triangleBary[1] = DdQxE2 * inv; result.triangleBary[2] = DdE1xQ * inv; result.triangleBary[0] = (T)1 - result.triangleBary[1] - result.triangleBary[2]; result.point = line.origin + result.parameter * line.direction; return result; } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/APInterval.h
.h
14,786
491
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ArbitraryPrecision.h> // The interval [e0,e1] must satisfy e0 <= e1. Expose this define to trap // invalid construction where e0 > e1. #define GTE_THROW_ON_INVALID_APINTERVAL namespace gte { // The APType must be an arbitrary-precision type. template <typename APType> class APInterval { public: // Construction. This is the only way to create an interval. All such // intervals are immutable once created. The constructor // APInterval(APType) is used to create the degenerate interval [e,e]. APInterval() : mEndpoints{ static_cast<APType>(0), static_cast<APType>(0) } { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); } APInterval(APInterval const& other) : mEndpoints(other.mEndpoints) { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); } explicit APInterval(APType e) : mEndpoints{ e, e } { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); } APInterval(APType e0, APType e1) : mEndpoints{ e0, e1 } { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); #if defined(GTE_THROW_ON_INVALID_APINTERVAL) LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid interval."); #endif } APInterval(std::array<APType, 2> const& endpoint) : mEndpoints(endpoint) { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); #if defined(GTE_THROW_ON_INVALID_APINTERVAL) LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid interval."); #endif } APInterval& operator=(APInterval const& other) { static_assert(is_arbitrary_precision<APType>::value, "Invalid type."); mEndpoints = other.mEndpoints; return *this; } // Member access. It is only possible to read the endpoints. You // cannot modify the endpoints outside the arithmetic operations. inline APType operator[](size_t i) const { return mEndpoints[i]; } inline std::array<APType, 2> GetEndpoints() const { return mEndpoints; } // Arithmetic operations to compute intervals at the leaf nodes of // an expression tree. Such nodes correspond to the raw floating-point // variables of the expression. The non-class operators defined after // the class definition are used to compute intervals at the interior // nodes of the expression tree. inline static APInterval Add(APType u, APType v) { APInterval w; w.mEndpoints[0] = u + v; w.mEndpoints[1] = w.mEndpoints[0]; return w; } inline static APInterval Sub(APType u, APType v) { APInterval w; w.mEndpoints[0] = u - v; w.mEndpoints[1] = w.mEndpoints[0]; return w; } inline static APInterval Mul(APType u, APType v) { APInterval w; w.mEndpoints[0] = u * v; w.mEndpoints[1] = w.mEndpoints[0]; return w; } template <typename Dummy = APType> inline static typename std::enable_if<has_division_operator<Dummy>::value, APInterval>::type Div(APType u, APType v) { APType const zero = static_cast<APType>(0); if (v != zero) { APInterval w; w.mEndpoints[0] = u / v; w.mEndpoints[1] = w.mEndpoints[0]; return w; } else { // Division by zero does not lead to a determinate interval. // Just return the entire set of real numbers. return Reals(); } } private: std::array<APType, 2> mEndpoints; public: // FOR INTERNAL USE ONLY. These are used by the non-class operators // defined after the class definition. inline static APInterval Add(APType u0, APType u1, APType v0, APType v1) { APInterval w; w.mEndpoints[0] = u0 + v0; w.mEndpoints[1] = u1 + v1; return w; } inline static APInterval Sub(APType u0, APType u1, APType v0, APType v1) { APInterval w; w.mEndpoints[0] = u0 - v1; w.mEndpoints[1] = u1 - v0; return w; } inline static APInterval Mul(APType u0, APType u1, APType v0, APType v1) { APInterval w; w.mEndpoints[0] = u0 * v0; w.mEndpoints[1] = u1 * v1; return w; } inline static APInterval Mul2(APType u0, APType u1, APType v0, APType v1) { APType u0mv1 = u0 * v1; APType u1mv0 = u1 * v0; APType u0mv0 = u0 * v0; APType u1mv1 = u1 * v1; return APInterval<APType>(std::min(u0mv1, u1mv0), std::max(u0mv0, u1mv1)); } template <typename Dummy = APType> inline static typename std::enable_if<has_division_operator<Dummy>::value, APInterval>::type Div(APType u0, APType u1, APType v0, APType v1) { APInterval w; w.mEndpoints[0] = u0 / v1; w.mEndpoints[1] = u1 / v0; return w; } template <typename Dummy = APType> inline static typename std::enable_if<has_division_operator<Dummy>::value, APInterval>::type Reciprocal(APType v0, APType v1) { APType const one = static_cast<APType>(1); APInterval w; w.mEndpoints[0] = one / v1; w.mEndpoints[1] = one / v0; return w; } template <typename Dummy = APType> inline static typename std::enable_if<has_division_operator<Dummy>::value, APInterval>::type ReciprocalDown(APType v) { APType recpv = static_cast<APType>(1) / v; APType posinf(0); posinf.SetSign(+2); return APInterval<APType>(recpv, posinf); } template <typename Dummy = APType> inline static typename std::enable_if<has_division_operator<Dummy>::value, APInterval>::type ReciprocalUp(APType v) { APType recpv = static_cast<APType>(1) / v; APType neginf(0); neginf.SetSign(-2); return APInterval<APType>(neginf, recpv); } inline static APInterval Reals() { APType posinf(0), neginf(0); posinf.SetSign(+2); neginf.SetSign(-2); return APInterval(neginf, posinf); } }; // Unary operations. Negation of [e0,e1] produces [-e1,-e0]. This // operation needs to be supported in the sense of negating a // "number" in an arithmetic expression. template <typename APType> APInterval<APType> operator+(APInterval<APType> const& u) { return u; } template <typename APType> APInterval<APType> operator-(APInterval<APType> const& u) { return APInterval<APType>(-u[1], -u[0]); } // Addition operations. template <typename APType> APInterval<APType> operator+(APType const& u, APInterval<APType> const& v) { return APInterval<APType>::Add(u, u, v[0], v[1]); } template <typename APType> APInterval<APType> operator+(APInterval<APType> const& u, APType const& v) { return APInterval<APType>::Add(u[0], u[1], v, v); } template <typename APType> APInterval<APType> operator+(APInterval<APType> const& u, APInterval<APType> const& v) { return APInterval<APType>::Add(u[0], u[1], v[0], v[1]); } template <typename APType> APInterval<APType>& operator+=(APInterval<APType>& u, APType const& v) { u = u + v; return u; } template <typename APType> APInterval<APType>& operator+=(APInterval<APType>& u, APInterval<APType> const& v) { u = u + v; return u; } // Subtraction operations. template <typename APType> APInterval<APType> operator-(APType const& u, APInterval<APType> const& v) { return APInterval<APType>::Sub(u, u, v[0], v[1]); } template <typename APType> APInterval<APType> operator-(APInterval<APType> const& u, APType const& v) { return APInterval<APType>::Sub(u[0], u[1], v, v); } template <typename APType> APInterval<APType> operator-(APInterval<APType> const& u, APInterval<APType> const& v) { return APInterval<APType>::Sub(u[0], u[1], v[0], v[1]); } template <typename APType> APInterval<APType>& operator-=(APInterval<APType>& u, APType const& v) { u = u - v; return u; } template <typename APType> APInterval<APType>& operator-=(APInterval<APType>& u, APInterval<APType> const& v) { u = u - v; return u; } // Multiplication operations. template <typename APType> APInterval<APType> operator*(APType const& u, APInterval<APType> const& v) { APType const zero = static_cast<APType>(0); if (u >= zero) { return APInterval<APType>::Mul(u, u, v[0], v[1]); } else { return APInterval<APType>::Mul(u, u, v[1], v[0]); } } template <typename APType> APInterval<APType> operator*(APInterval<APType> const& u, APType const& v) { APType const zero = static_cast<APType>(0); if (v >= zero) { return APInterval<APType>::Mul(u[0], u[1], v, v); } else { return APInterval<APType>::Mul(u[1], u[0], v, v); } } template <typename APType> APInterval<APType> operator*(APInterval<APType> const& u, APInterval<APType> const& v) { APType const zero = static_cast<APType>(0); if (u[0] >= zero) { if (v[0] >= zero) { return APInterval<APType>::Mul(u[0], u[1], v[0], v[1]); } else if (v[1] <= zero) { return APInterval<APType>::Mul(u[1], u[0], v[0], v[1]); } else // v[0] < 0 < v[1] { return APInterval<APType>::Mul(u[1], u[1], v[0], v[1]); } } else if (u[1] <= zero) { if (v[0] >= zero) { return APInterval<APType>::Mul(u[0], u[1], v[1], v[0]); } else if (v[1] <= zero) { return APInterval<APType>::Mul(u[1], u[0], v[1], v[0]); } else // v[0] < 0 < v[1] { return APInterval<APType>::Mul(u[0], u[0], v[1], v[0]); } } else // u[0] < 0 < u[1] { if (v[0] >= zero) { return APInterval<APType>::Mul(u[0], u[1], v[1], v[1]); } else if (v[1] <= zero) { return APInterval<APType>::Mul(u[1], u[0], v[0], v[0]); } else // v[0] < 0 < v[1] { return APInterval<APType>::Mul2(u[0], u[1], v[0], v[1]); } } } template <typename APType> APInterval<APType>& operator*=(APInterval<APType>& u, APType const& v) { u = u * v; return u; } template <typename APType> APInterval<APType>& operator*=(APInterval<APType>& u, APInterval<APType> const& v) { u = u * v; return u; } // Division operations. If the divisor interval is [v0,v1] with // v0 < 0 < v1, then the returned interval is (-infinity,+infinity) // instead of Union((-infinity,1/v0),(1/v1,+infinity)). An application // should try to avoid this case by branching based on [v0,0] and [0,v1]. template <typename APType> APInterval<APType> operator/(APType const& u, APInterval<APType> const& v) { APType const zero = static_cast<APType>(0); if (v[0] > zero || v[1] < zero) { return u * APInterval<APType>::Reciprocal(v[0], v[1]); } else { if (v[0] == zero) { return u * APInterval<APType>::ReciprocalDown(v[1]); } else if (v[1] == zero) { return u * APInterval<APType>::ReciprocalUp(v[0]); } else // v[0] < 0 < v[1] { return APInterval<APType>::Reals(); } } } template <typename APType> APInterval<APType> operator/(APInterval<APType> const& u, APType const& v) { APType const zero = static_cast<APType>(0); if (v > zero) { return APInterval<APType>::Div(u[0], u[1], v, v); } else if (v < zero) { return APInterval<APType>::Div(u[1], u[0], v, v); } else // v = 0 { return APInterval<APType>::Reals(); } } template <typename APType> APInterval<APType> operator/(APInterval<APType> const& u, APInterval<APType> const& v) { APType const zero = static_cast<APType>(0); if (v[0] > zero || v[1] < zero) { return u * APInterval<APType>::Reciprocal(v[0], v[1]); } else { if (v[0] == zero) { return u * APInterval<APType>::ReciprocalDown(v[1]); } else if (v[1] == zero) { return u * APInterval<APType>::ReciprocalUp(v[0]); } else // v[0] < 0 < v[1] { return APInterval<APType>::Reals(); } } } template <typename APType> APInterval<APType>& operator/=(APInterval<APType>& u, APType const& v) { u = u / v; return u; } template <typename APType> APInterval<APType>& operator/=(APInterval<APType>& u, APInterval<APType> const& v) { u = u / v; return u; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprParaboloid3.h
.h
4,933
130
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/LinearSystem.h> #include <Mathematics/Matrix.h> #include <Mathematics/Vector3.h> // Least-squares fit of a paraboloid to a set of point. The paraboloid is // of the form z = c0*x^2+c1*x*y+c2*y^2+c3*x+c4*y+c5. A successful fit is // indicated by return value of 'true'. // // Given a set of samples (x_i,y_i,z_i) for 0 <= i < N, and assuming // that the true values lie on a paraboloid // z = p0*x*x + p1*x*y + p2*y*y + p3*x + p4*y + p5 = Dot(P,Q(x,y)) // where P = (p0,p1,p2,p3,p4,p5) and Q(x,y) = (x*x,x*y,y*y,x,y,1), // select P to minimize the sum of squared errors // E(P) = sum_{i=0}^{N-1} [Dot(P,Q_i)-z_i]^2 // where Q_i = Q(x_i,y_i). // // The minimum occurs when the gradient of E is the zero vector, // grad(E) = 2 sum_{i=0}^{N-1} [Dot(P,Q_i)-z_i] Q_i = 0 // Some algebra converts this to a system of 6 equations in 6 unknowns: // [(sum_{i=0}^{N-1} Q_i Q_i^t] P = sum_{i=0}^{N-1} z_i Q_i // The product Q_i Q_i^t is a product of the 6x1 matrix Q_i with the // 1x6 matrix Q_i^t, the result being a 6x6 matrix. // // Define the 6x6 symmetric matrix A = sum_{i=0}^{N-1} Q_i Q_i^t and the 6x1 // vector B = sum_{i=0}^{N-1} z_i Q_i. The choice for P is the solution to // the linear system of equations A*P = B. The entries of A and B indicate // summations over the appropriate product of variables. For example, // s(x^3 y) = sum_{i=0}^{N-1} x_i^3 y_i. // // +- -++ + +- -+ // | s(x^4) s(x^3 y) s(x^2 y^2) s(x^3) s(x^2 y) s(x^2) ||p0| |s(z x^2)| // | s(x^2 y^2) s(x y^3) s(x^2 y) s(x y^2) s(x y) ||p1| |s(z x y)| // | s(y^4) s(x y^2) s(y^3) s(y^2) ||p2| = |s(z y^2)| // | s(x^2) s(x y) s(x) ||p3| |s(z x) | // | s(y^2) s(y) ||p4| |s(z y) | // | s(1) ||p5| |s(z) | // +- -++ + +- -+ namespace gte { template <typename Real> class ApprParaboloid3 { public: bool operator()(int32_t numPoints, Vector3<Real> const* points, Real coefficients[6]) const { Matrix<6, 6, Real> A; Vector<6, Real> B; B.MakeZero(); for (int32_t i = 0; i < numPoints; i++) { Real x2 = points[i][0] * points[i][0]; Real xy = points[i][0] * points[i][1]; Real y2 = points[i][1] * points[i][1]; Real zx = points[i][2] * points[i][0]; Real zy = points[i][2] * points[i][1]; Real x3 = points[i][0] * x2; Real x2y = x2 * points[i][1]; Real xy2 = points[i][0] * y2; Real y3 = points[i][1] * y2; Real zx2 = points[i][2] * x2; Real zxy = points[i][2] * xy; Real zy2 = points[i][2] * y2; Real x4 = x2 * x2; Real x3y = x3 * points[i][1]; Real x2y2 = x2 * y2; Real xy3 = points[i][0] * y3; Real y4 = y2 * y2; A(0, 0) += x4; A(0, 1) += x3y; A(0, 2) += x2y2; A(0, 3) += x3; A(0, 4) += x2y; A(0, 5) += x2; A(1, 2) += xy3; A(1, 4) += xy2; A(1, 5) += xy; A(2, 2) += y4; A(2, 4) += y3; A(2, 5) += y2; A(3, 3) += x2; A(3, 5) += points[i][0]; A(4, 5) += points[i][1]; B[0] += zx2; B[1] += zxy; B[2] += zy2; B[3] += zx; B[4] += zy; B[5] += points[i][2]; } A(1, 0) = A(0, 1); A(1, 1) = A(0, 2); A(1, 3) = A(0, 4); A(2, 0) = A(0, 2); A(2, 1) = A(1, 2); A(2, 3) = A(1, 4); A(3, 0) = A(0, 3); A(3, 1) = A(1, 3); A(3, 2) = A(2, 3); A(3, 4) = A(1, 5); A(4, 0) = A(0, 4); A(4, 1) = A(1, 4); A(4, 2) = A(2, 4); A(4, 3) = A(3, 4); A(4, 4) = A(2, 5); A(5, 0) = A(0, 5); A(5, 1) = A(1, 5); A(5, 2) = A(2, 5); A(5, 3) = A(3, 5); A(5, 4) = A(4, 5); A(5, 5) = static_cast<Real>(numPoints); return LinearSystem<Real>().Solve(6, &A[0], &B[0], &coefficients[0]); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SinEstimate.h
.h
4,490
137
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> // Minimax polynomial approximations to sin(x). The polynomial p(x) of // degree D has only odd-power terms, is required to have linear term x, // and p(pi/2) = sin(pi/2) = 1. It minimizes the quantity // maximum{|sin(x) - p(x)| : x in [-pi/2,pi/2]} over all polynomials of // degree D subject to the constraints mentioned. namespace gte { template <typename Real> class SinEstimate { public: // The input constraint is x in [-pi/2,pi/2]. For example, // float x; // in [-pi/2,pi/2] // float result = SinEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return Evaluate(degree<D>(), x); } // The input x can be any real number. Range reduction is used to // generate a value y in [-pi/2,pi/2] for which sin(y) = sin(x). // For example, // float x; // x any real number // float result = SinEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { return Degree<D>(Reduce(x)); } private: // Metaprogramming and private implementation to allow specialization // of a template member function. template <int32_t D> struct degree {}; inline static Real Evaluate(degree<3>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_SIN_DEG3_C1; poly = (Real)GTE_C_SIN_DEG3_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<5>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_SIN_DEG5_C2; poly = (Real)GTE_C_SIN_DEG5_C1 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG5_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<7>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_SIN_DEG7_C3; poly = (Real)GTE_C_SIN_DEG7_C2 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG7_C1 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG7_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<9>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_SIN_DEG9_C4; poly = (Real)GTE_C_SIN_DEG9_C3 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG9_C2 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG9_C1 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG9_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<11>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_SIN_DEG11_C5; poly = (Real)GTE_C_SIN_DEG11_C4 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG11_C3 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG11_C2 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG11_C1 + poly * xsqr; poly = (Real)GTE_C_SIN_DEG11_C0 + poly * xsqr; poly = poly * x; return poly; } // Support for range reduction. inline static Real Reduce(Real x) { // Map x to y in [-pi,pi], x = 2*pi*quotient + remainder. Real quotient = (Real)GTE_C_INV_TWO_PI * x; if (x >= (Real)0) { quotient = (Real)((int32_t)(quotient + (Real)0.5)); } else { quotient = (Real)((int32_t)(quotient - (Real)0.5)); } Real y = x - (Real)GTE_C_TWO_PI * quotient; // Map y to [-pi/2,pi/2] with sin(y) = sin(x). if (y > (Real)GTE_C_HALF_PI) { y = (Real)GTE_C_PI - y; } else if (y < (Real)-GTE_C_HALF_PI) { y = (Real)-GTE_C_PI - y; } return y; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/PdeFilter.h
.h
5,122
171
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> namespace gte { template <typename Real> class PdeFilter { public: enum class ScaleType { // The data is processed as is. NONE, // The data range is d in [min,max]. The scaled values are d'. // d' = (d-min)/(max-min) in [0,1] UNIT, // d' = -1 + 2*(d-min)/(max-min) in [-1,1] SYMMETRIC, // max > -min: d' = d/max in [min/max,1] // max < -min: d' = -d/min in [-1,-max/min] PRESERVE_ZERO }; // The abstract base class for all PDE-based filters. virtual ~PdeFilter() { } // Member access. inline int32_t GetQuantity() const { return mQuantity; } inline Real GetBorderValue() const { return mBorderValue; } inline ScaleType GetScaleType() const { return mScaleType; } // Access to the time step for the PDE solver. inline void SetTimeStep(Real timeStep) { mTimeStep = timeStep; } inline Real GetTimeStep() const { return mTimeStep; } // This function executes one iteration of the filter. It calls // OnPreUpdate, OnUpdate and OnPostUpdate, in that order. void Update() { OnPreUpdate(); OnUpdate(); OnPostUpdate(); } protected: PdeFilter(int32_t quantity, Real const* data, Real borderValue, ScaleType scaleType) : mQuantity(quantity), mBorderValue(borderValue), mScaleType(scaleType), mMin((Real)0), mOffset((Real)0), mScale((Real)0), mTimeStep((Real)0) { Real maxValue = data[0]; mMin = maxValue; for (int32_t i = 1; i < mQuantity; i++) { Real value = data[i]; if (value < mMin) { mMin = value; } else if (value > maxValue) { maxValue = value; } } if (mMin != maxValue) { switch (mScaleType) { case ScaleType::NONE: mOffset = (Real)0; mScale = (Real)1; break; case ScaleType::UNIT: mOffset = (Real)0; mScale = (Real)1 / (maxValue - mMin); break; case ScaleType::SYMMETRIC: mOffset = (Real)-1; mScale = (Real)2 / (maxValue - mMin); break; case ScaleType::PRESERVE_ZERO: mOffset = (Real)0; mScale = (maxValue >= -mMin ? (Real)1 / maxValue : (Real)-1 / mMin); mMin = (Real)0; break; } } else { mOffset = (Real)0; mScale = (Real)1; } } // The derived classes for 2D and 3D implement this to recompute the // boundary values when Neumann conditions are used. If derived // classes built on top of the 2D or 3D classes implement this also, // they must call the base-class OnPreUpdate first. virtual void OnPreUpdate() = 0; // The derived classes for 2D and 3D implement this to iterate over // the image elements, updating an element only if it is not masked // out. virtual void OnUpdate() = 0; // The derived classes for 2D and 3D implement this to swap the // buffers for the next pass. If derived classes built on top of the // 2D or 3D classes implement this also, they must call the base-class // OnPostUpdate last. virtual void OnPostUpdate() = 0; // The number of image elements. int32_t mQuantity; // When set to std::numeric_limits<Real>::max(), Neumann conditions // are in use (zero-valued derivatives on the image border). // Dirichlet conditions are used, otherwise (image is constant on the // border). Real mBorderValue; // This member stores how the image data was transformed during the // constructor call. ScaleType mScaleType; Real mMin, mOffset, mScale; // The time step for the PDE solver. The stability of an algorithm // depends on the magnitude of the time step, but the magnitude itself // depends on the algorithm. Real mTimeStep; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CircleThroughPointSpecifiedTangentAndRadius.h
.h
5,834
155
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector2.h> // This file provides an implementation of the algorithm in Section 8.7 of the // book // Geometric Tools for Computer Graphics, // Philip J. Schneider and David H. Eberly, // Morgan Kaufmnn, San Francisco CA, 2002 // // Given a point P, a radius r and a line Dot(N,X-A) = 0, where A is a point // on the line and N is a unit-length normal to the line. Compute the centers // of circles, each containing the point, having the specified radius and have // the line as a tangent line. The book describes one algebraic approach to // solving the problem. The implementation here is another approach, a portion // using the algorithm of Section 8.6. // // Let N = (n0,n1) and define the unit-length perpendicular D = Perp(N) = // (-n1,n0). Represent P = A+u*D+s*N with parameters u = Dot(D,P-A) and // s = Dot(N,P-A). The parameter s is the signed distance from P to the line. // To simplify the logic of the implementation, if s < 0, the values of s, N // and D are negated. The discussion below assumes s >= 0. // // The cases are // // (1) s = 0: P is on the line. There are two circles containing P and // tangent to the line at P. This is shown in the left image of Figure // 8.13. The circle centers are C0 = P-r*N and C1 = P+r*N. // // (2) s = r: The book does not have a figure to illustrate this case. The // two circles have a single point of intersection, which is P. The // circle centers are C0 = P-r*D and C1 = P+r*D. // // (3) s = 2*r: P is the farthest point on a circle of radius r which has // the line as the tangent line. The circle center is C0 = P-r*N. // // (4) s > 2*r: The distance from P to the tangent line is larger than the // desired circle diameter, so there is no circle that satisfies the // constraints. // // (5a) 0 < s < r: This is shown in Figure 8.12. Observe that the two // circles intersect in P. There is another point of intersection Q // that is not labeled in the figure. We can represent // Q = P+u*D+(2*r-s)*N. The bisector of segment <P,Q> has origin // (P+Q)/2 = P+u*D+r*N. The bisector direction is D. If a circle center // is C, the triangle <P,B,C> is a right triangle at B. Using the // Pythagorean theorem, the length of segment <B,C> is h = |B-C| = // sqrt(r^2 - (r-s)^2). The circle centers are C0 = B-h*D and // C1 = B+h*D. // // (5b) r < s < 2*r: This is analogous to (5a). Figure 8.12 still applies // except that Q must be the label on the intersection point closest to // the tangent line and P must be the label on the intersection point // farthest from the tangent line. The construction of the centers is // the same as that (5a). namespace gte { // The function returns the number of circles satisfying the constraints. // Any circle[i] with i >= numIntersections has members set to zero. template <typename T> size_t CircleThroughPointSpecifiedTangentAndRadius(Vector2<T> const& P, Vector2<T> const& A, Vector2<T> N, T const& r, std::array<Circle2<T>, 2>& circle) { T const zero = static_cast<T>(0); Vector2<T> PmA = P - A; T s = Dot(N, PmA); if (s == zero) { // Case (1). circle[0].center = P - r * N; circle[0].radius = r; circle[1].center = P + r * N; circle[1].radius = r; return 2; } if (s < zero) { N = -N; s = -s; } if (s == r) { // Case (2). Vector2<T> D = Perp(N); circle[0].center = P - r * D; circle[0].radius = r; circle[1].center = P + r * D; circle[1].radius = r; return 2; } T const twoR = static_cast<T>(2) * r; if (s == twoR) { // Case (3). circle[0].center = P - r * N; circle[0].radius = r; circle[1].center = { zero, zero }; circle[1].radius = zero; return 1; } if (s > twoR) { // Case (4). circle[0].center = { zero, zero }; circle[0].radius = zero; circle[1].center = { zero, zero }; circle[1].radius = zero; return 0; } // The bisector origin is D = Perp(N) and The bisector origin is // B = (P + Q) / 2 = A + t * D + r * N with t = Dot(D, P - A). Vector2<T> bisectorDirection = Perp(N); T t = Dot(bisectorDirection, PmA); Vector2<T> bisectorOrigin = A + t * bisectorDirection + r * N; T diffRS = r - s; T argument = r * r - diffRS * diffRS; if (argument > zero) { T h = std::sqrt(argument); circle[0].center = bisectorOrigin - h * bisectorDirection; circle[0].radius = r; circle[1].center = bisectorOrigin + h * bisectorDirection; circle[1].radius = r; return 2; } else { // Theoretically this code cannot be reached, but floating-point // rounding errors might trigger it. This corresponds to Case (3) // where r = s. circle[0].center = bisectorOrigin; circle[0].radius = r; circle[1].center = { zero, zero }; circle[1].radius = zero; return 1; } } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Image3.h
.h
29,649
750
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Image.h> #include <array> #include <string> //#define GTE_THROW_ON_IMAGE3_ERRORS namespace gte { template <typename PixelType> class Image3 : public Image<PixelType> { public: // Construction and destruction. The last constructor must have // positive dimensions; otherwise, the image is empty. virtual ~Image3() { } Image3() { } Image3(int32_t dimension0, int32_t dimension1, int32_t dimension2) : Image<PixelType>(std::vector<int32_t>{ dimension0, dimension1, dimension2 }) { } // Support for copy semantics. Image3(Image3 const& image) : Image<PixelType>(image) { } Image3& operator= (Image3 const& image) { Image<PixelType>::operator=(image); return *this; } // Support for move semantics. Image3(Image3&& image) noexcept { *this = std::move(image); } Image3& operator= (Image3&& image) noexcept { Image<PixelType>::operator=(image); return *this; } // Support for changing the image dimensions. All pixel data is lost // by this operation. void Reconstruct(int32_t dimension0, int32_t dimension1, int32_t dimension2) { Image<PixelType>::Reconstruct(std::vector<int32_t>{ dimension0, dimension1, dimension2 }); } // Conversion between 1-dimensional indices and 3-dimensional // coordinates. inline size_t GetIndex(int32_t x, int32_t y, int32_t z) const { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1] && 0 <= z && z < this->mDimensions[2]) { return static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ")."); } #else return static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); #endif } inline size_t GetIndex(std::array<int32_t, 3> const& coord) const { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1] && 0 <= coord[2] && coord[2] < this->mDimensions[2]) { return static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(coord[2])); } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + "," + std::to_string(coord[2]) + ")."); } #else return static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(coord[2])); #endif } inline void GetCoordinates(size_t index, int32_t& x, int32_t& y, int32_t& z) const { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (index < this->mPixels.size()) { x = static_cast<int32_t>(index % this->mDimensions[0]); index /= this->mDimensions[0]; y = static_cast<int32_t>(index % this->mDimensions[1]); z = static_cast<int32_t>(index / this->mDimensions[1]); } else { LogError( "Invalid index " + std::to_string(index) + "."); } #else x = static_cast<int32_t>(index % this->mDimensions[0]); index /= this->mDimensions[0]; y = static_cast<int32_t>(index % this->mDimensions[1]); z = static_cast<int32_t>(index / this->mDimensions[1]); #endif } inline std::array<int32_t, 3> GetCoordinates(size_t index) const { std::array<int32_t, 3> coord; #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (index < this->mPixels.size()) { coord[0] = static_cast<int32_t>(index % this->mDimensions[0]); index /= this->mDimensions[0]; coord[1] = static_cast<int32_t>(index % this->mDimensions[1]); coord[2] = static_cast<int32_t>(index / this->mDimensions[1]); return coord; } else { LogError( "Invalid index " + std::to_string(index) + "."); } #else coord[0] = static_cast<int32_t>(index % this->mDimensions[0]); index /= this->mDimensions[0]; coord[1] = static_cast<int32_t>(index % this->mDimensions[1]); coord[2] = static_cast<int32_t>(index / this->mDimensions[1]); return coord; #endif } // Access the data as a 3-dimensional array. The operator() functions // test for valid (x,y,z) when iterator checking is enabled and throw // on invalid (x,y,z). The Get() functions test for valid (x,y,z) and // clamp when invalid; these functions cannot fail. inline PixelType& operator() (int32_t x, int32_t y, int32_t z) { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1] && 0 <= z && z < this->mDimensions[2]) { size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ")."); } #else size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; #endif } inline PixelType const& operator() (int32_t x, int32_t y, int32_t z) const { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= x && x < this->mDimensions[0] && 0 <= y && y < this->mDimensions[1] && 0 <= z && z < this->mDimensions[2]) { size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; } else { LogError( "Invalid coordinates (" + std::to_string(x) + "," + std::to_string(y) + "," + std::to_string(z) + ")."); } #else size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; #endif } inline PixelType& operator() (std::array<int32_t, 3> const& coord) { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1] && 0 <= coord[2] && coord[2] < this->mDimensions[2]) { size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(coord[2])); return this->mPixels[i]; } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + "," + std::to_string(coord[2]) + ")."); } #else size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * coord[2]); return this->mPixels[i]; #endif } inline PixelType const& operator() (std::array<int32_t, 3> const& coord) const { #if defined(GTE_THROW_ON_IMAGE3_ERRORS) if (0 <= coord[0] && coord[0] < this->mDimensions[0] && 0 <= coord[1] && coord[1] < this->mDimensions[1] && 0 <= coord[2] && coord[2] < this->mDimensions[2]) { size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(coord[2])); return this->mPixels[i]; } else { LogError( "Invalid coordinates (" + std::to_string(coord[0]) + "," + std::to_string(coord[1]) + "," + std::to_string(coord[2]) + ")."); } #else size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * coord[2]); return this->mPixels[i]; #endif } inline PixelType& Get(int32_t x, int32_t y, int32_t z) { // Clamp to valid (x,y,z). if (x < 0) { x = 0; } else if (x >= this->mDimensions[0]) { x = this->mDimensions[0] - 1; } if (y < 0) { y = 0; } else if (y >= this->mDimensions[1]) { y = this->mDimensions[1] - 1; } if (z < 0) { z = 0; } else if (z >= this->mDimensions[2]) { z = this->mDimensions[2] - 1; } size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; } inline PixelType const& Get(int32_t x, int32_t y, int32_t z) const { // Clamp to valid (x,y,z). if (x < 0) { x = 0; } else if (x >= this->mDimensions[0]) { x = this->mDimensions[0] - 1; } if (y < 0) { y = 0; } else if (y >= this->mDimensions[1]) { y = this->mDimensions[1] - 1; } if (z < 0) { z = 0; } else if (z >= this->mDimensions[2]) { z = this->mDimensions[2] - 1; } size_t i = static_cast<size_t>(x) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(y) + static_cast<size_t>(this->mDimensions[1]) * static_cast<size_t>(z)); return this->mPixels[i]; } inline PixelType& Get(std::array<int32_t, 3> coord) { // Clamp to valid (x,y,z). for (int32_t d = 0; d < 3; ++d) { if (coord[d] < 0) { coord[d] = 0; } else if (coord[d] >= this->mDimensions[d]) { coord[d] = this->mDimensions[d] - 1; } } size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * coord[2]); return this->mPixels[i]; } inline PixelType const& Get(std::array<int32_t, 3> coord) const { // Clamp to valid (x,y,z). for (int32_t d = 0; d < 3; ++d) { if (coord[d] < 0) { coord[d] = 0; } else if (coord[d] >= this->mDimensions[d]) { coord[d] = this->mDimensions[d] - 1; } } size_t i = static_cast<size_t>(coord[0]) + static_cast<size_t>(this->mDimensions[0]) * (static_cast<size_t>(coord[1]) + static_cast<size_t>(this->mDimensions[1]) * coord[2]); return this->mPixels[i]; } // In the following discussion, u, v and w are in {-1,1}. Given a // voxel (x,y,z), the 6-connected neighbors have relative offsets // (u,0,0), (0,v,0), and (0,0,w). The 18-connected neighbors include // the 6-connected neighbors and have additional relative offsets // (u,v,0), (u,0,w), and (0,v,w). The 26-connected neighbors include // the 18-connected neighbors and have additional relative offsets // (u,v,w). The corner neighbors have offsets (0,0,0), (1,0,0), // (0,1,0), (1,1,0), (0,0,1), (1,0,1), (0,1,1), and (1,1,1) in that // order. The full neighborhood is the set of 3x3x3 pixels centered // at (x,y). // The neighborhoods can be accessed as 1-dimensional indices using // these functions. The first five functions provide 1-dimensional // indices relative to any voxel location; these depend only on the // image dimensions. The last five functions provide 1-dimensional // indices for the actual voxels in the neighborhood; no clamping is // used when (x,y,z) is on the boundary. void GetNeighborhood(std::array<int32_t, 6>& nbr) const { int32_t dim0 = this->mDimensions[0]; int32_t dim01 = this->mDimensions[0] * this->mDimensions[1]; nbr[0] = -1; // (x-1,y,z) nbr[1] = +1; // (x+1,y,z) nbr[2] = -dim0; // (x,y-1,z) nbr[3] = +dim0; // (x,y+1,z) nbr[4] = -dim01; // (x,y,z-1) nbr[5] = +dim01; // (x,y,z+1) } void GetNeighborhood(std::array<int32_t, 18>& nbr) const { int32_t dim0 = this->mDimensions[0]; int32_t dim01 = this->mDimensions[0] * this->mDimensions[1]; nbr[0] = -1; // (x-1,y,z) nbr[1] = +1; // (x+1,y,z) nbr[2] = -dim0; // (x,y-1,z) nbr[3] = +dim0; // (x,y+1,z) nbr[4] = -dim01; // (x,y,z-1) nbr[5] = +dim01; // (x,y,z+1) nbr[6] = -1 - dim0; // (x-1,y-1,z) nbr[7] = +1 - dim0; // (x+1,y-1,z) nbr[8] = -1 + dim0; // (x-1,y+1,z) nbr[9] = +1 + dim0; // (x+1,y+1,z) nbr[10] = -1 + dim01; // (x-1,y,z+1) nbr[11] = +1 + dim01; // (x+1,y,z+1) nbr[12] = -dim0 + dim01; // (x,y-1,z+1) nbr[13] = +dim0 + dim01; // (x,y+1,z+1) nbr[14] = -1 - dim01; // (x-1,y,z-1) nbr[15] = +1 - dim01; // (x+1,y,z-1) nbr[16] = -dim0 - dim01; // (x,y-1,z-1) nbr[17] = +dim0 - dim01; // (x,y+1,z-1) } void GetNeighborhood(std::array<int32_t, 26>& nbr) const { int32_t dim0 = this->mDimensions[0]; int32_t dim01 = this->mDimensions[0] * this->mDimensions[1]; nbr[0] = -1; // (x-1,y,z) nbr[1] = +1; // (x+1,y,z) nbr[2] = -dim0; // (x,y-1,z) nbr[3] = +dim0; // (x,y+1,z) nbr[4] = -dim01; // (x,y,z-1) nbr[5] = +dim01; // (x,y,z+1) nbr[6] = -1 - dim0; // (x-1,y-1,z) nbr[7] = +1 - dim0; // (x+1,y-1,z) nbr[8] = -1 + dim0; // (x-1,y+1,z) nbr[9] = +1 + dim0; // (x+1,y+1,z) nbr[10] = -1 + dim01; // (x-1,y,z+1) nbr[11] = +1 + dim01; // (x+1,y,z+1) nbr[12] = -dim0 + dim01; // (x,y-1,z+1) nbr[13] = +dim0 + dim01; // (x,y+1,z+1) nbr[14] = -1 - dim01; // (x-1,y,z-1) nbr[15] = +1 - dim01; // (x+1,y,z-1) nbr[16] = -dim0 - dim01; // (x,y-1,z-1) nbr[17] = +dim0 - dim01; // (x,y+1,z-1) nbr[18] = -1 - dim0 - dim01; // (x-1,y-1,z-1) nbr[19] = +1 - dim0 - dim01; // (x+1,y-1,z-1) nbr[20] = -1 + dim0 - dim01; // (x-1,y+1,z-1) nbr[21] = +1 + dim0 - dim01; // (x+1,y+1,z-1) nbr[22] = -1 - dim0 + dim01; // (x-1,y-1,z+1) nbr[23] = +1 - dim0 + dim01; // (x+1,y-1,z+1) nbr[24] = -1 + dim0 + dim01; // (x-1,y+1,z+1) nbr[25] = +1 + dim0 + dim01; // (x+1,y+1,z+1) } void GetCorners(std::array<int32_t, 8>& nbr) const { int32_t dim0 = this->mDimensions[0]; int32_t dim01 = this->mDimensions[0] * this->mDimensions[1]; nbr[0] = 0; // (x,y,z) nbr[1] = 1; // (x+1,y,z) nbr[2] = dim0; // (x,y+1,z) nbr[3] = dim0 + 1; // (x+1,y+1,z) nbr[4] = dim01; // (x,y,z+1) nbr[5] = dim01 + 1; // (x+1,y,z+1) nbr[6] = dim01 + dim0; // (x,y+1,z+1) nbr[7] = dim01 + dim0 + 1; // (x+1,y+1,z+1) } void GetFull(std::array<int32_t, 27>& nbr) const { int32_t dim0 = this->mDimensions[0]; int32_t dim01 = this->mDimensions[0] * this->mDimensions[1]; nbr[0] = -1 - dim0 - dim01; // (x-1,y-1,z-1) nbr[1] = -dim0 - dim01; // (x, y-1,z-1) nbr[2] = +1 - dim0 - dim01; // (x+1,y-1,z-1) nbr[3] = -1 - dim01; // (x-1,y, z-1) nbr[4] = -dim01; // (x, y, z-1) nbr[5] = +1 - dim01; // (x+1,y, z-1) nbr[6] = -1 + dim0 - dim01; // (x-1,y+1,z-1) nbr[7] = +dim0 - dim01; // (x, y+1,z-1) nbr[8] = +1 + dim0 - dim01; // (x+1,y+1,z-1) nbr[9] = -1 - dim0; // (x-1,y-1,z) nbr[10] = -dim0; // (x, y-1,z) nbr[11] = +1 - dim0; // (x+1,y-1,z) nbr[12] = -1; // (x-1,y, z) nbr[13] = 0; // (x, y, z) nbr[14] = +1; // (x+1,y, z) nbr[15] = -1 + dim0; // (x-1,y+1,z) nbr[16] = +dim0; // (x, y+1,z) nbr[17] = +1 + dim0; // (x+1,y+1,z) nbr[18] = -1 - dim0 + dim01; // (x-1,y-1,z+1) nbr[19] = -dim0 + dim01; // (x, y-1,z+1) nbr[20] = +1 - dim0 + dim01; // (x+1,y-1,z+1) nbr[21] = -1 + dim01; // (x-1,y, z+1) nbr[22] = +dim01; // (x, y, z+1) nbr[23] = +1 + dim01; // (x+1,y, z+1) nbr[24] = -1 + dim0 + dim01; // (x-1,y+1,z+1) nbr[25] = +dim0 + dim01; // (x, y+1,z+1) nbr[26] = +1 + dim0 + dim01; // (x+1,y+1,z+1) } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<size_t, 6>& nbr) const { size_t index = GetIndex(x, y, z); std::array<int32_t, 6> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 6; ++i) { nbr[i] = index + inbr[i]; } } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<size_t, 18>& nbr) const { size_t index = GetIndex(x, y, z); std::array<int32_t, 18> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 18; ++i) { nbr[i] = index + inbr[i]; } } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<size_t, 26>& nbr) const { size_t index = GetIndex(x, y, z); std::array<int32_t, 26> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 26; ++i) { nbr[i] = index + inbr[i]; } } void GetCorners(int32_t x, int32_t y, int32_t z, std::array<size_t, 8>& nbr) const { size_t index = GetIndex(x, y, z); std::array<int32_t, 8> inbr; GetCorners(inbr); for (int32_t i = 0; i < 8; ++i) { nbr[i] = index + inbr[i]; } } void GetFull(int32_t x, int32_t y, int32_t z, std::array<size_t, 27>& nbr) const { size_t index = GetIndex(x, y, z); std::array<int32_t, 27> inbr; GetFull(inbr); for (int32_t i = 0; i < 27; ++i) { nbr[i] = index + inbr[i]; } } // The neighborhoods can be accessed as 3-tuples using these // functions. The first five functions provide 3-tuples relative to // any voxel location; these depend only on the image dimensions. The // last five functions provide 3-tuples for the actual voxels in the // neighborhood; no clamping is used when (x,y,z) is on the boundary. void GetNeighborhood(std::array<std::array<int32_t, 3>, 6>& nbr) const { nbr[0] = { { -1, 0, 0 } }; nbr[1] = { { +1, 0, 0 } }; nbr[2] = { { 0, -1, 0 } }; nbr[3] = { { 0, +1, 0 } }; nbr[4] = { { 0, 0, -1 } }; nbr[5] = { { 0, 0, +1 } }; } void GetNeighborhood(std::array<std::array<int32_t, 3>, 18>& nbr) const { nbr[0] = { { -1, 0, 0 } }; nbr[1] = { { +1, 0, 0 } }; nbr[2] = { { 0, -1, 0 } }; nbr[3] = { { 0, +1, 0 } }; nbr[4] = { { 0, 0, -1 } }; nbr[5] = { { 0, 0, +1 } }; nbr[6] = { { -1, -1, 0 } }; nbr[7] = { { +1, -1, 0 } }; nbr[8] = { { -1, +1, 0 } }; nbr[9] = { { +1, +1, 0 } }; nbr[10] = { { -1, 0, +1 } }; nbr[11] = { { +1, 0, +1 } }; nbr[12] = { { 0, -1, +1 } }; nbr[13] = { { 0, +1, +1 } }; nbr[14] = { { -1, 0, -1 } }; nbr[15] = { { +1, 0, -1 } }; nbr[16] = { { 0, -1, -1 } }; nbr[17] = { { 0, +1, -1 } }; } void GetNeighborhood(std::array<std::array<int32_t, 3>, 26>& nbr) const { nbr[0] = { { -1, 0, 0 } }; nbr[1] = { { +1, 0, 0 } }; nbr[2] = { { 0, -1, 0 } }; nbr[3] = { { 0, +1, 0 } }; nbr[4] = { { 0, 0, -1 } }; nbr[5] = { { 0, 0, +1 } }; nbr[6] = { { -1, -1, 0 } }; nbr[7] = { { +1, -1, 0 } }; nbr[8] = { { -1, +1, 0 } }; nbr[9] = { { +1, +1, 0 } }; nbr[10] = { { -1, 0, +1 } }; nbr[11] = { { +1, 0, +1 } }; nbr[12] = { { 0, -1, +1 } }; nbr[13] = { { 0, +1, +1 } }; nbr[14] = { { -1, 0, -1 } }; nbr[15] = { { +1, 0, -1 } }; nbr[16] = { { 0, -1, -1 } }; nbr[17] = { { 0, +1, -1 } }; nbr[18] = { { -1, -1, -1 } }; nbr[19] = { { +1, -1, -1 } }; nbr[20] = { { -1, +1, -1 } }; nbr[21] = { { +1, +1, -1 } }; nbr[22] = { { -1, -1, +1 } }; nbr[23] = { { +1, -1, +1 } }; nbr[24] = { { -1, +1, +1 } }; nbr[25] = { { +1, +1, +1 } }; } void GetCorners(std::array<std::array<int32_t, 3>, 8>& nbr) const { nbr[0] = { { 0, 0, 0 } }; nbr[1] = { { 1, 0, 0 } }; nbr[2] = { { 0, 1, 0 } }; nbr[3] = { { 1, 1, 0 } }; nbr[4] = { { 0, 0, 1 } }; nbr[5] = { { 1, 0, 1 } }; nbr[6] = { { 0, 1, 1 } }; nbr[7] = { { 1, 1, 1 } }; } void GetFull(std::array<std::array<int32_t, 3>, 27>& nbr) const { nbr[0] = { { -1, -1, -1 } }; nbr[1] = { { 0, -1, -1 } }; nbr[2] = { { +1, -1, -1 } }; nbr[3] = { { -1, 0, -1 } }; nbr[4] = { { 0, 0, -1 } }; nbr[5] = { { +1, 0, -1 } }; nbr[6] = { { -1, +1, -1 } }; nbr[7] = { { 0, +1, -1 } }; nbr[8] = { { +1, +1, -1 } }; nbr[9] = { { -1, -1, 0 } }; nbr[10] = { { 0, -1, 0 } }; nbr[11] = { { +1, -1, 0 } }; nbr[12] = { { -1, 0, 0 } }; nbr[13] = { { 0, 0, 0 } }; nbr[14] = { { +1, 0, 0 } }; nbr[15] = { { -1, +1, 0 } }; nbr[16] = { { 0, +1, 0 } }; nbr[17] = { { +1, +1, 0 } }; nbr[18] = { { -1, -1, +1 } }; nbr[19] = { { 0, -1, +1 } }; nbr[20] = { { +1, -1, +1 } }; nbr[21] = { { -1, 0, +1 } }; nbr[22] = { { 0, 0, +1 } }; nbr[23] = { { +1, 0, +1 } }; nbr[24] = { { -1, +1, +1 } }; nbr[25] = { { 0, +1, +1 } }; nbr[26] = { { +1, +1, +1 } }; } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<std::array<size_t, 3>, 6>& nbr) const { std::array<std::array<int32_t, 3>, 6> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 6; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; nbr[i][2] = static_cast<size_t>(z) + inbr[i][2]; } } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<std::array<size_t, 3>, 18>& nbr) const { std::array<std::array<int32_t, 3>, 18> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 18; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; nbr[i][2] = static_cast<size_t>(z) + inbr[i][2]; } } void GetNeighborhood(int32_t x, int32_t y, int32_t z, std::array<std::array<size_t, 3>, 26>& nbr) const { std::array<std::array<int32_t, 3>, 26> inbr; GetNeighborhood(inbr); for (int32_t i = 0; i < 26; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; nbr[i][2] = static_cast<size_t>(z) + inbr[i][2]; } } void GetCorners(int32_t x, int32_t y, int32_t z, std::array<std::array<size_t, 3>, 8>& nbr) const { std::array<std::array<int32_t, 3>, 8> inbr; GetCorners(inbr); for (int32_t i = 0; i < 8; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; nbr[i][2] = static_cast<size_t>(z) + inbr[i][2]; } } void GetFull(int32_t x, int32_t y, int32_t z, std::array<std::array<size_t, 3>, 27>& nbr) const { std::array<std::array<int32_t, 3>, 27> inbr; GetFull(inbr); for (int32_t i = 0; i < 27; ++i) { nbr[i][0] = static_cast<size_t>(x) + inbr[i][0]; nbr[i][1] = static_cast<size_t>(y) + inbr[i][1]; nbr[i][2] = static_cast<size_t>(z) + inbr[i][2]; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrConvexMesh3Plane3.h
.h
37,926
913
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/ConvexMesh3.h> #include <Mathematics/EdgeKey.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/UniqueVerticesSimplices.h> namespace gte { template <typename Real> class FIQuery<Real, ConvexMesh3<Real>, Plane3<Real>> { public: // Convenient type definitions. using CM = ConvexMesh3<Real>; using Vertex = typename CM::Vertex; using Triangle = typename CM::Triangle; // The configuration describes geometrically how the input convex // polyhedron and the plane intersect. static int32_t constexpr CFG_EMPTY = 0x00000000; static int32_t constexpr CFG_POS_SIDE = 0x00000010; static int32_t constexpr CFG_NEG_SIDE = 0x00000020; // The plane intersects the convex polyhedron transversely. The set of // intersection is a convex polygon. The convex polyhedron is split // into two convex polyhedra, one on the positive side of the plane // and one on the negative side of the plane, both polyhedra sharing // the convex polygon of intersection. static int32_t constexpr CFG_SPLIT = CFG_POS_SIDE | CFG_NEG_SIDE; // 48 // The convex polyhedron is strictly on the positive side of the // plane. static int32_t constexpr CFG_POS_SIDE_STRICT = CFG_POS_SIDE; // 16 // The convex polyhedron is on the positive side of the plane with one // vertex in the plane. static int32_t constexpr CFG_POS_SIDE_VERTEX = CFG_POS_SIDE | 1; // 17 // The convex polyhedron is on the positive side of the plane with one // edge in the plane. static int32_t constexpr CFG_POS_SIDE_EDGE = CFG_POS_SIDE | 2; // 18 // The convex polyhedron is on the positive side of the plane with a // polygonal face in the plane. The face can consist of multiple // triangles. static int32_t constexpr CFG_POS_SIDE_POLYGON = CFG_POS_SIDE | 4; // 20 // Flags for any of the tangential cases (vertex touching, edge // touching, face touching). static int32_t constexpr CFG_POS_SIDE_TANGENT = CFG_POS_SIDE | 7; // 23 // The convex polyhedron is strictly on the negative side of the // plane. static int32_t constexpr CFG_NEG_SIDE_STRICT = CFG_NEG_SIDE; // 32 // The convex polyhedron is on the negative side of the plane with one // vertex in the plane. static int32_t constexpr CFG_NEG_SIDE_VERTEX = CFG_NEG_SIDE | 1; // 33 // The convex polyhedron is on the negative side of the plane with one // edge in the plane. static int32_t constexpr CFG_NEG_SIDE_EDGE = CFG_NEG_SIDE | 2; // 34 // The convex polyhedron is on the negative side of the plane with a // polygonal face in the plane. The face can consist of multiple // triangles. static int32_t constexpr CFG_NEG_SIDE_POLYGON = CFG_NEG_SIDE | 4; // 36 // Flags for any of the tangential cases (vertex touching, edge // touching, face touching). static int32_t constexpr CFG_NEG_SIDE_TANGENT = CFG_NEG_SIDE | 7; // 39 // Requested information for the query to compute. static int32_t constexpr REQ_CONFIGURATION_ONLY = 0x00000000; static int32_t constexpr REQ_INTR_MESH = 0x00000001; static int32_t constexpr REQ_INTR_POLYGON = 0x00000002; static int32_t constexpr REQ_INTR_BOTH = REQ_INTR_MESH | REQ_INTR_POLYGON; static int32_t constexpr REQ_POLYHEDRON_POS = 0x00000004; static int32_t constexpr REQ_POLYHEDRON_NEG = 0x00000008; static int32_t constexpr REQ_POLYHEDRON_BOTH = REQ_POLYHEDRON_POS | REQ_POLYHEDRON_NEG; static int32_t constexpr REQ_ALL = 0x0000000F; struct Result { Result() : configuration(CFG_EMPTY), requested(REQ_CONFIGURATION_ONLY), intersectionMesh{}, intersectionPolygon{}, positivePolyhedron{}, negativePolyhedron{} { } // The configuration describes geometrically how the input convex // polyhedron and the plane intersect. int32_t configuration; // You can specify the information you want from the query. int32_t requested; // The intersection of the convex polyhedron and the plane is // either empty, a single vertex, a single edge or a convex // polygon. The intersection members have the properties: // empty: mVertices has 0 elements, mMesh is empty // vertex: mVertices has 1 element, mMesh is empty // edge: mVertices has 2 elements, mMesh is empty // polygon: mVertices has 3 or more elements, mMesh is a // triangulation of the convex polygon // The convex polygon vertices are indexed by 'polygon' in the // order consistent with that of the positive polyhedron // triangles. The indices are into intersection.vertices. ConvexMesh3<Real> intersectionMesh; std::vector<Vertex> intersectionPolygon; // If the configuration is POSITIVE_* or SPLIT, this convex // polyhedron is the portion of the input convex polyhedron on the // positive side of the plane with possibly a vertex or edge on // the plane. ConvexMesh3<Real> positivePolyhedron; // If the configuration is NEGATIVE_* or SPLIT, this convex // polyhedron is the portion of the input convex polyhedron on the // negative side of the plane with possibly a vertex or edge on // the plane. ConvexMesh3<Real> negativePolyhedron; }; Result operator() (ConvexMesh3<Real> const& polyhedron, Plane3<Real> const& plane, int32_t requested) { static_assert(is_arbitrary_precision<Real>::value, "Real must be arbitrary precision."); static_assert(has_division_operator<Real>::value, "Real must support division."); Result result{}; result.requested = requested; // Storage for (Dot(N,X) - c) for each vertex X, where N is a // plane normal (not necessarily unit length) and c is the // corresponding plane constant. int32_t numPositive = 0, numNegative = 0, numZero = 0; size_t const numVertices = polyhedron.vertices.size(); std::vector<Real> dot(numVertices); std::vector<int32_t> sign(numVertices); for (size_t i = 0; i < numVertices; ++i) { dot[i] = Dot(plane.normal, polyhedron.vertices[i]) - plane.constant; if (dot[i] > (Real)0) { sign[i] = +1; ++numPositive; } else if (dot[i] < (Real)0) { sign[i] = -1; ++numNegative; } else { sign[i] = 0; ++numZero; } } if (numPositive == 0) { result.configuration = CFG_NEG_SIDE | (numZero < 3 ? numZero : 4); if ((requested & REQ_POLYHEDRON_NEG) != 0) { result.negativePolyhedron = polyhedron; } if (numZero > 0 && ((requested & REQ_INTR_BOTH) != 0)) { GetIntersection(polyhedron, numZero, sign, result); } } else if (numNegative == 0) { result.configuration = CFG_POS_SIDE | (numZero < 3 ? numZero : 4); if ((requested & REQ_POLYHEDRON_POS) != 0) { result.positivePolyhedron = polyhedron; } if (numZero > 0 && ((requested & REQ_INTR_BOTH) != 0)) { GetIntersection(polyhedron, numZero, sign, result); } } else { result.configuration = CFG_SPLIT; if (requested != REQ_CONFIGURATION_ONLY) { SplitPolyhedron(polyhedron, dot, sign, result); } } return result; } private: static void GetIntersection(CM const& polyhedron, int32_t numZero, std::vector<int32_t> const& sign, Result& result) { bool const wantIntrMesh = (result.requested & REQ_INTR_MESH) != 0; bool const wantIntrPolygon = (result.requested & REQ_INTR_POLYGON) != 0; if (numZero == 1) { GetIntersectionVertex(polyhedron, sign, wantIntrMesh, wantIntrPolygon, result); } else if (numZero == 2) { GetIntersectionEdge(polyhedron, sign, wantIntrMesh, wantIntrPolygon, result); } else // numZero >= 3 { GetIntersectionPolygon(polyhedron, sign, wantIntrMesh, wantIntrPolygon, result); } } static void GetIntersectionVertex(CM const& polyhedron, std::vector<int32_t> const& sign, bool wantIntrMesh, bool wantIntrPolygon, Result& result) { result.intersectionMesh.configuration = ConvexMesh3<Real>::CFG_POINT; if (wantIntrMesh) { result.intersectionMesh.vertices.resize(1); } if (wantIntrPolygon) { result.intersectionPolygon.resize(1); } size_t const numVertices = polyhedron.vertices.size(); for (size_t i = 0; i < numVertices; ++i) { if (sign[i] == 0) { if (wantIntrMesh) { result.intersectionMesh.vertices[0] = polyhedron.vertices[i]; } if (wantIntrPolygon) { result.intersectionPolygon[0] = polyhedron.vertices[i]; } return; } } } static void GetIntersectionEdge(CM const& polyhedron, std::vector<int32_t> const& sign, bool wantIntrMesh, bool wantIntrPolygon, Result& result) { result.intersectionMesh.configuration = ConvexMesh3<Real>::CFG_SEGMENT; if (wantIntrMesh) { result.intersectionMesh.vertices.resize(2); } if (wantIntrPolygon) { result.intersectionPolygon.resize(2); } size_t const numVertices = polyhedron.vertices.size(); for (size_t i = 0, numFound = 0; i < numVertices; ++i) { if (sign[i] == 0) { if (wantIntrMesh) { result.intersectionMesh.vertices[numFound] = polyhedron.vertices[i]; } if (wantIntrPolygon) { result.intersectionPolygon[numFound] = polyhedron.vertices[i]; } if (++numFound == 2) { return; } } } } static void GetIntersectionPolygon(CM const& polyhedron, std::vector<int32_t> const& sign, bool wantIntrMesh, bool wantIntrPolygon, Result& result) { result.intersectionMesh.configuration = ConvexMesh3<Real>::CFG_POLYGON; std::vector<Triangle> intersectionMeshTriangles; intersectionMeshTriangles.reserve(polyhedron.triangles.size()); for (auto const& triangle : polyhedron.triangles) { if (sign[triangle[0]] == 0 && sign[triangle[1]] == 0 && sign[triangle[2]] == 0) { intersectionMeshTriangles.push_back(triangle); } } std::vector<Vertex> outVertices; std::vector<Triangle> outTriangles; UniqueVerticesSimplices<Vertex, int32_t, 3> uvt; uvt.RemoveDuplicateAndUnusedVertices(polyhedron.vertices, intersectionMeshTriangles, outVertices, outTriangles); if (wantIntrPolygon) { // Get the boundary edges with ordering consistent with the // triangle face chirality. std::map<EdgeKey<false>, std::array<int32_t, 2>> edgeMap; for (auto const& triangle : outTriangles) { for (size_t j0 = 2, j1 = 0; j1 < 3; j0 = j1++) { EdgeKey<false> edge(triangle[j0], triangle[j1]); auto iter = edgeMap.find(edge); if (iter != edgeMap.end()) { // The edge is now visited twice, so it cannot be a // boundary edge. edgeMap.erase(iter); } else { // The edge is visited the first time, so it might be // a boundary edge. std::array<int32_t, 2> value = { triangle[j1], triangle[j0] }; edgeMap.insert(std::make_pair(edge, value)); } } } // Construct the boundary polygon. std::vector<int32_t> polygonIndices(edgeMap.size(), -1); for (auto const& element : edgeMap) { polygonIndices[element.second[0]] = element.second[1]; } result.intersectionPolygon.resize(edgeMap.size()); for (size_t i = 0; i < result.intersectionPolygon.size(); ++i) { result.intersectionPolygon[i] = outVertices[polygonIndices[i]]; } } if (wantIntrMesh) { result.intersectionMesh.vertices = std::move(outVertices); result.intersectionMesh.triangles = std::move(outTriangles); } } static void SplitPolyhedron(CM const& polyhedron, std::vector<Real> const& dot, std::vector<int32_t> const& sign, Result& result) { bool const wantPosMesh = (result.requested & REQ_POLYHEDRON_POS) != 0; bool const wantNegMesh = (result.requested & REQ_POLYHEDRON_NEG) != 0; bool const wantIntrMesh = (result.requested & REQ_INTR_MESH) != 0; bool const wantIntrPolygon = (result.requested & REQ_INTR_POLYGON) != 0; // The split polyhedra use the input polyhedron's vertices and any // edge-interior intersections between the plane and the mesh // edges. The center point of the polygon of intersection (if any) // is also used as a vertex. std::vector<Vertex> splitVertices; std::map<EdgeKey<false>, int32_t> eiVMap; GetVertexCandidates(polyhedron, dot, sign, splitVertices, eiVMap); // Split each triangle face of the polyhedron by the plane. std::vector<Triangle> posMesh, negMesh; std::map<int32_t, int32_t> posIntersection; DoSplit(polyhedron, sign, eiVMap, wantPosMesh, posMesh, wantNegMesh, negMesh, posIntersection); // Get the polygon of intersection. This is used by all of the // requested features. std::vector<int32_t> polygon; GetIntersectionPolygon(posIntersection, splitVertices, wantIntrPolygon, polygon, result); if (wantPosMesh || wantNegMesh || wantIntrMesh) { // Get the polyhedra split by the plane. The polygon of // intersection is also computed and used to close the // polyhedra. GetSplitPolyhedra(splitVertices, polygon, wantIntrMesh, wantPosMesh, posMesh, wantNegMesh, negMesh, result); } } static void GetVertexCandidates(CM const& polyhedron, std::vector<Real> const& dot, std::vector<int32_t> const& sign, std::vector<Vertex>& splitVertices, std::map<EdgeKey<false>, int32_t>& eiVMap) { // Get the edges of the polyhedron. std::set<EdgeKey<false>> edgeMap; for (auto const& triangle : polyhedron.triangles) { edgeMap.insert(EdgeKey<false>(triangle[0], triangle[1])); edgeMap.insert(EdgeKey<false>(triangle[1], triangle[2])); edgeMap.insert(EdgeKey<false>(triangle[2], triangle[0])); } // The vertex candidates include the original vertices, any // edge-interior intersections between the plane and polyhedron, // and the average of the convex-polygon intersection (if there // is such an intersection). The number of reserved elements of // splitVertices is large enough to avoid resizing of the array // later. splitVertices.reserve(polyhedron.vertices.size() + edgeMap.size() + 1); for (auto const& vertex : polyhedron.vertices) { splitVertices.push_back(vertex); } // Compute edge-interior points of intersection between the plane // and the mesh edges. The eiVMap container allows accessing the // edge-interior vertices when each triangle face of the // polyhedron is processed for intersection with the plane. for (auto const& element : edgeMap) { int32_t v0 = element.V[0]; int32_t v1 = element.V[1]; if (sign[v0] * sign[v1] < 0) { Real denom = dot[v1] - dot[v0]; Real w0 = dot[v1] / denom; Real w1 = -dot[v0] / denom; auto eiVertex = w0 * polyhedron.vertices[v0] + w1 * polyhedron.vertices[v1]; int32_t const eiIndex = static_cast<int32_t>(splitVertices.size()); eiVMap.insert(std::make_pair(EdgeKey<false>(v0, v1), eiIndex)); splitVertices.push_back(eiVertex); } } // The average point will be appended to splitVertices later when // necessary. } static void DoSplit(CM const& polyhedron, std::vector<int32_t> const& sign, std::map<EdgeKey<false>, int32_t>& eiVMap, bool wantPosMesh, std::vector<Triangle>& posMesh, bool wantNegMesh, std::vector<Triangle>& negMesh, std::map<int32_t, int32_t>& posIntersection) { for (auto const& triangle : polyhedron.triangles) { int32_t v0 = triangle[0], v1 = triangle[1], v2 = triangle[2]; int32_t v01 = -1, v12 = -1, v20 = -1; if (sign[v0] > 0) { if (sign[v1] > 0) { if (sign[v2] > 0) { // +++ if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } } else if (sign[v2] < 0) { // ++- v12 = eiVMap[EdgeKey<false>(v1, v2)]; v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v0, v12, v20 }); posMesh.push_back({ v0, v1, v12 }); } if (wantNegMesh) { negMesh.push_back({ v2, v20, v12 }); } posIntersection.insert(std::make_pair(v20, v12)); } else { // ++0 if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } } } else if (sign[v1] < 0) { if (sign[v2] > 0) { // +-+ v01 = eiVMap[EdgeKey<false>(v0, v1)]; v12 = eiVMap[EdgeKey<false>(v1, v2)]; if (wantPosMesh) { posMesh.push_back({ v0, v01, v12 }); posMesh.push_back({ v0, v12, v2 }); } if (wantNegMesh) { negMesh.push_back({ v1, v12, v01 }); } posIntersection.insert(std::make_pair(v12, v01)); } else if (sign[v2] < 0) { // +-- v01 = eiVMap[EdgeKey<false>(v0, v1)]; v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v0, v01, v20 }); } if (wantNegMesh) { negMesh.push_back({ v1, v20, v01 }); negMesh.push_back({ v1, v2, v20 }); } posIntersection.insert(std::make_pair(v20, v01)); } else { // +-0 v01 = eiVMap[EdgeKey<false>(v0, v1)]; if (wantPosMesh) { posMesh.push_back({ v2, v0, v01 }); } if (wantNegMesh) { negMesh.push_back({ v2, v01, v1 }); } posIntersection.insert(std::make_pair(v2, v01)); } } else { if (sign[v2] > 0) { // +0+ if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } } else if (sign[v2] < 0) { // +0- v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v1, v20, v0 }); } if (wantNegMesh) { negMesh.push_back({ v1, v2, v20 }); } posIntersection.insert(std::make_pair(v20, v1)); } else { // +00 if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } posIntersection.insert(std::make_pair(v2, v1)); } } } else if (sign[v0] < 0) { if (sign[v1] > 0) { if (sign[v2] > 0) { // -++ v01 = eiVMap[EdgeKey<false>(v0, v1)]; v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v1, v20, v01 }); posMesh.push_back({ v1, v2, v20 }); } if (wantNegMesh) { negMesh.push_back({ v0, v01, v20 }); } posIntersection.insert(std::make_pair(v01, v20)); } else if (sign[v2] < 0) { // -+- v01 = eiVMap[EdgeKey<false>(v0, v1)]; v12 = eiVMap[EdgeKey<false>(v1, v2)]; if (wantPosMesh) { posMesh.push_back({ v1, v12, v01 }); } if (wantNegMesh) { negMesh.push_back({ v0, v01, v12 }); negMesh.push_back({ v0, v12, v2 }); } posIntersection.insert(std::make_pair(v01, v12)); } else { // -+0 v01 = eiVMap[EdgeKey<false>(v0, v1)]; if (wantPosMesh) { posMesh.push_back({ v1, v2, v01 }); } if (wantNegMesh) { negMesh.push_back({ v2, v0, v01 }); } posIntersection.insert(std::make_pair(v01, v2)); } } else if (sign[v1] < 0) { if (sign[v2] > 0) { // --+ v12 = eiVMap[EdgeKey<false>(v1, v2)]; v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v2, v20, v12 }); } if (wantNegMesh) { negMesh.push_back({ v0, v1, v12 }); negMesh.push_back({ v0, v12, v20 }); } posIntersection.insert(std::make_pair(v12, v20)); } else if (sign[v2] < 0) { // --- if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } else { // --0 if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } } else { if (sign[v2] > 0) { // -0+ v20 = eiVMap[EdgeKey<false>(v2, v0)]; if (wantPosMesh) { posMesh.push_back({ v2, v20, v1 }); } if (wantNegMesh) { negMesh.push_back({ v0, v1, v20 }); } posIntersection.insert(std::make_pair(v1, v20)); } else if (sign[v2] < 0) { // -0- if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } else { // -00 if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } } } else { if (sign[v1] > 0) { if (sign[v2] > 0) { // 0++ if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } } else if (sign[v2] < 0) { // 0+- v12 = eiVMap[EdgeKey<false>(v1, v2)]; if (wantPosMesh) { posMesh.push_back({ v1, v12, v0 }); } if (wantNegMesh) { negMesh.push_back({ v2, v0, v12 }); } posIntersection.insert(std::make_pair(v0, v12)); } else { // 0+0 if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } posIntersection.insert(std::make_pair(v0, v2)); } } else if (sign[v1] < 0) { if (sign[v2] > 0) { // 0-+ v12 = eiVMap[EdgeKey<false>(v1, v2)]; if (wantPosMesh) { posMesh.push_back({ v2, v0, v12 }); } if (wantNegMesh) { negMesh.push_back({ v1, v12, v0 }); } posIntersection.insert(std::make_pair(v12, v0)); } else if (sign[v2] < 0) { // 0-- if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } else { // 0-0 if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } } else { if (sign[v2] > 0) { // 00+ if (wantPosMesh) { posMesh.push_back({ v0, v1, v2 }); } posIntersection.insert(std::make_pair(v1, v0)); } else if (sign[v2] < 0) { // 00- if (wantNegMesh) { negMesh.push_back({ v0, v1, v2 }); } } else { // 000 // This case cannot occur with exact arithmetic, // because it would have been trapped previously // by tests numPositive == 0 or numNegative == 0. LogError("This case cannot occur with exact arithmetic."); } } } } } static void GetIntersectionPolygon(std::map<int32_t, int32_t> const& posIntersection, std::vector<Vertex>& splitVertices, bool wantIntrPolygon, std::vector<int32_t>& polygon, Result& result) { size_t const numVertices = posIntersection.size(); polygon.resize(numVertices); auto posIter = posIntersection.begin(); for (size_t i = 0; i < numVertices; ++i) { polygon[i] = posIter->first; posIter = posIntersection.find(posIter->second); } if (wantIntrPolygon) { result.intersectionPolygon.resize(numVertices); for (size_t i = 0; i < numVertices; ++i) { result.intersectionPolygon[i] = splitVertices[polygon[i]]; } } } static void GetSplitPolyhedra(std::vector<Vertex>& splitVertices, std::vector<int32_t> const& polygon, bool wantIntrMesh, bool wantPosMesh, std::vector<Triangle>& posMesh, bool wantNegMesh, std::vector<Triangle>& negMesh, Result& result) { // Triangulate the polygon for use by the positive polyhedron. A // triangle fan will not work always work when the polygon has // collinear vertices. The average of the polygon vertices is // inserted as an extra vertex. The triangulation includes each // triangle that is formed by the average point and an edge of the // polygon. The negative polyhedron uses the same triangulation // but with opposite chirality. NOTE: To avoid biases in the // average due to vertex distribution, use the center of mass of // the polygon instead. Vertex average{ (Real)0, (Real)0, (Real)0 }; for (auto const& i : polygon) { average += splitVertices[i]; } int32_t const numVertices = static_cast<int32_t>(polygon.size()); average /= static_cast<Real>(numVertices); int32_t iAvrIndex = static_cast<int32_t>(splitVertices.size()); splitVertices.push_back(average); std::vector<Triangle> intrMesh; for (int32_t i0 = numVertices - 1, i1 = 0; i1 < numVertices; i0 = i1++) { if (wantPosMesh) { posMesh.push_back({ iAvrIndex, polygon[i0], polygon[i1] }); } if (wantNegMesh) { negMesh.push_back({ iAvrIndex, polygon[i1], polygon[i0] }); } if (wantIntrMesh) { intrMesh.push_back({ iAvrIndex, polygon[i0], polygon[i1] }); } } UniqueVerticesSimplices<Vertex, int32_t, 3> uvt; if (wantPosMesh) { result.positivePolyhedron.configuration = CM::CFG_POLYHEDRON; uvt.RemoveDuplicateAndUnusedVertices(splitVertices, posMesh, result.positivePolyhedron.vertices, result.positivePolyhedron.triangles); } if (wantNegMesh) { result.negativePolyhedron.configuration = CM::CFG_POLYHEDRON; uvt.RemoveDuplicateAndUnusedVertices(splitVertices, negMesh, result.negativePolyhedron.vertices, result.negativePolyhedron.triangles); } if (wantIntrMesh) { result.intersectionMesh.configuration = CM::CFG_POLYGON; uvt.RemoveDuplicateAndUnusedVertices(splitVertices, intrMesh, result.intersectionMesh.vertices, result.intersectionMesh.triangles); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3OrientedBox3.h
.h
3,335
104
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrLine3AlignedBox3.h> #include <Mathematics/OrientedBox.h> // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the six // faces of the box. The find-intersection queries use Liang-Barsky // clipping. The queries consider the box to be a solid. The algorithms // are described in // https://www.geometrictools.com/Documentation/IntersectionLineBox.pdf namespace gte { template <typename T> class TIQuery<T, Line3<T>, OrientedBox3<T>> : public TIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public TIQuery<T, Line3<T>, AlignedBox3<T>>::Result { // No additional relevant information to compute. Result() = default; }; Result operator()(Line3<T> const& line, OrientedBox3<T> const& box) { // Transform the line to the oriented-box coordinate system. Vector3<T> diff = line.origin - box.center; Vector3<T> lineOrigin { Dot(diff, box.axis[0]), Dot(diff, box.axis[1]), Dot(diff, box.axis[2]) }; Vector3<T> lineDirection { Dot(line.direction, box.axis[0]), Dot(line.direction, box.axis[1]), Dot(line.direction, box.axis[2]) }; Result result{}; this->DoQuery(lineOrigin, lineDirection, box.extent, result); return result; } }; template <typename T> class FIQuery<T, Line3<T>, OrientedBox3<T>> : public FIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public FIQuery<T, Line3<T>, AlignedBox3<T>>::Result { // No additional relevant information to compute. Result() = default; }; Result operator()(Line3<T> const& line, OrientedBox3<T> const& box) { // Transform the line to the oriented-box coordinate system. Vector3<T> diff = line.origin - box.center; Vector3<T> lineOrigin { Dot(diff, box.axis[0]), Dot(diff, box.axis[1]), Dot(diff, box.axis[2]) }; Vector3<T> lineDirection { Dot(line.direction, box.axis[0]), Dot(line.direction, box.axis[1]), Dot(line.direction, box.axis[2]) }; Result result{}; this->DoQuery(lineOrigin, lineDirection, box.extent, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NaturalSplineCurve.h
.h
15,606
419
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.07 #pragma once #include <Mathematics/LinearSystem.h> #include <Mathematics/ParametricCurve.h> namespace gte { // NOTE: This class is now deprecated and will not be ported to GTL. // Use instead the new class NaturalCubicSpline. There is also an // extension of the idea in the new class NaturalQuinticSpline. template <int32_t N, typename Real> class NaturalSplineCurve : public ParametricCurve<N, Real> { public: // Construction and destruction. The object copies the input arrays. // The number of points M must be at least 2. The first constructor // is for a spline with second derivatives zero at the endpoints // (isFree = true) or a spline that is closed (isFree = false). The // second constructor is for clamped splines, where you specify the // first derivatives at the endpoints. Usually, derivative0 = // points[1] - points[0] at the first point and derivative1 = // points[M-1] - points[M-2]. To validate construction, create an // object as shown: // NaturalSplineCurve<N, Real> curve(parameters); // if (!curve) { <constructor failed, handle accordingly>; } NaturalSplineCurve(bool isFree, int32_t numPoints, Vector<N, Real> const* points, Real const* times) : ParametricCurve<N, Real>(numPoints - 1, times), mNumPoints(0), mNumSegments(0) { LogAssert( numPoints >= 2 && points != nullptr && times != nullptr, "Invalid input."); mNumPoints = static_cast<size_t>(numPoints); mNumSegments = mNumPoints - 1; mCoefficients.resize(4 * mNumPoints - 2); mA = mCoefficients.data(); mB = mA + mNumPoints; mC = mB + mNumSegments; mD = mC + mNumSegments + 1; for (size_t i = 0; i < mNumPoints; ++i) { mA[i] = points[i]; } if (isFree) { CreateFree(); } else { CreateClosed(); } this->mConstructed = true; } NaturalSplineCurve(int32_t numPoints, Vector<N, Real> const* points, Real const* times, Vector<N, Real> const& derivative0, Vector<N, Real> const& derivative1) : ParametricCurve<N, Real>(numPoints - 1, times), mNumPoints(0), mNumSegments(0) { LogAssert( numPoints >= 2 && points != nullptr && times != nullptr, "Invalid input."); mNumPoints = static_cast<size_t>(numPoints); mNumSegments = mNumPoints - 1; mCoefficients.resize(4 * static_cast<size_t>(mNumPoints) - 2); mA = mCoefficients.data(); mB = mA + mNumPoints; mC = mB + mNumSegments; mD = mC + mNumSegments + 1; for (size_t i = 0; i < mNumPoints; ++i) { mA[i] = points[i]; } CreateClamped(derivative0, derivative1); this->mConstructed = true; } virtual ~NaturalSplineCurve() = default; // Member access. inline size_t GetNumPoints() const { return mNumPoints; } inline Vector<N, Real> const* GetPoints() const { return mA; } // Evaluation of the function and its derivatives through order 3. If // you want only the position, pass in order 0. If you want the // position and first derivative, pass in order of 1 and so on. The // output array 'jet' must have 'order + 1' elements. The values are // ordered as position, first derivative, second derivative and so on. virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const override { if (!this->mConstructed) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i <= order; ++i) { jet[i].MakeZero(); } return; } size_t key = 0; Real dt = (Real)0; GetKeyInfo(t, key, dt); // Compute position. jet[0] = mA[key] + dt * (mB[key] + dt * (mC[key] + dt * mD[key])); if (order >= 1) { // Compute first derivative. jet[1] = mB[key] + dt * ((Real)2 * mC[key] + (Real)3 * dt * mD[key]); if (order >= 2) { // Compute second derivative. jet[2] = (Real)2 * mC[key] + (Real)6 * dt * mD[key]; if (order >= 3) { jet[3] = (Real)6 * mD[key]; for (uint32_t i = 4; i <= order; ++i) { jet[i].MakeZero(); } } } } } protected: void CreateFree() { size_t const numP = mNumPoints; size_t const numS = mNumSegments; size_t const numSm1 = mNumSegments - 1; // Minimize allocation and deallocations when splines are created // and destroyed frequently in an application. // Real* dt : numSegments // Real* dt2 : numSegments // Vector<N,Real>* alpha : numSegments // Real* ell : numSegments + 1 // Real* mu : numSegments // Vector<N,Real>*z : numSegments + 1 size_t storageSize = numS + numS + numS + static_cast<size_t>(N) * numP + numS + static_cast<size_t>(N) * numP; std::vector<Real> storage(storageSize); auto dt = storage.data(); auto d2t = dt + numS; auto alpha = reinterpret_cast<Vector<N, Real>*>(d2t + numS); auto ell = reinterpret_cast<Real*>(alpha + numS); auto mu = ell + numP; auto z = reinterpret_cast<Vector<N, Real>*>(mu + numS); Real const r0 = static_cast<Real>(0); Real const r1 = static_cast<Real>(1); Real const r2 = static_cast<Real>(2); Real const r3 = static_cast<Real>(3); for (size_t i = 0, ip1 = 1; i < numS; ++i, ++ip1) { dt[i] = this->mTime[ip1] - this->mTime[i]; } d2t[0] = r0; // unused for (size_t im1 = 0, i = 1, ip1 = 2; i < numS; im1 = i, i = ip1++) { d2t[i] = this->mTime[ip1] - this->mTime[im1]; } alpha[0].MakeZero(); // unused for (size_t im1 = 0, i = 1, ip1 = 2; i < numS; im1 = i, i = ip1++) { auto numer = r3 * (dt[im1] * mA[ip1] - d2t[i] * mA[i] + dt[i] * mA[im1]); Real denom = dt[im1] * dt[i]; alpha[i] = numer / denom; } ell[0] = r1; mu[0] = r0; z[0].MakeZero(); for (size_t im1 = 0, i = 1; i < numS; im1 = i++) { ell[i] = r2 * d2t[i] - dt[im1] * mu[im1]; mu[i] = dt[i] / ell[i]; z[i] = (alpha[i] - dt[im1] * z[im1]) / ell[i]; } ell[numS] = r1; z[numS].MakeZero(); mC[numS].MakeZero(); for (size_t j = 0, i = numSm1; j < numS; ++j, --i) { mC[i] = z[i] - mu[i] * mC[i + 1]; mB[i] = (mA[i + 1] - mA[i]) / dt[i] - dt[i] * (mC[i + 1] + r2 * mC[i]) / r3; mD[i] = (mC[i + 1] - mC[i]) / (r3 * dt[i]); } } void CreateClosed() { size_t const numP = mNumPoints; size_t const numS = mNumSegments; size_t const numSm1 = mNumSegments - 1; // Minimize allocation and deallocations when splines are created // and destroyed frequently in an application. The matrices mat // and invMat are stored in row-major order. // Real* dt : numSegments // Real* mat : (numSegments + 1) * (numSegments + 1) // Real* solution : (numSegments + 1) * N size_t storageSize = numS + numP * numP + static_cast<size_t>(N) * numP; std::vector<Real> storage(storageSize); auto dt = storage.data(); auto mat = dt + numS; auto solution = mat + numP * numP; Real const r1 = static_cast<Real>(1); Real const r2 = static_cast<Real>(2); Real const r3 = static_cast<Real>(3); for (size_t i = 0, ip1 = 1; i < numS; ++i, ++ip1) { dt[i] = this->mTime[ip1] - this->mTime[i]; } // Construct matrix of system. mat[0 + numP * 0] = r1; // mat(0,0) mat[numS + numP * 0] = -r1; // mat(0,numS) for (size_t im1 = 0, i = 1, ip1 = 2; i <= numSm1; im1 = i, i = ip1++) { mat[im1 + numP * i] = dt[im1]; // mat(i,im1) mat[i + numP * i] = r2 * (dt[im1] + dt[i]); // mat(i, i) mat[ip1 + numP * i] = dt[i]; // mat(i,ip1) } mat[numSm1 + numP * numS] = dt[numSm1]; // mat(numS,numSm1) mat[0 + numP * numS] = r2 * (dt[numSm1] + dt[0]); // mat(numS,0) mat[1 + numP * numS] = dt[0]; // mat(numS,1) // Construct right-hand side of system. mC[0].MakeZero(); for (size_t im1 = 0, i = 1, ip1 = 2; ip1 <= numS; im1 = i, i = ip1++) { mC[i] = r3 * ((mA[ip1] - mA[i]) / dt[i] - (mA[i] - mA[im1]) / dt[im1]); } mC[numS] = r3 * ((mA[1] - mA[0]) / dt[0] - (mA[0] - mA[numSm1]) / dt[numSm1]); // Solve the linear systems. bool solved = LinearSystem<Real>::Solve(static_cast<int32_t>(numP), N, mat, reinterpret_cast<Real const*>(mC), solution); LogAssert( solved, "Failed to solve linear system."); for (size_t i = 0, k = 0; i <= numS; ++i) { for (int32_t j = 0; j < N; ++j, ++k) { mC[i][j] = solution[k]; } } for (size_t i = 0; i < numS; ++i) { mB[i] = (mA[i + 1] - mA[i]) / dt[i] - (mC[i + 1] + r2 * mC[i]) * dt[i] / r3; mD[i] = (mC[i + 1] - mC[i]) / (r3 * dt[i]); } } void CreateClamped(Vector<N, Real> const& derivative0, Vector<N, Real> const& derivative1) { size_t const numP = mNumPoints; size_t const numS = mNumSegments; size_t const numSm1 = mNumSegments - 1; // Minimize allocation and deallocations when splines are created // and destroyed frequently in an application. // Real* dt : numSegments // Real* dt2 : numSegments // Vector<N,Real>* alpha : numSegments + 1 // Real* ell : numSegments + 1 // Real* mu : numSegments // Vector<N,Real>*z : numSegments + 1 size_t storageSize = numS + numS + static_cast<size_t>(N) * numP + numP + numS + static_cast<size_t>(N) * numP; std::vector<Real> storage(storageSize); auto dt = storage.data(); auto d2t = dt + numS; auto alpha = reinterpret_cast<Vector<N, Real>*>(d2t + numS); auto ell = reinterpret_cast<Real*>(alpha + numS + 1); auto mu = ell + numS + 1; auto z = reinterpret_cast<Vector<N, Real>*>(mu + numS); Real const r2 = static_cast<Real>(2); Real const r3 = static_cast<Real>(3); Real const rHalf = static_cast<Real>(0.5); for (size_t i = 0, ip1 = 1; i < numS; i = ip1++) { dt[i] = this->mTime[ip1] - this->mTime[i]; } for (size_t im1 = 0, i = 1, ip1 = 2; i < numS; im1 = i, i = ip1++) { d2t[i] = this->mTime[ip1] - this->mTime[im1]; } alpha[0] = r3 * ((mA[1] - mA[0]) / dt[0] - derivative0); alpha[numS] = r3 * (derivative1 - (mA[numS] - mA[numS - 1]) / dt[numS - 1]); for (size_t im1 = 0, i = 1, ip1 = 2; i < numS; im1 = i, i = ip1++) { auto numer = r3 * (dt[im1] * mA[ip1] - d2t[i] * mA[i] + dt[i] * mA[im1]); Real denom = dt[im1] * dt[i]; alpha[i] = numer / denom; } ell[0] = r2 * dt[0]; mu[0] = rHalf; z[0] = alpha[0] / ell[0]; for (size_t im1 = 0, i = 1; i < numS; im1 = i++) { ell[i] = r2 * d2t[i] - dt[im1] * mu[im1]; mu[i] = dt[i] / ell[i]; z[i] = (alpha[i] - dt[im1] * z[im1]) / ell[i]; } ell[numS] = dt[numSm1] * (r2 - mu[numSm1]); z[numS] = (alpha[numS] - dt[numSm1] * z[numSm1]) / ell[numS]; mC[numS] = z[numS]; for (size_t j = 0, i = numSm1; j < numS; ++j, --i) { mC[i] = z[i] - mu[i] * mC[i + 1]; mB[i] = (mA[i + 1] - mA[i]) / dt[i] - dt[i] * (mC[i + 1] + r2 * mC[i]) / r3; mD[i] = (mC[i + 1] - mC[i]) / (r3 * dt[i]); } } // Determine the index i for which times[i] <= t < times[i+1]. void GetKeyInfo(Real t, size_t& key, Real& dt) const { if (t <= this->mTime[0]) { key = 0; dt = static_cast<Real>(0); } else if (t >= this->mTime[mNumSegments]) { key = mNumSegments - 1; dt = this->mTime[mNumSegments] - this->mTime[mNumSegments - 1]; } else { for (size_t i = 0, ip1 = 1; i < mNumSegments; i = ip1++) { if (t < this->mTime[ip1]) { key = i; dt = t - this->mTime[i]; break; } } } } // Polynomial coefficients. mA are the points (constant coefficients of // polynomials. mB are the degree 1 coefficients, mC are the degree 2 // coefficients and mD are the degree 3 coefficients. size_t mNumPoints, mNumSegments; Vector<N, Real>* mA; Vector<N, Real>* mB; Vector<N, Real>* mC; Vector<N, Real>* mD; private: std::vector<Vector<N, Real>> mCoefficients; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/AdaptiveSkeletonClimbing2.h
.h
34,345
937
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <array> #include <cstdint> #include <map> #include <memory> #include <ostream> #include <vector> // Extract level surfaces using an adaptive approach to reduce the triangle // count. The implementation is for the algorithm described in the paper // Multiresolution Isosurface Extraction with Adaptive Skeleton Climbing // Tim Poston, Tien-Tsin Wong and Pheng-Ann Heng // Computer Graphics forum, volume 17, issue 3, September 1998 // pages 137-147 // https://onlinelibrary.wiley.com/doi/abs/10.1111/1467-8659.00261 namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class AdaptiveSkeletonClimbing2 { public: // Construction and destruction. The input image is assumed to // contain (2^N+1)-by-(2^N+1) elements where N >= 0. The organization // is row-major order for (x,y). AdaptiveSkeletonClimbing2(int32_t N, T const* inputPixels) : mTwoPowerN(1 << N), mSize(mTwoPowerN + 1), mInputPixels(inputPixels), mXMerge(mSize), mYMerge(mSize) { static_assert(std::is_integral<T>::value && sizeof(T) <= 4, "Type T must be int{8,16,32}_t or uint{8,16,32}_t."); if (N <= 0 || mInputPixels == nullptr) { LogError("Invalid input."); } for (int32_t i = 0; i < mSize; ++i) { mXMerge[i] = std::make_shared<LinearMergeTree>(N); mYMerge[i] = std::make_shared<LinearMergeTree>(N); } mXYMerge = std::make_unique<AreaMergeTree>(N, mXMerge, mYMerge); } // TODO: Refactor this class to have base class CurveExtractor. typedef std::array<Real, 2> Vertex; typedef std::array<int32_t, 2> Edge; void Extract(Real level, int32_t depth, std::vector<Vertex>& vertices, std::vector<Edge>& edges) { std::vector<Rectangle> rectangles; std::vector<Vertex> localVertices; std::vector<Edge> localEdges; SetLevel(level, depth); GetRectangles(rectangles); for (auto& rectangle : rectangles) { if (rectangle.type > 0) { GetComponents(level, rectangle, localVertices, localEdges); } } vertices = std::move(localVertices); edges = std::move(localEdges); } void MakeUnique(std::vector<Vertex>& vertices, std::vector<Edge>& edges) { size_t numVertices = vertices.size(); size_t numEdges = edges.size(); if (numVertices == 0 || numEdges == 0) { return; } // Compute the map of unique vertices and assign to them new and // unique indices. std::map<Vertex, int32_t> vmap; int32_t nextVertex = 0; for (size_t v = 0; v < numVertices; ++v) { // Keep only unique vertices. auto result = vmap.insert(std::make_pair(vertices[v], nextVertex)); if (result.second) { ++nextVertex; } } // Compute the map of unique edges and assign to them new and // unique indices. std::map<Edge, int32_t> emap; int32_t nextEdge = 0; for (size_t e = 0; e < numEdges; ++e) { // Replace old vertex indices by new vertex indices. Edge& edge = edges[e]; for (int32_t i = 0; i < 2; ++i) { auto iter = vmap.find(vertices[edge[i]]); LogAssert(iter != vmap.end(), "Expecting the vertex to be in the vmap."); edge[i] = iter->second; } // Keep only unique edges. auto result = emap.insert(std::make_pair(edge, nextEdge)); if (result.second) { ++nextEdge; } } // Pack the vertices into an array. vertices.resize(vmap.size()); for (auto const& element : vmap) { vertices[element.second] = element.first; } // Pack the edges into an array. edges.resize(emap.size()); for (auto const& element : emap) { edges[element.second] = element.first; } } private: // Helper classes for the skeleton climbing. struct QuadRectangle { QuadRectangle() : xOrigin(0), yOrigin(0), xStride(0), yStride(0), valid(false) { } QuadRectangle(int32_t inXOrigin, int32_t inYOrigin, int32_t inXStride, int32_t inYStride) { Initialize(inXOrigin, inYOrigin, inXStride, inYStride); } void Initialize(int32_t inXOrigin, int32_t inYOrigin, int32_t inXStride, int32_t inYStride) { xOrigin = inXOrigin; yOrigin = inYOrigin; xStride = inXStride; yStride = inYStride; valid = true; } int32_t xOrigin, yOrigin, xStride, yStride; bool valid; }; struct QuadNode { QuadNode() { // The members are uninitialized. } QuadNode(int32_t xOrigin, int32_t yOrigin, int32_t xNext, int32_t yNext, int32_t stride) : r00(xOrigin, yOrigin, stride, stride), r10(xNext, yOrigin, stride, stride), r01(xOrigin, yNext, stride, stride), r11(xNext, yNext, stride, stride) { } void Initialize(int32_t xOrigin, int32_t yOrigin, int32_t xNext, int32_t yNext, int32_t stride) { r00.Initialize(xOrigin, yOrigin, stride, stride); r10.Initialize(xNext, yOrigin, stride, stride); r01.Initialize(xOrigin, yNext, stride, stride); r11.Initialize(xNext, yNext, stride, stride); } bool IsMono() const { return !r10.valid && !r01.valid && !r11.valid; } int32_t GetQuantity() const { int32_t quantity = 0; if (r00.valid) { ++quantity; } if (r10.valid) { ++quantity; } if (r01.valid) { ++quantity; } if (r11.valid) { ++quantity; } return quantity; } QuadRectangle r00, r10, r01, r11; }; class LinearMergeTree { public: LinearMergeTree(int32_t N) : mTwoPowerN(1 << N), mNodes(2 * static_cast<size_t>(mTwoPowerN) - 1) { } enum { CFG_NONE, CFG_INCR, CFG_DECR, CFG_MULT }; // Member access. int32_t GetQuantity() const { return 2 * mTwoPowerN - 1; } int32_t GetNode(int32_t i) const { return mNodes[i]; } int32_t GetEdge(int32_t i) const { // assert: mNodes[i] == CFG_INCR || mNodes[i] == CFG_DECR // Traverse binary tree looking for incr or decr leaf node. int32_t const firstLeaf = mTwoPowerN - 1; while (i < firstLeaf) { i = 2 * i + 1; if (mNodes[i] == CFG_NONE) { ++i; } } return i - firstLeaf; } void SetLevel(Real level, T const* data, int32_t offset, int32_t stride) { // Assert: The 'level' is not an image value. Because T is // an integer type, choose 'level' to be a Real-valued number // that does not represent an integer. // Determine the sign changes between pairs of consecutive // samples. int32_t const firstLeaf = mTwoPowerN - 1; for (int32_t i = 0, leaf = firstLeaf; i < mTwoPowerN; ++i, ++leaf) { int32_t base = offset + stride * i; Real value0 = static_cast<Real>(data[base]); Real value1 = static_cast<Real>(data[base + stride]); if (value0 > level) { if (value1 > level) { mNodes[leaf] = CFG_NONE; } else { mNodes[leaf] = CFG_DECR; } } else // value0 < level { if (value1 > level) { mNodes[leaf] = CFG_INCR; } else { mNodes[leaf] = CFG_NONE; } } } // Propagate the sign change information up the binary tree. for (int32_t i = firstLeaf - 1; i >= 0; --i) { int32_t twoIp1 = 2 * i + 1; int32_t child0 = mNodes[twoIp1]; int32_t child1 = mNodes[static_cast<size_t>(twoIp1) + 1]; mNodes[i] = (child0 | child1); } } private: int32_t mTwoPowerN; std::vector<int32_t> mNodes; }; struct Rectangle { Rectangle(int32_t inXOrigin, int32_t inYOrigin, int32_t inXStride, int32_t inYStride) : xOrigin(inXOrigin), yOrigin(inYOrigin), xStride(inXStride), yStride(inYStride), yOfXMin(-1), yOfXMax(-1), xOfYMin(-1), xOfYMax(-1), type(0) { } int32_t xOrigin, yOrigin, xStride, yStride; int32_t yOfXMin, yOfXMax, xOfYMin, xOfYMax; // A 4-bit flag for how the level set intersects the rectangle // boundary. // bit 0 = xmin edge // bit 1 = xmax edge // bit 2 = ymin edge // bit 3 = ymax edge // A bit is set if the corresponding edge is intersected by the // level set. This information is known from the CFG flags for // LinearMergeTree. Intersection occurs whenever the flag is // CFG_INCR or CFG_DECR. uint32_t type; }; class AreaMergeTree { public: AreaMergeTree(int32_t N, std::vector<std::shared_ptr<LinearMergeTree>> const& xMerge, std::vector<std::shared_ptr<LinearMergeTree>> const& yMerge) : mXMerge(xMerge), mYMerge(yMerge), mNodes(((static_cast<size_t>(1) << 2 * (N + 1)) - 1) / 3) { } void ConstructMono(int32_t A, int32_t LX, int32_t LY, int32_t xOrigin, int32_t yOrigin, int32_t stride, int32_t depth) { if (stride > 1) // internal nodes { int32_t hStride = stride / 2; int32_t ABase = 4 * A; int32_t A00 = ++ABase; int32_t A10 = ++ABase; int32_t A01 = ++ABase; int32_t A11 = ++ABase; int32_t LXBase = 2 * LX; int32_t LX0 = ++LXBase; int32_t LX1 = ++LXBase; int32_t LYBase = 2 * LY; int32_t LY0 = ++LYBase; int32_t LY1 = ++LYBase; int32_t xNext = xOrigin + hStride; int32_t yNext = yOrigin + hStride; int32_t depthM1 = depth - 1; ConstructMono(A00, LX0, LY0, xOrigin, yOrigin, hStride, depthM1); ConstructMono(A10, LX1, LY0, xNext, yOrigin, hStride, depthM1); ConstructMono(A01, LX0, LY1, xOrigin, yNext, hStride, depthM1); ConstructMono(A11, LX1, LY1, xNext, yNext, hStride, depthM1); if (depth >= 0) { // Merging is prevented above the specified depth in // the tree. This allows a single object to produce // any resolution isocontour rather than using // multiple objects to do so. mNodes[A].Initialize(xOrigin, yOrigin, xNext, yNext, hStride); return; } bool mono00 = mNodes[A00].IsMono(); bool mono10 = mNodes[A10].IsMono(); bool mono01 = mNodes[A01].IsMono(); bool mono11 = mNodes[A11].IsMono(); QuadNode node0(xOrigin, yOrigin, xNext, yNext, hStride); QuadNode node1 = node0; // Merge x first, y second. if (mono00 && mono10) { DoXMerge(node0.r00, node0.r10, LX, yOrigin); } if (mono01 && mono11) { DoXMerge(node0.r01, node0.r11, LX, yNext); } if (mono00 && mono01) { DoYMerge(node0.r00, node0.r01, xOrigin, LY); } if (mono10 && mono11) { DoYMerge(node0.r10, node0.r11, xNext, LY); } // Merge y first, x second. if (mono00 && mono01) { DoYMerge(node1.r00, node1.r01, xOrigin, LY); } if (mono10 && mono11) { DoYMerge(node1.r10, node1.r11, xNext, LY); } if (mono00 && mono10) { DoXMerge(node1.r00, node1.r10, LX, yOrigin); } if (mono01 && mono11) { DoXMerge(node1.r01, node1.r11, LX, yNext); } // Choose the merge that produced the smallest number of // rectangles. if (node0.GetQuantity() <= node1.GetQuantity()) { mNodes[A] = node0; } else { mNodes[A] = node1; } } else // leaf nodes { mNodes[A].r00.Initialize(xOrigin, yOrigin, 1, 1); } } void GetRectangles(int32_t A, int32_t LX, int32_t LY, int32_t xOrigin, int32_t yOrigin, int32_t stride, std::vector<Rectangle>& rectangles) { int32_t hStride = stride / 2; int32_t ABase = 4 * A; int32_t A00 = ++ABase; int32_t A10 = ++ABase; int32_t A01 = ++ABase; int32_t A11 = ++ABase; int32_t LXBase = 2 * LX; int32_t LX0 = ++LXBase; int32_t LX1 = ++LXBase; int32_t LYBase = 2 * LY; int32_t LY0 = ++LYBase; int32_t LY1 = ++LYBase; int32_t xNext = xOrigin + hStride; int32_t yNext = yOrigin + hStride; QuadRectangle const& r00 = mNodes[A].r00; if (r00.valid) { if (r00.xStride == stride) { if (r00.yStride == stride) { rectangles.push_back(GetRectangle(r00, LX, LY)); } else { rectangles.push_back(GetRectangle(r00, LX, LY0)); } } else { if (r00.yStride == stride) { rectangles.push_back(GetRectangle(r00, LX0, LY)); } else { GetRectangles(A00, LX0, LY0, xOrigin, yOrigin, hStride, rectangles); } } } QuadRectangle const& r10 = mNodes[A].r10; if (r10.valid) { if (r10.yStride == stride) { rectangles.push_back(GetRectangle(r10, LX1, LY)); } else { GetRectangles(A10, LX1, LY0, xNext, yOrigin, hStride, rectangles); } } QuadRectangle const& r01 = mNodes[A].r01; if (r01.valid) { if (r01.xStride == stride) { rectangles.push_back(GetRectangle(r01, LX, LY1)); } else { GetRectangles(A01, LX0, LY1, xOrigin, yNext, hStride, rectangles); } } QuadRectangle const& r11 = mNodes[A].r11; if (r11.valid) { GetRectangles(A11, LX1, LY1, xNext, yNext, hStride, rectangles); } } private: void DoXMerge(QuadRectangle& r0, QuadRectangle& r1, int32_t LX, int32_t yOrigin) { if (r0.valid && r1.valid && r0.yStride == r1.yStride) { // Rectangles are x-mergeable. int32_t incr = 0, decr = 0; for (int32_t y = 0; y <= r0.yStride; ++y) { switch (mXMerge[static_cast<size_t>(yOrigin) + static_cast<size_t>(y)]->GetNode(LX)) { case LinearMergeTree::CFG_MULT: return; case LinearMergeTree::CFG_INCR: ++incr; break; case LinearMergeTree::CFG_DECR: ++decr; break; } } if (incr == 0 || decr == 0) { // Strongly mono, x-merge the rectangles. r0.xStride *= 2; r1.valid = false; } } } void DoYMerge(QuadRectangle& r0, QuadRectangle& r1, int32_t xOrigin, int32_t LY) { if (r0.valid && r1.valid && r0.xStride == r1.xStride) { // Rectangles are y-mergeable. int32_t incr = 0, decr = 0; for (int32_t x = 0; x <= r0.xStride; ++x) { switch (mYMerge[static_cast<size_t>(xOrigin) + static_cast<size_t>(x)]->GetNode(LY)) { case LinearMergeTree::CFG_MULT: return; case LinearMergeTree::CFG_INCR: ++incr; break; case LinearMergeTree::CFG_DECR: ++decr; break; } } if (incr == 0 || decr == 0) { // Strongly mono, y-merge the rectangles. r0.yStride *= 2; r1.valid = false; } } } Rectangle GetRectangle(QuadRectangle const& qrect, int32_t LX, int32_t LY) { Rectangle rect(qrect.xOrigin, qrect.yOrigin, qrect.xStride, qrect.yStride); // xmin edge auto merge = mYMerge[qrect.xOrigin]; if (merge->GetNode(LY) != LinearMergeTree::CFG_NONE) { rect.yOfXMin = merge->GetEdge(LY); if (rect.yOfXMin != -1) { rect.type |= 0x01; } } // xmax edge merge = mYMerge[static_cast<size_t>(qrect.xOrigin) + static_cast<size_t>(qrect.xStride)]; if (merge->GetNode(LY) != LinearMergeTree::CFG_NONE) { rect.yOfXMax = merge->GetEdge(LY); if (rect.yOfXMax != -1) { rect.type |= 0x02; } } // ymin edge merge = mXMerge[qrect.yOrigin]; if (merge->GetNode(LX) != LinearMergeTree::CFG_NONE) { rect.xOfYMin = merge->GetEdge(LX); if (rect.xOfYMin != -1) { rect.type |= 0x04; } } // ymax edge merge = mXMerge[static_cast<size_t>(qrect.yOrigin) + static_cast<size_t>(qrect.yStride)]; if (merge->GetNode(LX) != LinearMergeTree::CFG_NONE) { rect.xOfYMax = merge->GetEdge(LX); if (rect.xOfYMax != -1) { rect.type |= 0x08; } } return rect; } std::vector<std::shared_ptr<LinearMergeTree>> mXMerge; std::vector<std::shared_ptr<LinearMergeTree>> mYMerge; std::vector<QuadNode> mNodes; }; private: // Support for extraction of level sets. Real GetInterp(Real level, int32_t base, int32_t index, int32_t increment) { Real f0 = static_cast<Real>(mInputPixels[index]); index += increment; Real f1 = static_cast<Real>(mInputPixels[index]); LogAssert((f0 - level) * (f1 - level) < (Real)0, "Unexpected condition."); return static_cast<Real>(base) + (level - f0) / (f1 - f0); } void AddVertex(std::vector<Vertex>& vertices, Real x, Real y) { Vertex vertex = { x, y }; vertices.push_back(vertex); } void AddEdge(std::vector<Vertex>& vertices, std::vector<Edge>& edges, Real x0, Real y0, Real x1, Real y1) { int32_t v0 = static_cast<int32_t>(vertices.size()); int32_t v1 = v0 + 1; Edge edge = { v0, v1 }; edges.push_back(edge); Vertex vertex0 = { x0, y0 }; Vertex vertex1 = { x1, y1 }; vertices.push_back(vertex0); vertices.push_back(vertex1); } void SetLevel(Real level, int32_t depth) { int32_t offset, stride; for (int32_t y = 0; y < mSize; ++y) { offset = mSize * y; stride = 1; mXMerge[y]->SetLevel(level, mInputPixels, offset, stride); } for (int32_t x = 0; x < mSize; ++x) { offset = x; stride = mSize; mYMerge[x]->SetLevel(level, mInputPixels, offset, stride); } mXYMerge->ConstructMono(0, 0, 0, 0, 0, mTwoPowerN, depth); } void GetRectangles(std::vector<Rectangle>& rectangles) { mXYMerge->GetRectangles(0, 0, 0, 0, 0, mTwoPowerN, rectangles); } void GetComponents(Real level, Rectangle const& rectangle, std::vector<Vertex>& vertices, std::vector<Edge>& edges) { int32_t x, y; Real x0, y0, x1, y1; switch (rectangle.type) { case 3: // two vertices, on xmin and xmax LogAssert(rectangle.yOfXMin != -1, "Unexpected condition."); x = rectangle.xOrigin; y = rectangle.yOfXMin; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.yOfXMax != -1, "Unexpected condition."); x = rectangle.xOrigin + rectangle.xStride; y = rectangle.yOfXMax; x1 = static_cast<Real>(x); y1 = GetInterp(level, y, x + mSize * y, mSize); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 5: // two vertices, on xmin and ymin LogAssert(rectangle.yOfXMin != -1, "Unexpected condition."); x = rectangle.xOrigin; y = rectangle.yOfXMin; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.xOfYMin != -1, "Unexpected condition."); x = rectangle.xOfYMin; y = rectangle.yOrigin; x1 = GetInterp(level, x, x + mSize * y, 1); y1 = static_cast<Real>(y); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 6: // two vertices, on xmax and ymin LogAssert(rectangle.yOfXMax != -1, "Unexpected condition."); x = rectangle.xOrigin + rectangle.xStride; y = rectangle.yOfXMax; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.xOfYMin != -1, "Unexpected condition."); x = rectangle.xOfYMin; y = rectangle.yOrigin; x1 = GetInterp(level, x, x + mSize * y, 1); y1 = static_cast<Real>(y); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 9: // two vertices, on xmin and ymax LogAssert(rectangle.yOfXMin != -1, "Unexpected condition."); x = rectangle.xOrigin; y = rectangle.yOfXMin; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.xOfYMax != -1, "Unexpected condition."); x = rectangle.xOfYMax; y = rectangle.yOrigin + rectangle.yStride; x1 = GetInterp(level, x, x + mSize * y, 1); y1 = static_cast<Real>(y); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 10: // two vertices, on xmax and ymax LogAssert(rectangle.yOfXMax != -1, "Unexpected condition."); x = rectangle.xOrigin + rectangle.xStride; y = rectangle.yOfXMax; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.xOfYMax != -1, "Unexpected condition."); x = rectangle.xOfYMax; y = rectangle.yOrigin + rectangle.yStride; x1 = GetInterp(level, x, x + mSize * y, 1); y1 = static_cast<Real>(y); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 12: // two vertices, on ymin and ymax LogAssert(rectangle.xOfYMin != -1, "Unexpected condition."); x = rectangle.xOfYMin; y = rectangle.yOrigin; x0 = GetInterp(level, x, x + mSize * y, 1); y0 = static_cast<Real>(y); LogAssert(rectangle.xOfYMax != -1, "Unexpected condition."); x = rectangle.xOfYMax; y = rectangle.yOrigin + rectangle.yStride; x1 = GetInterp(level, x, x + mSize * y, 1); y1 = static_cast<Real>(y); AddEdge(vertices, edges, x0, y0, x1, y1); break; case 15: // four vertices, one per edge, need to disambiguate { LogAssert(rectangle.xStride == 1 && rectangle.yStride == 1, "Unexpected condition."); LogAssert(rectangle.yOfXMin != -1, "Unexpected condition."); x = rectangle.xOrigin; y = rectangle.yOfXMin; x0 = static_cast<Real>(x); y0 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.yOfXMax != -1, "Unexpected condition."); x = rectangle.xOrigin + rectangle.xStride; y = rectangle.yOfXMax; x1 = static_cast<Real>(x); y1 = GetInterp(level, y, x + mSize * y, mSize); LogAssert(rectangle.xOfYMin != -1, "Unexpected condition."); x = rectangle.xOfYMin; y = rectangle.yOrigin; Real fx2 = GetInterp(level, x, x + mSize * y, 1); Real fy2 = static_cast<Real>(y); LogAssert(rectangle.xOfYMax != -1, "Unexpected condition."); x = rectangle.xOfYMax; y = rectangle.yOrigin + rectangle.yStride; Real fx3 = GetInterp(level, x, x + mSize * y, 1); Real fy3 = static_cast<Real>(y); int32_t index = rectangle.xOrigin + mSize * rectangle.yOrigin; int64_t i00 = static_cast<int64_t>(mInputPixels[index]); ++index; int64_t i10 = static_cast<int64_t>(mInputPixels[index]); index += mSize; int64_t i11 = static_cast<int64_t>(mInputPixels[index]); --index; int64_t i01 = static_cast<int64_t>(mInputPixels[index]); int64_t det = i00 * i11 - i01 * i10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2> and <P1,P3>. AddEdge(vertices, edges, x0, y0, fx2, fy2); AddEdge(vertices, edges, x1, y1, fx3, fy3); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3> and <P1,P2>. AddEdge(vertices, edges, x0, y0, fx3, fy3); AddEdge(vertices, edges, x1, y1, fx2, fy2); } else { // Plus-sign configuration, add branch point to // tessellation. Real fx4 = fx2, fy4 = y0; AddEdge(vertices, edges, x0, y0, fx4, fy4); AddEdge(vertices, edges, x1, y1, fx4, fy4); AddEdge(vertices, edges, fx2, fy2, fx4, fy4); AddEdge(vertices, edges, fx3, fy3, fx4, fy4); } break; } default: LogError("Unexpected condition."); } } // Support for debugging. void PrintRectangles(std::ostream& output, std::vector<Rectangle> const& rectangles) { for (size_t i = 0; i < rectangles.size(); ++i) { auto const& rectangle = rectangles[i]; output << "rectangle " << i << std::endl; output << " x origin = " << rectangle.xOrigin << std::endl; output << " y origin = " << rectangle.yOrigin << std::endl; output << " x stride = " << rectangle.xStride << std::endl; output << " y stride = " << rectangle.yStride << std::endl; output << " flag = " << rectangle.type << std::endl; output << " y of xmin = " << rectangle.yOfXMin << std::endl; output << " y of xmax = " << rectangle.yOfXMax << std::endl; output << " x of ymin = " << rectangle.xOfYMin << std::endl; output << " x of ymax = " << rectangle.xOfYMax << std::endl; output << std::endl; } } // Storage of image data. int32_t mTwoPowerN, mSize; T const* mInputPixels; // Trees for linear merging. std::vector<std::shared_ptr<LinearMergeTree>> mXMerge, mYMerge; // Tree for area merging. std::unique_ptr<AreaMergeTree> mXYMerge; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContPointInPolyhedron3.h
.h
20,984
576
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ContPointInPolygon2.h> #include <Mathematics/IntrRay3Plane3.h> #include <Mathematics/IntrRay3Triangle3.h> #include <vector> // This class contains various implementations for point-in-polyhedron // queries. The planes stored with the faces are used in all cases to // reject ray-face intersection tests, a quick culling operation. // // The algorithm is to cast a ray from the input point P and test for // intersection against each face of the polyhedron. If the ray only // intersects faces at interior points (not vertices, not edge points), // then the point is inside when the number of intersections is odd and // the point is outside when the number of intersections is even. If the // ray intersects an edge or a vertex, then the counting must be handled // differently. The details are tedious. As an alternative, the approach // here is to allow you to specify 2*N+1 rays, where N >= 0. You should // choose these rays randomly. Each ray reports "inside" or "outside". // Whichever result occurs N+1 or more times is the "winner". The input // rayQuantity is 2*N+1. The input array Direction must have rayQuantity // elements. If you are feeling lucky, choose rayQuantity to be 1. namespace gte { template <typename Real> class PointInPolyhedron3 { public: // For simple polyhedra with triangle faces. class TriangleFace { public: // When you view the face from outside, the vertices are // counterclockwise ordered. The indices array stores the indices // into the vertex array. std::array<int32_t, 3> indices; // The normal vector is unit length and points to the outside of // the polyhedron. Plane3<Real> plane; }; // The Contains query will use ray-triangle intersection queries. PointInPolyhedron3(int32_t numPoints, Vector3<Real> const* points, int32_t numFaces, TriangleFace const* faces, int32_t numRays, Vector3<Real> const* directions) : mNumPoints(numPoints), mPoints(points), mNumFaces(numFaces), mTFaces(faces), mCFaces(nullptr), mSFaces(nullptr), mMethod(0), mNumRays(numRays), mDirections(directions) { } // For simple polyhedra with convex polygon faces. class ConvexFace { public: // When you view the face from outside, the vertices are // counterclockwise ordered. The indices array stores the indices // into the vertex array. std::vector<int32_t> indices; // The normal vector is unit length and points to the outside of // the polyhedron. Plane3<Real> plane; }; // The Contains() query will use ray-convexpolygon intersection // queries. A ray-convexpolygon intersection query can be implemented // in many ways. In this context, uiMethod is one of three value: // 0 : Use a triangle fan and perform a ray-triangle intersection // query for each triangle. // 1 : Find the point of intersection of ray and plane of polygon. // Test whether that point is inside the convex polygon using an // O(N) test. // 2 : Find the point of intersection of ray and plane of polygon. // Test whether that point is inside the convex polygon using an // O(log N) test. PointInPolyhedron3(int32_t numPoints, Vector3<Real> const* points, int32_t numFaces, ConvexFace const* faces, int32_t numRays, Vector3<Real> const* directions, uint32_t method) : mNumPoints(numPoints), mPoints(points), mNumFaces(numFaces), mTFaces(nullptr), mCFaces(faces), mSFaces(nullptr), mMethod(method), mNumRays(numRays), mDirections(directions) { } // For simple polyhedra with simple polygon faces that are generally // not all convex. class SimpleFace { public: // When you view the face from outside, the vertices are // counterclockwise ordered. The Indices array stores the indices // into the vertex array. std::vector<int32_t> indices; // The normal vector is unit length and points to the outside of // the polyhedron. Plane3<Real> plane; // Each simple face may be triangulated. The indices are relative // to the vertex array. Each triple of indices represents a // triangle in the triangulation. std::vector<int32_t> triangles; }; // The Contains query will use ray-simplepolygon intersection queries. // A ray-simplepolygon intersection query can be implemented in a // couple of ways. In this context, uiMethod is one of two value: // 0 : Iterate over the triangles of each face and perform a // ray-triangle intersection query for each triangle. This // requires that the SimpleFace::Triangles array be initialized // for each face. // 1 : Find the point of intersection of ray and plane of polygon. // Test whether that point is inside the polygon using an O(N) // test. The SimpleFace::Triangles array is not used for this // method, so it does not have to be initialized for each face. PointInPolyhedron3(int32_t numPoints, Vector3<Real> const* points, int32_t numFaces, SimpleFace const* faces, int32_t numRays, Vector3<Real> const* directions, uint32_t method) : mNumPoints(numPoints), mPoints(points), mNumFaces(numFaces), mTFaces(nullptr), mCFaces(nullptr), mSFaces(faces), mMethod(method), mNumRays(numRays), mDirections(directions) { } // This function will select the actual algorithm based on which // constructor you used for this class. bool Contains(Vector3<Real> const& p) const { if (mTFaces) { return ContainsT0(p); } if (mCFaces) { if (mMethod == 0) { return ContainsC0(p); } return ContainsC1C2(p, mMethod); } if (mSFaces) { if (mMethod == 0) { return ContainsS0(p); } if (mMethod == 1) { return ContainsS1(p); } } return false; } private: // For all types of faces. The ray origin is the test point. The ray // direction is one of those passed to the constructors. The plane // origin is a point on the plane of the face. The plane normal is a // unit-length normal to the face and that points outside the // polyhedron. static bool FastNoIntersect(Ray3<Real> const& ray, Plane3<Real> const& plane) { Real planeDistance = Dot(plane.normal, ray.origin) - plane.constant; Real planeAngle = Dot(plane.normal, ray.direction); if (planeDistance < (Real)0) { // The ray origin is on the negative side of the plane. if (planeAngle <= (Real)0) { // The ray points away from the plane. return true; } } if (planeDistance > (Real)0) { // The ray origin is on the positive side of the plane. if (planeAngle >= (Real)0) { // The ray points away from the plane. return true; } } return false; } // For triangle faces. bool ContainsT0(Vector3<Real> const& p) const { int32_t insideCount = 0; TIQuery<Real, Ray3<Real>, Triangle3<Real>> rtQuery; Triangle3<Real> triangle; Ray3<Real> ray; ray.origin = p; for (int32_t j = 0; j < mNumRays; ++j) { ray.direction = mDirections[j]; // Zero intersections to start with. bool odd = false; TriangleFace const* face = mTFaces; for (int32_t i = 0; i < mNumFaces; ++i, ++face) { // Attempt to quickly cull the triangle. if (FastNoIntersect(ray, face->plane)) { continue; } // Get the triangle vertices. for (int32_t k = 0; k < 3; ++k) { triangle.v[k] = mPoints[face->indices[k]]; } // Test for intersection. if (rtQuery(ray, triangle).intersect) { // The ray intersects the triangle. odd = !odd; } } if (odd) { insideCount++; } } return insideCount > mNumRays / 2; } // For convex faces. bool ContainsC0(Vector3<Real> const& p) const { int32_t insideCount = 0; TIQuery<Real, Ray3<Real>, Triangle3<Real>> rtQuery; Triangle3<Real> triangle; Ray3<Real> ray; ray.origin = p; for (int32_t j = 0; j < mNumRays; ++j) { ray.direction = mDirections[j]; // Zero intersections to start with. bool odd = false; ConvexFace const* face = mCFaces; for (int32_t i = 0; i < mNumFaces; ++i, ++face) { // Attempt to quickly cull the triangle. if (FastNoIntersect(ray, face->plane)) { continue; } // Process the triangles in a trifan of the face. size_t numVerticesM1 = face->indices.size() - 1; triangle.v[0] = mPoints[face->indices[0]]; for (size_t k = 1; k < numVerticesM1; ++k) { triangle.v[1] = mPoints[face->indices[k]]; triangle.v[2] = mPoints[face->indices[k + 1]]; if (rtQuery(ray, triangle).intersect) { // The ray intersects the triangle. odd = !odd; } } } if (odd) { insideCount++; } } return insideCount > mNumRays / 2; } bool ContainsC1C2(Vector3<Real> const& p, uint32_t method) const { int32_t insideCount = 0; FIQuery<Real, Ray3<Real>, Plane3<Real>> rpQuery; Ray3<Real> ray; ray.origin = p; for (int32_t j = 0; j < mNumRays; ++j) { ray.direction = mDirections[j]; // Zero intersections to start with. bool odd = false; ConvexFace const* face = mCFaces; for (int32_t i = 0; i < mNumFaces; ++i, ++face) { // Attempt to quickly cull the triangle. if (FastNoIntersect(ray, face->plane)) { continue; } // Compute the ray-plane intersection. auto result = rpQuery(ray, face->plane); // If you trigger this assertion, numerical round-off // errors have led to a discrepancy between // FastNoIntersect and the Find() result. LogAssert(result.intersect, "Unexpected condition."); // Get a coordinate system for the plane. Use vertex 0 // as the origin. Vector3<Real> const& V0 = mPoints[face->indices[0]]; Vector3<Real> basis[3]; basis[0] = face->plane.normal; ComputeOrthogonalComplement(1, basis); // Project the intersection onto the plane. Vector3<Real> diff = result.point - V0; Vector2<Real> projIntersect{ Dot(basis[1], diff), Dot(basis[2], diff) }; // Project the face vertices onto the plane of the face. if (face->indices.size() > mProjVertices.size()) { mProjVertices.resize(face->indices.size()); } // Project the remaining vertices. Vertex 0 is always the // origin. size_t numIndices = face->indices.size(); mProjVertices[0] = Vector2<Real>::Zero(); for (size_t k = 1; k < numIndices; ++k) { diff = mPoints[face->indices[k]] - V0; mProjVertices[k][0] = Dot(basis[1], diff); mProjVertices[k][1] = Dot(basis[2], diff); } // Test whether the intersection point is in the convex // polygon. PointInPolygon2<Real> PIP(static_cast<int32_t>(mProjVertices.size()), &mProjVertices[0]); if (method == 1) { if (PIP.ContainsConvexOrderN(projIntersect)) { // The ray intersects the triangle. odd = !odd; } } else { if (PIP.ContainsConvexOrderLogN(projIntersect)) { // The ray intersects the triangle. odd = !odd; } } } if (odd) { insideCount++; } } return insideCount > mNumRays / 2; } // For simple faces. bool ContainsS0(Vector3<Real> const& p) const { int32_t insideCount = 0; TIQuery<Real, Ray3<Real>, Triangle3<Real>> rtQuery; Triangle3<Real> triangle; Ray3<Real> ray; ray.origin = p; for (int32_t j = 0; j < mNumRays; ++j) { ray.direction = mDirections[j]; // Zero intersections to start with. bool odd = false; SimpleFace const* face = mSFaces; for (int32_t i = 0; i < mNumFaces; ++i, ++face) { // Attempt to quickly cull the triangle. if (FastNoIntersect(ray, face->plane)) { continue; } // The triangulation must exist to use it. size_t numTriangles = face->triangles.size() / 3; LogAssert(numTriangles > 0, "Triangulation must exist."); // Process the triangles in a triangulation of the face. int32_t const* currIndex = &face->triangles[0]; for (size_t t = 0; t < numTriangles; ++t) { // Get the triangle vertices. for (int32_t k = 0; k < 3; ++k) { triangle.v[k] = mPoints[*currIndex++]; } // Test for intersection. if (rtQuery(ray, triangle).intersect) { // The ray intersects the triangle. odd = !odd; } } } if (odd) { insideCount++; } } return insideCount > mNumRays / 2; } bool ContainsS1(Vector3<Real> const& p) const { int32_t insideCount = 0; FIQuery<Real, Ray3<Real>, Plane3<Real>> rpQuery; Ray3<Real> ray; ray.origin = p; for (int32_t j = 0; j < mNumRays; ++j) { ray.direction = mDirections[j]; // Zero intersections to start with. bool odd = false; SimpleFace const* face = mSFaces; for (int32_t i = 0; i < mNumFaces; ++i, ++face) { // Attempt to quickly cull the triangle. if (FastNoIntersect(ray, face->plane)) { continue; } // Compute the ray-plane intersection. auto result = rpQuery(ray, face->plane); // If you trigger this assertion, numerical round-off // errors have led to a discrepancy between // FastNoIntersect and the Find() result. LogAssert(result.intersect, "Unexpected condition."); // Get a coordinate system for the plane. Use vertex 0 // as the origin. Vector3<Real> const& V0 = mPoints[face->indices[0]]; Vector3<Real> basis[3]; basis[0] = face->plane.normal; ComputeOrthogonalComplement(1, basis); // Project the intersection onto the plane. Vector3<Real> diff = result.point - V0; Vector2<Real> projIntersect{ Dot(basis[1], diff), Dot(basis[2], diff) }; // Project the face vertices onto the plane of the face. if (face->indices.size() > mProjVertices.size()) { mProjVertices.resize(face->indices.size()); } // Project the remaining vertices. Vertex 0 is always the // origin. size_t numIndices = face->indices.size(); mProjVertices[0] = Vector2<Real>::Zero(); for (size_t k = 1; k < numIndices; ++k) { diff = mPoints[face->indices[k]] - V0; mProjVertices[k][0] = Dot(basis[1], diff); mProjVertices[k][1] = Dot(basis[2], diff); } // Test whether the intersection point is in the convex // polygon. PointInPolygon2<Real> PIP(static_cast<int32_t>(mProjVertices.size()), &mProjVertices[0]); if (PIP.Contains(projIntersect)) { // The ray intersects the triangle. odd = !odd; } } if (odd) { insideCount++; } } return insideCount > mNumRays / 2; } int32_t mNumPoints; Vector3<Real> const* mPoints; int32_t mNumFaces; TriangleFace const* mTFaces; ConvexFace const* mCFaces; SimpleFace const* mSFaces; uint32_t mMethod; int32_t mNumRays; Vector3<Real> const* mDirections; // Temporary storage for those methods that reduce the problem to 2D // point-in-polygon queries. The array stores the projections of // face vertices onto the plane of the face. It is resized as needed. mutable std::vector<Vector2<Real>> mProjVertices; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/AlignedBox.h
.h
4,008
134
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> // The box is aligned with the standard coordinate axes, which allows us to // represent it using minimum and maximum values along each axis. Some // algorithms prefer the centered representation that is used for oriented // boxes. The center is C and the extents are the half-lengths in each // coordinate-axis direction. namespace gte { template <int32_t N, typename T> class AlignedBox { public: // Construction and destruction. The default constructor sets the // minimum values to -1 and the maximum values to +1. AlignedBox() { T const negOne = static_cast<T>(-1); T const one = static_cast<T>(1); for (int32_t i = 0; i < N; ++i) { min[i] = negOne; max[i] = one; } } // Please ensure that inMin[i] <= inMax[i] for all i. AlignedBox(Vector<N, T> const& inMin, Vector<N, T> const& inMax) { for (int32_t i = 0; i < N; ++i) { min[i] = inMin[i]; max[i] = inMax[i]; } } // Compute the centered representation. NOTE: If you set the minimum // and maximum values, compute C and extents, and then recompute the // minimum and maximum values, the numerical round-off errors can lead // to results different from what you started with. void GetCenteredForm(Vector<N, T>& center, Vector<N, T>& extent) const { T const half = static_cast<T>(0.5); center = (max + min) * half; extent = (max - min) * half; } // Compute the vertices of the box. If index i has the bit pattern // i = b[N-1]...b[0], then the corner at index i is vertex[i], where // vertex[i][d] = min[d] whern b[d] = 0 or vertex[i][d = max[d] when // b[d] = 1. void GetVertices(std::array<Vector<N, T>, (1 << N)>& vertex) const { int32_t const imax = (1 << N); for (int32_t i = 0; i < imax; ++i) { for (int32_t d = 0, mask = 1; d < N; ++d, mask <<= 1) { if ((i & mask) > 0) { vertex[i][d] = max[d]; } else { vertex[i][d] = min[d]; } } } } // Public member access. It is required that min[i] <= max[i]. Vector<N, T> min, max; public: // Comparisons to support sorted containers. bool operator==(AlignedBox const& box) const { return min == box.min && max == box.max; } bool operator!=(AlignedBox const& box) const { return !operator==(box); } bool operator< (AlignedBox const& box) const { if (min < box.min) { return true; } if (min > box.min) { return false; } return max < box.max; } bool operator<=(AlignedBox const& box) const { return !box.operator<(*this); } bool operator> (AlignedBox const& box) const { return box.operator<(*this); } bool operator>=(AlignedBox const& box) const { return !operator<(box); } }; // Template aliases for convenience. template <typename T> using AlignedBox2 = AlignedBox<2, T>; template <typename T> using AlignedBox3 = AlignedBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DisjointRectangles.h
.h
14,553
450
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DisjointIntervals.h> #include <functional> namespace gte { // Compute Boolean operations of disjoint sets of half-open rectangles of // the form [xmin,xmax)x[ymin,ymax) with xmin < xmax and ymin < ymax. template <typename Scalar> class DisjointRectangles { public: // Convenient type definition. typedef DisjointIntervals<Scalar> ISet; // Construction and destruction. The non-default constructor requires // that xmin < xmax and ymin < ymax. DisjointRectangles() : mNumRectangles(0) { } DisjointRectangles(Scalar const& xmin, Scalar const& xmax, Scalar const& ymin, Scalar const& ymax) { if (xmin < xmax && ymin < ymax) { mNumRectangles = 1; mStrips.push_back(Strip(ymin, ymax, ISet(xmin, xmax))); } else { mNumRectangles = 0; } } ~DisjointRectangles() { } // Copy operations. DisjointRectangles(DisjointRectangles const& other) { *this = other; } DisjointRectangles& operator=(DisjointRectangles const& other) { mNumRectangles = other.mNumRectangles; mStrips = other.mStrips; return *this; } // Move operations. DisjointRectangles(DisjointRectangles&& other) noexcept { *this = std::move(other); } DisjointRectangles& operator=(DisjointRectangles&& other) noexcept { mNumRectangles = other.mNumRectangles; mStrips = std::move(other.mStrips); return *this; } // The rectangle set consists of y-strips of interval sets. class Strip { public: // Construction and destruction. Strip() : ymin((Scalar)0), ymax((Scalar)0) { } Strip(Scalar const& inYMin, Scalar const& inYMax, ISet const& inIntervalSet) : ymin(inYMin), ymax(inYMax), intervalSet(inIntervalSet) { } ~Strip() { } // Copy operations. Strip(Strip const& other) { *this = other; } Strip& operator=(Strip const& other) { ymin = other.ymin; ymax = other.ymax; intervalSet = other.intervalSet; return *this; } // Move operations. Strip(Strip&& other) noexcept { *this = std::move(other); } Strip& operator=(Strip&& other) noexcept { ymin = other.ymin; ymax = other.ymax; intervalSet = std::move(other.intervalSet); other.ymin = (Scalar)0; other.ymax = (Scalar)0; return *this; } // Member access. Scalar ymin, ymax; ISet intervalSet; }; // The number of rectangles in the set. inline int32_t GetNumRectangles() const { return mNumRectangles; } // The i-th rectangle is [xmin,xmax)x[ymin,ymax). The values xmin, // xmax, ymin and ymax are valid when 0 <= i < GetNumRectangles(). bool GetRectangle(int32_t i, Scalar& xmin, Scalar& xmax, Scalar& ymin, Scalar& ymax) const { int32_t totalQuantity = 0; for (auto const& strip : mStrips) { ISet const& intervalSet = strip.intervalSet; int32_t xQuantity = intervalSet.GetNumIntervals(); int32_t nextTotalQuantity = totalQuantity + xQuantity; if (i < nextTotalQuantity) { i -= totalQuantity; intervalSet.GetInterval(i, xmin, xmax); ymin = strip.ymin; ymax = strip.ymax; return true; } totalQuantity = nextTotalQuantity; } return false; } // Make this set empty. inline void Clear() { mNumRectangles = 0; mStrips.clear(); } // The number of y-strips in the set. inline int32_t GetNumStrips() const { return static_cast<int32_t>(mStrips.size()); } // The i-th strip. The returned values are valid when // 0 <= i < GetStripQuantity(). bool GetStrip(int32_t i, Scalar& ymin, Scalar& ymax, ISet& xIntervalSet) const { if (0 <= i && i < GetNumStrips()) { Strip const& strip = mStrips[i]; ymin = strip.ymin; ymax = strip.ymax; xIntervalSet = strip.intervalSet; return true; } return false; } // Insert [xmin,xmax)x[ymin,ymax) into the set. This is a Boolean // union operation. The operation is successful only when xmin < xmax // and ymin < ymax. bool Insert(Scalar const& xmin, Scalar const& xmax, Scalar const& ymin, Scalar const& ymax) { if (xmin < xmax && ymin < ymax) { DisjointRectangles input(xmin, xmax, ymin, ymax); DisjointRectangles output = *this | input; *this = std::move(output); return true; } return false; } // Remove [xmin,xmax)x[ymin,ymax) from the set. This is a Boolean // difference operation. The operation is successful only when // xmin < xmax and ymin < ymax. bool Remove(Scalar const& xmin, Scalar const& xmax, Scalar const& ymin, Scalar const& ymax) { if (xmin < xmax && ymin < ymax) { DisjointRectangles input(xmin, xmax, ymin, ymax); DisjointRectangles output = *this - input; *this = std::move(output); return true; } return false; } // Get the union of the rectangle sets sets, input0 union input1. friend DisjointRectangles operator|(DisjointRectangles const& input0, DisjointRectangles const& input1) { return Execute( [](ISet const& i0, ISet const& i1) { return i0 | i1; }, true, true, input0, input1); } // Get the intersection of the rectangle sets, input0 intersect is1. friend DisjointRectangles operator&(DisjointRectangles const& input0, DisjointRectangles const& input1) { return Execute( [](ISet const& i0, ISet const& i1) { return i0 & i1; }, false, false, input0, input1); } // Get the differences of the rectangle sets, input0 minus input1. friend DisjointRectangles operator-(DisjointRectangles const& input0, DisjointRectangles const& input1) { return Execute( [](ISet const& i0, ISet const& i1) { return i0 - i1; }, false, true, input0, input1); } // Get the exclusive or of the rectangle sets, input0 xor input1 = // (input0 minus input1) or (input1 minus input0). friend DisjointRectangles operator^(DisjointRectangles const& input0, DisjointRectangles const& input1) { return Execute( [](ISet const& i0, ISet const& i1) { return i0 ^ i1; }, true, true, input0, input1); } private: static DisjointRectangles Execute( std::function<ISet(ISet const&, ISet const&)> const& operation, bool unionExclusiveOr, bool unionExclusiveOrDifference, DisjointRectangles const& input0, DisjointRectangles const& input1) { DisjointRectangles output; size_t const numStrips0 = input0.GetNumStrips(); size_t const numStrips1 = input1.GetNumStrips(); size_t i0 = 0, i1 = 0; bool getOriginal0 = true, getOriginal1 = true; Scalar ymin0 = (Scalar)0; Scalar ymax0 = (Scalar)0; Scalar ymin1 = (Scalar)0; Scalar ymax1 = (Scalar)0; while (i0 < numStrips0 && i1 < numStrips1) { ISet const& intr0 = input0.mStrips[i0].intervalSet; if (getOriginal0) { ymin0 = input0.mStrips[i0].ymin; ymax0 = input0.mStrips[i0].ymax; } ISet const& intr1 = input1.mStrips[i1].intervalSet; if (getOriginal1) { ymin1 = input1.mStrips[i1].ymin; ymax1 = input1.mStrips[i1].ymax; } // Case 1. if (ymax1 <= ymin0) { // operator(empty,strip1) if (unionExclusiveOr) { output.mStrips.push_back(Strip(ymin1, ymax1, intr1)); } ++i1; getOriginal0 = false; getOriginal1 = true; continue; // using next ymin1/ymax1 } // Case 11. if (ymin1 >= ymax0) { // operator(strip0,empty) if (unionExclusiveOrDifference) { output.mStrips.push_back(Strip(ymin0, ymax0, intr0)); } ++i0; getOriginal0 = true; getOriginal1 = false; continue; // using next ymin0/ymax0 } // Reduce cases 2, 3, 4 to cases 5, 6, 7. if (ymin1 < ymin0) { // operator(empty,[ymin1,ymin0)) if (unionExclusiveOr) { output.mStrips.push_back(Strip(ymin1, ymin0, intr1)); } ymin1 = ymin0; getOriginal1 = false; } // Reduce cases 8, 9, 10 to cases 5, 6, 7. if (ymin1 > ymin0) { // operator([ymin0,ymin1),empty) if (unionExclusiveOrDifference) { output.mStrips.push_back(Strip(ymin0, ymin1, intr0)); } ymin0 = ymin1; getOriginal0 = false; } // Case 5. if (ymax1 < ymax0) { // operator(strip0,[ymin1,ymax1)) auto result = operation(intr0, intr1); output.mStrips.push_back(Strip(ymin1, ymax1, result)); ymin0 = ymax1; ++i1; getOriginal0 = false; getOriginal1 = true; continue; // using next ymin1/ymax1 } // Case 6. if (ymax1 == ymax0) { // operator(strip0,[ymin1,ymax1)) auto result = operation(intr0, intr1); output.mStrips.push_back(Strip(ymin1, ymax1, result)); ++i0; ++i1; getOriginal0 = true; getOriginal1 = true; continue; // using next ymin0/ymax0 and ymin1/ymax1 } // Case 7. if (ymax1 > ymax0) { // operator(strip0,[ymin1,ymax0)) auto result = operation(intr0, intr1); output.mStrips.push_back(Strip(ymin1, ymax0, result)); ymin1 = ymax0; ++i0; getOriginal0 = true; getOriginal1 = false; // continue; using current ymin1/ymax1 } } if (unionExclusiveOrDifference) { while (i0 < numStrips0) { if (getOriginal0) { ymin0 = input0.mStrips[i0].ymin; ymax0 = input0.mStrips[i0].ymax; } else { getOriginal0 = true; } // operator(strip0,empty) output.mStrips.push_back(Strip(ymin0, ymax0, input0.mStrips[i0].intervalSet)); ++i0; } } if (unionExclusiveOr) { while (i1 < numStrips1) { if (getOriginal1) { ymin1 = input1.mStrips[i1].ymin; ymax1 = input1.mStrips[i1].ymax; } else { getOriginal1 = true; } // operator(empty,strip1) output.mStrips.push_back(Strip(ymin1, ymax1, input1.mStrips[i1].intervalSet)); ++i1; } } output.ComputeRectangleQuantity(); return output; } void ComputeRectangleQuantity() { mNumRectangles = 0; for (auto strip : mStrips) { mNumRectangles += strip.intervalSet.GetNumIntervals(); } } // The number of rectangles in the set. int32_t mNumRectangles; // The y-strips of the set, each containing an x-interval set. std::vector<Strip> mStrips; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Segment2.h
.h
6,009
172
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.25 #pragma once #include <Mathematics/IntrLine2Line2.h> #include <Mathematics/Segment.h> namespace gte { template <typename T> class TIQuery<T, Line2<T>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // If the line and segment do not intersect, // intersect = false // numIntersections = 0 // // If the line and segment intersect in a single point, // intersect = true // numIntersections = 1 // // If the line and segment are collinear, // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() bool intersect; int32_t numIntersections; }; Result operator()(Line2<T> const& line, Segment2<T> const& segment) { Result result{}; FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> segLine(segment.p[0], segment.p[1] - segment.p[0]); auto llResult = llQuery(line, segLine); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the segment. if (llResult.line1Parameter[0] >= static_cast<T>(0) && llResult.line1Parameter[1] <= static_cast<T>(1)) { result.intersect = true; result.numIntersections = 1; } else { result.intersect = false; result.numIntersections = 0; } } else { result.intersect = llResult.intersect; result.numIntersections = llResult.numIntersections; } return result; } }; template <typename T> class FIQuery<T, Line2<T>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), lineParameter{ static_cast<T>(0), static_cast<T>(0) }, segmentParameter{ static_cast<T>(0), static_cast<T>(0) }, point(Vector2<T>::Zero()) { } // If the line and segment do not intersect, // intersect = false // numIntersections = 0 // lineParameter[] = { 0, 0 } // invalid // segmentParameter[] = { 0, 0 } // invalid // point = { 0, 0 } // invalid // // If the line and segment intersect in a single point, the // parameter for line is s0 and the parameter for segment is // s1 in [0,1], // intersect = true // numIntersections = 1 // lineParameter = { s0, s0 } // segmentParameter = { s1, s1 } // point = line.origin + s0 * line.direction // = segment.p[0] + s1 * (segment.p[1] - segment.p[0]); // // If the line and segment are collinear, let // maxT = std::numeric_limits<T>::max(), // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() // lineParameter[] = { -maxT, +maxT } // segmentParameter[] = { 0, 1 } // point = { 0, 0 } // invalid bool intersect; int32_t numIntersections; std::array<T, 2> lineParameter; std::array<T, 2> segmentParameter; Vector2<T> point; }; Result operator()(Line2<T> const& line, Segment2<T> const& segment) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> segLine(segment.p[0], segment.p[1] - segment.p[0]); auto llResult = llQuery(line, segLine); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the ray. if (llResult.line1Parameter[0] >= zero && llResult.line1Parameter[1] <= one) { result.intersect = true; result.numIntersections = 1; result.lineParameter[0] = llResult.line0Parameter[0]; result.lineParameter[1] = result.lineParameter[0]; result.segmentParameter[0] = llResult.line1Parameter[0]; result.segmentParameter[1] = result.segmentParameter[0]; result.point = llResult.point; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); T maxT = std::numeric_limits<T>::max(); result.lineParameter[0] = -maxT; result.lineParameter[1] = +maxT; result.segmentParameter[0] = zero; result.segmentParameter[1] = one; } else { result.intersect = false; result.numIntersections = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ETManifoldMesh.h
.h
42,103
1,007
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.26 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/EdgeKey.h> #include <Mathematics/HashCombine.h> #include <Mathematics/TriangleKey.h> #include <limits> #include <map> #include <memory> #include <queue> #include <unordered_map> #include <unordered_set> #include <vector> // The ETManifoldMesh class represents an edge-triangle manifold mesh. It is // general purpose, allowing insertion and removal of triangles at any time. // Howver, the performance is limited because of the use of C++ container // classes (unordered sets and maps). If your application requires an // edge-triangle manifold mesh for which no triangles will be removed, a // much better choice is VETManifoldMeshVR. namespace gte { class ETManifoldMesh { public: // Edge data types. class Edge; typedef std::unique_ptr<Edge>(*ECreator)(int32_t, int32_t); using EMap = std::unordered_map<EdgeKey<false>, std::unique_ptr<Edge>, EdgeKey<false>, EdgeKey<false>>; // Triangle data types. class Triangle; typedef std::unique_ptr<Triangle>(*TCreator)(int32_t, int32_t, int32_t); using TMap = std::unordered_map<TriangleKey<true>, std::unique_ptr<Triangle>, TriangleKey<true>, TriangleKey<true>>; // Edge object. class Edge { public: virtual ~Edge() = default; Edge(int32_t v0, int32_t v1) : V{ v0, v1 } { T.fill(nullptr); } // Vertices of the edge. std::array<int32_t, 2> V; // Triangles sharing the edge. std::array<Triangle*, 2> T; }; // Triangle object. class Triangle { public: virtual ~Triangle() = default; Triangle(int32_t v0, int32_t v1, int32_t v2) : V{ v0, v1, v2 } { E.fill(nullptr); T.fill(nullptr); } // The edge <u0,u1> is directed. Determine whether the triangle // has an edge <V[i],V[(i+1)%3]> = <u0,u1> (return +1) or an edge // <V[i],V[(i+1)%3]> = <u1,u0> (return -1) or does not have an // edge meeting either condition (return 0). int32_t WhichSideOfEdge(int32_t u0, int32_t u1) const { for (size_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { if (V[i0] == u0 && V[i1] == u1) { return +1; } if (V[i0] == u1 && V[i1] == u0) { return -1; } } return 0; } Triangle* GetAdjacentOfEdge(int32_t u0, int32_t u1) { for (size_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { if ((V[i0] == u0 && V[i1] == u1) || (V[i0] == u1 && V[i1] == u0)) { return T[i0]; } } return nullptr; } bool GetOppositeVertexOfEdge(int32_t u0, int32_t u1, int32_t& uOpposite) { for (size_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { if ((V[i0] == u0 && V[i1] == u1) || (V[i0] == u1 && V[i1] == u0)) { uOpposite = V[(i1 + 1) % 3]; return true; } } return false; } // Vertices, listed in counterclockwise order (V[0],V[1],V[2]). std::array<int32_t, 3> V; // Adjacent edges. E[i] points to edge (V[i],V[(i+1)%3]). std::array<Edge*, 3> E; // Adjacent triangles. T[i] points to the adjacent triangle // sharing edge E[i]. std::array<Triangle*, 3> T; }; // Construction and destruction. virtual ~ETManifoldMesh() = default; ETManifoldMesh(ECreator eCreator = nullptr, TCreator tCreator = nullptr) : mECreator(eCreator ? eCreator : CreateEdge), mTCreator(tCreator ? tCreator : CreateTriangle), mThrowOnNonmanifoldInsertion(true) { } // Support for a deep copy of the mesh. The mEMap and mTMap objects // have dynamically allocated memory for edges and triangles. A // shallow copy of the pointers isn't possible with unique_ptr. ETManifoldMesh(ETManifoldMesh const& mesh) { *this = mesh; } ETManifoldMesh& operator=(ETManifoldMesh const& mesh) { Clear(); mECreator = mesh.mECreator; mTCreator = mesh.mTCreator; mThrowOnNonmanifoldInsertion = mesh.mThrowOnNonmanifoldInsertion; for (auto const& element : mesh.mTMap) { // The typecast avoids warnings about not storing the return // value in a named variable. The return value is discarded. (void)Insert(element.first.V[0], element.first.V[1], element.first.V[2]); } return *this; } // Member access. inline EMap const& GetEdges() const { return mEMap; } inline TMap const& GetTriangles() const { return mTMap; } // If the insertion of a triangle fails because the mesh would become // nonmanifold, the default behavior is to throw an exception. You // can disable this behavior and continue gracefully without an // exception. The return value is the previous value of the internal // state mAssertOnNonmanifoldInsertion. bool ThrowOnNonmanifoldInsertion(bool doException) { std::swap(doException, mThrowOnNonmanifoldInsertion); return doException; // return the previous state } // If <v0,v1,v2> is not in the mesh, a Triangle object is created and // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is // returned. If the insertion leads to a nonmanifold mesh, the call // fails with a nullptr returned. virtual Triangle* Insert(int32_t v0, int32_t v1, int32_t v2) { TriangleKey<true> tkey(v0, v1, v2); if (mTMap.find(tkey) != mTMap.end()) { // The triangle already exists. Return a null pointer as a // signal to the caller that the insertion failed. return nullptr; } // Create the new triangle. It will be added to mTMap at the end // of the function so that if an assertion is triggered and the // function returns early, the (bad) triangle will not be part of // the mesh. std::unique_ptr<Triangle> newTri = mTCreator(v0, v1, v2); Triangle* tri = newTri.get(); // Add the edges to the mesh if they do not already exist. for (int32_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { EdgeKey<false> ekey(tri->V[i0], tri->V[i1]); Edge* edge; auto eiter = mEMap.find(ekey); if (eiter == mEMap.end()) { // This is the first time the edge is encountered. std::unique_ptr<Edge> newEdge = mECreator(tri->V[i0], tri->V[i1]); edge = newEdge.get(); mEMap[ekey] = std::move(newEdge); // Update the edge and triangle. edge->T[0] = tri; tri->E[i0] = edge; } else { // This is the second time the edge is encountered. edge = eiter->second.get(); LogAssert(edge != nullptr, "Unexpected condition."); // Update the edge. if (edge->T[1]) { if (mThrowOnNonmanifoldInsertion) { LogError("Attempt to create nonmanifold mesh."); } else { return nullptr; } } edge->T[1] = tri; // Update the adjacent triangles. auto adjacent = edge->T[0]; LogAssert(adjacent != nullptr, "Unexpected condition."); for (int32_t j = 0; j < 3; ++j) { if (adjacent->E[j] == edge) { adjacent->T[j] = tri; break; } } // Update the triangle. tri->E[i0] = edge; tri->T[i0] = adjacent; } } mTMap[tkey] = std::move(newTri); return tri; } // If <v0,v1,v2> is in the mesh, it is removed and 'true' is // returned; otherwise, <v0,v1,v2> is not in the mesh and 'false' is // returned. virtual bool Remove(int32_t v0, int32_t v1, int32_t v2) { TriangleKey<true> tkey(v0, v1, v2); auto titer = mTMap.find(tkey); if (titer == mTMap.end()) { // The triangle does not exist. return false; } // Get the triangle. Triangle* tri = titer->second.get(); // Remove the edges and update adjacent triangles if necessary. for (int32_t i = 0; i < 3; ++i) { // Inform the edges the triangle is being deleted. auto edge = tri->E[i]; LogAssert(edge != nullptr, "Unexpected condition."); if (edge->T[0] == tri) { // One-triangle edges always have pointer at index zero. edge->T[0] = edge->T[1]; edge->T[1] = nullptr; } else if (edge->T[1] == tri) { edge->T[1] = nullptr; } else { LogError("Unexpected condition."); } // Remove the edge if you have the last reference to it. if (!edge->T[0] && !edge->T[1]) { EdgeKey<false> ekey(edge->V[0], edge->V[1]); mEMap.erase(ekey); } // Inform adjacent triangles the triangle is being deleted. auto adjacent = tri->T[i]; if (adjacent) { for (int32_t j = 0; j < 3; ++j) { if (adjacent->T[j] == tri) { adjacent->T[j] = nullptr; break; } } } } mTMap.erase(tkey); return true; } // Destroy the edges and triangles to obtain an empty mesh. virtual void Clear() { mEMap.clear(); mTMap.clear(); } // A manifold mesh is closed if each edge is shared twice. A closed // mesh is not necessarily oriented. For example, you could have a // mesh with spherical topology. The upper hemisphere has outer // facing normals and the lower hemisphere has inner-facing normals. // The discontinuity in orientation occurs on the circle shared by the // hemispheres. bool IsClosed() const { for (auto const& element : mEMap) { Edge* edge = element.second.get(); if (!edge->T[0] || !edge->T[1]) { return false; } } return true; } // Test whether all triangles in the mesh are oriented consistently // and that no two triangles are coincident. The latter means that // you cannot have both triangles <v0,v1,v2> and <v0,v2,v1> in the // mesh to be considered oriented. bool IsOriented() const { for (auto const& element : mEMap) { Edge* edge = element.second.get(); if (edge->T[0] && edge->T[1]) { // In each triangle, find the ordered edge that // corresponds to the unordered edge element.first. Also // find the vertex opposite that edge. bool edgePositive[2] = { false, false }; int32_t vOpposite[2] = { -1, -1 }; for (int32_t j = 0; j < 2; ++j) { auto tri = edge->T[j]; for (int32_t i = 0; i < 3; ++i) { size_t szI = static_cast<size_t>(i); if (tri->V[i] == element.first.V[0]) { int32_t vNext = tri->V[(szI + 1) % 3]; if (vNext == element.first.V[1]) { edgePositive[j] = true; vOpposite[j] = tri->V[(szI + 2) % 3]; } else { edgePositive[j] = false; vOpposite[j] = vNext; } break; } } } // To be oriented consistently, the edges must have // reversed ordering and the oppositive vertices cannot // match. if (edgePositive[0] == edgePositive[1] || vOpposite[0] == vOpposite[1]) { return false; } } } return true; } // Compute the connected components of the edge-triangle graph that // the mesh represents. The first function returns pointers into // 'this' object's containers, so you must consume the components // before clearing or destroying 'this'. The second function returns // triangle keys, which requires three times as much storage as the // pointers but allows you to clear or destroy 'this' before consuming // the components. void GetComponents(std::vector<std::vector<Triangle*>>& components) const { // visited: 0 (unvisited), 1 (discovered), 2 (finished) TrianglePtrIntMap visited; for (auto const& element : mTMap) { visited.insert(std::make_pair(element.second.get(), 0)); } for (auto& element : mTMap) { Triangle* tri = element.second.get(); if (visited[tri] == 0) { std::vector<Triangle*> component; DepthFirstSearch(tri, visited, component); components.push_back(std::move(component)); } } } void GetComponents(std::vector<std::vector<TriangleKey<true>>>& components) const { // visited: 0 (unvisited), 1 (discovered), 2 (finished) TrianglePtrIntMap visited; for (auto const& element : mTMap) { visited.insert(std::make_pair(element.second.get(), 0)); } for (auto& element : mTMap) { Triangle* tri = element.second.get(); if (visited[tri] == 0) { std::vector<Triangle*> component; DepthFirstSearch(tri, visited, component); std::vector<TriangleKey<true>> keyComponent; keyComponent.reserve(component.size()); for (auto const& t : component) { keyComponent.push_back(TriangleKey<true>(t->V[0], t->V[1], t->V[2])); } components.push_back(std::move(keyComponent)); } } } // Create a compact edge-triangle graph. The vertex indices are those // integers passed to an Insert(...) call. These have no meaning to // the semantics of maintaining an edge-triangle manifold mesh, so // this class makes no assumption about them. The vertex indices do // not necessarily start at 0 and they are not necessarily contiguous // numbers. The triangles are represented by triples of vertex // indices. The compact graph stores these in an array of N triples, // say, // T[0] = (v0,v1,v2), T[1] = (v3,v4,v5), ... // Each triangle has up to 3 adjacent triangles. The compact graph // stores the adjacency information in an array of N triples, say, // and the indices of adjacent triangle are stored in an array of Nt // A[0] = (t0,t1,t2), A[1] = (t3,t4,t5), ... // where the ti are indices into the array of triangles. For example, // the triangle T[0] has edges E[0] = (v0,v1), E[1] = (v1,v2) and // E[2] = (v2,v0). The edge E[0] has adjacent triangle T[0]. If E[0] // has another adjacent triangle, it is T[A[0][0]. If it does not have // another adjacent triangle, then A[0][0] = -1 (represented by // std::numeric_limits<size_t>::max()). Similar assignments are made // for the other two edges which produces A[0][1] for E[1] and // A[0][2] for E[2]. void CreateCompactGraph( std::vector<std::array<size_t, 3>>& triangles, std::vector<std::array<size_t, 3>>& adjacents) const { size_t const numTriangles = mTMap.size(); LogAssert(numTriangles > 0, "Invalid input."); triangles.resize(numTriangles); adjacents.resize(numTriangles); TrianglePtrSizeTMap triIndexMap; triIndexMap.insert(std::make_pair(nullptr, std::numeric_limits<size_t>::max())); size_t index = 0; for (auto const& element : mTMap) { triIndexMap.insert(std::make_pair(element.second.get(), index++)); } index = 0; for (auto const& element : mTMap) { auto const& triPtr = element.second; auto& tri = triangles[index]; auto& adj = adjacents[index]; for (size_t j = 0; j < 3; ++j) { tri[j] = triPtr->V[j]; adj[j] = triIndexMap[triPtr->T[j]]; } ++index; } } // The output of CreateCompactGraph can be used to compute the // connected components of the graph, each component having // triangles with the same chirality (winding order). Using only // the mesh topology, it is not possible to ensure that the // chirality is the same for all the components. Additional // application-specific geometric information is required. // // The 'components' contain indices into the 'triangles' array // and is partitioned into C subarrays, each representing a // connected component. The lengths of the subarrays are // stored in 'numComponentTriangles[]'. The number of elements // of this array is C. It is the case that the number of triangles // in the mesh is sum_{i=0}^{C-1} numComponentTriangles[i]. // // On return, the 'triangles' and 'adjacents' have been modified // and have the correct chirality. static void GetComponentsConsistentChirality( std::vector<std::array<size_t, 3>>& triangles, std::vector<std::array<size_t, 3>>& adjacents, std::vector<size_t>& components, std::vector<size_t>& numComponentTriangles) { LogAssert(triangles.size() > 0 && triangles.size() == adjacents.size(), "Invalid inputs."); // Use a breadth-first search to process the chirality of the // triangles. Keep track of the connected components. size_t const numTriangles = triangles.size(); std::vector<bool> visited(numTriangles, false); components.reserve(numTriangles); components.clear(); // The 'firstUnvisited' index is the that of the first triangle to // process in a connected component of the mesh. for (;;) { // Let n[i] be the number of elements of the i-th connected // component. Let C be the number of components. During the // execution of this loop, the array numComponentTriangles // stores // {0, n[0], n[0]+n[1], ..., n[0]+...+n[C-1]=numTriangles} // At the end of this function, the array is modified to // {n[0], n[1], ..., n[C-1]} numComponentTriangles.push_back(components.size()); // Find the starting index of a connected component. size_t firstUnvisited = numTriangles; for (size_t i = 0; i < numTriangles; ++i) { if (!visited[i]) { firstUnvisited = i; break; } } if (firstUnvisited == numTriangles) { // All connected components have been found. break; } // Initialize the queue to start at the first unvisited // triangle of a connected component. std::queue<size_t> triQueue; triQueue.push(firstUnvisited); visited[firstUnvisited] = true; components.push_back(firstUnvisited); // Perform the breadth-first search. while (!triQueue.empty()) { size_t curIndex = triQueue.front(); triQueue.pop(); auto const& curTriangle = triangles[curIndex]; for (size_t i0 = 0; i0 < 3; ++i0) { size_t adjIndex = adjacents[curIndex][i0]; if (adjIndex != std::numeric_limits<size_t>::max() && !visited[adjIndex]) { // The current-triangle has a directed edge // <curTriangle[i0],curTriangle[i1]> and there is // a triangle adjacent to it. size_t i1 = (i0 + 1) % 3; auto& adjTriangle = triangles[adjIndex]; size_t tv0 = curTriangle[i0]; size_t tv1 = curTriangle[i1]; // To have the same chirality, it is required // that the adjacent triangle have the directed // edge <curTriangle[i1],curTriangle[i0]> bool sameChirality = true; size_t j0, j1; for (j0 = 0; j0 < 3; ++j0) { j1 = (j0 + 1) % 3; if (adjTriangle[j0] == tv0) { if (adjTriangle[j1] == tv1) { // The adjacent triangle has the same // directed edge as the current // triangle, so the chiralities do // not match. sameChirality = false; } break; } } LogAssert(j0 < 3, "Unexpected condition"); if (!sameChirality) { // Swap the vertices of the adjacent triangle // that form the shared directed edge of the // current triangle. This requires that the // adjacency information for the other two // edges of the adjacent triangle be swapped. auto& adjAdjacent = adjacents[adjIndex]; size_t j2 = (j1 + 1) % 3; std::swap(adjTriangle[j0], adjTriangle[j1]); std::swap(adjAdjacent[j1], adjAdjacent[j2]); } // The adjacent triangle has been processed, but // it might have neighbors that need to be // processed. Push the adjacent triangle into the // queue to ensure this happens. Insert the // adjacent triangle into the active connected // component. triQueue.push(adjIndex); visited[adjIndex] = true; components.push_back(adjIndex); } } } } // Read the comments at the beginning of this function. size_t const numSizes = numComponentTriangles.size(); LogAssert(numSizes > 1, "Unexpected condition (this should not happen)."); for (size_t i0 = 0, i1 = 1; i1 < numComponentTriangles.size(); i0 = i1++) { numComponentTriangles[i0] = numComponentTriangles[i1] - numComponentTriangles[i0]; } numComponentTriangles.resize(numSizes - 1); } // This is a simple wrapper around CreateCompactGraph(...) and // GetComponentsConsistentChirality(...), in particular when you // do not need to work directly with the connected components. // The mesh is reconstructed, because the bookkeeping details of // trying to modify the mesh in-place are horrendous. NOTE: If // your mesh has more than 1 connected component, you should read // the comments for GetComponentsConsistentChirality(...) about // the potential for different chiralities between components. virtual void MakeConsistentChirality() { std::vector<std::array<size_t, 3>> triangles; std::vector<std::array<size_t, 3>> adjacents; CreateCompactGraph(triangles, adjacents); std::vector<size_t> components, numComponentTriangles; GetComponentsConsistentChirality(triangles, adjacents, components, numComponentTriangles); // Only the 'triangles' array is needed to reconstruct the // mesh. The other arrays are discarded. Clear(); for (auto const& triangle : triangles) { int32_t v0 = static_cast<int32_t>(triangle[0]); int32_t v1 = static_cast<int32_t>(triangle[1]); int32_t v2 = static_cast<int32_t>(triangle[2]); // The typecast avoids warnings about not storing the return // value in a named variable. The return value is discarded. (void)Insert(v0, v1, v2); } } // Compute the boundary-edge components of the mesh. These are // simple closed polygons. A vertex adjacency graph is computed // internally. A vertex with exactly 2 neighbors is the common // case that is easy to process. A vertex with 2n neighbors, where // n > 1, is a branch point of the graph. The algorithm computes // n pairs of edges at a branch point, each pair bounding a triangle // strip whose triangles all share the branch point. If you select // duplicateEndpoints to be false, a component has consecutive // vertices (v[0], v[1], ..., v[n-1]) and the polygon has edges // (v[0],v[1]), (v[1],v[2]), ..., (v[n-2],v[n-1]), (v[n-1],v[0]). // If duplicateEndpoints is set to true, a component has consecutive // vertices (v[0], v[1], ..., v[n-1], v[0]), emphasizing that the // component is closed. void GetBoundaryPolygons(std::vector<std::vector<int32_t>>& components, bool duplicateEndpoints) const { components.clear(); // Build the vertex adjacency graph. std::unordered_set<int32_t> boundaryVertices; std::multimap<int32_t, int32_t> vertexGraph; for (auto const& element : mEMap) { auto adj = element.second->T[1]; if (!adj) { int32_t v0 = element.first.V[0], v1 = element.first.V[1]; boundaryVertices.insert(v0); boundaryVertices.insert(v1); vertexGraph.insert(std::make_pair(v0, v1)); vertexGraph.insert(std::make_pair(v1, v0)); } } // Create a set of edge pairs. For a 2-adjacency vertex v with // adjacent vertices v0 and v1, an edge pair is (v, v0, v1) which // represents undirected edges (v, v0) and (v, v1). A vertex with // 2n-adjacency has n edge pairs of the form (v, v0, v1). Each // edge pair forms the boundary of a triangle strip where each // triangle shares v. When traversing a boundary curve for a // connected component of triangles, if a 2n-adjacency vertex v is // encountered, let v0 be the incoming vertex. The edge pair // containing v and v0 is selected to generate the outgoing // vertex v1. int32_t const invalidVertex = *boundaryVertices.begin() - 1; std::multimap<int32_t, std::array<int32_t, 2>> edgePairs; for (auto v : boundaryVertices) { // The number of adjacent vertices is positive and even. size_t numAdjacents = vertexGraph.count(v); if (numAdjacents == 2) { auto lbIter = vertexGraph.lower_bound(v); std::array<int32_t, 2> endpoints = { 0, 0 }; endpoints[0] = lbIter->second; ++lbIter; endpoints[1] = lbIter->second; edgePairs.insert(std::make_pair(v, endpoints)); } else { // Create pairs of vertices that form a wedge of triangles // at the vertex v, as a triangle strip of triangles all // sharing v. std::unordered_set<int32_t> adjacents; auto lbIter = vertexGraph.lower_bound(v); auto ubIter = vertexGraph.upper_bound(v); for (; lbIter != ubIter; ++lbIter) { adjacents.insert(lbIter->second); } size_t const numEdgePairs = adjacents.size() / 2; for (size_t j = 0; j < numEdgePairs; ++j) { // Get the first vertex of a pair of edges. auto adjIter = adjacents.begin(); int32_t vAdjacent = *adjIter; adjacents.erase(adjIter); // The wedge of triangles at v starts with a triangle // that has the boundary edge. EdgeKey<false> ekey(v, vAdjacent); auto edge = mEMap.find(ekey); LogAssert(edge != mEMap.end(), "unexpected condition"); auto tCurrent = edge->second->T[0]; LogAssert(tCurrent != nullptr, "unexpected condtion"); // Traverse the triangle strip to the other boundary // edge that bounds the wedge. int32_t vOpposite = invalidVertex; int32_t vStart = vAdjacent; for (;;) { size_t i; for (i = 0; i < 3; ++i) { vOpposite = tCurrent->V[i]; if (vOpposite != v && vOpposite != vAdjacent) { break; } } LogAssert(i < 3, "unexpected condition"); ekey = EdgeKey<false>(v, vOpposite); edge = mEMap.find(ekey); auto tNext = edge->second->T[1]; if (tNext == nullptr) { // Found the last triangle in the strip. break; } // The edge is interior to the component. Traverse // to the triangle adjacent to the current one. if (tNext == tCurrent) { tCurrent = edge->second->T[0]; } else { tCurrent = tNext; } vAdjacent = vOpposite; } // The boundary edge of the first triangle in the // wedge is (v, vAdjacent). The boundary edge of the // last triangle in the wedge is (v, vOpposite). std::array<int32_t, 2> endpoints{ vStart, vOpposite }; edgePairs.insert(std::make_pair(v, endpoints)); adjacents.erase(vOpposite); } } } while (edgePairs.size() > 0) { // The EdgeKey<false> represents an unordered edge (v0,v1). // Choose the starting vertex so that when you traverse from // it to the other vertex, the direction is consistent with // the chirality of the triangle containing that edge. For a // component whose triangles have the same chirality, this // approach ensures that the boundary polygon has the same // chirality as the triangles it bounds. If the component // triangles do not have the same chirality, it does not // matter what the starting vertex is. auto epIter = edgePairs.begin(); EdgeKey<false> boundaryEdge(epIter->first, epIter->second[0]); auto edge = mEMap.find(boundaryEdge); LogAssert(edge != mEMap.end(), "unexpected condtion"); auto currentTriangle = edge->second->T[0]; LogAssert(currentTriangle != nullptr, "unexpected condtion"); int32_t vStart = invalidVertex, vNext = invalidVertex; size_t i0, i1; for (i0 = 0; i0 < 3; ++i0) { if (currentTriangle->V[i0] == boundaryEdge.V[0]) { i1 = (i0 + 1) % 3; if (currentTriangle->V[i1] == boundaryEdge.V[1]) { vStart = boundaryEdge.V[0]; vNext = boundaryEdge.V[1]; } else { vStart = boundaryEdge.V[1]; vNext = boundaryEdge.V[0]; } break; } } LogAssert(i0 < 3, "unexpected condition"); // Find the the edge-pair for vStart that contains vNext and // remove it. auto lbIter = edgePairs.lower_bound(vStart); auto ubIter = edgePairs.upper_bound(vStart); bool foundStart = false; for (; lbIter != ubIter; ++lbIter) { if (lbIter->second[0] == vNext || lbIter->second[1] == vNext) { edgePairs.erase(lbIter); foundStart = true; break; } } LogAssert(foundStart, "unexpected condition"); // Compute the connected component of the boundary edges that // contains the edge <vStart, vNext>. std::vector<int32_t> component; component.push_back(vStart); int32_t vPrevious = vStart; while (vNext != vStart) { component.push_back(vNext); bool foundNext = false; lbIter = edgePairs.lower_bound(vNext); ubIter = edgePairs.upper_bound(vNext); for (epIter = lbIter; epIter != ubIter; ++epIter) { if (vPrevious == epIter->second[0]) { vPrevious = vNext; vNext = epIter->second[1]; edgePairs.erase(epIter); foundNext = true; break; } if (vPrevious == epIter->second[1]) { vPrevious = vNext; vNext = epIter->second[0]; edgePairs.erase(epIter); foundNext = true; break; } } LogAssert(foundNext, "unexpected condition"); } if (duplicateEndpoints) { // Explicitly duplicate the starting vertex to // emphasize that the component is a closed polyline. component.push_back(vStart); } components.push_back(component); } } protected: using TrianglePtrIntMap = std::unordered_map<Triangle*, int32_t>; using TrianglePtrSizeTMap = std::unordered_map<Triangle*, size_t>; // The edge data and default edge creation. static std::unique_ptr<Edge> CreateEdge(int32_t v0, int32_t v1) { return std::make_unique<Edge>(v0, v1); } ECreator mECreator; EMap mEMap; // The triangle data and default triangle creation. static std::unique_ptr<Triangle> CreateTriangle(int32_t v0, int32_t v1, int32_t v2) { return std::make_unique<Triangle>(v0, v1, v2); } TCreator mTCreator; TMap mTMap; bool mThrowOnNonmanifoldInsertion; // default: true // Support for computing connected components. This is a // straightforward depth-first search of the graph but uses a // preallocated stack rather than a recursive function that could // possibly overflow the call stack. void DepthFirstSearch( Triangle* tInitial, TrianglePtrIntMap& visited, std::vector<Triangle*>& component) const { // Allocate the maximum-size stack that can occur in the // depth-first search. The stack is empty when the index top // is -1. std::vector<Triangle*> tStack(mTMap.size()); int32_t top = -1; tStack[++top] = tInitial; while (top >= 0) { Triangle* tri = tStack[top]; visited[tri] = 1; int32_t i; for (i = 0; i < 3; ++i) { Triangle* adj = tri->T[i]; if (adj && visited[adj] == 0) { tStack[++top] = adj; break; } } if (i == 3) { visited[tri] = 2; component.push_back(tri); --top; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox3Cone3.h
.h
3,696
93
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Cone.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/IntrAlignedBox3Cone3.h> // Test for intersection of a box and a cone. The cone can be infinite // 0 <= minHeight < maxHeight = std::numeric_limits<Real>::max() // or finite (cone frustum) // 0 <= minHeight < maxHeight < std::numeric_limits<Real>::max(). // The algorithm is described in // https://www.geometrictools.com/Documentation/IntersectionBoxCone.pdf // and reports an intersection only when th intersection set has positive // volume. For example, let the box be outside the cone. If the box is // below the minHeight plane at the cone vertex and just touches the cone // vertex, no intersection is reported. If the box is above the maxHeight // plane and just touches the disk capping the cone, either at a single // point, a line segment of points or a polygon of points, no intersection // is reported. // TODO: These queries were designed when an infinite cone was defined // by choosing maxHeight of std::numeric_limits<Real>::max(). The Cone<N,Real> // class has been redesigned not to use std::numeric_limits to allow for // arithmetic systems that do not have representations for infinities // (such as BSNumber and BSRational). The intersection queries need to be // rewritten for the new class design. FOR NOW, the queries will work with // float/double when you create a cone using the cone-frustum constructor // Cone(ray, angle, minHeight, std::numeric_limits<Real>::max()). namespace gte { template <typename Real> class TIQuery<Real, OrientedBox3<Real>, Cone3<Real>> : public TIQuery<Real, AlignedBox3<Real>, Cone3<Real>> { public: struct Result : public TIQuery<Real, AlignedBox3<Real>, Cone3<Real>>::Result { Result() : TIQuery<Real, AlignedBox3<Real>, Cone3<Real>>::Result{} { } // No additional information to compute. }; Result operator()(OrientedBox3<Real> const& box, Cone3<Real> const& cone) { // Transform the cone and box so that the cone vertex is at the // origin and the box is axis aligned. This allows us to call the // base class operator()(...). Vector3<Real> diff = box.center - cone.ray.origin; Vector3<Real> xfrmBoxCenter { Dot(box.axis[0], diff), Dot(box.axis[1], diff), Dot(box.axis[2], diff) }; AlignedBox3<Real> xfrmBox{}; xfrmBox.min = xfrmBoxCenter - box.extent; xfrmBox.max = xfrmBoxCenter + box.extent; Cone3<Real> xfrmCone = cone; for (int32_t i = 0; i < 3; ++i) { xfrmCone.ray.origin[i] = (Real)0; xfrmCone.ray.direction[i] = Dot(box.axis[i], cone.ray.direction); } // Test for intersection between the aligned box and the cone. auto bcResult = TIQuery<Real, AlignedBox3<Real>, Cone3<Real>>::operator()(xfrmBox, xfrmCone); Result result{}; result.intersect = bcResult.intersect; return result; } }; // Template alias for convenience. template <typename Real> using TIOrientedBox3Cone3 = TIQuery<Real, OrientedBox3<Real>, Cone3<Real>>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SurfaceExtractorCubes.h
.h
36,510
1,044
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/SurfaceExtractor.h> // The level set extraction algorithm implemented here is described // in Section 3.2 of the document // https://www.geometrictools.com/Documentation/LevelSetExtraction.pdf namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class SurfaceExtractorCubes : public SurfaceExtractor<T, Real> { public: // Convenience type definitions. typedef typename SurfaceExtractor<T, Real>::Vertex Vertex; typedef typename SurfaceExtractor<T, Real>::Triangle Triangle; // The input is a 3D image with lexicographically ordered voxels // (x,y,z) stored in a linear array. Voxel (x,y,z) is stored in the // array at location index = x + xBound * (y + yBound * z). The // inputs xBound, yBound and zBound must each be 2 or larger so that // there is at least one image cube to process. The inputVoxels must // be nonnull and point to contiguous storage that contains at least // xBound * yBound * zBound elements. SurfaceExtractorCubes(int32_t xBound, int32_t yBound, int32_t zBound, T const* inputVoxels) : SurfaceExtractor<T, Real>(xBound, yBound, zBound, inputVoxels) { } // Extract level surfaces and return rational vertices. Use the // base-class Extract if you want real-valued vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) override { // Adjust the image so that the level set is F(x,y,z) = 0. The // precondition for 'level' is that it is not exactly a voxel // value. However, T is an integer type, so we cannot pass in // a 'level' that has a fractional value. To circumvent this, // the voxel values are doubled so that they are even integers. // The level value is doubled and 1 added to obtain an odd // integer, guaranteeing 'level' is not a voxel value. int64_t levelI64 = 2 * static_cast<int64_t>(level) + 1; for (size_t i = 0; i < this->mVoxels.size(); ++i) { int64_t inputI64 = 2 * static_cast<int64_t>(this->mInputVoxels[i]); this->mVoxels[i] = inputI64 - levelI64; } vertices.clear(); triangles.clear(); for (int32_t z = 0; z < this->mZBound - 1; ++z) { for (int32_t y = 0; y < this->mYBound - 1; ++y) { for (int32_t x = 0; x < this->mXBound - 1; ++x) { // Get vertices on edges of box (if any). VETable table; int32_t type = GetVertices(x, y, z, table); if (type != 0) { // Get edges on faces of box. GetXMinEdges(x, y, z, type, table); GetXMaxEdges(x, y, z, type, table); GetYMinEdges(x, y, z, type, table); GetYMaxEdges(x, y, z, type, table); GetZMinEdges(x, y, z, type, table); GetZMaxEdges(x, y, z, type, table); // Ear-clip the wireframe mesh. table.RemoveTriangles(vertices, triangles); } } } } } protected: enum { EI_XMIN_YMIN = 0, EI_XMIN_YMAX = 1, EI_XMAX_YMIN = 2, EI_XMAX_YMAX = 3, EI_XMIN_ZMIN = 4, EI_XMIN_ZMAX = 5, EI_XMAX_ZMIN = 6, EI_XMAX_ZMAX = 7, EI_YMIN_ZMIN = 8, EI_YMIN_ZMAX = 9, EI_YMAX_ZMIN = 10, EI_YMAX_ZMAX = 11, FI_XMIN = 12, FI_XMAX = 13, FI_YMIN = 14, FI_YMAX = 15, FI_ZMIN = 16, FI_ZMAX = 17, EB_XMIN_YMIN = 1 << EI_XMIN_YMIN, EB_XMIN_YMAX = 1 << EI_XMIN_YMAX, EB_XMAX_YMIN = 1 << EI_XMAX_YMIN, EB_XMAX_YMAX = 1 << EI_XMAX_YMAX, EB_XMIN_ZMIN = 1 << EI_XMIN_ZMIN, EB_XMIN_ZMAX = 1 << EI_XMIN_ZMAX, EB_XMAX_ZMIN = 1 << EI_XMAX_ZMIN, EB_XMAX_ZMAX = 1 << EI_XMAX_ZMAX, EB_YMIN_ZMIN = 1 << EI_YMIN_ZMIN, EB_YMIN_ZMAX = 1 << EI_YMIN_ZMAX, EB_YMAX_ZMIN = 1 << EI_YMAX_ZMIN, EB_YMAX_ZMAX = 1 << EI_YMAX_ZMAX, FB_XMIN = 1 << FI_XMIN, FB_XMAX = 1 << FI_XMAX, FB_YMIN = 1 << FI_YMIN, FB_YMAX = 1 << FI_YMAX, FB_ZMIN = 1 << FI_ZMIN, FB_ZMAX = 1 << FI_ZMAX }; // Vertex-edge-triangle table to support mesh topology. class VETable { public: VETable() : mVertex{} { } inline bool IsValidVertex(int32_t i) const { return mVertex[i].valid; } inline int64_t GetXN(int32_t i) const { return mVertex[i].pos.xNumer; } inline int64_t GetXD(int32_t i) const { return mVertex[i].pos.xDenom; } inline int64_t GetYN(int32_t i) const { return mVertex[i].pos.yNumer; } inline int64_t GetYD(int32_t i) const { return mVertex[i].pos.yDenom; } inline int64_t GetZN(int32_t i) const { return mVertex[i].pos.zNumer; } inline int64_t GetZD(int32_t i) const { return mVertex[i].pos.zDenom; } void Insert(int32_t i, Vertex const& pos) { TVertex& vertex = mVertex[i]; vertex.pos = pos; vertex.valid = true; } void Insert(int32_t i0, int32_t i1) { TVertex& vertex0 = mVertex[i0]; TVertex& vertex1 = mVertex[i1]; vertex0.adj[vertex0.numAdjacents++] = i1; vertex1.adj[vertex1.numAdjacents++] = i0; } void RemoveTriangles(std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) { // Ear-clip the wireframe to get the triangles. Triangle triangle; while (Remove(triangle)) { int32_t v0 = static_cast<int32_t>(vertices.size()); int32_t v1 = v0 + 1; int32_t v2 = v1 + 1; triangles.push_back(Triangle(v0, v1, v2)); vertices.push_back(mVertex[triangle.v[0]].pos); vertices.push_back(mVertex[triangle.v[1]].pos); vertices.push_back(mVertex[triangle.v[2]].pos); } } protected: void RemoveVertex(int32_t i) { TVertex& vertex0 = mVertex[i]; // assert: vertex0.numAdjacents == 2 int32_t a0 = vertex0.adj[0]; int32_t a1 = vertex0.adj[1]; TVertex& adjVertex0 = mVertex[a0]; TVertex& adjVertex1 = mVertex[a1]; int32_t j; for (j = 0; j < adjVertex0.numAdjacents; ++j) { if (adjVertex0.adj[j] == i) { adjVertex0.adj[j] = a1; break; } } // assert: j != adjVertex0.numAdjacents for (j = 0; j < adjVertex1.numAdjacents; j++) { if (adjVertex1.adj[j] == i) { adjVertex1.adj[j] = a0; break; } } // assert: j != adjVertex1.numAdjacents vertex0.valid = false; if (adjVertex0.numAdjacents == 2) { if (adjVertex0.adj[0] == adjVertex0.adj[1]) { adjVertex0.valid = false; } } if (adjVertex1.numAdjacents == 2) { if (adjVertex1.adj[0] == adjVertex1.adj[1]) { adjVertex1.valid = false; } } } bool Remove(Triangle& triangle) { for (int32_t i = 0; i < 18; ++i) { TVertex& vertex = mVertex[i]; if (vertex.valid && vertex.numAdjacents == 2) { triangle.v[0] = i; triangle.v[1] = vertex.adj[0]; triangle.v[2] = vertex.adj[1]; RemoveVertex(i); return true; } } return false; } class TVertex { public: TVertex() : pos{}, numAdjacents(0), adj{ 0, 0, 0, 0 }, valid(false) { } Vertex pos; int32_t numAdjacents; std::array<int32_t, 4> adj; bool valid; }; std::array<TVertex, 18> mVertex; }; virtual std::array<Real, 3> GetGradient(std::array<Real, 3> const& pos) override { std::array<Real, 3> const zero{ (Real)0, (Real)0, (Real)0 }; int32_t x = static_cast<int32_t>(pos[0]); if (x < 0 || x + 1 >= this->mXBound) { return zero; } int32_t y = static_cast<int32_t>(pos[1]); if (y < 0 || y + 1 >= this->mYBound) { return zero; } int32_t z = static_cast<int32_t>(pos[2]); if (z < 0 || z + 1 >= this->mZBound) { return zero; } // Get image values at corners of voxel. int32_t i000 = x + this->mXBound * (y + this->mYBound * z); int32_t i100 = i000 + 1; int32_t i010 = i000 + this->mXBound; int32_t i110 = i010 + 1; int32_t i001 = i000 + this->mXYBound; int32_t i101 = i001 + 1; int32_t i011 = i001 + this->mXBound; int32_t i111 = i011 + 1; Real f000 = static_cast<Real>(this->mVoxels[i000]); Real f100 = static_cast<Real>(this->mVoxels[i100]); Real f010 = static_cast<Real>(this->mVoxels[i010]); Real f110 = static_cast<Real>(this->mVoxels[i110]); Real f001 = static_cast<Real>(this->mVoxels[i001]); Real f101 = static_cast<Real>(this->mVoxels[i101]); Real f011 = static_cast<Real>(this->mVoxels[i011]); Real f111 = static_cast<Real>(this->mVoxels[i111]); Real const one = static_cast<Real>(1); Real dx = pos[0] - static_cast<Real>(x); Real dy = pos[1] - static_cast<Real>(y); Real dz = pos[2] - static_cast<Real>(z); Real oneMX = one - dx; Real oneMY = one - dy; Real oneMZ = one - dz; std::array<Real, 3> grad; Real tmp0 = oneMY * (f100 - f000) + dy * (f110 - f010); Real tmp1 = oneMY * (f101 - f001) + dy * (f111 - f011); grad[0] = oneMZ * tmp0 + dz * tmp1; tmp0 = oneMX * (f010 - f000) + dx * (f110 - f100); tmp1 = oneMX * (f011 - f001) + dx * (f111 - f101); grad[1] = oneMZ * tmp0 + dz * tmp1; tmp0 = oneMX * (f001 - f000) + dx * (f101 - f100); tmp1 = oneMX * (f011 - f010) + dx * (f111 - f110); grad[2] = oneMY * tmp0 + dy * tmp1; return grad; } int32_t GetVertices(int32_t x, int32_t y, int32_t z, VETable& table) { int32_t type = 0; // Get the image values at the corners of the voxel. int32_t i000 = x + this->mXBound * (y + this->mYBound * z); int32_t i100 = i000 + 1; int32_t i010 = i000 + this->mXBound; int32_t i110 = i010 + 1; int32_t i001 = i000 + this->mXYBound; int32_t i101 = i001 + 1; int32_t i011 = i001 + this->mXBound; int32_t i111 = i011 + 1; int64_t f000 = this->mVoxels[i000]; int64_t f100 = this->mVoxels[i100]; int64_t f010 = this->mVoxels[i010]; int64_t f110 = this->mVoxels[i110]; int64_t f001 = this->mVoxels[i001]; int64_t f101 = this->mVoxels[i101]; int64_t f011 = this->mVoxels[i011]; int64_t f111 = this->mVoxels[i111]; int64_t x0 = x; int64_t x1 = x0 + 1; int64_t y0 = y; int64_t y1 = y0 + 1; int64_t z0 = z; int64_t z1 = z0 + 1; int64_t d = 0; // xmin-ymin edge if (f000 * f001 < 0) { type |= EB_XMIN_YMIN; d = f001 - f000; table.Insert(EI_XMIN_YMIN, Vertex(x0, 1, y0, 1, z0 * d - f000, d)); } // xmin-ymax edge if (f010 * f011 < 0) { type |= EB_XMIN_YMAX; d = f011 - f010; table.Insert(EI_XMIN_YMAX, Vertex(x0, 1, y1, 1, z0 * d - f010, d)); } // xmax-ymin edge if (f100 * f101 < 0) { type |= EB_XMAX_YMIN; d = f101 - f100; table.Insert(EI_XMAX_YMIN, Vertex(x1, 1, y0, 1, z0 * d - f100, d)); } // xmax-ymax edge if (f110 * f111 < 0) { type |= EB_XMAX_YMAX; d = f111 - f110; table.Insert(EI_XMAX_YMAX, Vertex(x1, 1, y1, 1, z0 * d - f110, d)); } // xmin-zmin edge if (f000 * f010 < 0) { type |= EB_XMIN_ZMIN; d = f010 - f000; table.Insert(EI_XMIN_ZMIN, Vertex(x0, 1, y0 * d - f000, d, z0, 1)); } // xmin-zmax edge if (f001 * f011 < 0) { type |= EB_XMIN_ZMAX; d = f011 - f001; table.Insert(EI_XMIN_ZMAX, Vertex(x0, 1, y0 * d - f001, d, z1, 1)); } // xmax-zmin edge if (f100 * f110 < 0) { type |= EB_XMAX_ZMIN; d = f110 - f100; table.Insert(EI_XMAX_ZMIN, Vertex(x1, 1, y0 * d - f100, d, z0, 1)); } // xmax-zmax edge if (f101 * f111 < 0) { type |= EB_XMAX_ZMAX; d = f111 - f101; table.Insert(EI_XMAX_ZMAX, Vertex(x1, 1, y0 * d - f101, d, z1, 1)); } // ymin-zmin edge if (f000 * f100 < 0) { type |= EB_YMIN_ZMIN; d = f100 - f000; table.Insert(EI_YMIN_ZMIN, Vertex(x0 * d - f000, d, y0, 1, z0, 1)); } // ymin-zmax edge if (f001 * f101 < 0) { type |= EB_YMIN_ZMAX; d = f101 - f001; table.Insert(EI_YMIN_ZMAX, Vertex(x0 * d - f001, d, y0, 1, z1, 1)); } // ymax-zmin edge if (f010 * f110 < 0) { type |= EB_YMAX_ZMIN; d = f110 - f010; table.Insert(EI_YMAX_ZMIN, Vertex(x0 * d - f010, d, y1, 1, z0, 1)); } // ymax-zmax edge if (f011 * f111 < 0) { type |= EB_YMAX_ZMAX; d = f111 - f011; table.Insert(EI_YMAX_ZMAX, Vertex(x0 * d - f011, d, y1, 1, z1, 1)); } return type; } void GetXMinEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMIN_YMAX) { faceType |= 0x02; } if (type & EB_XMIN_ZMIN) { faceType |= 0x04; } if (type & EB_XMIN_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMIN_YMIN, EI_XMIN_YMAX); break; case 5: table.Insert(EI_XMIN_YMIN, EI_XMIN_ZMIN); break; case 6: table.Insert(EI_XMIN_YMAX, EI_XMIN_ZMIN); break; case 9: table.Insert(EI_XMIN_YMIN, EI_XMIN_ZMAX); break; case 10: table.Insert(EI_XMIN_YMAX, EI_XMIN_ZMAX); break; case 12: table.Insert(EI_XMIN_ZMIN, EI_XMIN_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = x + this->mXBound * (y + this->mYBound * z); // F(x,y,z) int64_t f00 = this->mVoxels[i]; i += this->mXBound; // F(x,y+1,z) int64_t f10 = this->mVoxels[i]; i += this->mXYBound; // F(x,y+1,z+1) int64_t f11 = this->mVoxels[i]; i -= this->mXBound; // F(x,y,z+1) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMIN_YMIN, EI_XMIN_ZMIN); table.Insert(EI_XMIN_YMAX, EI_XMIN_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMIN_YMIN, EI_XMIN_ZMAX); table.Insert(EI_XMIN_YMAX, EI_XMIN_ZMIN); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_XMIN, Vertex( table.GetXN(EI_XMIN_ZMIN), table.GetXD(EI_XMIN_ZMIN), table.GetYN(EI_XMIN_ZMIN), table.GetYD(EI_XMIN_ZMIN), table.GetZN(EI_XMIN_YMIN), table.GetZD(EI_XMIN_YMIN))); // Add edges sharing the branch point. table.Insert(EI_XMIN_YMIN, FI_XMIN); table.Insert(EI_XMIN_YMAX, FI_XMIN); table.Insert(EI_XMIN_ZMIN, FI_XMIN); table.Insert(EI_XMIN_ZMAX, FI_XMIN); } break; } default: LogError("Unexpected condition."); } } void GetXMaxEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMAX_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_XMAX_ZMIN) { faceType |= 0x04; } if (type & EB_XMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMAX_YMIN, EI_XMAX_YMAX); break; case 5: table.Insert(EI_XMAX_YMIN, EI_XMAX_ZMIN); break; case 6: table.Insert(EI_XMAX_YMAX, EI_XMAX_ZMIN); break; case 9: table.Insert(EI_XMAX_YMIN, EI_XMAX_ZMAX); break; case 10: table.Insert(EI_XMAX_YMAX, EI_XMAX_ZMAX); break; case 12: table.Insert(EI_XMAX_ZMIN, EI_XMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = (x + 1) + this->mXBound * (y + this->mYBound * z); // F(x,y,z) int64_t f00 = this->mVoxels[i]; i += this->mXBound; // F(x,y+1,z) int64_t f10 = this->mVoxels[i]; i += this->mXYBound; // F(x,y+1,z+1) int64_t f11 = this->mVoxels[i]; i -= this->mXBound; // F(x,y,z+1) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMAX_YMIN, EI_XMAX_ZMIN); table.Insert(EI_XMAX_YMAX, EI_XMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMAX_YMIN, EI_XMAX_ZMAX); table.Insert(EI_XMAX_YMAX, EI_XMAX_ZMIN); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_XMAX, Vertex( table.GetXN(EI_XMAX_ZMIN), table.GetXD(EI_XMAX_ZMIN), table.GetYN(EI_XMAX_ZMIN), table.GetYD(EI_XMAX_ZMIN), table.GetZN(EI_XMAX_YMIN), table.GetZD(EI_XMAX_YMIN))); // Add edges sharing the branch point. table.Insert(EI_XMAX_YMIN, FI_XMAX); table.Insert(EI_XMAX_YMAX, FI_XMAX); table.Insert(EI_XMAX_ZMIN, FI_XMAX); table.Insert(EI_XMAX_ZMAX, FI_XMAX); } break; } default: LogError("Unexpected condition."); } } void GetYMinEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMIN_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMIN_YMIN, EI_XMAX_YMIN); break; case 5: table.Insert(EI_XMIN_YMIN, EI_YMIN_ZMIN); break; case 6: table.Insert(EI_XMAX_YMIN, EI_YMIN_ZMIN); break; case 9: table.Insert(EI_XMIN_YMIN, EI_YMIN_ZMAX); break; case 10: table.Insert(EI_XMAX_YMIN, EI_YMIN_ZMAX); break; case 12: table.Insert(EI_YMIN_ZMIN, EI_YMIN_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = x + this->mXBound * (y + this->mYBound * z); // F(x,y,z) int64_t f00 = this->mVoxels[i]; ++i; // F(x+1,y,z) int64_t f10 = this->mVoxels[i]; i += this->mXYBound; // F(x+1,y,z+1) int64_t f11 = this->mVoxels[i]; --i; // F(x,y,z+1) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMIN_YMIN, EI_YMIN_ZMIN); table.Insert(EI_XMAX_YMIN, EI_YMIN_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMIN_YMIN, EI_YMIN_ZMAX); table.Insert(EI_XMAX_YMIN, EI_YMIN_ZMIN); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_YMIN, Vertex( table.GetXN(EI_YMIN_ZMIN), table.GetXD(EI_YMIN_ZMIN), table.GetYN(EI_XMIN_YMIN), table.GetYD(EI_XMIN_YMIN), table.GetZN(EI_XMIN_YMIN), table.GetZD(EI_XMIN_YMIN))); // Add edges sharing the branch point. table.Insert(EI_XMIN_YMIN, FI_YMIN); table.Insert(EI_XMAX_YMIN, FI_YMIN); table.Insert(EI_YMIN_ZMIN, FI_YMIN); table.Insert(EI_YMIN_ZMAX, FI_YMIN); } break; } default: LogError("Unexpected condition."); } } void GetYMaxEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMIN_YMAX) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_YMAX_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMIN_YMAX, EI_XMAX_YMAX); break; case 5: table.Insert(EI_XMIN_YMAX, EI_YMAX_ZMIN); break; case 6: table.Insert(EI_XMAX_YMAX, EI_YMAX_ZMIN); break; case 9: table.Insert(EI_XMIN_YMAX, EI_YMAX_ZMAX); break; case 10: table.Insert(EI_XMAX_YMAX, EI_YMAX_ZMAX); break; case 12: table.Insert(EI_YMAX_ZMIN, EI_YMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = x + this->mXBound * ((y + 1) + this->mYBound * z); // F(x,y,z) int64_t f00 = this->mVoxels[i]; ++i; // F(x+1,y,z) int64_t f10 = this->mVoxels[i]; i += this->mXYBound; // F(x+1,y,z+1) int64_t f11 = this->mVoxels[i]; --i; // F(x,y,z+1) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMIN_YMAX, EI_YMAX_ZMIN); table.Insert(EI_XMAX_YMAX, EI_YMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMIN_YMAX, EI_YMAX_ZMAX); table.Insert(EI_XMAX_YMAX, EI_YMAX_ZMIN); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_YMAX, Vertex( table.GetXN(EI_YMAX_ZMIN), table.GetXD(EI_YMAX_ZMIN), table.GetYN(EI_XMIN_YMAX), table.GetYD(EI_XMIN_YMAX), table.GetZN(EI_XMIN_YMAX), table.GetZD(EI_XMIN_YMAX))); // Add edges sharing the branch point. table.Insert(EI_XMIN_YMAX, FI_YMAX); table.Insert(EI_XMAX_YMAX, FI_YMAX); table.Insert(EI_YMAX_ZMIN, FI_YMAX); table.Insert(EI_YMAX_ZMAX, FI_YMAX); } break; } default: LogError("Unexpected condition."); } } void GetZMinEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMIN_ZMIN) { faceType |= 0x01; } if (type & EB_XMAX_ZMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMIN) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMIN_ZMIN, EI_XMAX_ZMIN); break; case 5: table.Insert(EI_XMIN_ZMIN, EI_YMIN_ZMIN); break; case 6: table.Insert(EI_XMAX_ZMIN, EI_YMIN_ZMIN); break; case 9: table.Insert(EI_XMIN_ZMIN, EI_YMAX_ZMIN); break; case 10: table.Insert(EI_XMAX_ZMIN, EI_YMAX_ZMIN); break; case 12: table.Insert(EI_YMIN_ZMIN, EI_YMAX_ZMIN); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = x + this->mXBound * (y + this->mYBound * z); // F(x,y,z) int64_t f00 = this->mVoxels[i]; ++i; // F(x+1,y,z) int64_t f10 = this->mVoxels[i]; i += this->mXBound; // F(x+1,y+1,z) int64_t f11 = this->mVoxels[i]; --i; // F(x,y+1,z) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMIN_ZMIN, EI_YMIN_ZMIN); table.Insert(EI_XMAX_ZMIN, EI_YMAX_ZMIN); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMIN_ZMIN, EI_YMAX_ZMIN); table.Insert(EI_XMAX_ZMIN, EI_YMIN_ZMIN); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_ZMIN, Vertex( table.GetXN(EI_YMIN_ZMIN), table.GetXD(EI_YMIN_ZMIN), table.GetYN(EI_XMIN_ZMIN), table.GetYD(EI_XMIN_ZMIN), table.GetZN(EI_XMIN_ZMIN), table.GetZD(EI_XMIN_ZMIN))); // Add edges sharing the branch point. table.Insert(EI_XMIN_ZMIN, FI_ZMIN); table.Insert(EI_XMAX_ZMIN, FI_ZMIN); table.Insert(EI_YMIN_ZMIN, FI_ZMIN); table.Insert(EI_YMAX_ZMIN, FI_ZMIN); } break; } default: LogError("Unexpected condition."); } } void GetZMaxEdges(int32_t x, int32_t y, int32_t z, int32_t type, VETable& table) { int32_t faceType = 0; if (type & EB_XMIN_ZMAX) { faceType |= 0x01; } if (type & EB_XMAX_ZMAX) { faceType |= 0x02; } if (type & EB_YMIN_ZMAX) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: break; case 3: table.Insert(EI_XMIN_ZMAX, EI_XMAX_ZMAX); break; case 5: table.Insert(EI_XMIN_ZMAX, EI_YMIN_ZMAX); break; case 6: table.Insert(EI_XMAX_ZMAX, EI_YMIN_ZMAX); break; case 9: table.Insert(EI_XMIN_ZMAX, EI_YMAX_ZMAX); break; case 10: table.Insert(EI_XMAX_ZMAX, EI_YMAX_ZMAX); break; case 12: table.Insert(EI_YMIN_ZMAX, EI_YMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = x + this->mXBound * (y + this->mYBound * (z + 1)); // F(x,y,z) int64_t f00 = this->mVoxels[i]; ++i; // F(x+1,y,z) int64_t f10 = this->mVoxels[i]; i += this->mXBound; // F(x+1,y+1,z) int64_t f11 = this->mVoxels[i]; --i; // F(x,y+1,z) int64_t f01 = this->mVoxels[i]; int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.Insert(EI_XMIN_ZMAX, EI_YMIN_ZMAX); table.Insert(EI_XMAX_ZMAX, EI_YMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.Insert(EI_XMIN_ZMAX, EI_YMAX_ZMAX); table.Insert(EI_XMAX_ZMAX, EI_YMIN_ZMAX); } else { // Plus-sign configuration, add branch point to tessellation. table.Insert(FI_ZMAX, Vertex( table.GetXN(EI_YMIN_ZMAX), table.GetXD(EI_YMIN_ZMAX), table.GetYN(EI_XMIN_ZMAX), table.GetYD(EI_XMIN_ZMAX), table.GetZN(EI_XMIN_ZMAX), table.GetZD(EI_XMIN_ZMAX))); // Add edges sharing the branch point. table.Insert(EI_XMIN_ZMAX, FI_ZMAX); table.Insert(EI_XMAX_ZMAX, FI_ZMAX); table.Insert(EI_YMIN_ZMAX, FI_ZMAX); table.Insert(EI_YMAX_ZMAX, FI_ZMAX); } break; } default: LogError("Unexpected condition."); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprCircle2.h
.h
6,198
159
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector2.h> #include <cstdint> // Least-squares fit of a circle to a set of points. The algorithms are // described in Section 5 of // https://www.geometrictools.com/Documentation/LeastSquaresFitting.pdf // FitUsingLengths uses the algorithm of Section 5.1. // FitUsingSquaredLengths uses the algorithm of Section 5.2. namespace gte { template <typename Real> class ApprCircle2 { public: // The return value is 'true' when the linear system of the algorithm // is solvable, 'false' otherwise. If 'false' is returned, the circle // center and radius are set to zero values. bool FitUsingSquaredLengths(int32_t numPoints, Vector2<Real> const* points, Circle2<Real>& circle) { // Compute the average of the data points. Real const zero(0); Vector2<Real> A = { zero, zero }; for (int32_t i = 0; i < numPoints; ++i) { A += points[i]; } Real invNumPoints = ((Real)1) / static_cast<Real>(numPoints); A *= invNumPoints; // Compute the covariance matrix M of the Y[i] = X[i]-A and the // right-hand side R of the linear system M*(C-A) = R. Real M00 = zero, M01 = zero, M11 = zero; Vector2<Real> R = { zero, zero }; for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> Y = points[i] - A; Real Y0Y0 = Y[0] * Y[0]; Real Y0Y1 = Y[0] * Y[1]; Real Y1Y1 = Y[1] * Y[1]; M00 += Y0Y0; M01 += Y0Y1; M11 += Y1Y1; R += (Y0Y0 + Y1Y1) * Y; } R *= (Real)0.5; // Solve the linear system M*(C-A) = R for the center C. Real det = M00 * M11 - M01 * M01; if (det != zero) { circle.center[0] = A[0] + (M11 * R[0] - M01 * R[1]) / det; circle.center[1] = A[1] + (M00 * R[1] - M01 * R[0]) / det; Real rsqr = zero; for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> delta = points[i] - circle.center; rsqr += Dot(delta, delta); } rsqr *= invNumPoints; circle.radius = std::sqrt(rsqr); return true; } else { circle.center = { zero, zero }; circle.radius = zero; return false; } } // Fit the points using lengths to drive the least-squares algorithm. // If initialCenterIsAverage is set to 'false', the initial guess for // the initial circle center is computed as the average of the data // points. If the data points are clustered along a small arc, the // algorithm is slow to converge. If initialCenterIsAverage is set to // 'true', the incoming circle center is used as-is to start the // iterative algorithm. This approach tends to converge more rapidly // than when using the average of points but can be much slower than // FitUsingSquaredLengths. // // The value epsilon may be chosen as a positive number for the // comparison of consecutive estimated circle centers, terminating the // iterations when the center difference has length less than or equal // to epsilon. // // The return value is the number of iterations used. If is is the // input maxIterations, you can either accept the result or polish the // result by calling the function again with initialCenterIsAverage // set to 'true'. uint32_t FitUsingLengths(int32_t numPoints, Vector2<Real> const* points, uint32_t maxIterations, bool initialCenterIsAverage, Circle2<Real>& circle, Real epsilon = (Real)0) { // Compute the average of the data points. Vector2<Real> average = points[0]; for (int32_t i = 1; i < numPoints; ++i) { average += points[i]; } Real invNumPoints = ((Real)1) / static_cast<Real>(numPoints); average *= invNumPoints; // The initial guess for the center. if (initialCenterIsAverage) { circle.center = average; } Real epsilonSqr = epsilon * epsilon; uint32_t iteration; for (iteration = 0; iteration < maxIterations; ++iteration) { // Update the iterates. Vector2<Real> current = circle.center; // Compute average L, dL/da, dL/db. Real lenAverage = (Real)0; Vector2<Real> derLenAverage = Vector2<Real>::Zero(); for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> diff = points[i] - circle.center; Real length = Length(diff); if (length > (Real)0) { lenAverage += length; Real invLength = ((Real)1) / length; derLenAverage -= invLength * diff; } } lenAverage *= invNumPoints; derLenAverage *= invNumPoints; circle.center = average + lenAverage * derLenAverage; circle.radius = lenAverage; Vector2<Real> diff = circle.center - current; Real diffSqrLen = Dot(diff, diff); if (diffSqrLen <= epsilonSqr) { break; } } return ++iteration; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RevolutionMesh.h
.h
12,236
318
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Mesh.h> #include <Mathematics/ParametricCurve.h> #include <memory> namespace gte { template <typename Real> class RevolutionMesh : public Mesh<Real> { public: // The axis of revolution is the z-axis. The curve of revolution is // p(t) = (x(t),z(t)), where t in [tmin,tmax], x(t) > 0 for t in // (tmin,tmax), x(tmin) >= 0, and x(tmax) >= 0. The values tmin and // tmax are those for the curve object passed to the constructor. The // curve must be non-self-intersecting, except possibly at its // endpoints. The curve is closed when p(tmin) = p(tmax), in which // case the surface of revolution has torus topology. The curve is // open when p(tmin) != p(tmax). For an open curve, define // x0 = x(tmin) and x1 = x(tmax). The surface has cylinder topology // when x0 > 0 and x1 > 0, disk topology when exactly one of x0 or x1 // is zero, or sphere topology when x0 and x1 are both zero. However, // to simplify the design, the mesh is always built using cylinder // topology. The row samples correspond to curve points and the // column samples correspond to the points on the circles of // revolution. RevolutionMesh(MeshDescription const& description, std::shared_ptr<ParametricCurve<2, Real>> const& curve, bool sampleByArcLength = false) : Mesh<Real>(description, { MeshTopology::CYLINDER, MeshTopology::TORUS, MeshTopology::DISK, MeshTopology::SPHERE }), mCurve(curve), mSampleByArcLength(sampleByArcLength) { if (!this->mDescription.constructed) { // The logger system will report these errors in the Mesh // constructor. mCurve = nullptr; return; } LogAssert(mCurve != nullptr, "A nonnull revolution curve is required."); // The four supported topologies all wrap around in the column // direction. mCosAngle.resize(static_cast<size_t>(this->mDescription.numCols) + 1); mSinAngle.resize(static_cast<size_t>(this->mDescription.numCols) + 1); Real invRadialSamples = (Real)1 / (Real)this->mDescription.numCols; for (uint32_t c = 0; c < this->mDescription.numCols; ++c) { Real angle = c * invRadialSamples * (Real)GTE_C_TWO_PI; mCosAngle[c] = std::cos(angle); mSinAngle[c] = std::sin(angle); } mCosAngle[this->mDescription.numCols] = mCosAngle[0]; mSinAngle[this->mDescription.numCols] = mSinAngle[0]; CreateSampler(); if (!this->mTCoords) { mDefaultTCoords.resize(this->mDescription.numVertices); this->mTCoords = mDefaultTCoords.data(); this->mTCoordStride = sizeof(Vector2<Real>); this->mDescription.allowUpdateFrame = this->mDescription.wantDynamicTangentSpaceUpdate; if (this->mDescription.allowUpdateFrame) { if (!this->mDescription.hasTangentSpaceVectors) { this->mDescription.allowUpdateFrame = false; } if (!this->mNormals) { this->mDescription.allowUpdateFrame = false; } } } this->ComputeIndices(); InitializeTCoords(); UpdatePositions(); if (this->mDescription.allowUpdateFrame) { this->UpdateFrame(); } else if (this->mNormals) { this->UpdateNormals(); } } // Member access. inline std::shared_ptr<ParametricCurve<2, Real>> const& GetCurve() const { return mCurve; } inline bool IsSampleByArcLength() const { return mSampleByArcLength; } private: void CreateSampler() { if (this->mDescription.topology == MeshTopology::CYLINDER || this->mDescription.topology == MeshTopology::TORUS) { mSamples.resize(static_cast<size_t>(this->mDescription.rMax) + 1); } else if (this->mDescription.topology == MeshTopology::DISK) { mSamples.resize(static_cast<size_t>(this->mDescription.rMax) + 2); } else if (this->mDescription.topology == MeshTopology::SPHERE) { mSamples.resize(static_cast<size_t>(this->mDescription.rMax) + 3); } Real invDenom = (Real)1 / ((Real)mSamples.size() - (Real)1); if (mSampleByArcLength) { Real factor = mCurve->GetTotalLength() * invDenom; mTSampler = [this, factor](uint32_t i) { return mCurve->GetTime(i * factor); }; } else { Real factor = (mCurve->GetTMax() - mCurve->GetTMin()) * invDenom; mTSampler = [this, factor](uint32_t i) { return mCurve->GetTMin() + i * factor; }; } } void InitializeTCoords() { Vector2<Real>tcoord; switch (this->mDescription.topology) { case MeshTopology::CYLINDER: { for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { tcoord[1] = (Real)r / (Real)(this->mDescription.numRows - 1); for (uint32_t c = 0; c <= this->mDescription.numCols; ++c, ++i) { tcoord[0] = (Real)c / (Real)this->mDescription.numCols; this->TCoord(i) = tcoord; } } break; } case MeshTopology::TORUS: { for (uint32_t r = 0, i = 0; r <= this->mDescription.numRows; ++r) { tcoord[1] = (Real)r / (Real)this->mDescription.numRows; for (uint32_t c = 0; c <= this->mDescription.numCols; ++c, ++i) { tcoord[0] = (Real)c / (Real)this->mDescription.numCols; this->TCoord(i) = tcoord; } } break; } case MeshTopology::DISK: { Vector2<Real> origin{ (Real)0.5, (Real)0.5 }; uint32_t i = 0; for (uint32_t r = 0; r < this->mDescription.numRows; ++r) { Real radius = ((Real)r + (Real)1) / ((Real)2 * (Real)this->mDescription.numRows); radius = std::min(radius, (Real)0.5); for (uint32_t c = 0; c <= this->mDescription.numCols; ++c, ++i) { Real angle = (Real)GTE_C_TWO_PI * (Real)c / (Real)this->mDescription.numCols; this->TCoord(i) = { radius * std::cos(angle), radius * std::sin(angle) }; } } this->TCoord(i) = origin; break; } case MeshTopology::SPHERE: { uint32_t i = 0; for (uint32_t r = 0; r < this->mDescription.numRows; ++r) { tcoord[1] = (Real)r / (Real)(this->mDescription.numRows - 1); for (uint32_t c = 0; c <= this->mDescription.numCols; ++c, ++i) { tcoord[0] = (Real)c / (Real)this->mDescription.numCols; this->TCoord(i) = tcoord; } } this->TCoord(i++) = { (Real)0.5, (Real)0 }; this->TCoord(i) = { (Real)0.5, (Real)1 }; break; } default: // Invalid topology is reported by the Mesh constructor, so there is // no need to log a message here. break; } } virtual void UpdatePositions() override { uint32_t const numSamples = static_cast<uint32_t>(mSamples.size()); for (uint32_t i = 0; i < numSamples; ++i) { Real t = mTSampler(i); Vector2<Real> position = mCurve->GetPosition(t); mSamples[i][0] = position[0]; mSamples[i][1] = (Real)0; mSamples[i][2] = position[1]; } switch (this->mDescription.topology) { case MeshTopology::CYLINDER: UpdateCylinderPositions(); break; case MeshTopology::TORUS: UpdateTorusPositions(); break; case MeshTopology::DISK: UpdateDiskPositions(); break; case MeshTopology::SPHERE: UpdateSpherePositions(); break; default: break; } } void UpdateCylinderPositions() { for (uint32_t r = 0, i = 0; r <= this->mDescription.rMax; ++r) { Real radius = mSamples[r][0]; for (uint32_t c = 0; c <= this->mDescription.cMax; ++c, ++i) { this->Position(i) = { radius * mCosAngle[c], radius * mSinAngle[c], mSamples[r][2] }; } } } void UpdateTorusPositions() { for (uint32_t r = 0, i = 0; r <= this->mDescription.rMax; ++r) { Real radius = mSamples[r][0]; for (uint32_t c = 0; c <= this->mDescription.cMax; ++c, ++i) { this->Position(i) = { radius * mCosAngle[c], radius * mSinAngle[c], mSamples[r][2] }; } } } void UpdateDiskPositions() { for (uint32_t r = 0, rp1 = 1, i = 0; r <= this->mDescription.rMax; ++r, ++rp1) { Real radius = mSamples[rp1][0]; for (uint32_t c = 0; c <= this->mDescription.cMax; ++c, ++i) { this->Position(i) = { radius * mCosAngle[c], radius * mSinAngle[c], mSamples[rp1][2] }; } } this->Position(this->mDescription.numVertices - 1) = { (Real)0, (Real)0, mSamples.front()[2] }; } void UpdateSpherePositions() { for (uint32_t r = 0, rp1 = 1, i = 0; r <= this->mDescription.rMax; ++r, ++rp1) { Real radius = mSamples[rp1][0]; for (uint32_t c = 0; c <= this->mDescription.cMax; ++c, ++i) { this->Position(i) = { radius * mCosAngle[c], radius * mSinAngle[c], mSamples[rp1][2] }; } } this->Position(this->mDescription.numVertices - 2) = { (Real)0, (Real)0, mSamples.front()[2] }; this->Position(this->mDescription.numVertices - 1) = { (Real)0, (Real)0, mSamples.back()[2] }; } std::shared_ptr<ParametricCurve<2, Real>> mCurve; bool mSampleByArcLength; std::vector<Real> mCosAngle, mSinAngle; std::function<Real(uint32_t)> mTSampler; std::vector<Vector3<Real>> mSamples; // If the client does not request texture coordinates, they will be // computed internally for use in evaluation of the surface geometry. std::vector<Vector2<Real>> mDefaultTCoords; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpAkimaUniform3.h
.h
58,870
1,419
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <Mathematics/Array3.h> #include <algorithm> #include <array> #include <cstring> // The interpolator is for uniformly spaced(x,y z)-values. The input samples // must be stored in lexicographical order to represent f(x,y,z); that is, // F[c + xBound*(r + yBound*s)] corresponds to f(x,y,z), where c is the index // corresponding to x, r is the index corresponding to y, and s is the index // corresponding to z. namespace gte { template <typename Real> class IntpAkimaUniform3 { public: // Construction and destruction. IntpAkimaUniform3(int32_t xBound, int32_t yBound, int32_t zBound, Real xMin, Real xSpacing, Real yMin, Real ySpacing, Real zMin, Real zSpacing, Real const* F) : mXBound(xBound), mYBound(yBound), mZBound(zBound), mQuantity(xBound* yBound* zBound), mXMin(xMin), mXSpacing(xSpacing), mYMin(yMin), mYSpacing(ySpacing), mZMin(zMin), mZSpacing(zSpacing), mF(F), mPoly(static_cast<size_t>(xBound) - 1, static_cast<size_t>(yBound) - 1, static_cast<size_t>(zBound) - 1) { // At least a 3x3x3 block of data points is needed to construct // the estimates of the boundary derivatives. LogAssert(mXBound >= 3 && mYBound >= 3 && mZBound >= 3 && mF != nullptr, "Invalid input."); LogAssert(mXSpacing > (Real)0 && mYSpacing > (Real)0 && mZSpacing > (Real)0, "Invalid input."); mXMax = mXMin + mXSpacing * static_cast<Real>(mXBound) - static_cast<Real>(1); mYMax = mYMin + mYSpacing * static_cast<Real>(mYBound) - static_cast<Real>(1); mZMax = mZMin + mZSpacing * static_cast<Real>(mZBound) - static_cast<Real>(1); // Create a 3D wrapper for the 1D samples. Array3<Real> Fmap(mXBound, mYBound, mZBound, const_cast<Real*>(mF)); // Construct first-order derivatives. Array3<Real> FX(mXBound, mYBound, mZBound); Array3<Real> FY(mXBound, mYBound, mZBound); Array3<Real> FZ(mXBound, mYBound, mZBound); GetFX(Fmap, FX); GetFX(Fmap, FY); GetFX(Fmap, FZ); // Construct second-order derivatives. Array3<Real> FXY(mXBound, mYBound, mZBound); Array3<Real> FXZ(mXBound, mYBound, mZBound); Array3<Real> FYZ(mXBound, mYBound, mZBound); GetFX(Fmap, FXY); GetFX(Fmap, FXZ); GetFX(Fmap, FYZ); // Construct third-order derivatives. Array3<Real> FXYZ(mXBound, mYBound, mZBound); GetFXYZ(Fmap, FXYZ); // Construct polynomials. GetPolynomials(Fmap, FX, FY, FZ, FXY, FXZ, FYZ, FXYZ); } ~IntpAkimaUniform3() = default; // Member access. inline int32_t GetXBound() const { return mXBound; } inline int32_t GetYBound() const { return mYBound; } inline int32_t GetZBound() const { return mZBound; } inline int32_t GetQuantity() const { return mQuantity; } inline Real const* GetF() const { return mF; } inline Real GetXMin() const { return mXMin; } inline Real GetXMax() const { return mXMax; } inline Real GetXSpacing() const { return mXSpacing; } inline Real GetYMin() const { return mYMin; } inline Real GetYMax() const { return mYMax; } inline Real GetYSpacing() const { return mYSpacing; } inline Real GetZMin() const { return mZMin; } inline Real GetZMax() const { return mZMax; } inline Real GetZSpacing() const { return mZSpacing; } // Evaluate the function and its derivatives. The functions clamp the // inputs to xmin <= x <= xmax, ymin <= y <= ymax and // zmin <= z <= zmax. The first operator is for function evaluation. // The second operator is for function or derivative evaluations. The // xOrder argument is the order of the x-derivative, the yOrder // argument is the order of the y-derivative, and the zOrder argument // is the order of the z-derivative. All orders are zero to get the // function value itself. Real operator()(Real x, Real y, Real z) const { x = std::min(std::max(x, mXMin), mXMax); y = std::min(std::max(y, mYMin), mYMax); z = std::min(std::max(z, mZMin), mZMax); int32_t ix, iy, iz; Real dx, dy, dz; XLookup(x, ix, dx); YLookup(y, iy, dy); ZLookup(z, iz, dz); return mPoly[iz][iy][ix](dx, dy, dz); } Real operator()(int32_t xOrder, int32_t yOrder, int32_t zOrder, Real x, Real y, Real z) const { x = std::min(std::max(x, mXMin), mXMax); y = std::min(std::max(y, mYMin), mYMax); z = std::min(std::max(z, mZMin), mZMax); int32_t ix, iy, iz; Real dx, dy, dz; XLookup(x, ix, dx); YLookup(y, iy, dy); ZLookup(z, iz, dz); return mPoly[iz][iy][ix](xOrder, yOrder, zOrder, dx, dy, dz); } private: class Polynomial { public: Polynomial() { for (size_t ix = 0; ix < 4; ++ix) { for (size_t iy = 0; iy < 4; ++iy) { mCoeff[ix][iy].fill((Real)0); } } } // P(x,y,z) = sum_{i=0}^3 sum_{j=0}^3 sum_{k=0}^3 a_{ijk} x^i y^j z^k. // The tensor term A[ix][iy][iz] corresponds to the polynomial term // x^{ix} y^{iy} z^{iz}. Real& A(int32_t ix, int32_t iy, int32_t iz) { return mCoeff[ix][iy][iz]; } Real operator()(Real x, Real y, Real z) const { std::array<Real, 4> xPow = { (Real)1, x, x * x, x * x * x }; std::array<Real, 4> yPow = { (Real)1, y, y * y, y * y * y }; std::array<Real, 4> zPow = { (Real)1, z, z * z, z * z * z }; Real p = (Real)0; for (size_t iz = 0; iz <= 3; ++iz) { for (size_t iy = 0; iy <= 3; ++iy) { for (size_t ix = 0; ix <= 3; ++ix) { p += mCoeff[ix][iy][iz] * xPow[ix] * yPow[iy] * zPow[iz]; } } } return p; } Real operator()(int32_t xOrder, int32_t yOrder, int32_t zOrder, Real x, Real y, Real z) const { std::array<Real, 4> xPow; switch (xOrder) { case 0: xPow[0] = (Real)1; xPow[1] = x; xPow[2] = x * x; xPow[3] = x * x * x; break; case 1: xPow[0] = (Real)0; xPow[1] = (Real)1; xPow[2] = (Real)2 * x; xPow[3] = (Real)3 * x * x; break; case 2: xPow[0] = (Real)0; xPow[1] = (Real)0; xPow[2] = (Real)2; xPow[3] = (Real)6 * x; break; case 3: xPow[0] = (Real)0; xPow[1] = (Real)0; xPow[2] = (Real)0; xPow[3] = (Real)6; break; default: return (Real)0; } std::array<Real, 4> yPow; switch (yOrder) { case 0: yPow[0] = (Real)1; yPow[1] = y; yPow[2] = y * y; yPow[3] = y * y * y; break; case 1: yPow[0] = (Real)0; yPow[1] = (Real)1; yPow[2] = (Real)2 * y; yPow[3] = (Real)3 * y * y; break; case 2: yPow[0] = (Real)0; yPow[1] = (Real)0; yPow[2] = (Real)2; yPow[3] = (Real)6 * y; break; case 3: yPow[0] = (Real)0; yPow[1] = (Real)0; yPow[2] = (Real)0; yPow[3] = (Real)6; break; default: return (Real)0; } std::array<Real, 4> zPow; switch (zOrder) { case 0: zPow[0] = (Real)1; zPow[1] = z; zPow[2] = z * z; zPow[3] = z * z * z; break; case 1: zPow[0] = (Real)0; zPow[1] = (Real)1; zPow[2] = (Real)2 * z; zPow[3] = (Real)3 * z * z; break; case 2: zPow[0] = (Real)0; zPow[1] = (Real)0; zPow[2] = (Real)2; zPow[3] = (Real)6 * z; break; case 3: zPow[0] = (Real)0; zPow[1] = (Real)0; zPow[2] = (Real)0; zPow[3] = (Real)6; break; default: return (Real)0; } Real p = (Real)0; for (size_t iz = 0; iz <= 3; ++iz) { for (size_t iy = 0; iy <= 3; ++iy) { for (size_t ix = 0; ix <= 3; ++ix) { p += mCoeff[ix][iy][iz] * xPow[ix] * yPow[iy] * zPow[iz]; } } } return p; } private: std::array<std::array<std::array<Real, 4>, 4>, 4> mCoeff; }; // Support for construction. void GetFX(Array3<Real> const& F, Array3<Real>& FX) { Array3<Real> slope(static_cast<size_t>(mXBound) + 3, mYBound, mZBound); Real invDX = (Real)1 / mXSpacing; int32_t ix, iy, iz; for (iz = 0; iz < mZBound; ++iz) { for (iy = 0; iy < mYBound; ++iy) { for (ix = 0; ix < mXBound - 1; ++ix) { slope[iz][iy][ix + 2] = (F[iz][iy][ix + 1] - F[iz][iy][ix]) * invDX; } slope[iz][iy][1] = (Real)2 * slope[iz][iy][2] - slope[iz][iy][3]; slope[iz][iy][0] = (Real)2 * slope[iz][iy][1] - slope[iz][iy][2]; slope[iz][iy][static_cast<size_t>(mXBound) + 1] = (Real)2 * slope[iz][iy][mXBound] - slope[iz][iy][static_cast<size_t>(mXBound) - 1]; slope[iz][iy][static_cast<size_t>(mXBound) + 2] = (Real)2 * slope[iz][iy][static_cast<size_t>(mXBound) + 1] - slope[iz][iy][mXBound]; } } for (iz = 0; iz < mZBound; ++iz) { for (iy = 0; iy < mYBound; ++iy) { for (ix = 0; ix < mXBound; ++ix) { FX[iz][iy][ix] = ComputeDerivative(slope[iz][iy] + ix); } } } } void GetFY(Array3<Real> const& F, Array3<Real>& FY) { Array3<Real> slope(static_cast<size_t>(mYBound) + 3, mXBound, mZBound); Real invDY = (Real)1 / mYSpacing; int32_t ix, iy, iz; for (iz = 0; iz < mZBound; ++iz) { for (ix = 0; ix < mXBound; ++ix) { for (iy = 0; iy < mYBound - 1; ++iy) { slope[iz][ix][iy + 2] = (F[iz][iy + 1][ix] - F[iz][iy][ix]) * invDY; } slope[iz][ix][1] = (Real)2 * slope[iz][ix][2] - slope[iz][ix][3]; slope[iz][ix][0] = (Real)2 * slope[iz][ix][1] - slope[iz][ix][2]; slope[iz][ix][static_cast<size_t>(mYBound) + 1] = (Real)2 * slope[iz][ix][mYBound] - slope[iz][ix][static_cast<size_t>(mYBound) - 1]; slope[iz][ix][static_cast<size_t>(mYBound) + 2] = (Real)2 * slope[iz][ix][static_cast<size_t>(mYBound) + 1] - slope[iz][ix][mYBound]; } } for (iz = 0; iz < mZBound; ++iz) { for (ix = 0; ix < mXBound; ++ix) { for (iy = 0; iy < mYBound; ++iy) { FY[iz][iy][ix] = ComputeDerivative(slope[iz][ix] + iy); } } } } void GetFZ(Array3<Real> const& F, Array3<Real>& FZ) { Array3<Real> slope(static_cast<size_t>(mZBound) + 3, mXBound, mYBound); Real invDZ = (Real)1 / mZSpacing; int32_t ix, iy, iz; for (iy = 0; iy < mYBound; ++iy) { for (ix = 0; ix < mXBound; ++ix) { for (iz = 0; iz < mZBound - 1; ++iz) { slope[iy][ix][iz + 2] = (F[iz + 1][iy][ix] - F[iz][iy][ix]) * invDZ; } slope[iy][ix][1] = (Real)2 * slope[iy][ix][2] - slope[iy][ix][3]; slope[iy][ix][0] = (Real)2 * slope[iy][ix][1] - slope[iy][ix][2]; slope[iy][ix][static_cast<size_t>(mZBound) + 1] = (Real)2 * slope[iy][ix][mZBound] - slope[iy][ix][static_cast<size_t>(mZBound) - 1]; slope[iy][ix][static_cast<size_t>(mZBound) + 2] = (Real)2 * slope[iy][ix][static_cast<size_t>(mZBound) + 1] - slope[iy][ix][mZBound]; } } for (iy = 0; iy < mYBound; ++iy) { for (ix = 0; ix < mXBound; ++ix) { for (iz = 0; iz < mZBound; ++iz) { FZ[iz][iy][ix] = ComputeDerivative(slope[iy][ix] + iz); } } } } void GetFXY(Array3<Real> const& F, Array3<Real>& FXY) { int32_t xBoundM1 = mXBound - 1; int32_t yBoundM1 = mYBound - 1; int32_t ix0 = xBoundM1, ix1 = ix0 - 1, ix2 = ix1 - 1; int32_t iy0 = yBoundM1, iy1 = iy0 - 1, iy2 = iy1 - 1; int32_t ix, iy, iz; Real invDXDY = (Real)1 / (mXSpacing * mYSpacing); for (iz = 0; iz < mZBound; ++iz) { // corners of z-slice FXY[iz][0][0] = (Real)0.25 * invDXDY * ( (Real)9 * F[iz][0][0] - (Real)12 * F[iz][0][1] + (Real)3 * F[iz][0][2] - (Real)12 * F[iz][1][0] + (Real)16 * F[iz][1][1] - (Real)4 * F[iz][1][2] + (Real)3 * F[iz][2][0] - (Real)4 * F[iz][2][1] + F[iz][2][2]); FXY[iz][0][xBoundM1] = (Real)0.25 * invDXDY * ( (Real)9 * F[iz][0][ix0] - (Real)12 * F[iz][0][ix1] + (Real)3 * F[iz][0][ix2] - (Real)12 * F[iz][1][ix0] + (Real)16 * F[iz][1][ix1] - (Real)4 * F[iz][1][ix2] + (Real)3 * F[iz][2][ix0] - (Real)4 * F[iz][2][ix1] + F[iz][2][ix2]); FXY[iz][yBoundM1][0] = (Real)0.25 * invDXDY * ( (Real)9 * F[iz][iy0][0] - (Real)12 * F[iz][iy0][1] + (Real)3 * F[iz][iy0][2] - (Real)12 * F[iz][iy1][0] + (Real)16 * F[iz][iy1][1] - (Real)4 * F[iz][iy1][2] + (Real)3 * F[iz][iy2][0] - (Real)4 * F[iz][iy2][1] + F[iz][iy2][2]); FXY[iz][yBoundM1][xBoundM1] = (Real)0.25 * invDXDY * ( (Real)9 * F[iz][iy0][ix0] - (Real)12 * F[iz][iy0][ix1] + (Real)3 * F[iz][iy0][ix2] - (Real)12 * F[iz][iy1][ix0] + (Real)16 * F[iz][iy1][ix1] - (Real)4 * F[iz][iy1][ix2] + (Real)3 * F[iz][iy2][ix0] - (Real)4 * F[iz][iy2][ix1] + F[iz][iy2][ix2]); // x-edges of z-slice for (ix = 1; ix < xBoundM1; ++ix) { FXY[iz][0][ix] = (Real)0.25 * invDXDY * ( (Real)3 * (F[iz][0][ix - 1] - F[iz][0][ix + 1]) - (Real)4 * (F[iz][1][ix - 1] - F[iz][1][ix + 1]) + (F[iz][2][ix - 1] - F[iz][2][ix + 1])); FXY[iz][yBoundM1][ix] = (Real)0.25 * invDXDY * ( (Real)3 * (F[iz][iy0][ix - 1] - F[iz][iy0][ix + 1]) - (Real)4 * (F[iz][iy1][ix - 1] - F[iz][iy1][ix + 1]) + (F[iz][iy2][ix - 1] - F[iz][iy2][ix + 1])); } // y-edges of z-slice for (iy = 1; iy < yBoundM1; ++iy) { FXY[iz][iy][0] = (Real)0.25 * invDXDY * ( (Real)3 * (F[iz][iy - 1][0] - F[iz][iy + 1][0]) - (Real)4 * (F[iz][iy - 1][1] - F[iz][iy + 1][1]) + (F[iz][iy - 1][2] - F[iz][iy + 1][2])); FXY[iz][iy][xBoundM1] = (Real)0.25 * invDXDY * ( (Real)3 * (F[iz][iy - 1][ix0] - F[iz][iy + 1][ix0]) - (Real)4 * (F[iz][iy - 1][ix1] - F[iz][iy + 1][ix1]) + (F[iz][iy - 1][ix2] - F[iz][iy + 1][ix2])); } // interior of z-slice for (iy = 1; iy < yBoundM1; ++iy) { for (ix = 1; ix < xBoundM1; ++ix) { FXY[iz][iy][ix] = (Real)0.25 * invDXDY * ( F[iz][iy - 1][ix - 1] - F[iz][iy - 1][ix + 1] - F[iz][iy + 1][ix - 1] + F[iz][iy + 1][ix + 1]); } } } } void GetFXZ(Array3<Real> const& F, Array3<Real> & FXZ) { int32_t xBoundM1 = mXBound - 1; int32_t zBoundM1 = mZBound - 1; int32_t ix0 = xBoundM1, ix1 = ix0 - 1, ix2 = ix1 - 1; int32_t iz0 = zBoundM1, iz1 = iz0 - 1, iz2 = iz1 - 1; int32_t ix, iy, iz; Real invDXDZ = (Real)1 / (mXSpacing * mZSpacing); for (iy = 0; iy < mYBound; ++iy) { // corners of z-slice FXZ[0][iy][0] = (Real)0.25 * invDXDZ * ( (Real)9 * F[0][iy][0] - (Real)12 * F[0][iy][1] + (Real)3 * F[0][iy][2] - (Real)12 * F[1][iy][0] + (Real)16 * F[1][iy][1] - (Real)4 * F[1][iy][2] + (Real)3 * F[2][iy][0] - (Real)4 * F[2][iy][1] + F[2][iy][2]); FXZ[0][iy][xBoundM1] = (Real)0.25 * invDXDZ * ( (Real)9 * F[0][iy][ix0] - (Real)12 * F[0][iy][ix1] + (Real)3 * F[0][iy][ix2] - (Real)12 * F[1][iy][ix0] + (Real)16 * F[1][iy][ix1] - (Real)4 * F[1][iy][ix2] + (Real)3 * F[2][iy][ix0] - (Real)4 * F[2][iy][ix1] + F[2][iy][ix2]); FXZ[zBoundM1][iy][0] = (Real)0.25 * invDXDZ * ( (Real)9 * F[iz0][iy][0] - (Real)12 * F[iz0][iy][1] + (Real)3 * F[iz0][iy][2] - (Real)12 * F[iz1][iy][0] + (Real)16 * F[iz1][iy][1] - (Real)4 * F[iz1][iy][2] + (Real)3 * F[iz2][iy][0] - (Real)4 * F[iz2][iy][1] + F[iz2][iy][2]); FXZ[zBoundM1][iy][xBoundM1] = (Real)0.25 * invDXDZ * ( (Real)9 * F[iz0][iy][ix0] - (Real)12 * F[iz0][iy][ix1] + (Real)3 * F[iz0][iy][ix2] - (Real)12 * F[iz1][iy][ix0] + (Real)16 * F[iz1][iy][ix1] - (Real)4 * F[iz1][iy][ix2] + (Real)3 * F[iz2][iy][ix0] - (Real)4 * F[iz2][iy][ix1] + F[iz2][iy][ix2]); // x-edges of y-slice for (ix = 1; ix < xBoundM1; ++ix) { FXZ[0][iy][ix] = (Real)0.25 * invDXDZ * ( (Real)3 * (F[0][iy][ix - 1] - F[0][iy][ix + 1]) - (Real)4 * (F[1][iy][ix - 1] - F[1][iy][ix + 1]) + (F[2][iy][ix - 1] - F[2][iy][ix + 1])); FXZ[zBoundM1][iy][ix] = (Real)0.25 * invDXDZ * ( (Real)3 * (F[iz0][iy][ix - 1] - F[iz0][iy][ix + 1]) - (Real)4 * (F[iz1][iy][ix - 1] - F[iz1][iy][ix + 1]) + (F[iz2][iy][ix - 1] - F[iz2][iy][ix + 1])); } // z-edges of y-slice for (iz = 1; iz < zBoundM1; ++iz) { FXZ[iz][iy][0] = (Real)0.25 * invDXDZ * ( (Real)3 * (F[iz - 1][iy][0] - F[iz + 1][iy][0]) - (Real)4 * (F[iz - 1][iy][1] - F[iz + 1][iy][1]) + (F[iz - 1][iy][2] - F[iz + 1][iy][2])); FXZ[iz][iy][xBoundM1] = (Real)0.25 * invDXDZ * ( (Real)3 * (F[iz - 1][iy][ix0] - F[iz + 1][iy][ix0]) - (Real)4 * (F[iz - 1][iy][ix1] - F[iz + 1][iy][ix1]) + (F[iz - 1][iy][ix2] - F[iz + 1][iy][ix2])); } // interior of y-slice for (iz = 1; iz < zBoundM1; ++iz) { for (ix = 1; ix < xBoundM1; ++ix) { FXZ[iz][iy][ix] = ((Real)0.25) * invDXDZ * ( F[iz - 1][iy][ix - 1] - F[iz - 1][iy][ix + 1] - F[iz + 1][iy][ix - 1] + F[iz + 1][iy][ix + 1]); } } } } void GetFYZ(Array3<Real> const& F, Array3<Real> & FYZ) { int32_t yBoundM1 = mYBound - 1; int32_t zBoundM1 = mZBound - 1; int32_t iy0 = yBoundM1, iy1 = iy0 - 1, iy2 = iy1 - 1; int32_t iz0 = zBoundM1, iz1 = iz0 - 1, iz2 = iz1 - 1; int32_t ix, iy, iz; Real invDYDZ = (Real)1 / (mYSpacing * mZSpacing); for (ix = 0; ix < mXBound; ++ix) { // corners of x-slice FYZ[0][0][ix] = (Real)0.25 * invDYDZ * ( (Real)9 * F[0][0][ix] - (Real)12 * F[0][1][ix] + (Real)3 * F[0][2][ix] - (Real)12 * F[1][0][ix] + (Real)16 * F[1][1][ix] - (Real)4 * F[1][2][ix] + (Real)3 * F[2][0][ix] - (Real)4 * F[2][1][ix] + F[2][2][ix]); FYZ[0][yBoundM1][ix] = (Real)0.25 * invDYDZ * ( (Real)9 * F[0][iy0][ix] - (Real)12 * F[0][iy1][ix] + (Real)3 * F[0][iy2][ix] - (Real)12 * F[1][iy0][ix] + (Real)16 * F[1][iy1][ix] - (Real)4 * F[1][iy2][ix] + (Real)3 * F[2][iy0][ix] - (Real)4 * F[2][iy1][ix] + F[2][iy2][ix]); FYZ[zBoundM1][0][ix] = (Real)0.25 * invDYDZ * ( (Real)9 * F[iz0][0][ix] - (Real)12 * F[iz0][1][ix] + (Real)3 * F[iz0][2][ix] - (Real)12 * F[iz1][0][ix] + (Real)16 * F[iz1][1][ix] - (Real)4 * F[iz1][2][ix] + (Real)3 * F[iz2][0][ix] - (Real)4 * F[iz2][1][ix] + F[iz2][2][ix]); FYZ[zBoundM1][yBoundM1][ix] = (Real)0.25 * invDYDZ * ( (Real)9 * F[iz0][iy0][ix] - (Real)12 * F[iz0][iy1][ix] + (Real)3 * F[iz0][iy2][ix] - (Real)12 * F[iz1][iy0][ix] + (Real)16 * F[iz1][iy1][ix] - (Real)4 * F[iz1][iy2][ix] + (Real)3 * F[iz2][iy0][ix] - (Real)4 * F[iz2][iy1][ix] + F[iz2][iy2][ix]); // y-edges of x-slice for (iy = 1; iy < yBoundM1; ++iy) { FYZ[0][iy][ix] = (Real)0.25 * invDYDZ * ( (Real)3 * (F[0][iy - 1][ix] - F[0][iy + 1][ix]) - (Real)4 * (F[1][iy - 1][ix] - F[1][iy + 1][ix]) + (F[2][iy - 1][ix] - F[2][iy + 1][ix])); FYZ[zBoundM1][iy][ix] = (Real)0.25 * invDYDZ * ( (Real)3 * (F[iz0][iy - 1][ix] - F[iz0][iy + 1][ix]) - (Real)4 * (F[iz1][iy - 1][ix] - F[iz1][iy + 1][ix]) + (F[iz2][iy - 1][ix] - F[iz2][iy + 1][ix])); } // z-edges of x-slice for (iz = 1; iz < zBoundM1; ++iz) { FYZ[iz][0][ix] = (Real)0.25 * invDYDZ * ( (Real)3 * (F[iz - 1][0][ix] - F[iz + 1][0][ix]) - (Real)4 * (F[iz - 1][1][ix] - F[iz + 1][1][ix]) + (F[iz - 1][2][ix] - F[iz + 1][2][ix])); FYZ[iz][yBoundM1][ix] = (Real)0.25 * invDYDZ * ( (Real)3 * (F[iz - 1][iy0][ix] - F[iz + 1][iy0][ix]) - (Real)4 * (F[iz - 1][iy1][ix] - F[iz + 1][iy1][ix]) + (F[iz - 1][iy2][ix] - F[iz + 1][iy2][ix])); } // interior of x-slice for (iz = 1; iz < zBoundM1; ++iz) { for (iy = 1; iy < yBoundM1; ++iy) { FYZ[iz][iy][ix] = (Real)0.25 * invDYDZ * ( F[iz - 1][iy - 1][ix] - F[iz - 1][iy + 1][ix] - F[iz + 1][iy - 1][ix] + F[iz + 1][iy + 1][ix]); } } } } void GetFXYZ(Array3<Real> const& F, Array3<Real> & FXYZ) { int32_t xBoundM1 = mXBound - 1; int32_t yBoundM1 = mYBound - 1; int32_t zBoundM1 = mZBound - 1; int32_t ix, iy, iz, ix0, iy0, iz0; Real invDXDYDZ = ((Real)1) / (mXSpacing * mYSpacing * mZSpacing); // convolution masks // centered difference, O(h^2) Real CDer[3] = { -(Real)0.5, (Real)0, (Real)0.5 }; // one-sided difference, O(h^2) Real ODer[3] = { -(Real)1.5, (Real)2, -(Real)0.5 }; Real mask; // corners FXYZ[0][0][0] = (Real)0; FXYZ[0][0][xBoundM1] = (Real)0; FXYZ[0][yBoundM1][0] = (Real)0; FXYZ[0][yBoundM1][xBoundM1] = (Real)0; FXYZ[zBoundM1][0][0] = (Real)0; FXYZ[zBoundM1][0][xBoundM1] = (Real)0; FXYZ[zBoundM1][yBoundM1][0] = (Real)0; FXYZ[zBoundM1][yBoundM1][xBoundM1] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * ODer[ix] * ODer[iy] * ODer[iz]; FXYZ[0][0][0] += mask * F[iz][iy][ix]; FXYZ[0][0][xBoundM1] += mask * F[iz][iy][xBoundM1 - ix]; FXYZ[0][yBoundM1][0] += mask * F[iz][yBoundM1 - iy][ix]; FXYZ[0][yBoundM1][xBoundM1] += mask * F[iz][yBoundM1 - iy][xBoundM1 - ix]; FXYZ[zBoundM1][0][0] += mask * F[zBoundM1 - iz][iy][ix]; FXYZ[zBoundM1][0][xBoundM1] += mask * F[zBoundM1 - iz][iy][xBoundM1 - ix]; FXYZ[zBoundM1][yBoundM1][0] += mask * F[zBoundM1 - iz][yBoundM1 - iy][ix]; FXYZ[zBoundM1][yBoundM1][xBoundM1] += mask * F[zBoundM1 - iz][yBoundM1 - iy][xBoundM1 - ix]; } } } // x-edges for (ix0 = 1; ix0 < xBoundM1; ++ix0) { FXYZ[0][0][ix0] = (Real)0; FXYZ[0][yBoundM1][ix0] = (Real)0; FXYZ[zBoundM1][0][ix0] = (Real)0; FXYZ[zBoundM1][yBoundM1][ix0] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * CDer[ix] * ODer[iy] * ODer[iz]; FXYZ[0][0][ix0] += mask * F[iz][iy][ix0 + ix - 1]; FXYZ[0][yBoundM1][ix0] += mask * F[iz][yBoundM1 - iy][ix0 + ix - 1]; FXYZ[zBoundM1][0][ix0] += mask * F[zBoundM1 - iz][iy][ix0 + ix - 1]; FXYZ[zBoundM1][yBoundM1][ix0] += mask * F[zBoundM1 - iz][yBoundM1 - iy][ix0 + ix - 1]; } } } } // y-edges for (iy0 = 1; iy0 < yBoundM1; ++iy0) { FXYZ[0][iy0][0] = (Real)0; FXYZ[0][iy0][xBoundM1] = (Real)0; FXYZ[zBoundM1][iy0][0] = (Real)0; FXYZ[zBoundM1][iy0][xBoundM1] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * ODer[ix] * CDer[iy] * ODer[iz]; FXYZ[0][iy0][0] += mask * F[iz][iy0 + iy - 1][ix]; FXYZ[0][iy0][xBoundM1] += mask * F[iz][iy0 + iy - 1][xBoundM1 - ix]; FXYZ[zBoundM1][iy0][0] += mask * F[zBoundM1 - iz][iy0 + iy - 1][ix]; FXYZ[zBoundM1][iy0][xBoundM1] += mask * F[zBoundM1 - iz][iy0 + iy - 1][xBoundM1 - ix]; } } } } // z-edges for (iz0 = 1; iz0 < zBoundM1; ++iz0) { FXYZ[iz0][0][0] = (Real)0; FXYZ[iz0][0][xBoundM1] = (Real)0; FXYZ[iz0][yBoundM1][0] = (Real)0; FXYZ[iz0][yBoundM1][xBoundM1] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * ODer[ix] * ODer[iy] * CDer[iz]; FXYZ[iz0][0][0] += mask * F[iz0 + iz - 1][iy][ix]; FXYZ[iz0][0][xBoundM1] += mask * F[iz0 + iz - 1][iy][xBoundM1 - ix]; FXYZ[iz0][yBoundM1][0] += mask * F[iz0 + iz - 1][yBoundM1 - iy][ix]; FXYZ[iz0][yBoundM1][xBoundM1] += mask * F[iz0 + iz - 1][yBoundM1 - iy][xBoundM1 - ix]; } } } } // xy-faces for (iy0 = 1; iy0 < yBoundM1; ++iy0) { for (ix0 = 1; ix0 < xBoundM1; ++ix0) { FXYZ[0][iy0][ix0] = (Real)0; FXYZ[zBoundM1][iy0][ix0] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * CDer[ix] * CDer[iy] * ODer[iz]; FXYZ[0][iy0][ix0] += mask * F[iz][iy0 + iy - 1][ix0 + ix - 1]; FXYZ[zBoundM1][iy0][ix0] += mask * F[zBoundM1 - iz][iy0 + iy - 1][ix0 + ix - 1]; } } } } } // xz-faces for (iz0 = 1; iz0 < zBoundM1; ++iz0) { for (ix0 = 1; ix0 < xBoundM1; ++ix0) { FXYZ[iz0][0][ix0] = (Real)0; FXYZ[iz0][yBoundM1][ix0] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * CDer[ix] * ODer[iy] * CDer[iz]; FXYZ[iz0][0][ix0] += mask * F[iz0 + iz - 1][iy][ix0 + ix - 1]; FXYZ[iz0][yBoundM1][ix0] += mask * F[iz0 + iz - 1][yBoundM1 - iy][ix0 + ix - 1]; } } } } } // yz-faces for (iz0 = 1; iz0 < zBoundM1; ++iz0) { for (iy0 = 1; iy0 < yBoundM1; ++iy0) { FXYZ[iz0][iy0][0] = (Real)0; FXYZ[iz0][iy0][xBoundM1] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * ODer[ix] * CDer[iy] * CDer[iz]; FXYZ[iz0][iy0][0] += mask * F[iz0 + iz - 1][iy0 + iy - 1][ix]; FXYZ[iz0][iy0][xBoundM1] += mask * F[iz0 + iz - 1][iy0 + iy - 1][xBoundM1 - ix]; } } } } } // interiors for (iz0 = 1; iz0 < zBoundM1; ++iz0) { for (iy0 = 1; iy0 < yBoundM1; ++iy0) { for (ix0 = 1; ix0 < xBoundM1; ++ix0) { FXYZ[iz0][iy0][ix0] = (Real)0; for (iz = 0; iz <= 2; ++iz) { for (iy = 0; iy <= 2; ++iy) { for (ix = 0; ix <= 2; ++ix) { mask = invDXDYDZ * CDer[ix] * CDer[iy] * CDer[iz]; FXYZ[iz0][iy0][ix0] += mask * F[iz0 + iz - 1][iy0 + iy - 1][ix0 + ix - 1]; } } } } } } } void GetPolynomials(Array3<Real> const& F, Array3<Real> const& FX, Array3<Real> const& FY, Array3<Real> const& FZ, Array3<Real> const& FXY, Array3<Real> const& FXZ, Array3<Real> const& FYZ, Array3<Real> const& FXYZ) { int32_t xBoundM1 = mXBound - 1; int32_t yBoundM1 = mYBound - 1; int32_t zBoundM1 = mZBound - 1; for (int32_t iz = 0; iz < zBoundM1; ++iz) { for (int32_t iy = 0; iy < yBoundM1; ++iy) { for (int32_t ix = 0; ix < xBoundM1; ++ix) { // Note the 'transposing' of the 2x2x2 blocks (to match // notation used in the polynomial definition). Real G[2][2][2] = { { { F[iz][iy][ix], F[iz + 1][iy][ix] }, { F[iz][iy + 1][ix], F[iz + 1][iy + 1][ix] } }, { { F[iz][iy][ix + 1], F[iz + 1][iy][ix + 1] }, { F[iz][iy + 1][ix + 1], F[iz + 1][iy + 1][ix + 1] } } }; Real GX[2][2][2] = { { { FX[iz][iy][ix], FX[iz + 1][iy][ix] }, { FX[iz][iy + 1][ix], FX[iz + 1][iy + 1][ix] } }, { { FX[iz][iy][ix + 1], FX[iz + 1][iy][ix + 1] }, { FX[iz][iy + 1][ix + 1], FX[iz + 1][iy + 1][ix + 1] } } }; Real GY[2][2][2] = { { { FY[iz][iy][ix], FY[iz + 1][iy][ix] }, { FY[iz][iy + 1][ix], FY[iz + 1][iy + 1][ix] } }, { { FY[iz][iy][ix + 1], FY[iz + 1][iy][ix + 1] }, { FY[iz][iy + 1][ix + 1], FY[iz + 1][iy + 1][ix + 1] } } }; Real GZ[2][2][2] = { { { FZ[iz][iy][ix], FZ[iz + 1][iy][ix] }, { FZ[iz][iy + 1][ix], FZ[iz + 1][iy + 1][ix] } }, { { FZ[iz][iy][ix + 1], FZ[iz + 1][iy][ix + 1] }, { FZ[iz][iy + 1][ix + 1], FZ[iz + 1][iy + 1][ix + 1] } } }; Real GXY[2][2][2] = { { { FXY[iz][iy][ix], FXY[iz + 1][iy][ix] }, { FXY[iz][iy + 1][ix], FXY[iz + 1][iy + 1][ix] } }, { { FXY[iz][iy][ix + 1], FXY[iz + 1][iy][ix + 1] }, { FXY[iz][iy + 1][ix + 1], FXY[iz + 1][iy + 1][ix + 1] } } }; Real GXZ[2][2][2] = { { { FXZ[iz][iy][ix], FXZ[iz + 1][iy][ix] }, { FXZ[iz][iy + 1][ix], FXZ[iz + 1][iy + 1][ix] } }, { { FXZ[iz][iy][ix + 1], FXZ[iz + 1][iy][ix + 1] }, { FXZ[iz][iy + 1][ix + 1], FXZ[iz + 1][iy + 1][ix + 1] } } }; Real GYZ[2][2][2] = { { { FYZ[iz][iy][ix], FYZ[iz + 1][iy][ix] }, { FYZ[iz][iy + 1][ix], FYZ[iz + 1][iy + 1][ix] } }, { { FYZ[iz][iy][ix + 1], FYZ[iz + 1][iy][ix + 1] }, { FYZ[iz][iy + 1][ix + 1], FYZ[iz + 1][iy + 1][ix + 1] } } }; Real GXYZ[2][2][2] = { { { FXYZ[iz][iy][ix], FXYZ[iz + 1][iy][ix] }, { FXYZ[iz][iy + 1][ix], FXYZ[iz + 1][iy + 1][ix] } }, { { FXYZ[iz][iy][ix + 1], FXYZ[iz + 1][iy][ix + 1] }, { FXYZ[iz][iy + 1][ix + 1], FXYZ[iz + 1][iy + 1][ix + 1] } } }; Construct(mPoly[iz][iy][ix], G, GX, GY, GZ, GXY, GXZ, GYZ, GXYZ); } } } } Real ComputeDerivative(Real const* slope) const { if (slope[1] != slope[2]) { if (slope[0] != slope[1]) { if (slope[2] != slope[3]) { Real ad0 = std::fabs(slope[3] - slope[2]); Real ad1 = std::fabs(slope[0] - slope[1]); return (ad0 * slope[1] + ad1 * slope[2]) / (ad0 + ad1); } else { return slope[2]; } } else { if (slope[2] != slope[3]) { return slope[1]; } else { return (Real)0.5 * (slope[1] + slope[2]); } } } else { return slope[1]; } } void Construct(Polynomial& poly, Real const F[2][2][2], Real const FX[2][2][2], Real const FY[2][2][2], Real const FZ[2][2][2], Real const FXY[2][2][2], Real const FXZ[2][2][2], Real const FYZ[2][2][2], Real const FXYZ[2][2][2]) { Real dx = mXSpacing, dy = mYSpacing, dz = mZSpacing; Real invDX = (Real)1 / dx, invDX2 = invDX * invDX; Real invDY = (Real)1 / dy, invDY2 = invDY * invDY; Real invDZ = (Real)1 / dz, invDZ2 = invDZ * invDZ; Real b0, b1, b2, b3, b4, b5, b6, b7; poly.A(0, 0, 0) = F[0][0][0]; poly.A(1, 0, 0) = FX[0][0][0]; poly.A(0, 1, 0) = FY[0][0][0]; poly.A(0, 0, 1) = FZ[0][0][0]; poly.A(1, 1, 0) = FXY[0][0][0]; poly.A(1, 0, 1) = FXZ[0][0][0]; poly.A(0, 1, 1) = FYZ[0][0][0]; poly.A(1, 1, 1) = FXYZ[0][0][0]; // solve for Aij0 b0 = (F[1][0][0] - poly(0, 0, 0, dx, (Real)0, (Real)0)) * invDX2; b1 = (FX[1][0][0] - poly(1, 0, 0, dx, (Real)0, (Real)0)) * invDX; poly.A(2, 0, 0) = (Real)3 * b0 - b1; poly.A(3, 0, 0) = ((Real)-2 * b0 + b1) * invDX; b0 = (F[0][1][0] - poly(0, 0, 0, (Real)0, dy, (Real)0)) * invDY2; b1 = (FY[0][1][0] - poly(0, 1, 0, (Real)0, dy, (Real)0)) * invDY; poly.A(0, 2, 0) = (Real)3 * b0 - b1; poly.A(0, 3, 0) = ((Real)-2 * b0 + b1) * invDY; b0 = (FY[1][0][0] - poly(0, 1, 0, dx, (Real)0, (Real)0)) * invDX2; b1 = (FXY[1][0][0] - poly(1, 1, 0, dx, (Real)0, (Real)0)) * invDX; poly.A(2, 1, 0) = (Real)3 * b0 - b1; poly.A(3, 1, 0) = ((Real)-2 * b0 + b1) * invDX; b0 = (FX[0][1][0] - poly(1, 0, 0, (Real)0, dy, (Real)0)) * invDY2; b1 = (FXY[0][1][0] - poly(1, 1, 0, (Real)0, dy, (Real)0)) * invDY; poly.A(1, 2, 0) = (Real)3 * b0 - b1; poly.A(1, 3, 0) = ((Real)-2 * b0 + b1) * invDY; b0 = (F[1][1][0] - poly(0, 0, 0, dx, dy, (Real)0)) * invDX2 * invDY2; b1 = (FX[1][1][0] - poly(1, 0, 0, dx, dy, (Real)0)) * invDX * invDY2; b2 = (FY[1][1][0] - poly(0, 1, 0, dx, dy, (Real)0)) * invDX2 * invDY; b3 = (FXY[1][1][0] - poly(1, 1, 0, dx, dy, (Real)0)) * invDX * invDY; poly.A(2, 2, 0) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(3, 2, 0) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDX; poly.A(2, 3, 0) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDY; poly.A(3, 3, 0) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDX * invDY; // solve for Ai0k b0 = (F[0][0][1] - poly(0, 0, 0, (Real)0, (Real)0, dz)) * invDZ2; b1 = (FZ[0][0][1] - poly(0, 0, 1, (Real)0, (Real)0, dz)) * invDZ; poly.A(0, 0, 2) = (Real)3 * b0 - b1; poly.A(0, 0, 3) = ((Real)-2 * b0 + b1) * invDZ; b0 = (FZ[1][0][0] - poly(0, 0, 1, dx, (Real)0, (Real)0)) * invDX2; b1 = (FXZ[1][0][0] - poly(1, 0, 1, dx, (Real)0, (Real)0)) * invDX; poly.A(2, 0, 1) = (Real)3 * b0 - b1; poly.A(3, 0, 1) = ((Real)-2 * b0 + b1) * invDX; b0 = (FX[0][0][1] - poly(1, 0, 0, (Real)0, (Real)0, dz)) * invDZ2; b1 = (FXZ[0][0][1] - poly(1, 0, 1, (Real)0, (Real)0, dz)) * invDZ; poly.A(1, 0, 2) = (Real)3 * b0 - b1; poly.A(1, 0, 3) = ((Real)-2 * b0 + b1) * invDZ; b0 = (F[1][0][1] - poly(0, 0, 0, dx, (Real)0, dz)) * invDX2 * invDZ2; b1 = (FX[1][0][1] - poly(1, 0, 0, dx, (Real)0, dz)) * invDX * invDZ2; b2 = (FZ[1][0][1] - poly(0, 0, 1, dx, (Real)0, dz)) * invDX2 * invDZ; b3 = (FXZ[1][0][1] - poly(1, 0, 1, dx, (Real)0, dz)) * invDX * invDZ; poly.A(2, 0, 2) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(3, 0, 2) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDX; poly.A(2, 0, 3) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDZ; poly.A(3, 0, 3) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDX * invDZ; // solve for A0jk b0 = (FZ[0][1][0] - poly(0, 0, 1, (Real)0, dy, (Real)0)) * invDY2; b1 = (FYZ[0][1][0] - poly(0, 1, 1, (Real)0, dy, (Real)0)) * invDY; poly.A(0, 2, 1) = (Real)3 * b0 - b1; poly.A(0, 3, 1) = ((Real)-2 * b0 + b1) * invDY; b0 = (FY[0][0][1] - poly(0, 1, 0, (Real)0, (Real)0, dz)) * invDZ2; b1 = (FYZ[0][0][1] - poly(0, 1, 1, (Real)0, (Real)0, dz)) * invDZ; poly.A(0, 1, 2) = (Real)3 * b0 - b1; poly.A(0, 1, 3) = ((Real)-2 * b0 + b1) * invDZ; b0 = (F[0][1][1] - poly(0, 0, 0, (Real)0, dy, dz)) * invDY2 * invDZ2; b1 = (FY[0][1][1] - poly(0, 1, 0, (Real)0, dy, dz)) * invDY * invDZ2; b2 = (FZ[0][1][1] - poly(0, 0, 1, (Real)0, dy, dz)) * invDY2 * invDZ; b3 = (FYZ[0][1][1] - poly(0, 1, 1, (Real)0, dy, dz)) * invDY * invDZ; poly.A(0, 2, 2) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(0, 3, 2) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDY; poly.A(0, 2, 3) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDZ; poly.A(0, 3, 3) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDY * invDZ; // solve for Aij1 b0 = (FYZ[1][0][0] - poly(0, 1, 1, dx, (Real)0, (Real)0)) * invDX2; b1 = (FXYZ[1][0][0] - poly(1, 1, 1, dx, (Real)0, (Real)0)) * invDX; poly.A(2, 1, 1) = (Real)3 * b0 - b1; poly.A(3, 1, 1) = ((Real)-2 * b0 + b1) * invDX; b0 = (FXZ[0][1][0] - poly(1, 0, 1, (Real)0, dy, (Real)0)) * invDY2; b1 = (FXYZ[0][1][0] - poly(1, 1, 1, (Real)0, dy, (Real)0)) * invDY; poly.A(1, 2, 1) = (Real)3 * b0 - b1; poly.A(1, 3, 1) = ((Real)-2 * b0 + b1) * invDY; b0 = (FZ[1][1][0] - poly(0, 0, 1, dx, dy, (Real)0)) * invDX2 * invDY2; b1 = (FXZ[1][1][0] - poly(1, 0, 1, dx, dy, (Real)0)) * invDX * invDY2; b2 = (FYZ[1][1][0] - poly(0, 1, 1, dx, dy, (Real)0)) * invDX2 * invDY; b3 = (FXYZ[1][1][0] - poly(1, 1, 1, dx, dy, (Real)0)) * invDX * invDY; poly.A(2, 2, 1) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(3, 2, 1) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDX; poly.A(2, 3, 1) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDY; poly.A(3, 3, 1) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDX * invDY; // solve for Ai1k b0 = (FXY[0][0][1] - poly(1, 1, 0, (Real)0, (Real)0, dz)) * invDZ2; b1 = (FXYZ[0][0][1] - poly(1, 1, 1, (Real)0, (Real)0, dz)) * invDZ; poly.A(1, 1, 2) = (Real)3 * b0 - b1; poly.A(1, 1, 3) = ((Real)-2 * b0 + b1) * invDZ; b0 = (FY[1][0][1] - poly(0, 1, 0, dx, (Real)0, dz)) * invDX2 * invDZ2; b1 = (FXY[1][0][1] - poly(1, 1, 0, dx, (Real)0, dz)) * invDX * invDZ2; b2 = (FYZ[1][0][1] - poly(0, 1, 1, dx, (Real)0, dz)) * invDX2 * invDZ; b3 = (FXYZ[1][0][1] - poly(1, 1, 1, dx, (Real)0, dz)) * invDX * invDZ; poly.A(2, 1, 2) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(3, 1, 2) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDX; poly.A(2, 1, 3) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDZ; poly.A(3, 1, 3) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDX * invDZ; // solve for A1jk b0 = (FX[0][1][1] - poly(1, 0, 0, (Real)0, dy, dz)) * invDY2 * invDZ2; b1 = (FXY[0][1][1] - poly(1, 1, 0, (Real)0, dy, dz)) * invDY * invDZ2; b2 = (FXZ[0][1][1] - poly(1, 0, 1, (Real)0, dy, dz)) * invDY2 * invDZ; b3 = (FXYZ[0][1][1] - poly(1, 1, 1, (Real)0, dy, dz)) * invDY * invDZ; poly.A(1, 2, 2) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3; poly.A(1, 3, 2) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDY; poly.A(1, 2, 3) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDZ; poly.A(1, 3, 3) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDY * invDZ; // solve for remaining Aijk with i >= 2, j >= 2, k >= 2 b0 = (F[1][1][1] - poly(0, 0, 0, dx, dy, dz)) * invDX2 * invDY2 * invDZ2; b1 = (FX[1][1][1] - poly(1, 0, 0, dx, dy, dz)) * invDX * invDY2 * invDZ2; b2 = (FY[1][1][1] - poly(0, 1, 0, dx, dy, dz)) * invDX2 * invDY * invDZ2; b3 = (FZ[1][1][1] - poly(0, 0, 1, dx, dy, dz)) * invDX2 * invDY2 * invDZ; b4 = (FXY[1][1][1] - poly(1, 1, 0, dx, dy, dz)) * invDX * invDY * invDZ2; b5 = (FXZ[1][1][1] - poly(1, 0, 1, dx, dy, dz)) * invDX * invDY2 * invDZ; b6 = (FYZ[1][1][1] - poly(0, 1, 1, dx, dy, dz)) * invDX2 * invDY * invDZ; b7 = (FXYZ[1][1][1] - poly(1, 1, 1, dx, dy, dz)) * invDX * invDY * invDZ; poly.A(2, 2, 2) = (Real)27 * b0 - (Real)9 * b1 - (Real)9 * b2 - (Real)9 * b3 + (Real)3 * b4 + (Real)3 * b5 + (Real)3 * b6 - b7; poly.A(3, 2, 2) = ((Real)-18 * b0 + (Real)9 * b1 + (Real)6 * b2 + (Real)6 * b3 - (Real)3 * b4 - (Real)3 * b5 - (Real)2 * b6 + b7) * invDX; poly.A(2, 3, 2) = ((Real)-18 * b0 + (Real)6 * b1 + (Real)9 * b2 + (Real)6 * b3 - (Real)3 * b4 - (Real)2 * b5 - (Real)3 * b6 + b7) * invDY; poly.A(2, 2, 3) = ((Real)-18 * b0 + (Real)6 * b1 + (Real)6 * b2 + (Real)9 * b3 - (Real)2 * b4 - (Real)3 * b5 - (Real)3 * b6 + b7) * invDZ; poly.A(3, 3, 2) = ((Real)12 * b0 - (Real)6 * b1 - (Real)6 * b2 - (Real)4 * b3 + (Real)3 * b4 + (Real)2 * b5 + (Real)2 * b6 - b7) * invDX * invDY; poly.A(3, 2, 3) = ((Real)12 * b0 - (Real)6 * b1 - (Real)4 * b2 - (Real)6 * b3 + (Real)2 * b4 + (Real)3 * b5 + (Real)2 * b6 - b7) * invDX * invDZ; poly.A(2, 3, 3) = ((Real)12 * b0 - (Real)4 * b1 - (Real)6 * b2 - (Real)6 * b3 + (Real)2 * b4 + (Real)2 * b5 + (Real)3 * b6 - b7) * invDY * invDZ; poly.A(3, 3, 3) = ((Real)-8 * b0 + (Real)4 * b1 + (Real)4 * b2 + (Real)4 * b3 - (Real)2 * b4 - (Real)2 * b5 - (Real)2 * b6 + b7) * invDX * invDY * invDZ; } void XLookup(Real x, int32_t& xIndex, Real& dx) const { int32_t xIndexP1; for (xIndex = 0, xIndexP1 = 1; xIndexP1 < mXBound; ++xIndex, ++xIndexP1) { if (x < mXMin + mXSpacing * static_cast<Real>(xIndexP1)) { dx = x - (mXMin + mXSpacing * xIndex); return; } } --xIndex; dx = x - (mXMin + mXSpacing * xIndex); } void YLookup(Real y, int32_t& yIndex, Real & dy) const { int32_t yIndexP1; for (yIndex = 0, yIndexP1 = 1; yIndexP1 < mYBound; ++yIndex, ++yIndexP1) { if (y < mYMin + mYSpacing * static_cast<Real>(yIndexP1)) { dy = y - (mYMin + mYSpacing * yIndex); return; } } --yIndex; dy = y - (mYMin + mYSpacing * yIndex); } void ZLookup(Real z, int32_t& zIndex, Real & dz) const { int32_t zIndexP1; for (zIndex = 0, zIndexP1 = 1; zIndexP1 < mZBound; ++zIndex, ++zIndexP1) { if (z < mZMin + mZSpacing * static_cast<Real>(zIndexP1)) { dz = z - (mZMin + mZSpacing * zIndex); return; } } --zIndex; dz = z - (mZMin + mZSpacing * zIndex); } int32_t mXBound, mYBound, mZBound, mQuantity; Real mXMin, mXMax, mXSpacing; Real mYMin, mYMax, mYSpacing; Real mZMin, mZMax, mZSpacing; Real const* mF; Array3<Polynomial> mPoly; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Matrix3x3.h
.h
4,527
143
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/Vector3.h> namespace gte { // Template alias for convenience. template <typename Real> using Matrix3x3 = Matrix<3, 3, Real>; // Geometric operations. template <typename Real> Matrix3x3<Real> Inverse(Matrix3x3<Real> const& M, bool* reportInvertibility = nullptr) { Matrix3x3<Real> inverse; bool invertible; Real c00 = M(1, 1) * M(2, 2) - M(1, 2) * M(2, 1); Real c10 = M(1, 2) * M(2, 0) - M(1, 0) * M(2, 2); Real c20 = M(1, 0) * M(2, 1) - M(1, 1) * M(2, 0); Real det = M(0, 0) * c00 + M(0, 1) * c10 + M(0, 2) * c20; if (det != (Real)0) { Real invDet = (Real)1 / det; inverse = Matrix3x3<Real> { c00 * invDet, (M(0, 2) * M(2, 1) - M(0, 1) * M(2, 2)) * invDet, (M(0, 1) * M(1, 2) - M(0, 2) * M(1, 1)) * invDet, c10 * invDet, (M(0, 0) * M(2, 2) - M(0, 2) * M(2, 0)) * invDet, (M(0, 2) * M(1, 0) - M(0, 0) * M(1, 2)) * invDet, c20 * invDet, (M(0, 1) * M(2, 0) - M(0, 0) * M(2, 1)) * invDet, (M(0, 0) * M(1, 1) - M(0, 1) * M(1, 0)) * invDet }; invertible = true; } else { inverse.MakeZero(); invertible = false; } if (reportInvertibility) { *reportInvertibility = invertible; } return inverse; } template <typename Real> Matrix3x3<Real> Adjoint(Matrix3x3<Real> const& M) { return Matrix3x3<Real> { M(1, 1)* M(2, 2) - M(1, 2) * M(2, 1), M(0, 2)* M(2, 1) - M(0, 1) * M(2, 2), M(0, 1)* M(1, 2) - M(0, 2) * M(1, 1), M(1, 2)* M(2, 0) - M(1, 0) * M(2, 2), M(0, 0)* M(2, 2) - M(0, 2) * M(2, 0), M(0, 2)* M(1, 0) - M(0, 0) * M(1, 2), M(1, 0)* M(2, 1) - M(1, 1) * M(2, 0), M(0, 1)* M(2, 0) - M(0, 0) * M(2, 1), M(0, 0)* M(1, 1) - M(0, 1) * M(1, 0) }; } template <typename Real> Real Determinant(Matrix3x3<Real> const& M) { Real c00 = M(1, 1) * M(2, 2) - M(1, 2) * M(2, 1); Real c10 = M(1, 2) * M(2, 0) - M(1, 0) * M(2, 2); Real c20 = M(1, 0) * M(2, 1) - M(1, 1) * M(2, 0); Real det = M(0, 0) * c00 + M(0, 1) * c10 + M(0, 2) * c20; return det; } template <typename Real> Real Trace(Matrix3x3<Real> const& M) { Real trace = M(0, 0) + M(1, 1) + M(2, 2); return trace; } // Multiply M and V according to the user-selected convention. If it is // GTE_USE_MAT_VEC, the function returns M*V. If it is GTE_USE_VEC_MAT, // the function returns V*M. This function is provided to hide the // preprocessor symbols in the GTEngine sample applications. template <typename Real> Vector3<Real> DoTransform(Matrix3x3<Real> const& M, Vector3<Real> const& V) { #if defined(GTE_USE_MAT_VEC) return M * V; #else return V * M; #endif } template <typename Real> Matrix3x3<Real> DoTransform(Matrix3x3<Real> const& A, Matrix3x3<Real> const& B) { #if defined(GTE_USE_MAT_VEC) return A * B; #else return B * A; #endif } // For GTE_USE_MAT_VEC, the columns of an invertible matrix form a basis // for the range of the matrix. For GTE_USE_VEC_MAT, the rows of an // invertible matrix form a basis for the range of the matrix. These // functions allow you to access the basis vectors. The caller is // responsible for ensuring that the matrix is invertible (although the // inverse is not calculated by these functions). template <typename Real> void SetBasis(Matrix3x3<Real>& M, int32_t i, Vector3<Real> const& V) { #if defined(GTE_USE_MAT_VEC) return M.SetCol(i, V); #else return M.SetRow(i, V); #endif } template <typename Real> Vector3<Real> GetBasis(Matrix3x3<Real> const& M, int32_t i) { #if defined(GTE_USE_MAT_VEC) return M.GetCol(i); #else return M.GetRow(i); #endif } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ParametricCurve.h
.h
10,741
309
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.08 #pragma once #include <Mathematics/Integration.h> #include <Mathematics/RootsBisection.h> #include <Mathematics/Vector.h> namespace gte { template <int32_t N, typename Real> class ParametricCurve { protected: // Abstract base class for a parameterized curve X(t), where t is the // parameter in [tmin,tmax] and X is an N-tuple position. The first // constructor is for single-segment curves. The second constructor is // for multiple-segment curves. The times must be strictly increasing. ParametricCurve(Real tmin, Real tmax) : mTime(2), mSegmentLength(1, (Real)0), mAccumulatedLength(1, (Real)0), mRombergOrder(DEFAULT_ROMBERG_ORDER), mMaxBisections(DEFAULT_MAX_BISECTIONS), mConstructed(false) { mTime[0] = tmin; mTime[1] = tmax; } ParametricCurve(int32_t numSegments, Real const* times) : mTime(static_cast<size_t>(numSegments) + 1), mSegmentLength(numSegments, (Real)0), mAccumulatedLength(numSegments, (Real)0), mRombergOrder(DEFAULT_ROMBERG_ORDER), mMaxBisections(DEFAULT_MAX_BISECTIONS), mConstructed(false) { std::copy(times, times + numSegments + 1, mTime.begin()); } public: virtual ~ParametricCurve() { } // To validate construction, create an object as shown: // DerivedClassCurve<N, Real> curve(parameters); // if (!curve) { <constructor failed, handle accordingly>; } inline operator bool() const { return mConstructed; } // Member access. inline Real GetTMin() const { return mTime.front(); } inline Real GetTMax() const { return mTime.back(); } inline int32_t GetNumSegments() const { return static_cast<int32_t>(mSegmentLength.size()); } inline Real const* GetTimes() const { return &mTime[0]; } // This function applies only when the first constructor is used (two // times rather than a sequence of three or more times). void SetTimeInterval(Real tmin, Real tmax) { if (mTime.size() == 2) { mTime[0] = tmin; mTime[1] = tmax; } } // Parameters used in GetLength(...), GetTotalLength() and // GetTime(...). // The default value is 8. inline void SetRombergOrder(int32_t order) { mRombergOrder = std::max(order, 1); } // The default value is 1024. inline void SetMaxBisections(uint32_t maxBisections) { mMaxBisections = std::max(maxBisections, 1u); } // Evaluation of the curve. The function supports derivative // calculation through order 3; that is, order <= 3 is required. If // you want/ only the position, pass in order of 0. If you want the // position and first derivative, pass in order of 1, and so on. The // output array 'jet' must have enough storage to support the maximum // order. The values are ordered as: position, first derivative, // second derivative, third derivative. enum { SUP_ORDER = 4 }; virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const = 0; void Evaluate(Real t, uint32_t order, Real* values) const { Evaluate(t, order, reinterpret_cast<Vector<N, Real>*>(values)); } // Differential geometric quantities. Vector<N, Real> GetPosition(Real t) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(t, 0, jet.data()); return jet[0]; } Vector<N, Real> GetTangent(Real t) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(t, 1, jet.data()); Normalize(jet[1]); return jet[1]; } Real GetSpeed(Real t) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(t, 1, jet.data()); return Length(jet[1]); } Real GetLength(Real t0, Real t1) const { std::function<Real(Real)> speed = [this](Real t) { return GetSpeed(t); }; if (mSegmentLength[0] == (Real)0) { // Lazy initialization of lengths of segments. int32_t const numSegments = static_cast<int32_t>(mSegmentLength.size()); Real accumulated = (Real)0; for (int32_t i = 0, ip1 = 1; i < numSegments; ++i, ++ip1) { mSegmentLength[i] = Integration<Real>::Romberg(mRombergOrder, mTime[i], mTime[ip1], speed); accumulated += mSegmentLength[i]; mAccumulatedLength[i] = accumulated; } } t0 = std::max(t0, GetTMin()); t1 = std::min(t1, GetTMax()); auto iter0 = std::lower_bound(mTime.begin(), mTime.end(), t0); int32_t index0 = static_cast<int32_t>(iter0 - mTime.begin()); auto iter1 = std::lower_bound(mTime.begin(), mTime.end(), t1); int32_t index1 = static_cast<int32_t>(iter1 - mTime.begin()); Real length; if (index0 < index1) { length = (Real)0; if (t0 < *iter0) { length += Integration<Real>::Romberg(mRombergOrder, t0, mTime[index0], speed); } int32_t isup; if (t1 < *iter1) { length += Integration<Real>::Romberg(mRombergOrder, mTime[static_cast<size_t>(index1) - 1], t1, speed); isup = index1 - 1; } else { isup = index1; } for (int32_t i = index0; i < isup; ++i) { length += mSegmentLength[i]; } } else { length = Integration<Real>::Romberg(mRombergOrder, t0, t1, speed); } return length; } Real GetTotalLength() const { if (mAccumulatedLength.back() == (Real)0) { // Lazy evaluation of the accumulated length array. return GetLength(mTime.front(), mTime.back()); } return mAccumulatedLength.back(); } // Inverse mapping of s = Length(t) given by t = Length^{-1}(s). The // inverse length function generally cannot be written in closed form, // in which case it is not directly computable. Instead, we can // specify s and estimate the root t for F(t) = Length(t) - s. The // derivative is F'(t) = Speed(t) >= 0, so F(t) is nondecreasing. To // be robust, we use bisection to locate the root, although it is // possible to use a hybrid of Newton's method and bisection. For // details, see the document // https://www.geometrictools.com/Documentation/MovingAlongCurveSpecifiedSpeed.pdf Real GetTime(Real length) const { if (length > (Real)0) { if (length < GetTotalLength()) { std::function<Real(Real)> F = [this, &length](Real t) { return Integration<Real>::Romberg(mRombergOrder, mTime.front(), t, [this](Real z) { return GetSpeed(z); }) - length; }; // We know that F(tmin) < 0 and F(tmax) > 0, which allows us to // use bisection. Rather than bisect the entire interval, let's // narrow it down with a reasonable initial guess. Real ratio = length / GetTotalLength(); Real omratio = (Real)1 - ratio; Real tmid = omratio * mTime.front() + ratio * mTime.back(); Real fmid = F(tmid); if (fmid > (Real)0) { RootsBisection<Real>::Find(F, mTime.front(), tmid, (Real)-1, (Real)1, mMaxBisections, tmid); } else if (fmid < (Real)0) { RootsBisection<Real>::Find(F, tmid, mTime.back(), (Real)-1, (Real)1, mMaxBisections, tmid); } return tmid; } else { return mTime.back(); } } else { return mTime.front(); } } // Compute a subset of curve points according to the specified attribute. // The input 'numPoints' must be two or larger. void SubdivideByTime(int32_t numPoints, Vector<N, Real>* points) const { Real delta = (mTime.back() - mTime.front()) / (Real)(numPoints - 1); for (int32_t i = 0; i < numPoints; ++i) { Real t = mTime.front() + delta * i; points[i] = GetPosition(t); } } void SubdivideByLength(int32_t numPoints, Vector<N, Real>* points) const { Real delta = GetTotalLength() / (Real)(numPoints - 1); for (int32_t i = 0; i < numPoints; ++i) { Real length = delta * i; Real t = GetTime(length); points[i] = GetPosition(t); } } protected: enum { DEFAULT_ROMBERG_ORDER = 8, DEFAULT_MAX_BISECTIONS = 1024 }; std::vector<Real> mTime; mutable std::vector<Real> mSegmentLength; mutable std::vector<Real> mAccumulatedLength; int32_t mRombergOrder; uint32_t mMaxBisections; bool mConstructed; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrCylinder3Cylinder3.h
.h
22,532
592
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once // Test for intersection of two finite cylinders using the method of // separating axes. The algorithm is described in the document // https://www.geometrictools.com/Documentation/IntersectionOfCylinders.pdf #include <Mathematics/TIQuery.h> #include <Mathematics/Cylinder3.h> #include <Mathematics/Vector3.h> #include <Mathematics/RootsBisection.h> #include <Mathematics/Minimize1.h> #include <vector> namespace gte { template <typename T> class TIQuery<T, Cylinder3<T>, Cylinder3<T>> { public: struct Result { Result() : separated(false), separatingDirection{} { } bool separated; Vector3<T> separatingDirection; }; TIQuery(size_t numLines) : mNumLines(numLines), mW0{}, mR0(static_cast<T>(0)), mHalfH0(static_cast<T>(0)), mW1{}, mR1(static_cast<T>(0)), mHalfH1(static_cast<T>(0)), mDelta{}, mLengthDelta(static_cast<T>(0)), mW0xW1{}, mBasis{}, mLineOrigin{}, mLineDirection{}, mQ0{}, mQ1{}, mDiffQ0P{}, mDiffQ1P{}, mDGDT([this](T const& t) { return DGDT(t); }) { } Result operator()(Cylinder3<T> const& cylinder0, Cylinder3<T> const& cylinder1) { // The constructor sets result.separated to false and // result.separatingDirection to (0,0,0). Result result{}; T const zero = static_cast<T>(0); mDelta = cylinder1.axis.origin - cylinder0.axis.origin; mLengthDelta = Length(mDelta); if (mLengthDelta == zero) { return result; } T const half = static_cast<T>(0.5); mW0 = cylinder0.axis.direction; mR0 = cylinder0.radius; mHalfH0 = half * cylinder0.height; mW1 = cylinder1.axis.direction; mR1 = cylinder1.radius; mHalfH1 = half * cylinder1.height; mW0xW1 = Cross(mW0, mW1); T lengthW0xW1 = Length(mW0xW1), test = zero; if (lengthW0xW1 > zero) { // Test for separation by W0. T absDotW0W1 = std::fabs(Dot(mW0, mW1)); T absDotW0Delta = std::fabs(Dot(mW0, mDelta)); test = mR1 * lengthW0xW1 + mHalfH0 + mHalfH1 * absDotW0W1 - absDotW0Delta; if (test < zero) { result.separated = true; result.separatingDirection = mW0; return result; } // Test for separation by W1. T absDotW1Delta = std::fabs(Dot(mW1, mDelta)); test = mR0 * lengthW0xW1 + mHalfH0 * absDotW0W1 + mHalfH1 - absDotW1Delta; if (test < zero) { result.separated = true; result.separatingDirection = mW1; return result; } // Test for separation by W0xW1. T absDotW0xW1Delta = std::fabs(Dot(mW0xW1, mDelta)); test = (mR0 + mR1) * lengthW0xW1 - absDotW0xW1Delta; if (test < zero) { result.separated = true; result.separatingDirection = mW0xW1; Normalize(result.separatingDirection); return result; } // Test for separation by Delta. test = mR0 * Length(Cross(mDelta, mW0)) + mR1 * Length(Cross(mDelta, mW1)) + mHalfH0 * absDotW0Delta + mHalfH1 * absDotW1Delta - Dot(mDelta, mDelta); if (test < zero) { result.separated = true; result.separatingDirection = mDelta; Normalize(result.separatingDirection); return result; } // Test for separation by other directions. This function // implements the minimum search described in the PDF. if (SeparatedByOtherDirections(result.separatingDirection)) { result.separated = true; return result; } } else { // Test for separation by height. T dotDeltaW0 = Dot(mDelta, mW0); test = mHalfH0 + mHalfH1 - std::fabs(dotDeltaW0); if (test < zero) { result.separated = true; result.separatingDirection = mW0; return result; } // Test for separation radially. test = mR0 + mR1 - Length(Cross(mDelta, mW0)); if (test < zero) { result.separated = true; result.separatingDirection = mDelta - dotDeltaW0 * mW0; Normalize(result.separatingDirection); return result; } } return result; } private: // Maximum number of iterations to locate an endpoint of a // root-bounding interval for g'(t). size_t const imax = static_cast<size_t>( std::numeric_limits<T>::max_exponent); // Maximum number of bisections for the bisector that locates // roots of g'(t). uint32_t const maxBisections = static_cast<uint32_t>( std::numeric_limits<T>::max_exponent - std::numeric_limits<T>::min_exponent + std::numeric_limits<T>::digits); bool SeparatedByOtherDirections(Vector3<T>& separatingDirection) { // Convert to the coordinate system where N = Delta/|Delta| is the // north pole of the hemisphere to be searched. Using the notation // of the PDF, N is mBasis[1], U is mBasis[0] and V is mBasis[1]. // The ComputeOrthonormalBasis function will normalize mBasis[2] // before computing orthogonal vectors mBasis[0] and mBasis[1]. std::array<Vector3<T>, 3> tempBasis{}; // { N, U, V } tempBasis[0] = mDelta; ComputeOrthogonalComplement(1, tempBasis.data()); mBasis[0] = std::move(tempBasis[1]); // { U, V, N } mBasis[1] = std::move(tempBasis[2]); mBasis[2] = std::move(tempBasis[0]); mW0 = { Dot(mBasis[0], mW0), Dot(mBasis[1], mW0), Dot(mBasis[2], mW0) }; mW1 = { Dot(mBasis[0], mW1), Dot(mBasis[1], mW1), Dot(mBasis[2], mW1) }; mW0xW1 = { Dot(mBasis[0], mW0xW1), Dot(mBasis[1], mW0xW1), Dot(mBasis[2], mW0xW1) }; // The axis directions and their cross product must be in the // hemisphere with north pole N. T const zero = static_cast<T>(0); if (mW0[2] < zero) { mW0 = -mW0; } if (mW1[2] < zero) { mW1 = -mW1; } if (mW0xW1[2] < zero) { mW0xW1 = -mW0xW1; } // Compute the common origin for the line discontinuities. T const one = static_cast<T>(1); mLineOrigin = { mW0xW1[0] / mW0xW1[2], mW0xW1[1] / mW0xW1[2], one }; // Compute the point discontinuities. mQ0 = { mW0[0] / mW0[2], mW0[1] / mW0[2], one }; mQ1 = { mW1[0] / mW1[2], mW1[1] / mW1[2], one }; mDiffQ0P = mQ0 - mLineOrigin; mDiffQ1P = mQ1 - mLineOrigin; // Search the lines with common origin for a separating direction. std::vector<T> lineMinimum(mNumLines + 1); T multiplier = static_cast<T>(GTE_C_PI) / static_cast<T>(mNumLines); T tMin = zero, gMin = zero; for (size_t i = 0; i < mNumLines; ++i) { // The line direction is (cos(angle), sin(angle), 0). T angle = multiplier * static_cast<T>(i); // Compute the minimum of g(t) on the line P + t * L(angle). mLineDirection = { std::cos(angle), std::sin(angle), zero }; ComputeLineMinimum(mLineDirection, tMin, gMin); lineMinimum[i] = gMin; // Exit early when a line minimum is negative. if (gMin < zero) { // Transform to the original coordinate system. Vector3<T> polePoint = mLineOrigin + tMin * mLineDirection; separatingDirection = polePoint[0] * mBasis[0] + polePoint[1] * mBasis[1] + mBasis[2]; Normalize(separatingDirection); return true; } } lineMinimum[mNumLines] = lineMinimum[0]; // The mNumLines samples did not produce a negative minimum. Use a // derivativeless minimizer to refine the search. // The function to minimize. The input is the angle of the line // and the output is the minimum of g(t) along that line. auto lineFunction = [this, &tMin, &zero](T const& angle) { mLineDirection = { std::cos(angle), std::sin(angle), zero }; T gMin = zero; ComputeLineMinimum(mLineDirection, tMin, gMin); return gMin; }; Minimize1<T> minimizer(lineFunction, 1, maxBisections, zero, zero); // Locate a triple of angles that bracket the minimum. std::array<size_t, 3> bracket = { mNumLines - 1, 0, 1 }; for (size_t i0 = 0, i1 = 1, i2 = 2; i2 <= mNumLines; i0 = i1, i1 = i2++) { if (lineMinimum[i1] < lineMinimum[bracket[1]]) { bracket = { i0, i1, i2 }; } } T angle0 = multiplier * static_cast<T>(bracket[0]); T angle1 = multiplier * static_cast<T>(bracket[1]); T angle2 = multiplier * static_cast<T>(bracket[2]); // If bracket = { mNumLines - 1, 0, 1 }, then angle0 > angle1. // The minimizer expects angle0 < angle1, so subtract pi from // angle0 to generate an equivalent angle. if (bracket[1] == 0) { angle0 -= static_cast<T>(GTE_C_PI); } T angleMin = zero; minimizer.GetMinimum(angle0, angle2, angle1, angleMin, gMin); if (gMin < zero) { // Reconstruct the tMin value associated with angleMin. lineFunction(angleMin); // Transform to the original coordinate system. Vector3<T> polePoint = mLineOrigin + tMin * mLineDirection; separatingDirection = polePoint[0] * mBasis[0] + polePoint[1] * mBasis[1] + mBasis[2]; Normalize(separatingDirection); return true; } return false; } void ComputeLineMinimum(Vector3<T> const& L, T& tMin, T& gMin) const { T const zero = static_cast<T>(0); Vector3<T> LPerp{ L[1], -L[0] , zero }; T dgdt0n = zero, dgdt0p = zero, dgdt1n = zero, dgdt1p = zero; if (Dot(LPerp, mDiffQ0P) != zero) { // Q0 is not on the line P + t * L(angle). if (Dot(LPerp, mDiffQ1P) != zero) { // Q1 is not on the line P + t * L(angle). LimitsDGDTZero(dgdt0n, dgdt0p); ComputeMinimumSingularZero(dgdt0n, dgdt0p, tMin, gMin); } else { // Q1 is not on the line P + t * L(angle). LimitsDGDTZero(dgdt0n, dgdt0p); LimitsDGDTOneQ1(dgdt1n, dgdt1p); ComputeMinimumSingularZeroOne(dgdt0n, dgdt0p, dgdt1n, dgdt1p, tMin, gMin); } } else { // Q0 is on the line P + t * L(angle). LimitsDGDTZero(dgdt0n, dgdt0p); LimitsDGDTOneQ0(dgdt1n, dgdt1p); ComputeMinimumSingularZeroOne(dgdt0n, dgdt0p, dgdt1n, dgdt1p, tMin, gMin); } } // Compute one-sided limits along the line D(t) = P+t*L at t = 0. void LimitsDGDTZero(T& dgdt0n, T& dgdt0p) const { Vector3<T> crossPW0 = Cross(mLineOrigin, mW0); Vector3<T> crossPW1 = Cross(mLineOrigin, mW1); Vector3<T> crossLW0 = Cross(mLineDirection, mW0); Vector3<T> crossLW1 = Cross(mLineDirection, mW1); T dotLW0 = Dot(mLineDirection, mW0); T dotLW1 = Dot(mLineDirection, mW1); T r0Term = mR0 * Dot(crossPW0, crossLW0) / Length(crossPW0); T r1Term = mR1 * Dot(crossPW1, crossLW1) / Length(crossPW1); T sumRTerms = r0Term + r1Term; T prdH0Term = mHalfH0 * std::fabs(dotLW0); T prdH1Term = mHalfH1 * std::fabs(dotLW1); T sumHTerms = prdH0Term + prdH1Term; dgdt0n = sumRTerms - sumHTerms; dgdt0p = sumRTerms + sumHTerms; } // Compute one-sided limits along the line D(t) = (1-t)*P + t*(Q0-P) // at t = 1. void LimitsDGDTOneQ0(T& dgdt1n, T& dgdt1p) const { Vector3<T> crossQ0W1 = Cross(mQ0, mW1); Vector3<T> crossLW0 = Cross(mLineDirection, mW0); Vector3<T> crossLW1 = Cross(mLineDirection, mW1); T dotLW0 = Dot(mLineDirection, mW0); T dotLW1 = Dot(mLineDirection, mW1); T r0Term = mR0 * Length(crossLW0); T r1Term = mR1 * Dot(crossQ0W1, crossLW1) / Length(crossQ0W1); T prdH0Term = mHalfH0 * std::fabs(dotLW0); T prdH1Term = mHalfH1 * std::fabs(dotLW1); T sumHTerms = prdH0Term + prdH1Term; T sumRHTerms = r1Term + sumHTerms; dgdt1n = sumRHTerms - r0Term; dgdt1p = sumRHTerms + r0Term; } // Compute one-sided limits along the line D(t) = (1-t)*P + t*(Q1-P) // at t = 1. void LimitsDGDTOneQ1(T& dgdt1n, T& dgdt1p) const { Vector3<T> crossQ1W0 = Cross(mQ1, mW0); Vector3<T> crossLW0 = Cross(mLineDirection, mW0); Vector3<T> crossLW1 = Cross(mLineDirection, mW1); T dotLW0 = Dot(mLineDirection, mW0); T dotLW1 = Dot(mLineDirection, mW1); T r0Term = mR0 * Dot(crossQ1W0, crossLW0) / Length(crossQ1W0); T r1Term = mR1 * Length(crossLW1); T prdH0Term = mHalfH0 * std::fabs(dotLW0); T prdH1Term = mHalfH1 * std::fabs(dotLW1); T sumHTerms = prdH0Term + prdH1Term; T sumRHTerms = r0Term + sumHTerms; dgdt1n = sumRHTerms - r1Term; dgdt1p = sumRHTerms + r1Term; } void LimitsDGDTInfinity(T& dgdtInfinity) { Vector3<T> crossLW0 = Cross(mLineDirection, mW0); Vector3<T> crossLW1 = Cross(mLineDirection, mW1); T dotLW0 = Dot(mLineDirection, mW0); T dotLW1 = Dot(mLineDirection, mW1); dgdtInfinity = mR0 * Length(crossLW0) + mR1 * Length(crossLW1) + mHalfH0 * std::fabs(dotLW0) + mHalfH1 * std::fabs(dotLW1); } // Evaluation of g(t) = F(D(t)). T G(T const& t) const { Vector3<T> D = mLineOrigin + mLineDirection * t; Vector3<T> crossDW0 = Cross(D, mW0); Vector3<T> crossDW1 = Cross(D, mW1); T dotDW0 = Dot(D, mW0); T dotDW1 = Dot(D, mW1); T r0Term = mR0 * Length(crossDW0); T r1Term = mR1 * Length(crossDW1); T h0Term = mHalfH0 * std::fabs(dotDW0); T h1Term = mHalfH1 * std::fabs(dotDW1); T result = r0Term + r1Term + h0Term + h1Term - mLengthDelta; return result; }; // Evaluation of g'(t) except at derivative singularities // t = 0 and t = 1. T DGDT(T const& t) const { Vector3<T> D = mLineOrigin + mLineDirection * t; Vector3<T> crossDW0 = Cross(D, mW0); Vector3<T> crossDW1 = Cross(D, mW1); Vector3<T> crossLW0 = Cross(mLineDirection, mW0); Vector3<T> crossLW1 = Cross(mLineDirection, mW1); T dotLW0 = Dot(mLineDirection, mW0); T dotLW1 = Dot(mLineDirection, mW1); T r0Term = mR0 * Dot(crossDW0, crossLW0) / Length(crossDW0); T r1Term = mR1 * Dot(crossDW1, crossLW1) / Length(crossDW1); T sgn = sign(t); T h0Term = mHalfH0 * std::fabs(dotLW0) * sgn; T h1Term = mHalfH1 * std::fabs(dotLW1) * sgn; T result = r0Term + r1Term + h0Term + h1Term; return result; } void ComputeMinimumSingularZero(T const& dgdt0n, T const& dgdt0p, T& tMin, T& gMin) const { // Determine the interval that contains the unique root of g'(t) // by analyzing the one-sided limits g'(0^-) and g'(0^+). T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const two = static_cast<T>(2); T const negOne = static_cast<T>(-1); if (dgdt0n > zero) { // The root of g'(t) occurs on (-infinity,0). T t0 = negOne, dgdtT0 = zero; for (size_t i = 0; i < imax; ++i) { dgdtT0 = DGDT(t0); if (dgdtT0 < zero) { break; } t0 *= two; } (void)RootsBisection<T>::Find(mDGDT, t0, zero, dgdtT0, dgdt0n, maxBisections, tMin); } else if (dgdt0p < zero) { // The root of g'(t) occurs on (0,+infinity). T t1 = one, dgdtT1 = zero; for (size_t i = 0; i < imax; ++i) { dgdtT1 = DGDT(t1); if (dgdtT1 > zero) { break; } t1 *= two; } (void)RootsBisection<T>::Find(mDGDT, zero, t1, dgdt0p, dgdtT1, maxBisections, tMin); } else { // At this time, g'(0^-) <= 0 <= g'(0+). The minimum of g(t) // occurs at g(0). tMin = zero; } gMin = G(tMin); } void ComputeMinimumSingularZeroOne(T const& dgdt0n, T const& dgdt0p, T const& dgdt1n, T const& dgdt1p, T& tMin, T& gMin) const { // Determine the interval that contains the unique root of g'(t) // by analyzing the one-sided limits g'(0^-), g'(0^+), g'(1^-) // and g'(1^+). T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const two = static_cast<T>(2); T const negOne = static_cast<T>(-1); if (dgdt0n > zero) { // The root of g'(t) occurs on (-infinity,0). T t0 = negOne, dgdtT0 = zero; for (size_t i = 0; i < imax; ++i) { dgdtT0 = DGDT(t0); if (dgdtT0 < zero) { break; } t0 *= two; } (void)RootsBisection<T>::Find(mDGDT, t0, zero, dgdtT0, dgdt0n, maxBisections, tMin); } else if (dgdt0p < zero) { // The root of g'(t) occurs on (1,+infinity). T t1 = two, dgdtT1 = zero; for (size_t i = 0; i < imax; ++i) { dgdtT1 = DGDT(t1); if (dgdtT1 > zero) { break; } t1 *= two; } (void)RootsBisection<T>::Find(mDGDT, one, t1, dgdt1p, dgdtT1, maxBisections, tMin); } else { // At this time, g'(0^-) <= 0 <= g'(1^+). if (dgdt0p < zero) { if (dgdt1n > zero) { // The root of g'(t) occurs on (0,1). (void)RootsBisection<T>::Find(mDGDT, zero, one, dgdt0p, dgdt1n, maxBisections, tMin); } else { // The minimum of g(t) occurs at g(1). tMin = one; } } else { // The minimum of g(t) occurs at g(0). tMin = zero; } } gMin = G(tMin); } // The number of lines to search in the pole plane for the minimum. size_t mNumLines; // Cylinder 0. Vector3<T> mW0; // W0 T mR0; // r0 T mHalfH0; // h0/2 // Cylinder 1. Vector3<T> mW1; // W1 T mR1; // r1 T mHalfH1; // h1/2 // Members dependent on both cylinders. Vector3<T> mDelta; // C1 - C0 (difference of centers) T mLengthDelta; // Length(Delta) Vector3<T> mW0xW1; // Cross(W0, W1); std::array<Vector3<T>, 3> mBasis; // { U, V, N } // Members to support the line search for a minimum; Vector3<T> mLineOrigin, mLineDirection, mQ0, mQ1, mDiffQ0P, mDiffQ1P; std::function<T(T const&)> mDGDT; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprTorus3.h
.h
16,908
397
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/ApprOrthogonalPlane3.h> #include <Mathematics/RootsPolynomial.h> #include <Mathematics/GaussNewtonMinimizer.h> #include <Mathematics/LevenbergMarquardtMinimizer.h> // Let the torus center be C with plane of symmetry containing C and having // directions D0 and D1. The axis of symmetry is the line containing C and // having direction N (the plane normal). The radius from the center of the // torus is r0 and the radius of the tube of the torus is r1. A point P may // be written as P = C + x*D0 + y*D1 + z*N, where matrix [D0 D1 N] is // orthogonal and has determinant 1. Thus, x = Dot(D0,P-C), y = Dot(D1,P-C) // and z = Dot(N,P-C). The implicit equation defining the torus is // (|P-C|^2 + r0^2 - r1^2)^2 - 4*r0^2*(|P-C|^2 - (Dot(N,P-C))^2) = 0 // Observe that D0 and D1 are not present in the equation, which is to be // expected by the symmetry. // // Define u = r0^2 and v = r0^2 - r1^2. Define // F(X;C,N,u,v) = (|P-C|^2 + v)^2 - 4*u*(|P-C|^2 - (Dot(N,P-C))^2) // The nonlinear least-squares fitting of points {X[i]}_{i=0}^{n-1} computes // C, N, u and v to minimize the error function // E(C,N,u,v) = sum_{i=0}^{n-1} F(X[i];C,N,u,v)^2 // When the sample points are distributed so that there is large coverage // by a purported fitted torus, a variation on fitting is the following. // Compute the least-squares plane with origin C and normal N that fits the // points. Define G(X;u,v) = F(X;C,N,u,v); the only variables now are u and // v. Define L[i] = |X[i]-C|^2 and S[i] = 4 * (L[i] - (Dot(N,X[i]-C))^2). // Define the error function // H(u,v) = sum_{i=0}^{n-1} G(X[i];u,v)^2 // = sum_{i=0}^{n-1} ((v + L[i])^2 - S[i]*u)^2 // The first-order partial derivatives are // dH/du = -2 sum_{i=0}^{n-1} ((v + L[i])^2 - S[i]*u) * S[i] // dH/dv = 4 sum_{i=0}^{n-1} ((v + L[i])^2 - S[i]*u) * (v + L[i]) // Setting these to zero and expanding the terms, we have // 0 = a2 * v^2 + a1 * v + a0 - b0 * u // 0 = c3 * v^3 + c2 * v^2 + c1 * v + c0 - u * (d1 * v + d0) // where a2 = sum(S[i]), a1 = 2*sum(S[i]*L[i]), a2 = sum(S[i]*L[i]^2), // b0 = sum(S[i]^2), c3 = sum(1) = n, c2 = 3*sum(L[i]), c1 = 3*sum(L[i]^2), // c0 = sum(L[i]^3), d1 = sum(S[i]) = a2 and d0 = sum(S[i]*L[i]) = a1/2. // The first equation is solved for // u = (a2 * v^2 + a1 * v + a0) / b0 = e2 * v^2 + e1 * v + e0 // and substituted into the second equation to obtain a cubic polynomial // equation // 0 = f3 * v^3 + f2 * v^2 + f1 * v + f0 // where f3 = c3 - d1 * e2, f2 = c2 - d1 * e1 - d0 * e2, // f1 = c1 - d1 * e0 - d0 * e1 and f0 = c0 - d0 * e0. The positive v-roots // are computed. For each root compute the corresponding u. For all pairs // (u,v) with u > v > 0, evaluate H(u,v) and choose the pair that minimizes // H(u,v). The torus radii are r0 = sqrt(u) and r1 = sqrt(u - v). namespace gte { template <typename Real> class ApprTorus3 { public: ApprTorus3() { // The unit-length normal is // N = (cos(theta)*sin(phi), sin(theta)*sin(phi), cos(phi) // for theta in [0,2*pi) and phi in [0,*pi). The radii are // encoded as // u = r0^2, v = r0^2 - r1^2 // with 0 < v < u. Let D = C - X[i] where X[i] is a sample point. // The parameters P = (C0,C1,C2,theta,phi,u,v). // F[i](C,theta,phi,u,v) = // (|D|^2 + v)^2 - 4*u*(|D|^2 - Dot(N,D)^2) mFFunction = [this](GVector<Real> const& P, GVector<Real>& F) { Real csTheta = std::cos(P[3]); Real snTheta = std::sin(P[3]); Real csPhi = std::cos(P[4]); Real snPhi = std::sin(P[4]); Vector<3, Real> C = { P[0], P[1], P[2] }; Vector<3, Real> N = { csTheta * snPhi, snTheta * snPhi, csPhi }; Real u = P[5]; Real v = P[6]; for (int32_t i = 0; i < mNumPoints; ++i) { Vector<3, Real> D = C - mPoints[i]; Real DdotD = Dot(D, D), NdotD = Dot(N, D); Real sum = DdotD + v; F[i] = sum * sum - (Real)4 * u * (DdotD - NdotD * NdotD); } }; // dF[i]/dC = 4 * (|D|^2 + v) * D - 8 * u * (I - N*N^T) * D // dF[i]/dTheta = 8 * u * Dot(dN/dTheta, D) // dF[i]/dPhi = 8 * u * Dot(dN/dPhi, D) // dF[i]/du = -4 * u * (|D|^2 - Dot(N,D)^2) // dF[i]/dv = 2 * (|D|^2 + v) mJFunction = [this](GVector<Real> const& P, GMatrix<Real>& J) { Real const r2(2), r4(4), r8(8); Real csTheta = std::cos(P[3]); Real snTheta = std::sin(P[3]); Real csPhi = std::cos(P[4]); Real snPhi = std::sin(P[4]); Vector<3, Real> C = { P[0], P[1], P[2] }; Vector<3, Real> N = { csTheta * snPhi, snTheta * snPhi, csPhi }; Real u = P[5]; Real v = P[6]; for (int32_t row = 0; row < mNumPoints; ++row) { Vector<3, Real> D = C - mPoints[row]; Real DdotD = Dot(D, D), NdotD = Dot(N, D); Real sum = DdotD + v; Vector<3, Real> dNdTheta{ -snTheta * snPhi, csTheta * snPhi, (Real)0 }; Vector<3, Real> dNdPhi{ csTheta * csPhi, snTheta * csPhi, -snPhi }; Vector<3, Real> temp = r4 * sum * D - r8 * u * (D - NdotD * N); J(row, 0) = temp[0]; J(row, 1) = temp[1]; J(row, 2) = temp[2]; J(row, 3) = r8 * u * Dot(dNdTheta, D); J(row, 4) = r8 * u * Dot(dNdPhi, D); J(row, 5) = -r4 * u * (DdotD - NdotD * NdotD); J(row, 6) = r2 * sum; } }; } // When the samples are distributed approximately uniformly near a // torus, use this method. For example, if the purported torus has // center (0,0,0) and normal (0,0,1), you want the (x,y,z) samples // to occur in all 8 octants. If the samples occur, say, only in // one octant, this method will estimate a C and N that are nowhere // near (0,0,0) and (0,0,1). The function sets the output variables // C, N, r0 and r1 as the fitted torus. // // The return value is a pair <bool,Real>. The first element is // 'true' when the estimate is valid, in which case the second // element is the least-squares error for that estimate. If any // unexpected condition occurs that prevents computing an estimate, // the first element is 'false' and the second element is // std::numeric_limits<Real>::max(). std::pair<bool, Real> operator()(int32_t numPoints, Vector<3, Real> const* points, Vector<3, Real>& C, Vector<3, Real>& N, Real& r0, Real& r1) const { ApprOrthogonalPlane3<Real> fitter; if (!fitter.Fit(numPoints, points)) { return std::make_pair(false, std::numeric_limits<Real>::max()); } C = fitter.GetParameters().first; N = fitter.GetParameters().second; Real const zero(0); Real a0 = zero, a1 = zero, a2 = zero, b0 = zero; Real c0 = zero, c1 = zero, c2 = zero, c3 = (Real)numPoints; for (int32_t i = 0; i < numPoints; ++i) { Vector<3, Real> delta = points[i] - C; Real dot = Dot(N, delta); Real L = Dot(delta, delta), L2 = L * L, L3 = L * L2; Real S = (Real)4 * (L - dot * dot), S2 = S * S; a2 += S; a1 += S * L; a0 += S * L2; b0 += S2; c2 += L; c1 += L2; c0 += L3; } Real d1 = a2; Real d0 = a1; a1 *= (Real)2; c2 *= (Real)3; c1 *= (Real)3; Real invB0 = (Real)1 / b0; Real e0 = a0 * invB0; Real e1 = a1 * invB0; Real e2 = a2 * invB0; Rational f0 = c0 - d0 * e0; Rational f1 = c1 - d1 * e0 - d0 * e1; Rational f2 = c2 - d1 * e1 - d0 * e2; Rational f3 = c3 - d1 * e2; std::map<Real, int32_t> rmMap; RootsPolynomial<Real>::SolveCubic(f0, f1, f2, f3, rmMap); Real hmin = std::numeric_limits<Real>::max(); Real umin = zero, vmin = zero; for (auto const& element : rmMap) { Real v = element.first; if (v > zero) { Real u = e0 + v * (e1 + v * e2); if (u > v) { Real h = zero; for (int32_t i = 0; i < numPoints; ++i) { Vector<3, Real> delta = points[i] - C; Real dot = Dot(N, delta); Real L = Dot(delta, delta); Real S = (Real)4 * (L - dot * dot); Real sum = v + L; Real term = sum * sum - S * u; h += term * term; } if (h < hmin) { hmin = h; umin = u; vmin = v; } } } } if (hmin == std::numeric_limits<Real>::max()) { return std::make_pair(false, std::numeric_limits<Real>::max()); } r0 = std::sqrt(umin); r1 = std::sqrt(umin - vmin); return std::make_pair(true, hmin); } // If you want to specify that C, N, r0 and r1 are the initial guesses // for the minimizer, set the parameter useTorusInputAsInitialGuess to // 'true'. If you want the function to compute initial guesses, set // useTorusInputAsInitialGuess to 'false'. A Gauss-Newton minimizer // is used to fit a torus using nonlinear least-squares. The fitted // torus is returned in C, N, r0 and r1. See GaussNewtonMinimizer.h // for a description of the least-squares algorithm and the parameters // that it requires. typename GaussNewtonMinimizer<Real>::Result operator()(int32_t numPoints, Vector<3, Real> const* points, size_t maxIterations, Real updateLengthTolerance, Real errorDifferenceTolerance, bool useTorusInputAsInitialGuess, Vector<3, Real>& C, Vector<3, Real>& N, Real& r0, Real& r1) const { mNumPoints = numPoints; mPoints = points; GaussNewtonMinimizer<Real> minimizer(7, mNumPoints, mFFunction, mJFunction); if (!useTorusInputAsInitialGuess) { operator()(numPoints, points, C, N, r0, r1); } GVector<Real> initial(7); // The initial guess for the plane origin. initial[0] = C[0]; initial[1] = C[1]; initial[2] = C[2]; // The initial guess for the plane normal. The angles must be // extracted for spherical coordinates. if (std::fabs(N[2]) < (Real)1) { initial[3] = std::atan2(N[1], N[0]); initial[4] = std::acos(N[2]); } else { initial[3] = (Real)0; initial[4] = (Real)0; } // The initial guess for the radii-related parameters. initial[5] = r0 * r0; initial[6] = initial[5] - r1 * r1; auto result = minimizer(initial, maxIterations, updateLengthTolerance, errorDifferenceTolerance); // No test is made for result.converged so that we return some // estimates of the torus. The caller can decide how to respond // when result.converged is false. C[0] = result.minLocation[0]; C[1] = result.minLocation[1]; C[2] = result.minLocation[2]; Real theta = result.minLocation[3]; Real phi = result.minLocation[4]; Real csTheta = std::cos(theta); Real snTheta = std::sin(theta); Real csPhi = std::cos(phi); Real snPhi = std::sin(phi); N[0] = csTheta * snPhi; N[1] = snTheta * snPhi; N[2] = csPhi; Real u = result.minLocation[5]; Real v = result.minLocation[6]; r0 = std::sqrt(u); r1 = std::sqrt(u - v); mNumPoints = 0; mPoints = nullptr; return result; } // If you want to specify that C, N, r0 and r1 are the initial guesses // for the minimizer, set the parameter useTorusInputAsInitialGuess to // 'true'. If you want the function to compute initial guesses, set // useTorusInputAsInitialGuess to 'false'. A Gauss-Newton minimizer // is used to fit a torus using nonlinear least-squares. The fitted // torus is returned in C, N, r0 and r1. See GaussNewtonMinimizer.h // for a description of the least-squares algorithm and the parameters // that it requires. typename LevenbergMarquardtMinimizer<Real>::Result operator()(int32_t numPoints, Vector<3, Real> const* points, size_t maxIterations, Real updateLengthTolerance, Real errorDifferenceTolerance, Real lambdaFactor, Real lambdaAdjust, size_t maxAdjustments, bool useTorusInputAsInitialGuess, Vector<3, Real>& C, Vector<3, Real>& N, Real& r0, Real& r1) const { mNumPoints = numPoints; mPoints = points; LevenbergMarquardtMinimizer<Real> minimizer(7, mNumPoints, mFFunction, mJFunction); if (!useTorusInputAsInitialGuess) { operator()(numPoints, points, C, N, r0, r1); } GVector<Real> initial(7); // The initial guess for the plane origin. initial[0] = C[0]; initial[1] = C[1]; initial[2] = C[2]; // The initial guess for the plane normal. The angles must be // extracted for spherical coordinates. if (std::fabs(N[2]) < (Real)1) { initial[3] = std::atan2(N[1], N[0]); initial[4] = std::acos(N[2]); } else { initial[3] = (Real)0; initial[4] = (Real)0; } // The initial guess for the radii-related parameters. initial[5] = r0 * r0; initial[6] = initial[5] - r1 * r1; auto result = minimizer(initial, maxIterations, updateLengthTolerance, errorDifferenceTolerance, lambdaFactor, lambdaAdjust, maxAdjustments); // No test is made for result.converged so that we return some // estimates of the torus. The caller can decide how to respond // when result.converged is false. C[0] = result.minLocation[0]; C[1] = result.minLocation[1]; C[2] = result.minLocation[2]; Real theta = result.minLocation[3]; Real phi = result.minLocation[4]; Real csTheta = std::cos(theta); Real snTheta = std::sin(theta); Real csPhi = std::cos(phi); Real snPhi = std::sin(phi); N[0] = csTheta * snPhi; N[1] = snTheta * snPhi; N[2] = csPhi; Real u = result.minLocation[5]; Real v = result.minLocation[6]; r0 = std::sqrt(u); r1 = std::sqrt(u - v); mNumPoints = 0; mPoints = nullptr; return result; } private: typedef BSRational<UIntegerAP32> Rational; mutable int32_t mNumPoints; mutable Vector<3, Real> const* mPoints; std::function<void(GVector<Real> const&, GVector<Real>&)> mFFunction; std::function<void(GVector<Real> const&, GMatrix<Real>&)> mJFunction; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Circle2.h
.h
3,490
115
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/DistPointLine.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector2.h> // The queries consider the circle to be a solid (disk). namespace gte { template <typename T> class TIQuery<T, Line2<T>, Circle2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line2<T> const& line, Circle2<T> const& circle) { Result result{}; DCPQuery<T, Vector2<T>, Line2<T>> plQuery; auto plResult = plQuery(circle.center, line); result.intersect = (plResult.distance <= circle.radius); return result; } }; template <typename T> class FIQuery<T, Line2<T>, Circle2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ (T)0, (T)0 }, point{ Vector2<T>::Zero(), Vector2<T>::Zero() } { } bool intersect; int32_t numIntersections; std::array<T, 2> parameter; std::array<Vector2<T>, 2> point; }; Result operator()(Line2<T> const& line, Circle2<T> const& circle) { Result result{}; DoQuery(line.origin, line.direction, circle, result); for (int32_t i = 0; i < result.numIntersections; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } return result; } protected: void DoQuery(Vector2<T> const& lineOrigin, Vector2<T> const& lineDirection, Circle2<T> const& circle, Result& result) { // Intersection of a the line P+t*D and the circle |X-C| = R. // The line direction is unit length. The t-value is a // real-valued root to the quadratic equation // 0 = |t*D+P-C|^2 - R^2 // = t^2 + 2*Dot(D,P-C)*t + |P-C|^2-R^2 // = t^2 + 2*a1*t + a0 // If there are two distinct roots, the order is t0 < t1. Vector2<T> diff = lineOrigin - circle.center; T a0 = Dot(diff, diff) - circle.radius * circle.radius; T a1 = Dot(lineDirection, diff); T discr = a1 * a1 - a0; if (discr > (T)0) { T root = std::sqrt(discr); result.intersect = true; result.numIntersections = 2; result.parameter[0] = -a1 - root; result.parameter[1] = -a1 + root; } else if (discr < (T)0) { result.intersect = false; result.numIntersections = 0; } else // discr == 0 { result.intersect = true; result.numIntersections = 1; result.parameter[0] = -a1; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GaussNewtonMinimizer.h
.h
9,562
233
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/CholeskyDecomposition.h> #include <functional> // Let F(p) = (F_{0}(p), F_{1}(p), ..., F_{n-1}(p)) be a vector-valued // function of the parameters p = (p_{0}, p_{1}, ..., p_{m-1}). The // nonlinear least-squares problem is to minimize the real-valued error // function E(p) = |F(p)|^2, which is the squared length of F(p). // // Let J = dF/dp = [dF_{r}/dp_{c}] denote the Jacobian matrix, which is the // matrix of first-order partial derivatives of F. The matrix has n rows and // m columns, and the indexing (r,c) refers to row r and column c. A // first-order approximation is F(p + d) = F(p) + J(p)d, where d is an m-by-1 // vector with small length. Consequently, an approximation to E is E(p + d) // = |F(p + d)|^2 = |F(p) + J(p)d|^2. The goal is to choose d to minimize // |F(p) + J(p)d|^2 and, hopefully, with E(p + d) < E(p). Choosing an initial // p_{0}, the hope is that the algorithm generates a sequence p_{i} for which // E(p_{i+1}) < E(p_{i}) and, in the limit, E(p_{j}) approaches the global // minimum of E. The algorithm is referred to as Gauss-Newton iteration. If // E does not decrease for a step of the algorithm, one can modify the // algorithm to the Levenberg-Marquardt iteration. See // LevenbergMarquardtMinimizer.h for a description and an implementation. // // For a single Gauss-Newton iteration, we need to choose d to minimize // |F(p) + J(p)d|^2 where p is fixed. This is a linear least squares problem // which can be formulated using the normal equations // (J^T(p)*J(p))*d = -J^T(p)*F(p). The matrix J^T*J is positive semidefinite. // If it is invertible, then d = -(J^T(p)*J(p))^{-1}*F(p). If it is not // invertible, some other algorithm must be used to choose d; one option is // to use gradient descent for the step. A Cholesky decomposition can be // used to solve the linear system. // // Although an implementation can allow the caller to pass an array of // functions F_{i}(p) and an array of derivatives dF_{r}/dp_{c}, some // applications might involve a very large n that precludes storing all // the computed Jacobian matrix entries because of excessive memory // requirements. In such an application, it is better to compute instead // the entries of the m-by-m matrix J^T*J and the m-by-1 vector J^T*F. // Typically, m is small, so the memory requirements are not excessive. Also, // there might be additional structure to F for which the caller can take // advantage; for example, 3-tuples of components of F(p) might correspond to // vectors that can be manipulated using an already existing mathematics // library. The implementation here supports both approaches. namespace gte { template <typename T> class GaussNewtonMinimizer { public: // Convenient types for the domain vectors, the range vectors, the // function F and the Jacobian J. typedef GVector<T> DVector; // numPDimensions typedef GVector<T> RVector; // numFDimensions typedef GMatrix<T> JMatrix; // numFDimensions-by-numPDimensions typedef GMatrix<T> JTJMatrix; // numPDimensions-by-numPDimensions typedef GVector<T> JTFVector; // numPDimensions typedef std::function<void(DVector const&, RVector&)> FFunction; typedef std::function<void(DVector const&, JMatrix&)> JFunction; typedef std::function<void(DVector const&, JTJMatrix&, JTFVector&)> JPlusFunction; // Create the minimizer that computes F(p) and J(p) directly. GaussNewtonMinimizer(int32_t numPDimensions, int32_t numFDimensions, FFunction const& inFFunction, JFunction const& inJFunction) : mNumPDimensions(numPDimensions), mNumFDimensions(numFDimensions), mFFunction(inFFunction), mJFunction(inJFunction), mF(mNumFDimensions), mJ(mNumFDimensions, mNumPDimensions), mJTJ(mNumPDimensions, mNumPDimensions), mNegJTF(mNumPDimensions), mDecomposer(mNumPDimensions), mUseJFunction(true) { LogAssert(mNumPDimensions > 0 && mNumFDimensions > 0, "Invalid dimensions."); } // Create the minimizer that computes J^T(p)*J(p) and -J(p)*F(p). GaussNewtonMinimizer(int32_t numPDimensions, int32_t numFDimensions, FFunction const& inFFunction, JPlusFunction const& inJPlusFunction) : mNumPDimensions(numPDimensions), mNumFDimensions(numFDimensions), mFFunction(inFFunction), mJPlusFunction(inJPlusFunction), mF(mNumFDimensions), mJ(mNumFDimensions, mNumPDimensions), mJTJ(mNumPDimensions, mNumPDimensions), mNegJTF(mNumPDimensions), mDecomposer(mNumPDimensions), mUseJFunction(false) { LogAssert(mNumPDimensions > 0 && mNumFDimensions > 0, "Invalid dimensions."); } // Disallow copy, assignment and move semantics. GaussNewtonMinimizer(GaussNewtonMinimizer const&) = delete; GaussNewtonMinimizer& operator=(GaussNewtonMinimizer const&) = delete; GaussNewtonMinimizer(GaussNewtonMinimizer&&) = delete; GaussNewtonMinimizer& operator=(GaussNewtonMinimizer&&) = delete; inline int32_t GetNumPDimensions() const { return mNumPDimensions; } inline int32_t GetNumFDimensions() const { return mNumFDimensions; } struct Result { Result() : minLocation{}, minError(static_cast<T>(0)), minErrorDifference(static_cast<T>(0)), minUpdateLength(static_cast<T>(0)), numIterations(0), converged(false) { minLocation.MakeZero(); } DVector minLocation; T minError; T minErrorDifference; T minUpdateLength; size_t numIterations; bool converged; }; Result operator()(DVector const& p0, size_t maxIterations, T updateLengthTolerance, T errorDifferenceTolerance) { Result result{}; result.minLocation = p0; result.minError = std::numeric_limits<T>::max(); result.minErrorDifference = std::numeric_limits<T>::max(); result.minUpdateLength = (T)0; result.numIterations = 0; result.converged = false; // As a simple precaution, ensure the tolerances are nonnegative. updateLengthTolerance = std::max(updateLengthTolerance, (T)0); errorDifferenceTolerance = std::max(errorDifferenceTolerance, (T)0); // Compute the initial error. mFFunction(p0, mF); result.minError = Dot(mF, mF); // Do the Gauss-Newton iterations. auto pCurrent = p0; for (result.numIterations = 1; result.numIterations <= maxIterations; ++result.numIterations) { ComputeLinearSystemInputs(pCurrent); if (!mDecomposer.Factor(mJTJ)) { // TODO: The matrix mJTJ is positive semi-definite, so the // failure can occur when mJTJ has a zero eigenvalue in // which case mJTJ is not invertible. Generate an iterate // anyway, perhaps using gradient descent? return result; } mDecomposer.SolveLower(mJTJ, mNegJTF); mDecomposer.SolveUpper(mJTJ, mNegJTF); auto pNext = pCurrent + mNegJTF; mFFunction(pNext, mF); T error = Dot(mF, mF); if (error < result.minError) { result.minErrorDifference = result.minError - error; result.minUpdateLength = Length(mNegJTF); result.minLocation = pNext; result.minError = error; if (result.minErrorDifference <= errorDifferenceTolerance || result.minUpdateLength <= updateLengthTolerance) { result.converged = true; return result; } } pCurrent = pNext; } return result; } private: void ComputeLinearSystemInputs(DVector const& pCurrent) { if (mUseJFunction) { mJFunction(pCurrent, mJ); mJTJ = MultiplyATB(mJ, mJ); mNegJTF = -(mF * mJ); } else { mJPlusFunction(pCurrent, mJTJ, mNegJTF); } } int32_t mNumPDimensions, mNumFDimensions; FFunction mFFunction; JFunction mJFunction; JPlusFunction mJPlusFunction; // Storage for J^T(p)*J(p) and -J^T(p)*F(p) during the iterations. RVector mF; JMatrix mJ; JTJMatrix mJTJ; JTFVector mNegJTF; CholeskyDecomposition<T> mDecomposer; bool mUseJFunction; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Rectangle.h
.h
4,060
148
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> // Points are R(s0,s1) = C + s0*A0 + s1*A1, where C is the center of the // rectangle and A0 and A1 are unit-length and perpendicular axes. The // parameters s0 and s1 are constrained by |s0| <= e0 and |s1| <= e1, // where e0 > 0 and e1 > 0 are the extents of the rectangle. namespace gte { template <int32_t N, typename Real> class Rectangle { public: // Construction and destruction. The default constructor sets the // origin to (0,...,0), axis A0 to (1,0,...,0), axis A1 to // (0,1,0,...0) and both extents to 1. Rectangle() { center.MakeZero(); for (int32_t i = 0; i < 2; ++i) { axis[i].MakeUnit(i); extent[i] = (Real)1; } } Rectangle(Vector<N, Real> const& inCenter, std::array<Vector<N, Real>, 2> const& inAxis, Vector<2, Real> const& inExtent) : center(inCenter), axis(inAxis), extent(inExtent) { } // Compute the vertices of the rectangle. If index i has the bit // pattern i = b[1]b[0], then // vertex[i] = center + sum_{d=0}^{1} sign[d] * extent[d] * axis[d] // where sign[d] = 2*b[d] - 1. void GetVertices(std::array<Vector<N, Real>, 4>& vertex) const { Vector<N, Real> product0 = extent[0] * axis[0]; Vector<N, Real> product1 = extent[1] * axis[1]; Vector<N, Real> sum = product0 + product1; Vector<N, Real> dif = product0 - product1; vertex[0] = center - sum; vertex[1] = center + dif; vertex[2] = center - dif; vertex[3] = center + sum; } Vector<N, Real> center; std::array<Vector<N, Real>, 2> axis; Vector<2, Real> extent; public: // Comparisons to support sorted containers. bool operator==(Rectangle const& rectangle) const { if (center != rectangle.center) { return false; } for (int32_t i = 0; i < 2; ++i) { if (axis[i] != rectangle.axis[i]) { return false; } } for (int32_t i = 0; i < 2; ++i) { if (extent[i] != rectangle.extent[i]) { return false; } } return true; } bool operator!=(Rectangle const& rectangle) const { return !operator==(rectangle); } bool operator< (Rectangle const& rectangle) const { if (center < rectangle.center) { return true; } if (center > rectangle.center) { return false; } if (axis < rectangle.axis) { return true; } if (axis > rectangle.axis) { return false; } return extent < rectangle.extent; } bool operator<=(Rectangle const& rectangle) const { return !rectangle.operator<(*this); } bool operator> (Rectangle const& rectangle) const { return rectangle.operator<(*this); } bool operator>=(Rectangle const& rectangle) const { return !operator<(rectangle); } }; // Template alias for convenience. template <typename Real> using Rectangle2 = Rectangle<2, Real>; template <typename Real> using Rectangle3 = Rectangle<3, Real>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RectanglePatchMesh.h
.h
6,458
197
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Mesh.h> #include <Mathematics/ParametricSurface.h> #include <memory> namespace gte { template <typename Real> class RectanglePatchMesh : public Mesh<Real> { public: // Create a mesh (x(u,v),y(u,v),z(u,v)) defined by the specified // surface. It is required that surface->IsRectangular() return // 'true'. RectanglePatchMesh(MeshDescription const& description, std::shared_ptr<ParametricSurface<3, Real>> const& surface) : Mesh<Real>(description, { MeshTopology::RECTANGLE }), mSurface(surface) { if (!this->mDescription.constructed) { // The logger system will report these errors in the Mesh // constructor. mSurface = nullptr; return; } LogAssert(mSurface != nullptr && mSurface->IsRectangular(), "A nonnull rectangular surface is required."); if (!this->mTCoords) { mDefaultTCoords.resize(this->mDescription.numVertices); this->mTCoords = mDefaultTCoords.data(); this->mTCoordStride = sizeof(Vector2<Real>); this->mDescription.allowUpdateFrame = this->mDescription.wantDynamicTangentSpaceUpdate; if (this->mDescription.allowUpdateFrame) { if (!this->mDescription.hasTangentSpaceVectors) { this->mDescription.allowUpdateFrame = false; } if (!this->mNormals) { this->mDescription.allowUpdateFrame = false; } } } this->ComputeIndices(); InitializeTCoords(); InitializePositions(); if (this->mDescription.allowUpdateFrame) { InitializeFrame(); } else if (this->mNormals) { InitializeNormals(); } } // Member access. inline std::shared_ptr<ParametricSurface<3, Real>> const& GetSurface() const { return mSurface; } protected: void InitializeTCoords() { Real uMin = mSurface->GetUMin(); Real uDelta = (mSurface->GetUMax() - uMin) / static_cast<Real>(this->mDescription.numCols - 1); Real vMin = mSurface->GetVMin(); Real vDelta = (mSurface->GetVMax() - vMin) / static_cast<Real>(this->mDescription.numRows - 1); Vector2<Real> tcoord; for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { tcoord[1] = vMin + vDelta * (Real)r; for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { tcoord[0] = uMin + uDelta * (Real)c; this->TCoord(i) = tcoord; } } } void InitializePositions() { for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { Vector2<Real> tcoord = this->TCoord(i); this->Position(i) = mSurface->GetPosition(tcoord[0], tcoord[1]); } } } void InitializeNormals() { for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { Vector2<Real> tcoord = this->TCoord(i); Vector3<Real> values[6]; mSurface->Evaluate(tcoord[0], tcoord[1], 1, values); Normalize(values[1], true); Normalize(values[2], true); this->Normal(i) = UnitCross(values[1], values[2], true); } } } void InitializeFrame() { for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { Vector2<Real> tcoord = this->TCoord(i); Vector3<Real> values[6]; mSurface->Evaluate(tcoord[0], tcoord[1], 1, values); Normalize(values[1], true); Normalize(values[2], true); if (this->mDPDUs) { this->DPDU(i) = values[1]; } if (this->mDPDVs) { this->DPDV(i) = values[2]; } ComputeOrthogonalComplement(2, &values[1], true); if (this->mNormals) { this->Normal(i) = values[3]; } if (this->mTangents) { this->Tangent(i) = values[1]; } if (this->mBitangents) { this->Bitangent(i) = values[2]; } } } } virtual void UpdatePositions() override { if (mSurface) { InitializePositions(); } } virtual void UpdateNormals() override { if (mSurface) { InitializeNormals(); } } virtual void UpdateFrame() override { if (mSurface) { InitializeFrame(); } } std::shared_ptr<ParametricSurface<3, Real>> mSurface; // If the client does not request texture coordinates, they will be // computed internally for use in evaluation of the surface geometry. std::vector<Vector2<Real>> mDefaultTCoords; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrPlane3Cylinder3.h
.h
11,841
324
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once // The intersection queries between a plane and a cylinder (finite or // infinite) are described in // https://www.geometrictools.com/Documentation/IntersectionCylinderPlane.pdf // // The plane is Dot(N, X - P) = 0, where P is a point on the plane and N is a // nonzero vector that is not necessarily unit length. // // The cylinder is (X - C)^T * (I - W * W^T) * (X - C) = r^2, where C is the // center, W is the axis direction and r > 0 is the radius. The cylinder has // height h. In the intersection queries, an infinite cylinder is specified // by setting h = -1. Read the aforementioned PDF for details about this // choice. #include <Mathematics/Cylinder3.h> #include <Mathematics/Ellipse3.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/Matrix.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/IntrPlane3Plane3.h> namespace gte { template <typename T> class TIQuery<T, Plane3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; // For an infinite cylinder, call cylinder.MakeInfiniteCylinder(). // Internally, the height is set to -1. This avoids the problem // of setting height to std::numeric_limits<T>::max() or // std::numeric_limits<T>::infinity() that are designed for // floating-point types but that do not work for exact rational types. // // For a finite cylinder, set cylinder.height > 0. Result operator()(Plane3<T> const& plane, Cylinder3<T> const& cylinder) { Result result{}; // Convenient names. auto const& P = plane.origin; auto const& N = plane.normal; auto const& C = cylinder.axis.origin; auto const& W = cylinder.axis.direction; auto const& r = cylinder.radius; auto const& h = cylinder.height; if (cylinder.IsInfinite()) { if (Dot(N, W) != static_cast<T>(0)) { // The cylinder direction and plane are not parallel. result.intersect = true; } else { // The cylinder direction and plane are parallel. T dotNCmP = Dot(N, C - P); result.intersect = (std::fabs(dotNCmP) <= r); } } else // cylinder is finite { T dotNCmP = Dot(N, C - P); T dotNW = Dot(N, W); Vector3<T> crossNW = Cross(N, W); T lhs = std::fabs(dotNCmP); T rhs = r * Length(crossNW) + static_cast<T>(0.5) * h * std::fabs(dotNW); result.intersect = (lhs <= rhs); } return result; } }; template <typename T> class FIQuery<T, Plane3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false), type(Type::NO_INTERSECTION), line{}, ellipse{}, trimLine{} { } // The type of intersection. enum class Type { // The cylinder and plane are separated. NO_INTERSECTION, // The plane is tangent to the cylinder direction. SINGLE_LINE, // The cylinder direction is parallel to the plane and the // plane cuts through the cylinder in two lines. PARALLEL_LINES, // The cylinder direction is perpendicular to the plane. CIRCLE, // The cylinder direction is not parallel to the plane. When // the direction is perpendicular to the plane, the // intersection is a circle which is an ellipse with equal // extents. ELLIPSE }; // The result members are set according to type. // // type = NONE // intersect = false // line[0,1] and ellipse have all zero members // // type = SINGLE_LINE // intersect = true // line[0] is valid // line[1] and ellipse have all zero members // // type = PARALLEL_LINES // intersect = true // line[0] and line[1] are valid // ellipse has all zero members // // type = CIRCLE // intersect = true // ellipse is valid (with extent[0] = extent[1]) // line[0,1] have all zero members // // type = ELLIPSE // intersect = true // ellipse is valid // line[0,1] have all zero members bool intersect; Type type; std::array<Line3<T>, 2> line; Ellipse3<T> ellipse; // Trim lines when the cylinder is finite. They are computed when // the plane and infinite cylinder intersect. If there is no // intersection, the trim lines have all zero members. std::array<Line3<T>, 2> trimLine; }; Result operator()(Plane3<T> const& plane, Cylinder3<T> const& cylinder) { Result result{}; TIQuery<T, Plane3<T>, Cylinder3<T>> tiQuery{}; auto tiOutput = tiQuery(plane, cylinder); if (tiOutput.intersect) { T const zero = static_cast<T>(0); T dotNW = Dot(plane.normal, cylinder.axis.direction); if (dotNW != zero) { // The cylinder direction is not parallel to the plane. // The intersection is an ellipse or circle. GetEllipseOfIntersection(plane, cylinder, result); GetTrimLines(plane, cylinder, result.trimLine); } else { // The cylinder direction is parallel to the plane. There // are no trim lines for this geometric configuration. GetLinesOfIntersection(plane, cylinder, result); } } return result; } private: // The cylinder is infinite and its direction is not parallel to the // plane. static void GetEllipseOfIntersection(Plane3<T> const& plane, Cylinder3<T> const& cylinder, Result& result) { // Convenient names. auto const& P = plane.origin; auto const& N = plane.normal; auto const& C = cylinder.axis.origin; auto const& W = cylinder.axis.direction; auto const& r = cylinder.radius; // Compute a right-handed orthonormal basis {N,A,B}. The // plane is spanned by A and B. std::array<Vector3<T>, 3> basis{}; basis[0] = N; Vector3<T> const& A = basis[1]; Vector3<T> const& B = basis[2]; ComputeOrthogonalComplement(1, basis.data()); // Compute the projection matrix M = I - W * W^T. Matrix3x3<T> M{}; M.MakeIdentity(); M = M - OuterProduct(W, W); // Compute the coefficients of the quadratic equation // c00 + c10*x + c01*y + c20*x^2 + c11*x*y + c02*y^2 = 0. T const two = static_cast<T>(2); Vector3<T> PmC = P - C; Vector3<T> MtPmC = M * PmC; Vector3<T> MtA = M * A; Vector3<T> MtB = M * B; std::array<T, 6> coefficients { Dot(PmC, MtPmC) - r * r, two * Dot(A, MtPmC), two * Dot(B, MtPmC), Dot(A, MtA), two * Dot(A, MtB), Dot(B, MtB) }; // Compute the 2D ellipse parameters in plane coordinates. Ellipse2<T> ellipse2{}; (void)ellipse2.FromCoefficients(coefficients); // Lift the 2D ellipse/circle to the 3D ellipse/circle. result.intersect = true; result.type = (ellipse2.extent[0] != ellipse2.extent[1] ? Result::Type::ELLIPSE : Result::Type::CIRCLE); result.ellipse.center = plane.origin + ellipse2.center[0] * A + ellipse2.center[1] * B; result.ellipse.normal = plane.normal; result.ellipse.axis[0] = ellipse2.axis[0][0] * A + ellipse2.axis[0][1] * B; result.ellipse.axis[1] = ellipse2.axis[1][0] * A + ellipse2.axis[1][1] * B; result.ellipse.extent = ellipse2.extent; } // The cylinder is infinite and its direction is parallel to the // plane. static void GetLinesOfIntersection(Plane3<T> const& plane, Cylinder3<T> const& cylinder, Result& result) { // Convenient names. auto const& P = plane.origin; auto const& N = plane.normal; auto const& C = cylinder.axis.origin; auto const& W = cylinder.axis.direction; auto const& r = cylinder.radius; T const zero = static_cast<T>(0); Vector3<T> CmP = C - P; T dotNCmP = Dot(N, CmP); T ellSqr = r * r - dotNCmP * dotNCmP; // r^2 - d^2 if (ellSqr > zero) { // The plane cuts through the cylinder in two lines. result.intersect = true; result.type = Result::Type::PARALLEL_LINES; Vector3<T> projC = C - dotNCmP * N; Vector3<T> crsNW = Cross(N, W); T ell = std::sqrt(ellSqr); result.line[0].origin = projC - ell * crsNW; result.line[0].direction = W; result.line[1].origin = projC + ell * crsNW; result.line[1].direction = W; } else if (ellSqr < zero) { // The cylinder does not intersect the plane. result.intersect = false; result.type = Result::Type::NO_INTERSECTION; } else // ellSqr = 0 { // The plane is tangent to the cylinder. result.intersect = true; result.type = Result::Type::SINGLE_LINE; result.line[0].origin = C - dotNCmP * N; result.line[0].direction = W; } } static void GetTrimLines(Plane3<T> const& plane, Cylinder3<T> const& cylinder, std::array<Line3<T>, 2>& trimLine) { // Compute the cylinder end planes. auto const& C = cylinder.axis.origin; auto const& D = cylinder.axis.direction; auto const& h = cylinder.height; Vector3<T> offset = (static_cast<T>(0.5) * h) * D; FIQuery<T, Plane3<T>, Plane3<T>> ppQuery{}; Plane3<T> endPlaneNeg(D, C - offset); auto ppResult = ppQuery(plane, endPlaneNeg); trimLine[0] = ppResult.line; Plane3<T> endPlanePos(D, C + offset); ppResult = ppQuery(plane, endPlanePos); trimLine[1] = ppResult.line; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/VETManifoldMesh.h
.h
6,898
205
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.26 #pragma once #include <Mathematics/ETManifoldMesh.h> #include <map> // The VETManifoldMesh class represents an edge-triangle manifold mesh but // additionally stores vertex adjacency information. It is general purpose, // allowing insertion and removal of triangles at any time. Howver, the // performance is limited because of the use of C++ container classes // (unordered sets and maps). If your application requires a // vertex-edge-triangle manifold mesh for which no triangles will be // removed, a much better choice is VETManifoldMeshVR. namespace gte { class VETManifoldMesh : public ETManifoldMesh { public: // Vertex data types. class Vertex; typedef std::unique_ptr<Vertex>(*VCreator)(int32_t); using VMap = std::unordered_map<int32_t, std::unique_ptr<Vertex>>; // Vertex object. class Vertex { public: virtual ~Vertex() = default; Vertex(int32_t vIndex) : V(vIndex) { } // The index into the vertex pool of the mesh. int32_t V; // Adjacent objects. std::unordered_set<int32_t> VAdjacent; std::unordered_set<Edge*> EAdjacent; std::unordered_set<Triangle*> TAdjacent; }; // Construction and destruction. virtual ~VETManifoldMesh() = default; VETManifoldMesh(VCreator vCreator = nullptr, ECreator eCreator = nullptr, TCreator tCreator = nullptr) : ETManifoldMesh(eCreator, tCreator), mVCreator(vCreator ? vCreator : CreateVertex) { } // Support for a deep copy of the mesh. The mVMap, mEMap, and mTMap // objects have dynamically allocated memory for vertices, edges, and // triangles. A shallow copy of the pointers to this memory is // problematic. Allowing sharing, say, via std::shared_ptr, is an // option but not really the intent of copying the mesh graph. VETManifoldMesh(VETManifoldMesh const& mesh) { *this = mesh; } VETManifoldMesh& operator=(VETManifoldMesh const& mesh) { Clear(); mVCreator = mesh.mVCreator; ETManifoldMesh::operator=(mesh); return *this; } // Member access. inline VMap const& GetVertices() const { return mVMap; } // If <v0,v1,v2> is not in the mesh, a Triangle object is created and // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is // returned. If the insertion leads to a nonmanifold mesh, the call // fails with a nullptr returned. virtual Triangle* Insert(int32_t v0, int32_t v1, int32_t v2) override { Triangle* tri = ETManifoldMesh::Insert(v0, v1, v2); if (!tri) { return nullptr; } for (int32_t i = 0; i < 3; ++i) { int32_t vIndex = tri->V[i]; auto vItem = mVMap.find(vIndex); Vertex* vertex; if (vItem == mVMap.end()) { std::unique_ptr<Vertex> newVertex = mVCreator(vIndex); vertex = newVertex.get(); mVMap[vIndex] = std::move(newVertex); } else { vertex = vItem->second.get(); } vertex->TAdjacent.insert(tri); for (int32_t j = 0; j < 3; ++j) { auto edge = tri->E[j]; LogAssert(edge != nullptr, "Malformed mesh."); if (edge->V[0] == vIndex) { vertex->VAdjacent.insert(edge->V[1]); vertex->EAdjacent.insert(edge); } else if (edge->V[1] == vIndex) { vertex->VAdjacent.insert(edge->V[0]); vertex->EAdjacent.insert(edge); } } } return tri; } // If <v0,v1,v2> is in the mesh, it is removed and 'true' is returned; // otherwise, <v0,v1,v2> is not in the mesh and 'false' is returned. virtual bool Remove(int32_t v0, int32_t v1, int32_t v2) override { auto tItem = mTMap.find(TriangleKey<true>(v0, v1, v2)); if (tItem == mTMap.end()) { return false; } Triangle* tri = tItem->second.get(); for (int32_t i = 0; i < 3; ++i) { int32_t vIndex = tri->V[i]; auto vItem = mVMap.find(vIndex); LogAssert(vItem != mVMap.end(), "Malformed mesh."); Vertex* vertex = vItem->second.get(); for (int32_t j = 0; j < 3; ++j) { auto edge = tri->E[j]; LogAssert(edge != nullptr, "Malformed mesh."); if (edge->T[0] && !edge->T[1]) { if (edge->V[0] == vIndex) { vertex->VAdjacent.erase(edge->V[1]); vertex->EAdjacent.erase(edge); } else if (edge->V[1] == vIndex) { vertex->VAdjacent.erase(edge->V[0]); vertex->EAdjacent.erase(edge); } } } vertex->TAdjacent.erase(tri); if (vertex->TAdjacent.size() == 0) { LogAssert(vertex->VAdjacent.size() == 0 && vertex->EAdjacent.size() == 0, "Malformed mesh: Inconsistent vertex adjacency information."); mVMap.erase(vItem); } } return ETManifoldMesh::Remove(v0, v1, v2); } // Destroy the vertices, edges, and triangles to obtain an empty mesh. virtual void Clear() override { mVMap.clear(); ETManifoldMesh::Clear(); } protected: // The vertex data and default vertex creation. static std::unique_ptr<Vertex> CreateVertex(int32_t vIndex) { return std::make_unique<Vertex>(vIndex); } VCreator mVCreator; VMap mVMap; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContAlignedBox.h
.h
1,634
51
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/AlignedBox.h> namespace gte { // Compute the minimum size aligned bounding box of the points. The // extreme values are the minima and maxima of the point coordinates. template <int32_t N, typename Real> bool GetContainer(int32_t numPoints, Vector<N, Real> const* points, AlignedBox<N, Real>& box) { return ComputeExtremes(numPoints, points, box.min, box.max); } // Test for containment. template <int32_t N, typename Real> bool InContainer(Vector<N, Real> const& point, AlignedBox<N, Real> const& box) { for (int32_t i = 0; i < N; ++i) { Real value = point[i]; if (value < box.min[i] || value > box.max[i]) { return false; } } return true; } // Construct an aligned box that contains two other aligned boxes. The // result is the minimum size box containing the input boxes. template <int32_t N, typename Real> bool MergeContainers(AlignedBox<N, Real> const& box0, AlignedBox<N, Real> const& box1, AlignedBox<N, Real>& merge) { for (int32_t i = 0; i < N; ++i) { merge.min[i] = std::min(box0.min[i], box1.min[i]); merge.max[i] = std::max(box0.max[i], box1.max[i]); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpSphere2.h
.h
8,682
235
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Delaunay2Mesh.h> #include <Mathematics/IntpQuadraticNonuniform2.h> #include <memory> // Interpolation of a scalar-valued function defined on a sphere. Although // the sphere lives in 3D, the interpolation is a 2D method whose input // points are angles (theta,phi) from spherical coordinates. The domains of // the angles are -pi <= theta <= pi and 0 <= phi <= pi. namespace gte { template <typename T, typename...> class IntpSphere2 {}; } namespace gte { // The InputType is 'float' or 'double'. The ComputeType can be a // floating-point type or BSNumber<*> type, because it does not require // divisions. The RationalType requires division, so you can use // BSRational<*>. template <typename InputType, typename ComputeType, typename RationalType> class // [[deprecated("Use IntpSphere2<InputType> instead.")]] IntpSphere2<InputType, ComputeType, RationalType> { public: // Construction and destruction. For complete spherical coverage, // include the two antipodal (theta,phi) points (-pi,0,F(-pi,0)) and // (-pi,pi,F(-pi,pi)) in the input data. These correspond to the // sphere poles x = 0, y = 0, and |z| = 1. ~IntpSphere2() = default; IntpSphere2(int32_t numPoints, InputType const* theta, InputType const* phi, InputType const* F) : mMesh(mDelaunay) { // Copy the input data. The larger arrays are used to support // wrap-around in the Delaunay triangulation for the interpolator. int32_t totalPoints = 3 * numPoints; mWrapAngles.resize(totalPoints); mWrapF.resize(totalPoints); for (int32_t i = 0; i < numPoints; ++i) { mWrapAngles[i][0] = theta[i]; mWrapAngles[i][1] = phi[i]; mWrapF[i] = F[i]; } // Use periodicity to get wrap-around in the Delaunay // triangulation. int32_t i0 = 0, i1 = numPoints, i2 = 2 * numPoints; for (/**/; i0 < numPoints; ++i0, ++i1, ++i2) { mWrapAngles[i1][0] = mWrapAngles[i0][0] + (InputType)GTE_C_TWO_PI; mWrapAngles[i2][0] = mWrapAngles[i0][0] - (InputType)GTE_C_TWO_PI; mWrapAngles[i1][1] = mWrapAngles[i0][1]; mWrapAngles[i2][1] = mWrapAngles[i0][1]; mWrapF[i1] = mWrapF[i0]; mWrapF[i2] = mWrapF[i0]; } mDelaunay(totalPoints, &mWrapAngles[0], (ComputeType)0); mInterp = std::make_unique<IntpQuadraticNonuniform2<InputType, TriangleMesh>>( mMesh, &mWrapF[0], (InputType)1); } // Spherical coordinates are // x = cos(theta)*sin(phi) // y = sin(theta)*sin(phi) // z = cos(phi) // for -pi <= theta <= pi, 0 <= phi <= pi. The application can use // this function to convert unit length vectors (x,y,z) to (theta,phi). static void GetSphericalCoordinates(InputType x, InputType y, InputType z, InputType& theta, InputType& phi) { // Assumes (x,y,z) is unit length. Returns -pi <= theta <= pi and // 0 <= phiAngle <= pi. if (z < (InputType)1) { if (z > -(InputType)1) { theta = std::atan2(y, x); phi = std::acos(z); } else { theta = -(InputType)GTE_C_PI; phi = (InputType)GTE_C_PI; } } else { theta = -(InputType)GTE_C_PI; phi = (InputType)0; } } // The return value is 'true' if and only if the input point is in the // convex hull of the input (theta,pi) array, in which case the // interpolation is valid. bool operator()(InputType theta, InputType phi, InputType& F) const { Vector2<InputType> angles{ theta, phi }; InputType thetaDeriv = static_cast<InputType>(0); InputType phiDeriv = static_cast<InputType>(0); return (*mInterp)(angles, F, thetaDeriv, phiDeriv); } private: typedef Delaunay2Mesh<InputType, ComputeType, RationalType> TriangleMesh; std::vector<Vector2<InputType>> mWrapAngles; Delaunay2<InputType, ComputeType> mDelaunay; TriangleMesh mMesh; std::vector<InputType> mWrapF; std::unique_ptr<IntpQuadraticNonuniform2<InputType, TriangleMesh>> mInterp; }; } namespace gte { // The input type T is 'float' or 'double'. template <typename T> class IntpSphere2<T> { public: // Construction and destruction. For complete spherical coverage, // include the two antipodal (theta,phi) points (-pi,0,F(-pi,0)) and // (-pi,pi,F(-pi,pi)) in the input data. These correspond to the // sphere poles x = 0, y = 0, and |z| = 1. ~IntpSphere2() = default; IntpSphere2(int32_t numPoints, T const* theta, T const* phi, T const* F) : mMesh(mDelaunay) { // Copy the input data. The larger arrays are used to support // wrap-around in the Delaunay triangulation for the interpolator. int32_t totalPoints = 3 * numPoints; mWrapAngles.resize(totalPoints); mWrapF.resize(totalPoints); for (int32_t i = 0; i < numPoints; ++i) { mWrapAngles[i][0] = theta[i]; mWrapAngles[i][1] = phi[i]; mWrapF[i] = F[i]; } // Use periodicity to get wrap-around in the Delaunay // triangulation. int32_t i0 = 0, i1 = numPoints, i2 = 2 * numPoints; for (/**/; i0 < numPoints; ++i0, ++i1, ++i2) { mWrapAngles[i1][0] = mWrapAngles[i0][0] + static_cast<T>(GTE_C_TWO_PI); mWrapAngles[i2][0] = mWrapAngles[i0][0] - static_cast<T>(GTE_C_TWO_PI); mWrapAngles[i1][1] = mWrapAngles[i0][1]; mWrapAngles[i2][1] = mWrapAngles[i0][1]; mWrapF[i1] = mWrapF[i0]; mWrapF[i2] = mWrapF[i0]; } mDelaunay(mWrapAngles); mInterp = std::make_unique<IntpQuadraticNonuniform2<T, TriangleMesh>>( mMesh, &mWrapF[0], static_cast<T>(1)); } // Spherical coordinates are // x = cos(theta)*sin(phi) // y = sin(theta)*sin(phi) // z = cos(phi) // for -pi <= theta <= pi, 0 <= phi <= pi. The application can use // this function to convert unit length vectors (x,y,z) to (theta,phi). static void GetSphericalCoordinates(T x, T y, T z, T& theta, T& phi) { // Assumes (x,y,z) is unit length. Returns -pi <= theta <= pi and // 0 <= phiAngle <= pi. T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const pi = static_cast<T>(GTE_C_PI); if (z < one) { if (z > -one) { theta = std::atan2(y, x); phi = std::acos(z); } else { theta = -pi; phi = pi; } } else { theta = -pi; phi = zero; } } // The return value is 'true' if and only if the input point is in the // convex hull of the input (theta,pi) array, in which case the // interpolation is valid. bool operator()(T theta, T phi, T& F) const { Vector2<T> angles{ theta, phi }; T thetaDeriv = static_cast<T>(0); T phiDeriv = static_cast<T>(0); return (*mInterp)(angles, F, thetaDeriv, phiDeriv); } private: using TriangleMesh = Delaunay2Mesh<T>; std::vector<Vector2<T>> mWrapAngles; Delaunay2<T> mDelaunay; TriangleMesh mMesh; std::vector<T> mWrapF; std::unique_ptr<IntpQuadraticNonuniform2<T, TriangleMesh>> mInterp; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Triangle2.h
.h
9,151
249
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Line.h> #include <Mathematics/Triangle.h> #include <Mathematics/Vector2.h> // The queries consider the triangle to be a solid. The algorithms are based // on determining on which side of the line the vertices lie. The test uses // the sign of the projections of the vertices onto a normal line that is // perpendicular to the specified line. The table of possibilities is listed // next with n = numNegative, p = numPositive and z = numZero. // // n p z intersection // ------------------------------------ // 0 3 0 none // 0 2 1 vertex // 0 1 2 edge // 0 0 3 none (degenerate triangle) // 1 2 0 segment (2 edges clipped) // 1 1 1 segment (1 edge clipped) // 1 0 2 edge // 2 1 0 segment (2 edges clipped) // 2 0 1 vertex // 3 0 0 none // // The case (n,p,z) = (0,0,3) is treated as a no-intersection because the // triangle is degenerate. namespace gte { template <typename T> class TIQuery<T, Line2<T>, Triangle2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; // The line is P + t * D, where P is a point on the line and D is a // direction vector that does not have to be unit length. This is // useful when using a 2-point representation P0 + t * (P1 - P0). Result operator()(Line2<T> const& line, Triangle2<T> const& triangle) { Result result{}; T const zero = static_cast<T>(0); int32_t numPositive = 0, numNegative = 0, numZero = 0; for (size_t i = 0; i < 3; ++i) { Vector2<T> diff = triangle.v[i] - line.origin; T s = DotPerp(line.direction, diff); if (s > zero) { ++numPositive; } else if (s < zero) { ++numNegative; } else { ++numZero; } } result.intersect = (numZero == 0 && numPositive > 0 && numNegative > 0) || (numZero == 1) || (numZero == 2); return result; } }; template <typename T> class FIQuery<T, Line2<T>, Triangle2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector2<T>{ static_cast<T>(0), static_cast<T>(0) }, Vector2<T>{ static_cast<T>(0), static_cast<T>(0) }} { } bool intersect; int32_t numIntersections; std::array<T, 2> parameter; std::array<Vector2<T>, 2> point; }; // The line is P + t * D, where P is a point on the line and D is a // direction vector that does not have to be unit length. This is // useful when using a 2-point representation P0 + t * (P1 - P0). Result operator()(Line2<T> const& line, Triangle2<T> const& triangle) { Result result{}; DoQuery(line.origin, line.direction, triangle, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector2<T> const& origin, Vector2<T> const& direction, Triangle2<T> const& triangle, Result& result) { T const zero = static_cast<T>(0); std::array<T, 3> s{ zero, zero, zero }; int32_t numPositive = 0, numNegative = 0, numZero = 0; for (size_t i = 0; i < 3; ++i) { Vector2<T> diff = triangle.v[i] - origin; s[i] = DotPerp(direction, diff); if (s[i] > zero) { ++numPositive; } else if (s[i] < zero) { ++numNegative; } else { ++numZero; } } if (numZero == 0 && numPositive > 0 && numNegative > 0) { // (n,p,z) is (1,2,0) or (2,1,0). result.intersect = true; result.numIntersections = 2; // sign is +1 when (n,p) is (2,1) or -1 when (n,p) is (1,2). T sign = (3 > numPositive * 2 ? static_cast<T>(1) : static_cast<T>(-1)); for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (sign * s[i2] > zero) { Vector2<T> diffVi0P0 = triangle.v[i0] - origin; Vector2<T> diffVi2Vi0 = triangle.v[i2] - triangle.v[i0]; T lambda0 = s[i0] / (s[i0] - s[i2]); Vector2<T> q0 = diffVi0P0 + lambda0 * diffVi2Vi0; result.parameter[0] = Dot(direction, q0); Vector2<T> diffVi1P0 = triangle.v[i1] - origin; Vector2<T> diffVi2Vi1 = triangle.v[i2] - triangle.v[i1]; T lambda1 = s[i1] / (s[i1] - s[i2]); Vector2<T> q1 = diffVi1P0 + lambda1 * diffVi2Vi1; result.parameter[1] = Dot(direction, q1); break; } } } else if (numZero == 1) { // (n,p,z) is (1,1,1), (2,0,1) or (0,2,1). result.intersect = true; for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (s[i2] == zero) { Vector2<T> diffVi2P0 = triangle.v[i2] - origin; result.parameter[0] = Dot(direction, diffVi2P0); if (numPositive == 2 || numNegative == 2) { // (n,p,z) is (2,0,1) or (0,2,1). result.numIntersections = 1; result.parameter[1] = result.parameter[0]; } else { // (n,p,z) is (1,1,1). result.numIntersections = 2; Vector2<T> diffVi0P0 = triangle.v[i0] - origin; Vector2<T> diffVi1Vi0 = triangle.v[i1] - triangle.v[i0]; T lambda0 = s[i0] / (s[i0] - s[i1]); Vector2<T> q = diffVi0P0 + lambda0 * diffVi1Vi0; result.parameter[1] = Dot(direction, q); } break; } } } else if (numZero == 2) { // (n,p,z) is (1,0,2) or (0,1,2). result.intersect = true; result.numIntersections = 2; for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++) { if (s[i2] != zero) { Vector2<T> diffVi0P0 = triangle.v[i0] - origin; result.parameter[0] = Dot(direction, diffVi0P0); Vector2<T> diffVi1P0 = triangle.v[i1] - origin; result.parameter[1] = Dot(direction, diffVi1P0); break; } } } // else: (n,p,z) is (3,0,0), (0,3,0) or (0,0,3). The constructor // for Result initializes all members to zero, so no additional // assignments are needed for 'result'. if (result.intersect) { T directionSqrLength = Dot(direction, direction); result.parameter[0] /= directionSqrLength; result.parameter[1] /= directionSqrLength; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MinimumVolumeSphere3.h
.h
27,374
704
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ContSphere3.h> #include <Mathematics/LinearSystem.h> #include <functional> #include <random> // Compute the minimum volume sphere containing the input set of points. The // algorithm randomly permutes the input points so that the construction // occurs in 'expected' O(N) time. All internal minimal sphere calculations // store the squared radius in the radius member of Sphere3. Only at // the end is a sqrt computed. // // The most robust choice for ComputeType is BSRational<T> for exact rational // arithmetic. As long as this code is a correct implementation of the theory // (which I hope it is), you will obtain the minimum-volume sphere // containing the points. // // Instead, if you choose ComputeType to be float or double, floating-point // rounding errors can cause the UpdateSupport{2,3,4} functions to fail. // The failure is trapped in those functions and a simple bounding sphere is // computed using GetContainer in file ContSphere3.h. This sphere is // generally not the minimum-volume sphere containing the points. The // minimum-volume algorithm is terminated immediately. The sphere is // returned as well as a bool value of 'true' when the sphere is minimum // volume or 'false' when the failure is trapped. When 'false' is returned, // you can try another call to the operator()(...) function. The random // shuffle that occurs is highly likely to be different from the previous // shuffle, and there is a chance that the algorithm can succeed just because // of the different ordering of points. namespace gte { template <typename InputType, typename ComputeType> class MinimumVolumeSphere3 { public: MinimumVolumeSphere3() : mNumSupport(0), mSupport{ 0, 0, 0, 0 }, mDRE{}, mComputePoints{} { } bool operator()(int32_t numPoints, Vector3<InputType> const* points, Sphere3<InputType>& minimal) { if (numPoints >= 1 && points) { // Function array to avoid switch statement in the main loop. std::function<UpdateResult(int32_t)> update[5]; update[1] = [this](int32_t i) { return UpdateSupport1(i); }; update[2] = [this](int32_t i) { return UpdateSupport2(i); }; update[3] = [this](int32_t i) { return UpdateSupport3(i); }; update[4] = [this](int32_t i) { return UpdateSupport4(i); }; // Process only the unique points. std::vector<int32_t> permuted(numPoints); for (int32_t i = 0; i < numPoints; ++i) { permuted[i] = i; } std::sort(permuted.begin(), permuted.end(), [points](int32_t i0, int32_t i1) { return points[i0] < points[i1]; }); auto end = std::unique(permuted.begin(), permuted.end(), [points](int32_t i0, int32_t i1) { return points[i0] == points[i1]; }); permuted.erase(end, permuted.end()); numPoints = static_cast<int32_t>(permuted.size()); // Create a random permutation of the points. std::shuffle(permuted.begin(), permuted.end(), mDRE); // Convert to the compute type, which is a simple copy when // ComputeType is the same as InputType. mComputePoints.resize(numPoints); for (int32_t i = 0; i < numPoints; ++i) { for (int32_t j = 0; j < 3; ++j) { mComputePoints[i][j] = points[permuted[i]][j]; } } // Start with the first point. Sphere3<ComputeType> ctMinimal = ExactSphere1(0); mNumSupport = 1; mSupport[0] = 0; // The loop restarts from the beginning of the point list each // time the sphere needs updating. Linus Källberg (Computer // Science at Mälardalen University in Sweden) discovered that // performance is/ better when the remaining points in the // array are processed before restarting. The points // processed before the point that caused the/ update are // likely to be enclosed by the new sphere (or near the sphere // boundary) because they were enclosed by the previous // sphere. The chances are better that points after the // current one will cause growth of the bounding sphere. for (int32_t i = 1 % numPoints, n = 0; i != n; i = (i + 1) % numPoints) { if (!SupportContains(i)) { if (!Contains(i, ctMinimal)) { auto result = update[mNumSupport](i); if (result.second == true) { if (result.first.radius > ctMinimal.radius) { ctMinimal = result.first; n = i; } } else { // This case can happen when ComputeType is // float or double. See the comments at the // beginning of this file. ComputeType is not // exact and failure occurred. Returning // non-minimal circle. TODO: Should we throw // an exception? GetContainer(numPoints, points, minimal); mNumSupport = 0; mSupport.fill(0); return false; } } } } for (int32_t j = 0; j < 3; ++j) { minimal.center[j] = static_cast<InputType>(ctMinimal.center[j]); } minimal.radius = static_cast<InputType>(ctMinimal.radius); minimal.radius = std::sqrt(minimal.radius); for (int32_t i = 0; i < mNumSupport; ++i) { mSupport[i] = permuted[mSupport[i]]; } return true; } else { LogError("Input must contain points."); } } // Member access. inline int32_t GetNumSupport() const { return mNumSupport; } inline std::array<int32_t, 4> const& GetSupport() const { return mSupport; } private: // Test whether point P is inside sphere S using squared distance and // squared radius. bool Contains(int32_t i, Sphere3<ComputeType> const& sphere) const { // NOTE: In this algorithm, sphere.radius is the *squared radius* // until the function returns at which time a square root is // applied. Vector3<ComputeType> diff = mComputePoints[i] - sphere.center; return Dot(diff, diff) <= sphere.radius; } Sphere3<ComputeType> ExactSphere1(int32_t i0) const { Sphere3<ComputeType> minimal; minimal.center = mComputePoints[i0]; minimal.radius = (ComputeType)0; return minimal; } Sphere3<ComputeType> ExactSphere2(int32_t i0, int32_t i1) const { Vector3<ComputeType> const& P0 = mComputePoints[i0]; Vector3<ComputeType> const& P1 = mComputePoints[i1]; Sphere3<ComputeType> minimal; minimal.center = (ComputeType)0.5 * (P0 + P1); Vector3<ComputeType> diff = P1 - P0; minimal.radius = (ComputeType)0.25 * Dot(diff, diff); return minimal; } Sphere3<ComputeType> ExactSphere3(int32_t i0, int32_t i1, int32_t i2) const { // Compute the 2D circle containing P0, P1, and P2. The center in // barycentric coordinates is C = x0*P0 + x1*P1 + x2*P2, where // x0 + x1 + x2 = 1. The center is equidistant from the three // points, so |C - P0| = |C - P1| = |C - P2| = R, where R is the // radius of the circle. From these conditions, // C - P0 = x0*E0 + x1*E1 - E0 // C - P1 = x0*E0 + x1*E1 - E1 // C - P2 = x0*E0 + x1*E1 // where E0 = P0 - P2 and E1 = P1 - P2, which leads to // r^2 = |x0*E0 + x1*E1|^2 - 2*Dot(E0, x0*E0 + x1*E1) + |E0|^2 // r^2 = |x0*E0 + x1*E1|^2 - 2*Dot(E1, x0*E0 + x1*E1) + |E1|^2 // r^2 = |x0*E0 + x1*E1|^2 // Subtracting the last equation from the first two and writing // the equations as a linear system, // // +- -++ -+ +- -+ // | Dot(E0,E0) Dot(E0,E1) || x0 | = 0.5 | Dot(E0,E0) | // | Dot(E1,E0) Dot(E1,E1) || x1 | | Dot(E1,E1) | // +- -++ -+ +- -+ // // The following code solves this system for x0 and x1 and then // evaluates the third equation in r^2 to obtain r. Vector3<ComputeType> const& P0 = mComputePoints[i0]; Vector3<ComputeType> const& P1 = mComputePoints[i1]; Vector3<ComputeType> const& P2 = mComputePoints[i2]; Vector3<ComputeType> E0 = P0 - P2; Vector3<ComputeType> E1 = P1 - P2; Matrix2x2<ComputeType> A; A(0, 0) = Dot(E0, E0); A(0, 1) = Dot(E0, E1); A(1, 0) = A(0, 1); A(1, 1) = Dot(E1, E1); ComputeType const half = (ComputeType)0.5; Vector2<ComputeType> B{ half * A(0, 0), half * A(1, 1) }; Sphere3<ComputeType> minimal; Vector2<ComputeType> X; if (LinearSystem<ComputeType>::Solve(A, B, X)) { ComputeType x2 = (ComputeType)1 - X[0] - X[1]; minimal.center = X[0] * P0 + X[1] * P1 + x2 * P2; Vector3<ComputeType> tmp = X[0] * E0 + X[1] * E1; minimal.radius = Dot(tmp, tmp); } else { minimal.center = Vector3<ComputeType>::Zero(); minimal.radius = (ComputeType)std::numeric_limits<InputType>::max(); } return minimal; } Sphere3<ComputeType> ExactSphere4(int32_t i0, int32_t i1, int32_t i2, int32_t i3) const { // Compute the sphere containing P0, P1, P2, and P3. The center // in barycentric coordinates is // C = x0*P0 + x1*P1 + x2*P2 + x3*P3, // where x0 + x1 + x2 + x3 = 1. The center is equidistant from // the three points, so |C - P0| = |C - P1| = |C - P2| = |C - P3| // = R, where R is the radius of the sphere. From these // conditions, // C - P0 = x0*E0 + x1*E1 + x2*E2 - E0 // C - P1 = x0*E0 + x1*E1 + x2*E2 - E1 // C - P2 = x0*E0 + x1*E1 + x2*E2 - E2 // C - P3 = x0*E0 + x1*E1 + x2*E2 // where E0 = P0 - P3, E1 = P1 - P3, and E2 = P2 - P3, which // leads to // r^2 = |x0*E0+x1*E1+x2*E2|^2-2*Dot(E0,x0*E0+x1*E1+x2*E2)+|E0|^2 // r^2 = |x0*E0+x1*E1+x2*E2|^2-2*Dot(E1,x0*E0+x1*E1+x2*E2)+|E1|^2 // r^2 = |x0*E0+x1*E1+x2*E2|^2-2*Dot(E2,x0*E0+x1*E1+x2*E2)+|E2|^2 // r^2 = |x0*E0+x1*E1+x2*E2|^2 // Subtracting the last equation from the first three and writing // the equations as a linear system, // // +- -++ -+ +- -+ // | Dot(E0,E0) Dot(E0,E1) Dot(E0,E2) || x0 | = 0.5 | Dot(E0,E0) | // | Dot(E1,E0) Dot(E1,E1) Dot(E1,E2) || x1 | | Dot(E1,E1) | // | Dot(E2,E0) Dot(E2,E1) Dot(E2,E2) || x2 | | Dot(E2,E2) | // +- -++ -+ +- -+ // // The following code solves this system for x0, x1, and x2 and // then evaluates the fourth equation in r^2 to obtain r. Vector3<ComputeType> const& P0 = mComputePoints[i0]; Vector3<ComputeType> const& P1 = mComputePoints[i1]; Vector3<ComputeType> const& P2 = mComputePoints[i2]; Vector3<ComputeType> const& P3 = mComputePoints[i3]; Vector3<ComputeType> E0 = P0 - P3; Vector3<ComputeType> E1 = P1 - P3; Vector3<ComputeType> E2 = P2 - P3; Matrix3x3<ComputeType> A; A(0, 0) = Dot(E0, E0); A(0, 1) = Dot(E0, E1); A(0, 2) = Dot(E0, E2); A(1, 0) = A(0, 1); A(1, 1) = Dot(E1, E1); A(1, 2) = Dot(E1, E2); A(2, 0) = A(0, 2); A(2, 1) = A(1, 2); A(2, 2) = Dot(E2, E2); ComputeType const half = (ComputeType)0.5; Vector3<ComputeType> B{ half * A(0, 0), half * A(1, 1), half * A(2, 2) }; Sphere3<ComputeType> minimal; Vector3<ComputeType> X; if (LinearSystem<ComputeType>::Solve(A, B, X)) { ComputeType x3 = (ComputeType)1 - X[0] - X[1] - X[2]; minimal.center = X[0] * P0 + X[1] * P1 + X[2] * P2 + x3 * P3; Vector3<ComputeType> tmp = X[0] * E0 + X[1] * E1 + X[2] * E2; minimal.radius = Dot(tmp, tmp); } else { minimal.center = Vector3<ComputeType>::Zero(); minimal.radius = (ComputeType)std::numeric_limits<InputType>::max(); } return minimal; } typedef std::pair<Sphere3<ComputeType>, bool> UpdateResult; UpdateResult UpdateSupport1(int32_t i) { Sphere3<ComputeType> minimal = ExactSphere2(mSupport[0], i); mNumSupport = 2; mSupport[1] = i; return std::make_pair(minimal, true); } UpdateResult UpdateSupport2(int32_t i) { // Permutations of type 2, used for calling ExactSphere2(...). int32_t const numType2 = 2; int32_t const type2[numType2][2] = { { 0, /*2*/ 1 }, { 1, /*2*/ 0 } }; // Permutations of type 3, used for calling ExactSphere3(...). int32_t const numType3 = 1; // {0, 1, 2} Sphere3<ComputeType> sphere[numType2 + numType3]; ComputeType minRSqr = (ComputeType)std::numeric_limits<InputType>::max(); int32_t iSphere = 0, iMinRSqr = -1; int32_t k0, k1; // Permutations of type 2. for (int32_t j = 0; j < numType2; ++j, ++iSphere) { k0 = mSupport[type2[j][0]]; sphere[iSphere] = ExactSphere2(k0, i); if (sphere[iSphere].radius < minRSqr) { k1 = mSupport[type2[j][1]]; if (Contains(k1, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } // Permutations of type 3. k0 = mSupport[0]; k1 = mSupport[1]; sphere[iSphere] = ExactSphere3(k0, k1, i); if (sphere[iSphere].radius < minRSqr) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } switch (iMinRSqr) { case 0: mSupport[1] = i; break; case 1: mSupport[0] = i; break; case 2: mNumSupport = 3; mSupport[2] = i; break; case -1: // For exact arithmetic, iMinRSqr >= 0, but for floating-point // arithmetic, round-off errors can lead to iMinRSqr == -1. // When this happens, use a simple bounding sphere for the // result and terminate the minimum-volume algorithm. return std::make_pair(Sphere3<ComputeType>(), false); } return std::make_pair(sphere[iMinRSqr], true); } UpdateResult UpdateSupport3(int32_t i) { // Permutations of type 2, used for calling ExactSphere2(...). int32_t const numType2 = 3; int32_t const type2[numType2][3] = { { 0, /*3*/ 1, 2 }, { 1, /*3*/ 0, 2 }, { 2, /*3*/ 0, 1 } }; // Permutations of type 3, used for calling ExactSphere3(...). int32_t const numType3 = 3; int32_t const type3[numType3][3] = { { 0, 1, /*3*/ 2 }, { 0, 2, /*3*/ 1 }, { 1, 2, /*3*/ 0 } }; // Permutations of type 4, used for calling ExactSphere4(...). int32_t const numType4 = 1; // {0, 1, 2, 3} Sphere3<ComputeType> sphere[numType2 + numType3 + numType4]; ComputeType minRSqr = (ComputeType)std::numeric_limits<InputType>::max(); int32_t iSphere = 0, iMinRSqr = -1; int32_t k0, k1, k2; // Permutations of type 2. for (int32_t j = 0; j < numType2; ++j, ++iSphere) { k0 = mSupport[type2[j][0]]; sphere[iSphere] = ExactSphere2(k0, i); if (sphere[iSphere].radius < minRSqr) { k1 = mSupport[type2[j][1]]; k2 = mSupport[type2[j][2]]; if (Contains(k1, sphere[iSphere]) && Contains(k2, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } // Permutations of type 3. for (int32_t j = 0; j < numType3; ++j, ++iSphere) { k0 = mSupport[type3[j][0]]; k1 = mSupport[type3[j][1]]; sphere[iSphere] = ExactSphere3(k0, k1, i); if (sphere[iSphere].radius < minRSqr) { k2 = mSupport[type3[j][2]]; if (Contains(k2, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } // Permutations of type 4. k0 = mSupport[0]; k1 = mSupport[1]; k2 = mSupport[2]; sphere[iSphere] = ExactSphere4(k0, k1, k2, i); if (sphere[iSphere].radius < minRSqr) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } switch (iMinRSqr) { case 0: mNumSupport = 2; mSupport[1] = i; break; case 1: mNumSupport = 2; mSupport[0] = i; break; case 2: mNumSupport = 2; mSupport[0] = mSupport[2]; mSupport[1] = i; break; case 3: mSupport[2] = i; break; case 4: mSupport[1] = i; break; case 5: mSupport[0] = i; break; case 6: mNumSupport = 4; mSupport[3] = i; break; case -1: // For exact arithmetic, iMinRSqr >= 0, but for floating-point // arithmetic, round-off errors can lead to iMinRSqr == -1. // When this happens, use a simple bounding sphere for the // result and terminate the minimum-area algorithm. return std::make_pair(Sphere3<ComputeType>(), false); } return std::make_pair(sphere[iMinRSqr], true); } UpdateResult UpdateSupport4(int32_t i) { // Permutations of type 2, used for calling ExactSphere2(...). int32_t const numType2 = 4; int32_t const type2[numType2][4] = { { 0, /*4*/ 1, 2, 3 }, { 1, /*4*/ 0, 2, 3 }, { 2, /*4*/ 0, 1, 3 }, { 3, /*4*/ 0, 1, 2 } }; // Permutations of type 3, used for calling ExactSphere3(...). int32_t const numType3 = 6; int32_t const type3[numType3][4] = { { 0, 1, /*4*/ 2, 3 }, { 0, 2, /*4*/ 1, 3 }, { 0, 3, /*4*/ 1, 2 }, { 1, 2, /*4*/ 0, 3 }, { 1, 3, /*4*/ 0, 2 }, { 2, 3, /*4*/ 0, 1 } }; // Permutations of type 4, used for calling ExactSphere4(...). int32_t const numType4 = 4; int32_t const type4[numType4][4] = { { 0, 1, 2, /*4*/ 3 }, { 0, 1, 3, /*4*/ 2 }, { 0, 2, 3, /*4*/ 1 }, { 1, 2, 3, /*4*/ 0 } }; Sphere3<ComputeType> sphere[numType2 + numType3 + numType4]; ComputeType minRSqr = (ComputeType)std::numeric_limits<InputType>::max(); int32_t iSphere = 0, iMinRSqr = -1; int32_t k0, k1, k2, k3; // Permutations of type 2. for (int32_t j = 0; j < numType2; ++j, ++iSphere) { k0 = mSupport[type2[j][0]]; sphere[iSphere] = ExactSphere2(k0, i); if (sphere[iSphere].radius < minRSqr) { k1 = mSupport[type2[j][1]]; k2 = mSupport[type2[j][2]]; k3 = mSupport[type2[j][3]]; if (Contains(k1, sphere[iSphere]) && Contains(k2, sphere[iSphere]) && Contains(k3, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } // Permutations of type 3. for (int32_t j = 0; j < numType3; ++j, ++iSphere) { k0 = mSupport[type3[j][0]]; k1 = mSupport[type3[j][1]]; sphere[iSphere] = ExactSphere3(k0, k1, i); if (sphere[iSphere].radius < minRSqr) { k2 = mSupport[type3[j][2]]; k3 = mSupport[type3[j][3]]; if (Contains(k2, sphere[iSphere]) && Contains(k3, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } // Permutations of type 4. for (int32_t j = 0; j < numType4; ++j, ++iSphere) { k0 = mSupport[type4[j][0]]; k1 = mSupport[type4[j][1]]; k2 = mSupport[type4[j][2]]; sphere[iSphere] = ExactSphere4(k0, k1, k2, i); if (sphere[iSphere].radius < minRSqr) { k3 = mSupport[type4[j][3]]; if (Contains(k3, sphere[iSphere])) { minRSqr = sphere[iSphere].radius; iMinRSqr = iSphere; } } } switch (iMinRSqr) { case 0: mNumSupport = 2; mSupport[1] = i; break; case 1: mNumSupport = 2; mSupport[0] = i; break; case 2: mNumSupport = 2; mSupport[0] = mSupport[2]; mSupport[1] = i; break; case 3: mNumSupport = 2; mSupport[0] = mSupport[3]; mSupport[1] = i; break; case 4: mNumSupport = 3; mSupport[2] = i; break; case 5: mNumSupport = 3; mSupport[1] = i; break; case 6: mNumSupport = 3; mSupport[1] = mSupport[3]; mSupport[2] = i; break; case 7: mNumSupport = 3; mSupport[0] = i; break; case 8: mNumSupport = 3; mSupport[0] = mSupport[3]; mSupport[2] = i; break; case 9: mNumSupport = 3; mSupport[0] = mSupport[3]; mSupport[1] = i; break; case 10: mSupport[3] = i; break; case 11: mSupport[2] = i; break; case 12: mSupport[1] = i; break; case 13: mSupport[0] = i; break; case -1: // For exact arithmetic, iMinRSqr >= 0, but for floating-point // arithmetic, round-off errors can lead to iMinRSqr == -1. // When this happens, use a simple bounding sphere for the // result and terminate the minimum-area algorithm. return std::make_pair(Sphere3<ComputeType>(), false); } return std::make_pair(sphere[iMinRSqr], true); } // Indices of points that support current minimum volume sphere. bool SupportContains(int32_t j) const { for (int32_t i = 0; i < mNumSupport; ++i) { if (j == mSupport[i]) { return true; } } return false; } int32_t mNumSupport; std::array<int32_t, 4> mSupport; // Random permutation of the unique input points to produce expected // linear time for the algorithm. std::default_random_engine mDRE; std::vector<Vector3<ComputeType>> mComputePoints; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace3OrientedBox3.h
.h
1,716
55
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/Halfspace.h> #include <Mathematics/OrientedBox.h> // Queries for intersection of objects with halfspaces. These are useful for // containment testing, object culling, and clipping. namespace gte { template <typename T> class TIQuery<T, Halfspace3<T>, OrientedBox3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Halfspace3<T> const& halfspace, OrientedBox3<T> const& box) { Result result{}; // Project the box center onto the normal line. The plane of the // halfspace occurs at the origin (zero) of the normal line. T center = Dot(halfspace.normal, box.center) - halfspace.constant; // Compute the radius of the interval of projection. T radius = std::fabs(box.extent[0] * Dot(halfspace.normal, box.axis[0])) + std::fabs(box.extent[1] * Dot(halfspace.normal, box.axis[1])) + std::fabs(box.extent[2] * Dot(halfspace.normal, box.axis[2])); // The box and halfspace intersect when the projection interval // maximum is nonnegative. result.intersect = (center + radius >= (T)0); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistTriangle3OrientedBox3.h
.h
2,663
77
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistTriangle3CanonicalBox3.h> #include <Mathematics/DistSegment3CanonicalBox3.h> #include <Mathematics/OrientedBox.h> // Compute the distance between a solid triangle and a solid oriented box // in 3D. // // The triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where // |y[i]| <= e[i] for all i. // // The closest point on the triangle closest is stored in closest[0] with // barycentric coordinates (b[0],b[1],b[2). The closest point on the box is // stored in closest[1]. When there are infinitely many choices for the pair // of closest points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Triangle3<T>, OrientedBox3<T>> { public: using TBQuery = DCPQuery<T, Triangle3<T>, CanonicalBox3<T>>; using Result = typename TBQuery::Result; Result operator()(Triangle3<T> const& triangle, OrientedBox3<T> const& box) { Result result{}; // Rotate and translate the line and box so that the box is // aligned and has center at the origin. CanonicalBox3<T> cbox(box.extent); Triangle3<T> xfrmTriangle{}; for (size_t j = 0; j < 3; ++j) { Vector3<T> delta = triangle.v[j] - box.center; for (int32_t i = 0; i < 3; ++i) { xfrmTriangle.v[j][i] = Dot(box.axis[i], delta); } } // The query computes 'result' relative to the box with center // at the origin. TBQuery tbQuery{}; result = tbQuery(xfrmTriangle, cbox); // Rotate and translate the closest points to the original // coordinates. std::array<Vector3<T>, 2> closest{ box.center, box.center }; for (size_t i = 0; i < 2; ++i) { for (int32_t j = 0; j < 3; ++j) { closest[i] += result.closest[i][j] * box.axis[j]; } } result.closest = closest; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BasisFunction.h
.h
17,755
482
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <Mathematics/Array2.h> #include <array> #include <cstring> namespace gte { template <typename Real> struct UniqueKnot { Real t; int32_t multiplicity; }; template <typename Real> struct BasisFunctionInput { // The members are uninitialized. BasisFunctionInput() : numControls(0), degree(0), uniform(false), periodic(false), numUniqueKnots(0), uniqueKnots{} { } // Construct an open uniform curve with t in [0,1]. BasisFunctionInput(int32_t inNumControls, int32_t inDegree) : numControls(inNumControls), degree(inDegree), uniform(true), periodic(false), numUniqueKnots(numControls - degree + 1), uniqueKnots(numUniqueKnots) { uniqueKnots.front().t = (Real)0; uniqueKnots.front().multiplicity = degree + 1; for (int32_t i = 1; i <= numUniqueKnots - 2; ++i) { uniqueKnots[i].t = i / (numUniqueKnots - (Real)1); uniqueKnots[i].multiplicity = 1; } uniqueKnots.back().t = (Real)1; uniqueKnots.back().multiplicity = degree + 1; } int32_t numControls; int32_t degree; bool uniform; bool periodic; int32_t numUniqueKnots; std::vector<UniqueKnot<Real>> uniqueKnots; }; template <typename Real> class BasisFunction { public: // Let n be the number of control points. Let d be the degree, where // 1 <= d <= n-1. The number of knots is k = n + d + 1. The knots // are t[i] for 0 <= i < k and must be nondecreasing, t[i] <= t[i+1], // but a knot value can be repeated. Let s be the number of distinct // knots. Let the distinct knots be u[j] for 0 <= j < s, so u[j] < // u[j+1] for all j. The set of u[j] is called a 'breakpoint // sequence'. Let m[j] >= 1 be the multiplicity; that is, if t[i] is // the first occurrence of u[j], then t[i+r] = t[i] for 1 <= r < m[j]. // The multiplicities have the constraints m[0] <= d+1, m[s-1] <= d+1, // and m[j] <= d for 1 <= j <= s-2. Also, k = sum_{j=0}^{s-1} m[j], // which says the multiplicities account for all k knots. // // Given a knot vector (t[0],...,t[n+d]), the domain of the // corresponding B-spline curve is the interval [t[d],t[n]]. // // The corresponding B-spline or NURBS curve is characterized as // follows. See "Geometric Modeling with Splines: An Introduction" by // Elaine Cohen, Richard F. Riesenfeld and Gershon Elber, AK Peters, // 2001, Natick MA. The curve is 'open' when m[0] = m[s-1] = d+1; // otherwise, it is 'floating'. An open curve is uniform when the // knots t[d] through t[n] are equally spaced; that is, t[i+1] - t[i] // are a common value for d <= i <= n-1. By implication, s = n-d+1 // and m[j] = 1 for 1 <= j <= s-2. An open curve that does not // satisfy these conditions is said to be nonuniform. A floating // curve is uniform when m[j] = 1 for 0 <= j <= s-1 and t[i+1] - t[i] // are a common value for 0 <= i <= k-2; otherwise, the floating curve // is nonuniform. // // A special case of a floating curve is a periodic curve. The intent // is that the curve is closed, so the first and last control points // should be the same, which ensures C^{0} continuity. Higher-order // continuity is obtained by repeating more control points. If the // control points are P[0] through P[n-1], append the points P[0] // through P[d-1] to ensure C^{d-1} continuity. Additionally, the // knots must be chosen properly. You may choose t[d] through t[n] as // you wish. The other knots are defined by // t[i] - t[i-1] = t[n-d+i] - t[n-d+i-1] // t[n+i] - t[n+i-1] = t[d+i] - t[d+i-1] // for 1 <= i <= d. // Construction and destruction. The determination that the curve is // open or floating is based on the multiplicities. The 'uniform' // input is used to avoid misclassifications due to floating-point // rounding errors. Specifically, the breakpoints might be equally // spaced (uniform) as real numbers, but the floating-point // representations can have rounding errors that cause the knot // differences not to be exactly the same constant. A periodic curve // can have uniform or nonuniform knots. This object makes copies of // the input arrays. BasisFunction() : mNumControls(0), mDegree(0), mTMin((Real)0), mTMax((Real)0), mTLength((Real)0), mOpen(false), mUniform(false), mPeriodic(false) { } BasisFunction(BasisFunctionInput<Real> const& input) : mNumControls(0), mDegree(0), mTMin((Real)0), mTMax((Real)0), mTLength((Real)0), mOpen(false), mUniform(false), mPeriodic(false) { Create(input); } ~BasisFunction() { } // No copying is allowed. BasisFunction(BasisFunction const&) = delete; BasisFunction& operator=(BasisFunction const&) = delete; // Support for explicit creation in classes that have std::array // members involving BasisFunction. This is a call-once function. void Create(BasisFunctionInput<Real> const& input) { LogAssert(mNumControls == 0 && mDegree == 0, "Object already created."); LogAssert(input.numControls >= 2, "Invalid number of control points."); LogAssert(1 <= input.degree && input.degree < input.numControls, "Invalid degree."); LogAssert(input.numUniqueKnots >= 2, "Invalid number of unique knots."); mNumControls = (input.periodic ? input.numControls + input.degree : input.numControls); mDegree = input.degree; mTMin = (Real)0; mTMax = (Real)0; mTLength = (Real)0; mOpen = false; mUniform = input.uniform; mPeriodic = input.periodic; for (int32_t i = 0; i < 4; ++i) { mJet[i] = Array2<Real>(); } mUniqueKnots.resize(input.numUniqueKnots); std::copy(input.uniqueKnots.begin(), input.uniqueKnots.begin() + input.numUniqueKnots, mUniqueKnots.begin()); Real u = mUniqueKnots.front().t; for (int32_t i = 1; i < input.numUniqueKnots - 1; ++i) { Real uNext = mUniqueKnots[i].t; LogAssert(u < uNext, "Unique knots are not strictly increasing."); u = uNext; } int32_t mult0 = mUniqueKnots.front().multiplicity; LogAssert(mult0 >= 1 && mult0 <= mDegree + 1, "Invalid first multiplicity."); int32_t mult1 = mUniqueKnots.back().multiplicity; LogAssert(mult1 >= 1 && mult1 <= mDegree + 1, "Invalid last multiplicity."); for (int32_t i = 1; i <= input.numUniqueKnots - 2; ++i) { int32_t mult = mUniqueKnots[i].multiplicity; LogAssert(mult >= 1 && mult <= mDegree + 1, "Invalid interior multiplicity."); } mOpen = (mult0 == mult1 && mult0 == mDegree + 1); mKnots.resize(static_cast<size_t>(mNumControls) + static_cast<size_t>(mDegree) + 1); mKeys.resize(input.numUniqueKnots); int32_t sum = 0; for (int32_t i = 0, j = 0; i < input.numUniqueKnots; ++i) { Real tCommon = mUniqueKnots[i].t; int32_t mult = mUniqueKnots[i].multiplicity; for (int32_t k = 0; k < mult; ++k, ++j) { mKnots[j] = tCommon; } mKeys[i].first = tCommon; mKeys[i].second = sum - 1; sum += mult; } mTMin = mKnots[mDegree]; mTMax = mKnots[mNumControls]; mTLength = mTMax - mTMin; size_t numRows = static_cast<size_t>(mDegree) + 1; size_t numCols = static_cast<size_t>(mNumControls) + static_cast<size_t>(mDegree); size_t numBytes = numRows * numCols * sizeof(Real); for (int32_t i = 0; i < 4; ++i) { mJet[i] = Array2<Real>(numCols, numRows); std::memset(mJet[i][0], 0, numBytes); } } // Member access. inline int32_t GetNumControls() const { return mNumControls; } inline int32_t GetDegree() const { return mDegree; } inline int32_t GetNumUniqueKnots() const { return static_cast<int32_t>(mUniqueKnots.size()); } inline int32_t GetNumKnots() const { return static_cast<int32_t>(mKnots.size()); } inline Real GetMinDomain() const { return mTMin; } inline Real GetMaxDomain() const { return mTMax; } inline bool IsOpen() const { return mOpen; } inline bool IsUniform() const { return mUniform; } inline bool IsPeriodic() const { return mPeriodic; } inline UniqueKnot<Real> const* GetUniqueKnots() const { return &mUniqueKnots[0]; } inline Real const* GetKnots() const { return &mKnots[0]; } // Evaluation of the basis function and its derivatives through // order 3. For the function value only, pass order 0. For the // function and first derivative, pass order 1, and so on. void Evaluate(Real t, uint32_t order, int32_t& minIndex, int32_t& maxIndex) const { LogAssert(order <= 3, "Invalid order."); int32_t i = GetIndex(t); mJet[0][0][i] = (Real)1; if (order >= 1) { mJet[1][0][i] = (Real)0; if (order >= 2) { mJet[2][0][i] = (Real)0; if (order >= 3) { mJet[3][0][i] = (Real)0; } } } Real n0 = t - mKnots[i], n1 = mKnots[static_cast<size_t>(i) + 1] - t; Real e0, e1, d0, d1, invD0, invD1; int32_t j; for (j = 1; j <= mDegree; j++) { d0 = mKnots[static_cast<size_t>(i) + static_cast<size_t>(j)] - mKnots[i]; d1 = mKnots[static_cast<size_t>(i) + 1] - mKnots[static_cast<size_t>(i) - static_cast<size_t>(j) + 1]; invD0 = (d0 > (Real)0 ? (Real)1 / d0 : (Real)0); invD1 = (d1 > (Real)0 ? (Real)1 / d1 : (Real)0); e0 = n0 * mJet[0][j - 1][i]; mJet[0][j][i] = e0 * invD0; e1 = n1 * mJet[0][j - 1][i - j + 1]; mJet[0][j][i - j] = e1 * invD1; if (order >= 1) { e0 = n0 * mJet[1][j - 1][i] + mJet[0][j - 1][i]; mJet[1][j][i] = e0 * invD0; e1 = n1 * mJet[1][j - 1][i - j + 1] - mJet[0][j - 1][i - j + 1]; mJet[1][j][i - j] = e1 * invD1; if (order >= 2) { e0 = n0 * mJet[2][j - 1][i] + ((Real)2) * mJet[1][j - 1][i]; mJet[2][j][i] = e0 * invD0; e1 = n1 * mJet[2][j - 1][i - j + 1] - ((Real)2) * mJet[1][j - 1][i - j + 1]; mJet[2][j][i - j] = e1 * invD1; if (order >= 3) { e0 = n0 * mJet[3][j - 1][i] + ((Real)3) * mJet[2][j - 1][i]; mJet[3][j][i] = e0 * invD0; e1 = n1 * mJet[3][j - 1][i - j + 1] - ((Real)3) * mJet[2][j - 1][i - j + 1]; mJet[3][j][i - j] = e1 * invD1; } } } } for (j = 2; j <= mDegree; ++j) { for (int32_t k = i - j + 1; k < i; ++k) { n0 = t - mKnots[k]; n1 = mKnots[static_cast<size_t>(k) + static_cast<size_t>(j) + 1] - t; d0 = mKnots[static_cast<size_t>(k) + static_cast<size_t>(j)] - mKnots[k]; d1 = mKnots[static_cast<size_t>(k) + static_cast<size_t>(j) + 1] - mKnots[static_cast<size_t>(k) + 1]; invD0 = (d0 > (Real)0 ? (Real)1 / d0 : (Real)0); invD1 = (d1 > (Real)0 ? (Real)1 / d1 : (Real)0); e0 = n0 * mJet[0][j - 1][k]; e1 = n1 * mJet[0][j - 1][k + 1]; mJet[0][j][k] = e0 * invD0 + e1 * invD1; if (order >= 1) { e0 = n0 * mJet[1][j - 1][k] + mJet[0][j - 1][k]; e1 = n1 * mJet[1][j - 1][k + 1] - mJet[0][j - 1][k + 1]; mJet[1][j][k] = e0 * invD0 + e1 * invD1; if (order >= 2) { e0 = n0 * mJet[2][j - 1][k] + ((Real)2) * mJet[1][j - 1][k]; e1 = n1 * mJet[2][j - 1][k + 1] - ((Real)2) * mJet[1][j - 1][k + 1]; mJet[2][j][k] = e0 * invD0 + e1 * invD1; if (order >= 3) { e0 = n0 * mJet[3][j - 1][k] + ((Real)3) * mJet[2][j - 1][k]; e1 = n1 * mJet[3][j - 1][k + 1] - ((Real)3) * mJet[2][j - 1][k + 1]; mJet[3][j][k] = e0 * invD0 + e1 * invD1; } } } } } minIndex = i - mDegree; maxIndex = i; } // Access the results of the call to Evaluate(...). The index i must // satisfy minIndex <= i <= maxIndex. If it is not, the function // returns zero. The separation of evaluation and access is based on // local control of the basis function; that is, only the accessible // values are (potentially) not zero. Real GetValue(uint32_t order, int32_t i) const { if (order < 4) { if (0 <= i && i < mNumControls + mDegree) { return mJet[order][mDegree][i]; } LogError("Invalid index."); } LogError("Invalid order."); } private: // Determine the index i for which knot[i] <= t < knot[i+1]. The // t-value is modified (wrapped for periodic splines, clamped for // nonperiodic splines). int32_t GetIndex(Real& t) const { // Find the index i for which knot[i] <= t < knot[i+1]. if (mPeriodic) { // Wrap to [tmin,tmax]. Real r = std::fmod(t - mTMin, mTLength); if (r < (Real)0) { r += mTLength; } t = mTMin + r; } // Clamp to [tmin,tmax]. For the periodic case, this handles // small numerical rounding errors near the domain endpoints. if (t <= mTMin) { t = mTMin; return mDegree; } if (t >= mTMax) { t = mTMax; return mNumControls - 1; } // At this point, tmin < t < tmax. for (auto const& key : mKeys) { if (t < key.first) { return key.second; } } // We should not reach this code. LogError("Unexpected condition."); } // Constructor inputs and values derived from them. int32_t mNumControls; int32_t mDegree; Real mTMin, mTMax, mTLength; bool mOpen; bool mUniform; bool mPeriodic; std::vector<UniqueKnot<Real>> mUniqueKnots; std::vector<Real> mKnots; // Lookup information for the GetIndex() function. The first element // of the pair is a unique knot value. The second element is the // index in mKnots[] for the last occurrence of that knot value. std::vector<std::pair<Real, int32_t>> mKeys; // Storage for the basis functions and their first three derivatives; // mJet[i] is array[d+1][n+d]. mutable std::array<Array2<Real>, 4> mJet; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPoint3Circle3.h
.h
5,968
145
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/DCPQuery.h> #include <Mathematics/Circle3.h> // The 3D point-circle distance algorithm is described in // https://www.geometrictools.com/Documentation/DistanceToCircle3.pdf // The notation used in the code matches that of the document. namespace gte { template <typename T> class DCPQuery<T, Vector3<T>, Circle3<T>> { public: // The input point is stored in the member closest[0]. If a single // point on the circle is closest to the input point, the member // closest[1] is set to that point and the equidistant member is set // to false. If the entire circle is equidistant to the point, the // member closest[1] is set to C+r*U, where C is the circle center, // r is the circle radius and U is a vector perpendicular to the // normal N for the plane of the circles. Moreover, the equidistant // member is set to true. struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, equidistant(false) { } T distance, sqrDistance; std::array<Vector3<T>, 2> closest; bool equidistant; }; Result operator()(Vector3<T> const& point, Circle3<T> const& circle) { Result result{}; // The projection of P-C onto the plane of the circle is // Q - C = (P - C) - Dot(N, P - C) * N. When P is nearly on the // normal line C + t * N, Q - C is nearly the zero vector. In this // case, floating-point rounding errors are a problem when the // closest point is computed as C + r * (Q - C) / Length(Q - C). // The rounding errors in Q - C are magnified by the division by // length, leading to an inaccurate result. Experiments indicate // it is better to compute an orthonormal basis {U, V, N}, where // the vectors are unit length and mutually perpendicular. The // point is P = C + x * U + y * V + z * N, with x = Dot(U, P - C), // y = Dot(V, Q - C) and z = Dot(N, Q - C). The projection is // Q = C + x * U + y * V. The computation of U and V involves // normalizations (divisions by square roots) which can be // avoided by instead computing an orthogonal basis {U, V, N}, // where the vectors are mutually perpendicular but not required // to be unit length. U is computed by swapping two components // of N with at least one component nonzero and then negating a // component. V is computed as Cross(N, U). For example, if // N = (n0, n1, n2) with n0 != 0 or n1 != 0, then U = (-n1, n0, 0) // and V = (-n0*n2, -n1*n2, n0^2 + n1^2). Observe that the length // of V is |V| = |N|*|U|. In this case the projection is // Q - C = x * U + y * V, // x = Dot(U, Q - C) / Dot(U, U) // y = Dot(V, Q - C) / (Dot(U, U) * Dot(N, N)) // It is sufficient to process the scaled // Dot(N, N) * Dot(U, U) * (Q - C) // to avoid the divisions before normalization. Vector3<T> PmC = point - circle.center; Vector3<T> U{}, V{}, N = circle.normal; ComputeOrthogonalBasis(1, N, U, V); Vector3<T> scaledQmC = (Dot(N, N) * Dot(U, PmC)) * U + Dot(V, PmC) * V; T lengthScaledQmC = Length(scaledQmC); if (lengthScaledQmC > static_cast<T>(0)) { result.closest[0] = point; result.closest[1] = circle.center + circle.radius * (scaledQmC / lengthScaledQmC); T height = Dot(N, PmC); T radial = Length(Cross(N, PmC)) - circle.radius; result.sqrDistance = height * height + radial * radial; result.distance = std::sqrt(result.sqrDistance); result.equidistant = false; } else { // All circle points are equidistant from P. Return one of // them. result.closest[0] = point; result.closest[1] = circle.center + circle.radius * GetOrthogonal(N, true); result.sqrDistance = Dot(PmC, PmC) + circle.radius * circle.radius; result.distance = std::sqrt(result.sqrDistance); result.equidistant = true; } return result; } private: bool ComputeOrthogonalBasis(size_t numInputs, Vector3<T>& v0, Vector3<T>& v1, Vector3<T>& v2) { LogAssert( 1 <= numInputs && numInputs <= 3, "Invalid number of inputs."); if (numInputs == 1) { T const zero = static_cast<T>(0); if (std::fabs(v0[0]) > std::fabs(v0[1])) { v1 = { -v0[2], zero, v0[0] }; } else { v1 = { zero, v0[2], -v0[1] }; } } else // numInputs == 2 || numInputs == 3 { v1 = Dot(v0, v0) * v1 - Dot(v1, v0) * v0; } if (v1 == Vector3<T>::Zero()) { v2.MakeZero(); return false; } v2 = Cross(v0, v1); return v2 != Vector3<T>::Zero(); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrEllipse2Ellipse2.h
.h
49,212
1,291
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/RootsBisection.h> #include <Mathematics/RootsPolynomial.h> #include <Mathematics/SymmetricEigensolver2x2.h> #include <Mathematics/Matrix2x2.h> // The test-intersection and find-intersection queries implemented here are // discussed in the document // https://www.geometrictools.com/Documentation/IntersectionOfEllipses.pdf // The T type should support exact rational arithmetic in order for the // polynomial root construction to be robust. The classification of the // intersections depends on various sign tests of computed values. If these // values are computed with floating-point arithmetic, the sign tests can // lead to misclassification. // // The area-of-intersection query is discussed in the document // https://www.geometrictools.com/Documentation/AreaIntersectingEllipses.pdf namespace gte { template <typename T> class TIQuery<T, Ellipse2<T>, Ellipse2<T>> { public: // The query tests the relationship between the ellipses as solid // objects. enum class Classification { ELLIPSES_SEPARATED, ELLIPSES_OVERLAP, ELLIPSE0_OUTSIDE_ELLIPSE1_BUT_TANGENT, ELLIPSE0_STRICTLY_CONTAINS_ELLIPSE1, ELLIPSE0_CONTAINS_ELLIPSE1_BUT_TANGENT, ELLIPSE1_STRICTLY_CONTAINS_ELLIPSE0, ELLIPSE1_CONTAINS_ELLIPSE0_BUT_TANGENT, ELLIPSES_EQUAL }; // The ellipse axes are already normalized, which most likely // introduced rounding errors. Classification operator()(Ellipse2<T> const& ellipse0, Ellipse2<T> const& ellipse1) { T const zero = 0, one = 1; // Get the parameters of ellipe0. Vector2<T> K0 = ellipse0.center; Matrix2x2<T> R0; R0.SetCol(0, ellipse0.axis[0]); R0.SetCol(1, ellipse0.axis[1]); Matrix2x2<T> D0{ one / (ellipse0.extent[0] * ellipse0.extent[0]), zero, zero, one / (ellipse0.extent[1] * ellipse0.extent[1]) }; // Get the parameters of ellipse1. Vector2<T> K1 = ellipse1.center; Matrix2x2<T> R1; R1.SetCol(0, ellipse1.axis[0]); R1.SetCol(1, ellipse1.axis[1]); Matrix2x2<T> D1{ one / (ellipse1.extent[0] * ellipse1.extent[0]), zero, zero, one / (ellipse1.extent[1] * ellipse1.extent[1]) }; // Compute K2 = D0^{1/2}*R0^T*(K1-K0). In the GTE code, the // quantity U = R0^T*(K1-K0) is a 2x1 vector which can be computed // in the GTE code by U = Transpose(R0)*(K1-K0). However, to avoid // the creation of the matrix object Transpose(R0), you can use // U^T = V^T*R0 which can be computed in the GTE code by // W = (K1-K0)*R0. The output W is mathematically a 1x2 vector, // but as a Vector<?> object, it is a 2-tuple. You can then // compute K2 = D0Half*W, where the 2-tuple W is now thought of // as a 2x1 vector. See Matrix.h, the operator function // Vector<?> operator*(Vector<?> const&, Matrix<?> const&) which // computes V^T*M for a Vector<?> V and a Matrix<?> M. Matrix2x2<T> D0NegHalf{ ellipse0.extent[0], zero, zero, ellipse0.extent[1] }; Matrix2x2<T> D0Half{ one / ellipse0.extent[0], zero, zero, one / ellipse0.extent[1] }; Vector2<T> K2 = D0Half * ((K1 - K0) * R0); // Compute M2. Matrix2x2<T> R1TR0D0NegHalf = MultiplyATB(R1, R0 * D0NegHalf); Matrix2x2<T> M2 = MultiplyATB(R1TR0D0NegHalf, D1) * R1TR0D0NegHalf; // Factor M2 = R*D*R^T. SymmetricEigensolver2x2<T> es; std::array<T, 2> D; std::array<std::array<T, 2>, 2> evec; es(M2(0, 0), M2(0, 1), M2(1, 1), +1, D, evec); Matrix2x2<T> R; R.SetCol(0, evec[0]); R.SetCol(1, evec[1]); // Compute K = R^T*K2. Vector2<T> K = K2 * R; // Transformed ellipse0 is Z^T*Z = 1 and transformed ellipse1 is // (Z-K)^T*D*(Z-K) = 0. // The minimum and maximum squared distances from the origin of // points on transformed ellipse1 are used to determine whether // the ellipses intersect, are separated or one contains the // other. T minSqrDistance = std::numeric_limits<T>::max(); T maxSqrDistance = zero; if (K == Vector2<T>::Zero()) { // The special case of common centers must be handled // separately. It is not possible for the ellipses to be // separated. for (int32_t i = 0; i < 2; ++i) { T invD = one / D[i]; if (invD < minSqrDistance) { minSqrDistance = invD; } if (invD > maxSqrDistance) { maxSqrDistance = invD; } } return Classify(minSqrDistance, maxSqrDistance, zero); } // The closest point P0 and farthest point P1 are solutions to // s0*D*(P0 - K) = P0 and s1*D1*(P1 - K) = P1 for some scalars s0 // and s1 that are roots to the function // f(s) = d0*k0^2/(d0*s-1)^2 + d1*k1^2/(d1*s-1)^2 - 1 // where D = diagonal(d0,d1) and K = (k0,k1). T d0 = D[0], d1 = D[1]; T c0 = K[0] * K[0], c1 = K[1] * K[1]; // Sort the values so that d0 >= d1. This allows us to bound the // roots of f(s), of which there are at most 4. std::vector<std::pair<T, T>> param(2); if (d0 >= d1) { param[0] = std::make_pair(d0, c0); param[1] = std::make_pair(d1, c1); } else { param[0] = std::make_pair(d1, c1); param[1] = std::make_pair(d0, c0); } std::vector<std::pair<T, T>> valid{}; valid.reserve(2); if (param[0].first > param[1].first) { // d0 > d1 for (int32_t i = 0; i < 2; ++i) { if (param[i].second > zero) { valid.push_back(param[i]); } } } else { // d0 = d1 param[0].second += param[1].second; if (param[0].second > zero) { valid.push_back(param[0]); } } size_t numValid = valid.size(); int32_t numRoots = 0; std::array<T, 4> roots{}; if (numValid == 2) { GetRoots(valid[0].first, valid[1].first, valid[0].second, valid[1].second, numRoots, roots.data()); } else if (numValid == 1) { GetRoots(valid[0].first, valid[0].second, numRoots, roots.data()); } // else: numValid cannot be zero because we already handled case // K = 0 for (int32_t i = 0; i < numRoots; ++i) { T s = roots[i]; T p0 = d0 * K[0] * s / (d0 * s - (T)1); T p1 = d1 * K[1] * s / (d1 * s - (T)1); T sqrDistance = p0 * p0 + p1 * p1; if (sqrDistance < minSqrDistance) { minSqrDistance = sqrDistance; } if (sqrDistance > maxSqrDistance) { maxSqrDistance = sqrDistance; } } return Classify(minSqrDistance, maxSqrDistance, d0 * c0 + d1 * c1); } private: void GetRoots(T d0, T c0, int32_t& numRoots, T* roots) { // f(s) = d0*c0/(d0*s-1)^2 - 1 T const one = (T)1; T temp = std::sqrt(d0 * c0); T inv = one / d0; numRoots = 2; roots[0] = (one - temp) * inv; roots[1] = (one + temp) * inv; } void GetRoots(T d0, T d1, T c0, T c1, int32_t& numRoots, T* roots) { // f(s) = d0*c0/(d0*s-1)^2 + d1*c1/(d1*s-1)^2 - 1 with d0 > d1 T const zero = 0, one = (T)1; T d0c0 = d0 * c0; T d1c1 = d1 * c1; T sum = d0c0 + d1c1; T sqrtsum = std::sqrt(sum); std::function<T(T)> F = [&one, d0, d1, d0c0, d1c1](T s) { T invN0 = one / (d0 * s - one); T invN1 = one / (d1 * s - one); T term0 = d0c0 * invN0 * invN0; T term1 = d1c1 * invN1 * invN1; T f = term0 + term1 - one; return f; }; std::function<T(T)> DF = [&one, d0, d1, d0c0, d1c1](T s) { T const two = 2; T invN0 = one / (d0 * s - one); T invN1 = one / (d1 * s - one); T term0 = d0 * d0c0 * invN0 * invN0 * invN0; T term1 = d1 * d1c1 * invN1 * invN1 * invN1; T df = -two * (term0 + term1); return df; }; uint32_t const maxIterations = static_cast<uint32_t>( 3 + std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent); uint32_t iterations; numRoots = 0; T invD0 = one / d0; T invD1 = one / d1; T smin, smax, fval, s = (T)0; // Compute root in (-infinity,1/d0). Obtain a lower bound for the // root better than -std::numeric_limits<T>::max(). smax = invD0; fval = sum - one; if (fval > zero) { smin = (one - sqrtsum) * invD1; // < 0 fval = F(smin); LogAssert(fval <= zero, "Unexpected condition."); } else { smin = zero; } iterations = RootsBisection<T>::Find(F, smin, smax, -one, one, maxIterations, s); fval = F(s); LogAssert(iterations > 0, "Unexpected condition."); roots[numRoots++] = s; // Compute roots (if any) in (1/d0,1/d1). It is the case that // F(1/d0) = +infinity, F'(1/d0) = -infinity // F(1/d1) = +infinity, F'(1/d1) = +infinity // F"(s) > 0 for all s in the domain of F // Compute the unique root r of F'(s) on (1/d0,1/d1). The // bisector needs only the signs at the endpoints, so we pass -1 // and +1 instead of the infinite values. If F(r) < 0, F(s) has // two roots in the interval. If F(r) = 0, F(s) has only one root // in the interval. T const oneThird = (T)1 / (T)3; T rho = std::pow(d0 * d0c0 / (d1 * d1c1), oneThird); T smid = (one + rho) / (d0 + rho * d1); T fmid = F(smid); if (fmid < zero) { // Pass in signs rather than infinities, because the bisector cares // only about the signs. iterations = RootsBisection<T>::Find(F, invD0, smid, one, -one, maxIterations, s); fval = F(s); LogAssert(iterations > 0, "Unexpected condition."); roots[numRoots++] = s; iterations = RootsBisection<T>::Find(F, smid, invD1, -one, one, maxIterations, s); fval = F(s); LogAssert(iterations > 0, "Unexpected condition."); roots[numRoots++] = s; } else if (fmid == zero) { roots[numRoots++] = smid; } // Compute root in (1/d1,+infinity). Obtain an upper bound for // the root better than std::numeric_limits<T>::max(). smin = invD1; smax = (one + sqrtsum) * invD1; // > 1/d1 fval = F(smax); LogAssert(fval <= zero, "Unexpected condition."); iterations = RootsBisection<T>::Find(F, smin, smax, one, -one, maxIterations, s); fval = F(s); LogAssert(iterations > 0, "Unexpected condition."); roots[numRoots++] = s; } Classification Classify(T minSqrDistance, T maxSqrDistance, T d0c0pd1c1) { T const one = (T)1; if (maxSqrDistance < one) { return Classification::ELLIPSE0_STRICTLY_CONTAINS_ELLIPSE1; } else if (maxSqrDistance > one) { if (minSqrDistance < one) { return Classification::ELLIPSES_OVERLAP; } else if (minSqrDistance > one) { if (d0c0pd1c1 > one) { return Classification::ELLIPSES_SEPARATED; } else { return Classification::ELLIPSE1_STRICTLY_CONTAINS_ELLIPSE0; } } else // minSqrDistance = 1 { if (d0c0pd1c1 > one) { return Classification::ELLIPSE0_OUTSIDE_ELLIPSE1_BUT_TANGENT; } else { return Classification::ELLIPSE1_CONTAINS_ELLIPSE0_BUT_TANGENT; } } } else // maxSqrDistance = 1 { if (minSqrDistance < one) { return Classification::ELLIPSE0_CONTAINS_ELLIPSE1_BUT_TANGENT; } else // minSqrDistance = 1 { return Classification::ELLIPSES_EQUAL; } } } }; template <typename T> class FIQuery<T, Ellipse2<T>, Ellipse2<T>> { public: // The queries find the intersections (if any) of the ellipses treated // as hollow objects. The implementations use the same concepts. FIQuery() : mZero((T)0), mOne((T)1), mTwo((T)2), mPi((T)GTE_C_PI), mTwoPi((T)GTE_C_TWO_PI), mA{ (T)0, (T)0, (T)0, (T)0, (T)0 }, mB{ (T)0, (T)0, (T)0, (T)0, (T)0 }, mD{ (T)0, (T)0, (T)0, (T)0, (T)0 }, mF{ (T)0, (T)0, (T)0, (T)0, (T)0 }, mC{ (T)0, (T)0, (T)0 }, mE{ (T)0, (T)0, (T)0 }, mA2Div2((T)0), mA4Div2((T)0) { } struct Result { // This value is true when the ellipses intersect in at least one // point. bool intersect; // If the ellipses are not the same, numPoints is 0 through 4 and // that number of elements of 'points' are valid. If the ellipses // are the same, numPoints is set to maxInt and 'points' is // invalid. int32_t numPoints; std::array<Vector2<T>, 4> points; std::array<bool, 4> isTransverse; }; // The ellipse axes are already normalized, which most likely // introducedrounding errors. Result operator()(Ellipse2<T> const& ellipse0, Ellipse2<T> const& ellipse1) { Vector2<T> rCenter, rAxis[2], rSqrExtent; rCenter = { ellipse0.center[0], ellipse0.center[1] }; rAxis[0] = { ellipse0.axis[0][0], ellipse0.axis[0][1] }; rAxis[1] = { ellipse0.axis[1][0], ellipse0.axis[1][1] }; rSqrExtent = { ellipse0.extent[0] * ellipse0.extent[0], ellipse0.extent[1] * ellipse0.extent[1] }; ToCoefficients(rCenter, rAxis, rSqrExtent, mA); rCenter = { ellipse1.center[0], ellipse1.center[1] }; rAxis[0] = { ellipse1.axis[0][0], ellipse1.axis[0][1] }; rAxis[1] = { ellipse1.axis[1][0], ellipse1.axis[1][1] }; rSqrExtent = { ellipse1.extent[0] * ellipse1.extent[0], ellipse1.extent[1] * ellipse1.extent[1] }; ToCoefficients(rCenter, rAxis, rSqrExtent, mB); Result result; DoRootFinding(result); return result; } // The axis directions do not have to be unit length. The quadratic // equations are constructed according to the details of the PDF // document about the intersection of ellipses. Result operator()(Vector2<T> const& center0, Vector2<T> const axis0[2], Vector2<T> const& sqrExtent0, Vector2<T> const& center1, Vector2<T> const axis1[2], Vector2<T> const& sqrExtent1) { Vector2<T> rCenter, rAxis[2], rSqrExtent; rCenter = { center0[0], center0[1] }; rAxis[0] = { axis0[0][0], axis0[0][1] }; rAxis[1] = { axis0[1][0], axis0[1][1] }; rSqrExtent = { sqrExtent0[0], sqrExtent0[1] }; ToCoefficients(rCenter, rAxis, rSqrExtent, mA); rCenter = { center1[0], center1[1] }; rAxis[0] = { axis1[0][0], axis1[0][1] }; rAxis[1] = { axis1[1][0], axis1[1][1] }; rSqrExtent = { sqrExtent1[0], sqrExtent1[1] }; ToCoefficients(rCenter, rAxis, rSqrExtent, mB); Result result; DoRootFinding(result); return result; } // Compute the area of intersection of ellipses. struct AreaResult { // The configuration of the two ellipses. enum class Configuration { ELLIPSES_ARE_EQUAL, ELLIPSES_ARE_SEPARATED, E0_CONTAINS_E1, E1_CONTAINS_E0, ONE_CHORD_REGION, FOUR_CHORD_REGION, INVALID }; AreaResult() : configuration(Configuration::INVALID), findResult{}, area((T)0) { } // One of the enumerates, determined in the call to AreaDispatch. Configuration configuration; // Information about the ellipse-ellipse intersection points. Result findResult; // The area of intersection of the ellipses. T area; }; // The ellipse axes are already normalized, which most likely // introduced rounding errors. AreaResult AreaOfIntersection(Ellipse2<T> const& ellipse0, Ellipse2<T> const& ellipse1) { EllipseInfo E0{}; E0.center = ellipse0.center; E0.axis = ellipse0.axis; E0.extent = ellipse0.extent; E0.sqrExtent = ellipse0.extent * ellipse0.extent; FinishEllipseInfo(E0); EllipseInfo E1{}; E1.center = ellipse1.center; E1.axis = ellipse1.axis; E1.extent = ellipse1.extent; E1.sqrExtent = ellipse1.extent * ellipse1.extent; FinishEllipseInfo(E1); AreaResult ar{}; ar.configuration = AreaResult::Configuration::INVALID; ar.findResult = operator()(ellipse0, ellipse1); ar.area = mZero; AreaDispatch(E0, E1, ar); return ar; } // The axis directions do not have to be unit length. The positive // definite matrices are constructed according to the details of the // PDF documentabout the intersection of ellipses. AreaResult AreaOfIntersection(Vector2<T> const& center0, Vector2<T> const axis0[2], Vector2<T> const& sqrExtent0, Vector2<T> const& center1, Vector2<T> const axis1[2], Vector2<T> const& sqrExtent1) { EllipseInfo E0{}; E0.center = center0; E0.axis = { axis0[0], axis0[1] }; E0.extent = { std::sqrt(sqrExtent0[0]), std::sqrt(sqrExtent0[1]) }; E0.sqrExtent = sqrExtent0; FinishEllipseInfo(E0); EllipseInfo E1{}; E1.center = center1; E1.axis = { axis1[0], axis1[1] }; E1.extent = { std::sqrt(sqrExtent1[0]), std::sqrt(sqrExtent1[1]) }; E1.sqrExtent = sqrExtent1; FinishEllipseInfo(E1); AreaResult ar{}; ar.configuration = AreaResult::Configuration::INVALID; ar.findResult = operator()(center0, axis0, sqrExtent0, center1, axis1, sqrExtent1); ar.area = mZero; AreaDispatch(E0, E1, ar); return ar; } private: // Compute the coefficients of the quadratic equation but with the // y^2-coefficient of 1. void ToCoefficients(Vector2<T> const& center, Vector2<T> const axis[2], Vector2<T> const& sqrExtent, std::array<T, 5>& coeff) { T denom0 = Dot(axis[0], axis[0]) * sqrExtent[0]; T denom1 = Dot(axis[1], axis[1]) * sqrExtent[1]; Matrix2x2<T> outer0 = OuterProduct(axis[0], axis[0]); Matrix2x2<T> outer1 = OuterProduct(axis[1], axis[1]); Matrix2x2<T> A = outer0 / denom0 + outer1 / denom1; Vector2<T> product = A * center; Vector2<T> B = -mTwo * product; T const& denom = A(1, 1); coeff[0] = (Dot(center, product) - mOne) / denom; coeff[1] = B[0] / denom; coeff[2] = B[1] / denom; coeff[3] = A(0, 0) / denom; coeff[4] = mTwo * A(0, 1) / denom; // coeff[5] = A(1, 1) / denom = 1; } void DoRootFinding(Result& result) { bool allZero = true; for (int32_t i = 0; i < 5; ++i) { mD[i] = mA[i] - mB[i]; if (mD[i] != mZero) { allZero = false; } } if (allZero) { result.intersect = false; result.numPoints = std::numeric_limits<int32_t>::max(); return; } result.numPoints = 0; mA2Div2 = mA[2] / mTwo; mA4Div2 = mA[4] / mTwo; mC[0] = mA[0] - mA2Div2 * mA2Div2; mC[1] = mA[1] - mA2Div2 * mA[4]; mC[2] = mA[3] - mA4Div2 * mA4Div2; // c[2] > 0 mE[0] = mD[0] - mA2Div2 * mD[2]; mE[1] = mD[1] - mA2Div2 * mD[4] - mA4Div2 * mD[2]; mE[2] = mD[3] - mA4Div2 * mD[4]; if (mD[4] != mZero) { T xbar = -mD[2] / mD[4]; T ebar = mE[0] + xbar * (mE[1] + xbar * mE[2]); if (ebar != mZero) { D4NotZeroEBarNotZero(result); } else { D4NotZeroEBarZero(xbar, result); } } else if (mD[2] != mZero) // d[4] = 0 { if (mE[2] != mZero) { D4ZeroD2NotZeroE2NotZero(result); } else { D4ZeroD2NotZeroE2Zero(result); } } else // d[2] = d[4] = 0 { D4ZeroD2Zero(result); } result.intersect = (result.numPoints > 0); } void D4NotZeroEBarNotZero(Result& result) { // The graph of w = -e(x)/d(x) is a hyperbola. T d2d2 = mD[2] * mD[2], d2d4 = mD[2] * mD[4], d4d4 = mD[4] * mD[4]; T e0e0 = mE[0] * mE[0], e0e1 = mE[0] * mE[1], e0e2 = mE[0] * mE[2]; T e1e1 = mE[1] * mE[1], e1e2 = mE[1] * mE[2], e2e2 = mE[2] * mE[2]; std::array<T, 5> f = { mC[0] * d2d2 + e0e0, mC[1] * d2d2 + mTwo * (mC[0] * d2d4 + e0e1), mC[2] * d2d2 + mC[0] * d4d4 + e1e1 + mTwo * (mC[1] * d2d4 + e0e2), mC[1] * d4d4 + mTwo * (mC[2] * d2d4 + e1e2), mC[2] * d4d4 + e2e2 // > 0 }; std::map<T, int32_t> rmMap; RootsPolynomial<T>::template SolveQuartic<T>(f[0], f[1], f[2], f[3], f[4], rmMap); // xbar cannot be a root of f(x), so d(x) != 0 and we can solve // directly for w = -e(x)/d(x). for (auto const& rm : rmMap) { T const& x = rm.first; T w = -(mE[0] + x * (mE[1] + x * mE[2])) / (mD[2] + mD[4] * x); T y = w - (mA2Div2 + x * mA4Div2); result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = (rm.second == 1); } } void D4NotZeroEBarZero(T const& xbar, Result& result) { // Factor e(x) = (d2 + d4*x)*(h0 + h1*x). The w-equation has // two solution components, x = xbar and w = -(h0 + h1*x). T translate, w, y; // Compute intersection of x = xbar with ellipse. T ncbar = -(mC[0] + xbar * (mC[1] + xbar * mC[2])); if (ncbar >= mZero) { translate = mA2Div2 + xbar * mA4Div2; w = std::sqrt(ncbar); y = w - translate; result.points[result.numPoints] = { xbar, y }; if (w > mZero) { result.isTransverse[result.numPoints++] = true; w = -w; y = w - translate; result.points[result.numPoints] = { xbar, y }; result.isTransverse[result.numPoints++] = true; } else { result.isTransverse[result.numPoints++] = false; } } // Compute intersections of w = -(h0 + h1*x) with ellipse. std::array<T, 2> h; h[1] = mE[2] / mD[4]; h[0] = (mE[1] - mD[2] * h[1]) / mD[4]; std::array<T, 3> f = { mC[0] + h[0] * h[0], mC[1] + mTwo * h[0] * h[1], mC[2] + h[1] * h[1] // > 0 }; std::map<T, int32_t> rmMap; RootsPolynomial<T>::template SolveQuadratic<T>(f[0], f[1], f[2], rmMap); for (auto const& rm : rmMap) { T const& x = rm.first; translate = mA2Div2 + x * mA4Div2; w = -(h[0] + x * h[1]); y = w - translate; result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = (rm.second == 1); } } void D4ZeroD2NotZeroE2NotZero(Result& result) { T d2d2 = mD[2] * mD[2]; std::array<T, 5> f = { mC[0] * d2d2 + mE[0] * mE[0], mC[1] * d2d2 + mTwo * mE[0] * mE[1], mC[2] * d2d2 + mE[1] * mE[1] + mTwo * mE[0] * mE[2], mTwo * mE[1] * mE[2], mE[2] * mE[2] // > 0 }; std::map<T, int32_t> rmMap; RootsPolynomial<T>::template SolveQuartic<T>(f[0], f[1], f[2], f[3], f[4], rmMap); for (auto const& rm : rmMap) { T const& x = rm.first; T translate = mA2Div2 + x * mA4Div2; T w = -(mE[0] + x * (mE[1] + x * mE[2])) / mD[2]; T y = w - translate; result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = (rm.second == 1); } } void D4ZeroD2NotZeroE2Zero(Result& result) { T d2d2 = mD[2] * mD[2]; std::array<T, 3> f = { mC[0] * d2d2 + mE[0] * mE[0], mC[1] * d2d2 + mTwo * mE[0] * mE[1], mC[2] * d2d2 + mE[1] * mE[1] }; std::map<T, int32_t> rmMap; RootsPolynomial<T>::template SolveQuadratic<T>(f[0], f[1], f[2], rmMap); for (auto const& rm : rmMap) { T const& x = rm.first; T translate = mA2Div2 + x * mA4Div2; T w = -(mE[0] + x * mE[1]) / mD[2]; T y = w - translate; result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = (rm.second == 1); } } void D4ZeroD2Zero(Result& result) { // e(x) cannot be identically zero, because if it were, then all // d[i] = 0. But we tested that case previously and exited. if (mE[2] != mZero) { // Make e(x) monic, f(x) = e(x)/e2 = x^2 + (e1/e2)*x + (e0/e2) // = x^2 + f1*x + f0. std::array<T, 2> f = { mE[0] / mE[2], mE[1] / mE[2] }; T mid = -f[1] / mTwo; T discr = mid * mid - f[0]; if (discr > mZero) { // The theoretical roots of e(x) are // x = -f1/2 + s*sqrt(discr) where s in {-1,+1}. For each // root, determine exactly the sign of c(x). We need // c(x) <= 0 in order to solve for w^2 = -c(x). At the // root, // c(x) = c0 + c1*x + c2*x^2 = c0 + c1*x - c2*(f0 + f1*x) // = (c0 - c2*f0) + (c1 - c2*f1)*x // = g0 + g1*x // We need g0 + g1*x <= 0. T sqrtDiscr = std::sqrt(discr); std::array<T, 2> g = { mC[0] - mC[2] * f[0], mC[1] - mC[2] * f[1] }; if (g[1] > mZero) { // We need s*sqrt(discr) <= -g[0]/g[1] + f1/2. T r = -g[0] / g[1] - mid; // s = +1: if (r >= mZero) { T rsqr = r * r; if (discr < rsqr) { SpecialIntersection(mid + sqrtDiscr, true, result); } else if (discr == rsqr) { SpecialIntersection(mid + sqrtDiscr, false, result); } } // s = -1: if (r > mZero) { SpecialIntersection(mid - sqrtDiscr, true, result); } else { T rsqr = r * r; if (discr > rsqr) { SpecialIntersection(mid - sqrtDiscr, true, result); } else if (discr == rsqr) { SpecialIntersection(mid - sqrtDiscr, false, result); } } } else if (g[1] < mZero) { // We need s*sqrt(discr) >= -g[0]/g[1] + f1/2. T r = -g[0] / g[1] - mid; // s = -1: if (r <= mZero) { T rsqr = r * r; if (discr < rsqr) { SpecialIntersection(mid - sqrtDiscr, true, result); } else { SpecialIntersection(mid - sqrtDiscr, false, result); } } // s = +1: if (r < mZero) { SpecialIntersection(mid + sqrtDiscr, true, result); } else { T rsqr = r * r; if (discr > rsqr) { SpecialIntersection(mid + sqrtDiscr, true, result); } else if (discr == rsqr) { SpecialIntersection(mid + sqrtDiscr, false, result); } } } else // g[1] = 0 { // The graphs of c(x) and f(x) are parabolas of the // same shape. One is a vertical translation of the // other. if (g[0] < mZero) { // The graph of f(x) is above that of c(x). SpecialIntersection(mid - sqrtDiscr, true, result); SpecialIntersection(mid + sqrtDiscr, true, result); } else if (g[0] == mZero) { // The graphs of c(x) and f(x) are the same parabola. SpecialIntersection(mid - sqrtDiscr, false, result); SpecialIntersection(mid + sqrtDiscr, false, result); } } } else if (discr == mZero) { // The theoretical root of f(x) is x = -f1/2. T nchat = -(mC[0] + mid * (mC[1] + mid * mC[2])); if (nchat > mZero) { SpecialIntersection(mid, true, result); } else if (nchat == mZero) { SpecialIntersection(mid, false, result); } } } else if (mE[1] != mZero) { T xhat = -mE[0] / mE[1]; T nchat = -(mC[0] + xhat * (mC[1] + xhat * mC[2])); if (nchat > mZero) { SpecialIntersection(xhat, true, result); } else if (nchat == mZero) { SpecialIntersection(xhat, false, result); } } } // Helper function for D4ZeroD2Zero. void SpecialIntersection(T const& x, bool transverse, Result& result) { if (transverse) { T translate = mA2Div2 + x * mA4Div2; T nc = -(mC[0] + x * (mC[1] + x * mC[2])); if (nc < mZero) { // Clamp to eliminate the rounding error, but duplicate // the point because we know that it is a transverse // intersection. nc = mZero; } T w = std::sqrt(nc); T y = w - translate; result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = true; w = -w; y = w - translate; result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = true; } else { // The vertical line at the root is tangent to the ellipse. T y = -(mA2Div2 + x * mA4Div2); // w = 0 result.points[result.numPoints] = { x, y }; result.isTransverse[result.numPoints++] = false; } } // Helper functions for AreaOfIntersection. struct EllipseInfo { EllipseInfo() : center(Vector2<T>::Zero()), axis{ Vector2<T>::Zero() , Vector2<T>::Zero() }, extent(Vector2<T>::Zero()), sqrExtent(Vector2<T>::Zero()), M{}, AB((T)0), halfAB((T)0), BpA((T)0), BmA((T)0) { } Vector2<T> center; std::array<Vector2<T>, 2> axis; Vector2<T> extent, sqrExtent; Matrix2x2<T> M; T AB; // extent[0] * extent[1] T halfAB; // extent[0] * extent[1] / 2 T BpA; // extent[1] + extent[0] T BmA; // extent[1] - extent[0] }; // The axis, extent and sqrExtent members of E must be set before // this function is called. void FinishEllipseInfo(EllipseInfo& E) { E.M = OuterProduct(E.axis[0], E.axis[0]) / (E.sqrExtent[0] * Dot(E.axis[0], E.axis[0])); E.M += OuterProduct(E.axis[1], E.axis[1]) / (E.sqrExtent[1] * Dot(E.axis[1], E.axis[1])); E.AB = E.extent[0] * E.extent[1]; E.halfAB = E.AB / mTwo; E.BpA = E.extent[1] + E.extent[0]; E.BmA = E.extent[1] - E.extent[0]; } void AreaDispatch(EllipseInfo const& E0, EllipseInfo const& E1, AreaResult& ar) { if (ar.findResult.intersect) { if (ar.findResult.numPoints == 1) { // Containment or separation. AreaCS(E0, E1, ar); } else if (ar.findResult.numPoints == 2) { if (ar.findResult.isTransverse[0]) { // Both intersection points are transverse. Area2(E0, E1, 0, 1, ar); } else { // Both intersection points are tangential, so one // ellipse is contained in the other. AreaCS(E0, E1, ar); } } else if (ar.findResult.numPoints == 3) { // The tangential intersection is irrelevant in the area // computation. if (!ar.findResult.isTransverse[0]) { Area2(E0, E1, 1, 2, ar); } else if (!ar.findResult.isTransverse[1]) { Area2(E0, E1, 2, 0, ar); } else // ar.findResult.isTransverse[2] == false { Area2(E0, E1, 0, 1, ar); } } else // ar.findResult.numPoints == 4 { Area4(E0, E1, ar); } } else { // Containment, separation, or same ellipse. AreaCS(E0, E1, ar); } } void AreaCS(EllipseInfo const& E0, EllipseInfo const& E1, AreaResult& ar) { if (ar.findResult.numPoints <= 1) { Vector2<T> diff = E0.center - E1.center; T qform0 = Dot(diff, E0.M * diff); T qform1 = Dot(diff, E1.M * diff); if (qform0 > mOne && qform1 > mOne) { // Each ellipse center is outside the other ellipse, so // the ellipses are separated (numPoints == 0) or outside // each other and just touching (numPoints == 1). ar.configuration = AreaResult::Configuration::ELLIPSES_ARE_SEPARATED; ar.area = mZero; } else { // One ellipse is inside the other. Determine this // indirectly by comparing areas. if (E0.AB < E1.AB) { ar.configuration = AreaResult::Configuration::E1_CONTAINS_E0; ar.area = mPi * E0.AB; } else { ar.configuration = AreaResult::Configuration::E0_CONTAINS_E1; ar.area = mPi * E1.AB; } } } else { ar.configuration = AreaResult::Configuration::ELLIPSES_ARE_EQUAL; ar.area = mPi * E0.AB; } } void Area2(EllipseInfo const& E0, EllipseInfo const& E1, int32_t i0, int32_t i1, AreaResult& ar) { ar.configuration = AreaResult::Configuration::ONE_CHORD_REGION; // The endpoints of the chord. Vector2<T> const& P0 = ar.findResult.points[i0]; Vector2<T> const& P1 = ar.findResult.points[i1]; // Compute locations relative to the ellipses. Vector2<T> P0mC0 = P0 - E0.center, P0mC1 = P0 - E1.center; Vector2<T> P1mC0 = P1 - E0.center, P1mC1 = P1 - E1.center; // Compute the ellipse normal vectors at endpoint P0. This is // sufficient information to determine chord endpoint order. Vector2<T> N0 = E0.M * P0mC0, N1 = E1.M * P0mC1; T dotperp = DotPerp(N1, N0); // Choose the endpoint order for the chord region associated // with E0. if (dotperp > mZero) { // The chord order for E0 is <P0,P1> and for E1 is <P1,P0>. ar.area = ComputeAreaChordRegion(E0, P0mC0, P1mC0) + ComputeAreaChordRegion(E1, P1mC1, P0mC1); } else { // The chord order for E0 is <P1,P0> and for E1 is <P0,P1>. ar.area = ComputeAreaChordRegion(E0, P1mC0, P0mC0) + ComputeAreaChordRegion(E1, P0mC1, P1mC1); } } void Area4(EllipseInfo const& E0, EllipseInfo const& E1, AreaResult& ar) { ar.configuration = AreaResult::Configuration::FOUR_CHORD_REGION; // Select a counterclockwise ordering of the points of // intersection. Use the polar coordinates for E0 to do this. // The multimap is used in the event that computing the // intersections involved numerical rounding errors that lead to // a duplicate intersection, even though the intersections are all // labeled as transverse. [See the comment in the function // SpecialIntersection.] std::multimap<T, int32_t> ordering; int32_t i; for (i = 0; i < 4; ++i) { Vector2<T> PmC = ar.findResult.points[i] - E0.center; T x = Dot(E0.axis[0], PmC); T y = Dot(E0.axis[1], PmC); T theta = std::atan2(y, x); ordering.insert(std::make_pair(theta, i)); } std::array<int32_t, 4> permute{ 0, 0, 0, 0 }; i = 0; for (auto const& element : ordering) { permute[i++] = element.second; } // Start with the area of the convex quadrilateral. Vector2<T> diag20 = ar.findResult.points[permute[2]] - ar.findResult.points[permute[0]]; Vector2<T> diag31 = ar.findResult.points[permute[3]] - ar.findResult.points[permute[1]]; ar.area = std::fabs(DotPerp(diag20, diag31)) / mTwo; // Visit each pair of consecutive points. The selection of // ellipse for the chord-region area calculation uses the "most // counterclockwise" tangent vector. for (int32_t i0 = 3, i1 = 0; i1 < 4; i0 = i1++) { // Get a pair of consecutive points. Vector2<T> const& P0 = ar.findResult.points[permute[i0]]; Vector2<T> const& P1 = ar.findResult.points[permute[i1]]; // Compute locations relative to the ellipses. Vector2<T> P0mC0 = P0 - E0.center, P0mC1 = P0 - E1.center; Vector2<T> P1mC0 = P1 - E0.center, P1mC1 = P1 - E1.center; // Compute the ellipse normal vectors at endpoint P0. Vector2<T> N0 = E0.M * P0mC0, N1 = E1.M * P0mC1; T dotperp = DotPerp(N1, N0); if (dotperp > mZero) { // The chord goes with ellipse E0. ar.area += ComputeAreaChordRegion(E0, P0mC0, P1mC0); } else { // The chord goes with ellipse E1. ar.area += ComputeAreaChordRegion(E1, P0mC1, P1mC1); } } } T ComputeAreaChordRegion(EllipseInfo const& E, Vector2<T> const& P0mC, Vector2<T> const& P1mC) { // Compute polar coordinates for P0 and P1 on the ellipse. T x0 = Dot(E.axis[0], P0mC); T y0 = Dot(E.axis[1], P0mC); T theta0 = std::atan2(y0, x0); T x1 = Dot(E.axis[0], P1mC); T y1 = Dot(E.axis[1], P1mC); T theta1 = std::atan2(y1, x1); // The arc straddles the atan2 discontinuity on the negative // x-axis. Wrap the second angle to be larger than the first // angle. if (theta1 < theta0) { theta1 += mTwoPi; } // Compute the area portion of the sector due to the triangle. T triArea = std::fabs(DotPerp(P0mC, P1mC)) / mTwo; // Compute the chord region area. T dtheta = theta1 - theta0; T F0, F1, sectorArea; if (dtheta <= mPi) { // Use the area formula directly. // area(theta0,theta1) = F(theta1)-F(theta0)-area(triangle) F0 = ComputeIntegral(E, theta0); F1 = ComputeIntegral(E, theta1); sectorArea = F1 - F0; return sectorArea - triArea; } else { // The angle of the elliptical sector is larger than pi // radians. Use the area formula // area(theta0,theta1) = pi*a*b - area(theta1,theta0) theta0 += mTwoPi; // ensure theta0 > theta1 F0 = ComputeIntegral(E, theta0); F1 = ComputeIntegral(E, theta1); sectorArea = F0 - F1; return mPi * E.AB - (sectorArea - triArea); } } T ComputeIntegral(EllipseInfo const& E, T const& theta) { T twoTheta = mTwo * theta; T sn = std::sin(twoTheta); T cs = std::cos(twoTheta); T arg = E.BmA * sn / (E.BpA + E.BmA * cs); return E.halfAB * (theta - std::atan(arg)); } // Constants that are set up once (optimization for rational // arithmetic). T mZero, mOne, mTwo, mPi, mTwoPi; // Various polynomial coefficients. The names are intended to // match the variable names used in the PDF documentation. std::array<T, 5> mA, mB, mD, mF; std::array<T, 3> mC, mE; T mA2Div2, mA4Div2; }; // Template aliases for convenience. template <typename T> using TIEllipses2 = TIQuery<T, Ellipse2<T>, Ellipse2<T>>; template <typename T> using FIEllipses2 = FIQuery<T, Ellipse2<T>, Ellipse2<T>>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointOrientedBox.h
.h
2,466
76
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistPointCanonicalBox.h> #include <Mathematics/OrientedBox.h> // Compute the distance from a point to a solid oriented box in nD. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where // |y[i]| <= e[i] for all i. // // The input point is stored in closest[0]. The closest point on the box // point is stored in closest[1]. namespace gte { template <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, OrientedBox<N, T>> { public: using PCQuery = DCPQuery<T, Vector<N, T>, CanonicalBox<N, T>>; using Result = typename PCQuery::Result; Result operator()(Vector<N, T> const& point, OrientedBox<N, T> const& box) { Result result{}; // Rotate and translate the point and box so that the box is // aligned and has center at the origin. CanonicalBox<N, T> cbox(box.extent); Vector<N, T> delta = point - box.center; Vector<N, T> xfrmPoint{}; for (int32_t i = 0; i < N; ++i) { xfrmPoint[i] = Dot(box.axis[i], delta); } // The query computes 'result' relative to the box with center // at the origin. PCQuery pcQuery{}; result = pcQuery(xfrmPoint, cbox); // Store the input point. result.closest[0] = point; // Rotate and translate the closest box point to the original // coordinates. Vector<N, T> closest1 = box.center; for (int32_t i = 0; i < N; ++i) { closest1 += result.closest[1][i] * box.axis[i]; } result.closest[1] = closest1; return result; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPPointOrientedBox = DCPQuery<T, Vector<N, T>, OrientedBox<N, T>>; template <typename T> using DCPPoint2OrientedBox2 = DCPPointOrientedBox<2, T>; template <typename T> using DCPPoint3OrientedBox3 = DCPPointOrientedBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLineRay.h
.h
3,584
108
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Line.h> #include <Mathematics/Ray.h> // Compute the distance between a line and a ray in nD. // // The line is P[0] + s[0] * D[0] and the ray is P[1] + s[1] * D[1] for // s[1] >= 0. The D[i] are not required to be unit length. // // The closest point on the line is stored in closest[0] with parameter[0] // storing s[0]. The closest point on the ray is stored in closest[1] with // parameter[1] storing s[1]. When there are infinitely many choices for the // pair of closest points, only one of them is returned. namespace gte { template <int32_t N, typename T> class DCPQuery<T, Line<N, T>, Ray<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 2> parameter; std::array<Vector<N, T>, 2> closest; }; Result operator()(Line<N, T> const& line, Ray<N, T> const& ray) { Result result{}; T const zero = static_cast<T>(0); Vector<N, T> diff = line.origin - ray.origin; T a00 = Dot(line.direction, line.direction); T a01 = -Dot(line.direction, ray.direction); T a11 = Dot(ray.direction, ray.direction); T b0 = Dot(line.direction, diff); T det = std::max(a00 * a11 - a01 * a01, zero); T s0{}, s1{}; if (det > zero) { // The line and ray are not parallel. T b1 = -Dot(ray.direction, diff); s1 = a01 * b0 - a00 * b1; if (s1 >= zero) { // Two interior points are closest, one on the line and // one on the ray. s0 = (a01 * b1 - a11 * b0) / det; s1 /= det; } else { // The origin of the ray is the closest ray point. s0 = -b0 / a00; s1 = zero; } } else { // The line and ray are parallel. Select the pair of closest // points where the closest ray point is the ray origin. s0 = -b0 / a00; s1 = zero; } result.parameter[0] = s0; result.parameter[1] = s1; result.closest[0] = line.origin + s0 * line.direction; result.closest[1] = ray.origin + s1 * ray.direction; diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPLineRay = DCPQuery<T, Line<N, T>, Ray<N, T>>; template <typename T> using DCPLine2Ray2 = DCPLineRay<2, T>; template <typename T> using DCPLine3Ray3 = DCPLineRay<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine3Circle3.h
.h
19,334
447
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Circle3.h> #include <Mathematics/Line.h> #include <Mathematics/RootsBisection.h> #include <Mathematics/RootsPolynomial.h> // The 3D line-circle distance algorithm is described in // https://www.geometrictools.com/Documentation/DistanceToCircle3.pdf // The notation used in the code matches that of the document. namespace gte { template <typename T> class DCPQuery<T, Line3<T>, Circle3<T>> { public: // The possible number of closest line-circle pairs is 1, 2 or all // circle points. If 1 or 2, numClosestPairs is set to this number // and 'equidistant' is false; the number of valid elements in // lineClosest[] and circleClosest[] is numClosestPairs. If all // circle points are closest, the line must be C+t*N where C is the // circle center, N is the normal to the plane of the circle, and // lineClosest[0] is set to C. In this case, 'equidistant' is true // and circleClosest[0] is set to C+r*U, where r is the circle // and U is a vector perpendicular to N. struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), numClosestPairs(0), lineClosest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, circleClosest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, equidistant(false) { } T distance, sqrDistance; size_t numClosestPairs; std::array<Vector3<T>, 2> lineClosest, circleClosest; bool equidistant; }; // The polynomial-based algorithm. Type T can be floating-point or // rational. Result operator()(Line3<T> const& line, Circle3<T> const& circle) { Result result{}; Vector3<T> const vzero = Vector3<T>::Zero(); T const zero = (T)0; Vector3<T> D = line.origin - circle.center; Vector3<T> NxM = Cross(circle.normal, line.direction); Vector3<T> NxD = Cross(circle.normal, D); T t = zero; if (NxM != vzero) { if (NxD != vzero) { T NdM = Dot(circle.normal, line.direction); if (NdM != zero) { // H(t) = (a*t^2 + 2*b*t + c)*(t + d)^2 // - r^2*(a*t + b)^2 // = h0 + h1*t + h2*t^2 + h3*t^3 + h4*t^4 T a = Dot(NxM, NxM), b = Dot(NxM, NxD); T c = Dot(NxD, NxD), d = Dot(line.direction, D); T rsqr = circle.radius * circle.radius; T asqr = a * a, bsqr = b * b, dsqr = d * d; T h0 = c * dsqr - bsqr * rsqr; T h1 = (T)2 * (c * d + b * dsqr - a * b * rsqr); T h2 = c + (T)4 * b * d + a * dsqr - asqr * rsqr; T h3 = (T)2 * (b + a * d); T h4 = a; std::map<T, int32_t> rmMap{}; RootsPolynomial<T>::template SolveQuartic<T>(h0, h1, h2, h3, h4, rmMap); std::array<ClosestInfo, 4> candidates{}; size_t numRoots = 0; for (auto const& rm : rmMap) { t = rm.first; ClosestInfo info{}; Vector3<T> NxDelta = NxD + t * NxM; if (NxDelta != vzero) { GetPair(line, circle, D, t, info.lineClosest, info.circleClosest); info.equidistant = false; } else { Vector3<T> U = GetOrthogonal(circle.normal, true); info.lineClosest = circle.center; info.circleClosest = circle.center + circle.radius * U; info.equidistant = true; } Vector3<T> diff = info.lineClosest - info.circleClosest; info.sqrDistance = Dot(diff, diff); candidates[numRoots++] = info; } std::sort(candidates.begin(), candidates.begin() + numRoots); result.numClosestPairs = 1; result.lineClosest[0] = candidates[0].lineClosest; result.circleClosest[0] = candidates[0].circleClosest; if (numRoots > 1 && candidates[1].sqrDistance == candidates[0].sqrDistance) { result.numClosestPairs = 2; result.lineClosest[1] = candidates[1].lineClosest; result.circleClosest[1] = candidates[1].circleClosest; } } else { // The line is parallel to the plane of the circle. // The polynomial has the form // H(t) = (t+v)^2*[(t+v)^2-(r^2-u^2)]. T u = Dot(NxM, D), v = Dot(line.direction, D); T discr = circle.radius * circle.radius - u * u; if (discr > zero) { result.numClosestPairs = 2; T rootDiscr = std::sqrt(discr); t = -v + rootDiscr; GetPair(line, circle, D, t, result.lineClosest[0], result.circleClosest[0]); t = -v - rootDiscr; GetPair(line, circle, D, t, result.lineClosest[1], result.circleClosest[1]); } else { result.numClosestPairs = 1; t = -v; GetPair(line, circle, D, t, result.lineClosest[0], result.circleClosest[0]); } } } else { // The line is C+t*M, where M is not parallel to N. The // polynomial is // H(t) = |Cross(N,M)|^2*t^2*(t^2 - r^2*|Cross(N,M)|^2) // where root t = 0 does not correspond to the global // minimum. The other roots produce the global minimum. result.numClosestPairs = 2; t = circle.radius * Length(NxM); GetPair(line, circle, D, t, result.lineClosest[0], result.circleClosest[0]); t = -t; GetPair(line, circle, D, t, result.lineClosest[1], result.circleClosest[1]); } result.equidistant = false; } else { if (NxD != vzero) { // The line is A+t*N (perpendicular to plane) but with // A != C. The polyhomial is // H(t) = |Cross(N,D)|^2*(t + Dot(M,D))^2. result.numClosestPairs = 1; t = -Dot(line.direction, D); GetPair(line, circle, D, t, result.lineClosest[0], result.circleClosest[0]); result.equidistant = false; } else { // The line is C+t*N, so C is the closest point for the // line and all circle points are equidistant from it. Vector3<T> U = GetOrthogonal(circle.normal, true); result.numClosestPairs = 1; result.lineClosest[0] = circle.center; result.circleClosest[0] = circle.center + circle.radius * U; result.equidistant = true; } } Vector3<T> diff = result.lineClosest[0] - result.circleClosest[0]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } // The nonpolynomial-based algorithm that uses bisection. Because the // bisection is iterative, you should choose T to be a // floating-point type. However, the algorithm will still work for a // rational type, but it is costly because of the increase in // arbitrary-size integers used during the bisection. Result Robust(Line3<T> const& line, Circle3<T> const& circle) { // The line is P(t) = B+t*M. The circle is |X-C| = r with // Dot(N,X-C)=0. Result result{}; Vector3<T> vzero = Vector3<T>::Zero(); T const zero = (T)0; Vector3<T> D = line.origin - circle.center; Vector3<T> MxN = Cross(line.direction, circle.normal); Vector3<T> DxN = Cross(D, circle.normal); T m0sqr = Dot(MxN, MxN); if (m0sqr > zero) { // Compute the critical points s for F'(s) = 0. T s{}, t{}; size_t numRoots = 0; std::array<T, 3> roots{}; // The line direction M and the plane normal N are not // parallel. Move the line origin B = (b0,b1,b2) to // B' = B + lambda*line.direction = (0,b1',b2'). T m0 = std::sqrt(m0sqr); T rm0 = circle.radius * m0; T lambda = -Dot(MxN, DxN) / m0sqr; Vector3<T> oldD = D; D += lambda * line.direction; DxN += lambda * MxN; T m2b2 = Dot(line.direction, D); T b1sqr = Dot(DxN, DxN); if (b1sqr > zero) { // B' = (0,b1',b2') where b1' != 0. See Sections 1.1.2 // and 1.2.2 of the PDF documentation. T b1 = std::sqrt(b1sqr); T rm0sqr = circle.radius * m0sqr; if (rm0sqr > b1) { T const twoThirds = (T)2 / (T)3; T sHat = std::sqrt(std::pow(rm0sqr * b1sqr, twoThirds) - b1sqr) / m0; T gHat = rm0sqr * sHat / std::sqrt(m0sqr * sHat * sHat + b1sqr); T cutoff = gHat - sHat; if (m2b2 <= -cutoff) { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2, -m2b2 + rm0); roots[numRoots++] = s; if (m2b2 == -cutoff) { roots[numRoots++] = -sHat; } } else if (m2b2 >= cutoff) { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2 - rm0, -m2b2); roots[numRoots++] = s; if (m2b2 == cutoff) { roots[numRoots++] = sHat; } } else { if (m2b2 <= zero) { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2, -m2b2 + rm0); roots[numRoots++] = s; s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2 - rm0, -sHat); roots[numRoots++] = s; } else { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2 - rm0, -m2b2); roots[numRoots++] = s; s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, sHat, -m2b2 + rm0); roots[numRoots++] = s; } } } else { if (m2b2 < zero) { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2, -m2b2 + rm0); } else if (m2b2 > zero) { s = Bisect(m2b2, rm0sqr, m0sqr, b1sqr, -m2b2 - rm0, -m2b2); } else { s = zero; } roots[numRoots++] = s; } } else { // The new line origin is B' = (0,0,b2'). if (m2b2 < zero) { s = -m2b2 + rm0; roots[numRoots++] = s; } else if (m2b2 > zero) { s = -m2b2 - rm0; roots[numRoots++] = s; } else { s = -m2b2 + rm0; roots[numRoots++] = s; s = -m2b2 - rm0; roots[numRoots++] = s; } } std::array<ClosestInfo, 4> candidates; for (size_t i = 0; i < numRoots; ++i) { t = roots[i] + lambda; ClosestInfo info{}; Vector3<T> NxDelta = Cross(circle.normal, oldD + t * line.direction); if (NxDelta != vzero) { GetPair(line, circle, oldD, t, info.lineClosest, info.circleClosest); info.equidistant = false; } else { Vector3<T> U = GetOrthogonal(circle.normal, true); info.lineClosest = circle.center; info.circleClosest = circle.center + circle.radius * U; info.equidistant = true; } Vector3<T> diff = info.lineClosest - info.circleClosest; info.sqrDistance = Dot(diff, diff); candidates[i] = info; } std::sort(candidates.begin(), candidates.begin() + numRoots); result.numClosestPairs = 1; result.lineClosest[0] = candidates[0].lineClosest; result.circleClosest[0] = candidates[0].circleClosest; if (numRoots > 1 && candidates[1].sqrDistance == candidates[0].sqrDistance) { result.numClosestPairs = 2; result.lineClosest[1] = candidates[1].lineClosest; result.circleClosest[1] = candidates[1].circleClosest; } result.equidistant = false; } else { // The line direction and the plane normal are parallel. if (DxN != vzero) { // The line is A+t*N but with A != C. result.numClosestPairs = 1; GetPair(line, circle, D, -Dot(line.direction, D), result.lineClosest[0], result.circleClosest[0]); result.equidistant = false; } else { // The line is C+t*N, so C is the closest point for the // line and all circle points are equidistant from it. Vector3<T> U = GetOrthogonal(circle.normal, true); result.numClosestPairs = 1; result.lineClosest[0] = circle.center; result.circleClosest[0] = circle.center + circle.radius * U; result.equidistant = true; } } Vector3<T> diff = result.lineClosest[0] - result.circleClosest[0]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } private: // Support for operator(...). struct ClosestInfo { ClosestInfo() : sqrDistance(static_cast<T>(0)), lineClosest(Vector3<T>::Zero()), circleClosest(Vector3<T>::Zero()), equidistant(false) { } bool operator< (ClosestInfo const& info) const { return sqrDistance < info.sqrDistance; } T sqrDistance; Vector3<T> lineClosest, circleClosest; bool equidistant; }; void GetPair(Line3<T> const& line, Circle3<T> const& circle, Vector3<T> const& D, T t, Vector3<T>& lineClosest, Vector3<T>& circleClosest) { Vector3<T> delta = D + t * line.direction; lineClosest = circle.center + delta; delta -= Dot(circle.normal, delta) * circle.normal; Normalize(delta); circleClosest = circle.center + circle.radius * delta; } // Support for Robust(...). Bisect the function // F(s) = s + m2b2 - r*m0sqr*s/sqrt(m0sqr*s*s + b1sqr) // on the specified interval [smin,smax]. T Bisect(T m2b2, T rm0sqr, T m0sqr, T b1sqr, T smin, T smax) { std::function<T(T)> G = [&, m2b2, rm0sqr, m0sqr, b1sqr](T s) { return s + m2b2 - rm0sqr * s / std::sqrt(m0sqr * s * s + b1sqr); }; // The function is known to be increasing, so we can specify -1 and +1 // as the function values at the bounding interval endpoints. The use // of 'double' is intentional in case T is a BSNumber or BSRational // type. We want the bisections to terminate in a reasonable amount of // time. uint32_t const maxIterations = GTE_C_MAX_BISECTIONS_GENERIC; T root = static_cast<T>(0); RootsBisection<T>::Find(G, smin, smax, (T)-1, (T)+1, maxIterations, root); return root; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay3Triangle3.h
.h
6,240
186
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Ray.h> #include <Mathematics/Triangle.h> #include <Mathematics/Vector3.h> namespace gte { template <typename T> class TIQuery<T, Ray3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Ray3<T> const& ray, Triangle3<T> const& triangle) { Result result{}; // Compute the offset origin, edges, and normal. Vector3<T> diff = ray.origin - triangle.v[0]; Vector3<T> edge1 = triangle.v[1] - triangle.v[0]; Vector3<T> edge2 = triangle.v[2] - triangle.v[0]; Vector3<T> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) T DdN = Dot(ray.direction, normal); T sign = (T)0; if (DdN > (T)0) { sign = (T)1; } else if (DdN < (T)0) { sign = (T)-1; DdN = -DdN; } else { // Ray and triangle are parallel, call it a "no intersection" // even if the ray does intersect. result.intersect = false; return result; } T DdQxE2 = sign * DotCross(ray.direction, diff, edge2); if (DdQxE2 >= (T)0) { T DdE1xQ = sign * DotCross(ray.direction, edge1, diff); if (DdE1xQ >= (T)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle, check whether ray does. T QdN = -sign * Dot(diff, normal); if (QdN >= (T)0) { // Ray intersects triangle. result.intersect = true; return result; } // else: t < 0, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; template <typename T> class FIQuery<T, Ray3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false), parameter((T)0), triangleBary{ (T)0, (T)0, (T)0 }, point(Vector3<T>::Zero()) { } bool intersect; T parameter; std::array<T, 3> triangleBary; Vector3<T> point; }; Result operator()(Ray3<T> const& ray, Triangle3<T> const& triangle) { Result result{}; // Compute the offset origin, edges, and normal. Vector3<T> diff = ray.origin - triangle.v[0]; Vector3<T> edge1 = triangle.v[1] - triangle.v[0]; Vector3<T> edge2 = triangle.v[2] - triangle.v[0]; Vector3<T> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) T DdN = Dot(ray.direction, normal); T sign = (T)0; if (DdN > (T)0) { sign = (T)1; } else if (DdN < (T)0) { sign = (T)-1; DdN = -DdN; } else { // Ray and triangle are parallel, call it a "no intersection" // even if the ray does intersect. result.intersect = false; return result; } T DdQxE2 = sign * DotCross(ray.direction, diff, edge2); if (DdQxE2 >= (T)0) { T DdE1xQ = sign * DotCross(ray.direction, edge1, diff); if (DdE1xQ >= (T)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle, check whether ray does. T QdN = -sign * Dot(diff, normal); if (QdN >= (T)0) { // Ray intersects triangle. result.intersect = true; result.parameter = QdN / DdN; result.triangleBary[1] = DdQxE2 / DdN; result.triangleBary[2] = DdE1xQ / DdN; result.triangleBary[0] = (T)1 - result.triangleBary[1] - result.triangleBary[2]; result.point = ray.origin + result.parameter * ray.direction; return result; } // else: t < 0, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NaturalQuinticSpline.h
.h
17,596
453
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.07 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/Matrix4x4.h> #include <Mathematics/ParametricCurve.h> #include <array> #include <cstdint> #include <vector> // Documentation for natural splines is found in // https://www.geometrictools.com/Documentation/NaturalSplines.pdf // The number of points must be 2 or larger. The points[] and times[] arrays // must have the same number of elements. The times[] values must be strictly // increasing. namespace gte { template <int32_t N, typename T> class NaturalQuinticSpline : public ParametricCurve<N, T> { public: // Construct a free spline by setting 'isFree' to true or construct a // closed spline by setting 'isFree' to false. The function values are // f0[] and the first derivative values are f1[]. NaturalQuinticSpline(bool isFree, int32_t numPoints, Vector<N, T> const* f0, Vector<N, T> const* f1, T const* times) : ParametricCurve<N, T>(numPoints - 1, times), mPolynomials{}, mDelta{} { LogAssert( numPoints >= 2 && f0 != nullptr && f1 != nullptr && times != nullptr, "Invalid input."); int32_t numPm1 = numPoints - 1; mPolynomials.resize(numPm1); mDelta.resize(numPm1); for (int32_t i0 = 0, i1 = 1; i1 < numPoints; i0 = i1++) { mDelta[i0] = times[i1] - times[i0]; } // Free splines and closed splines have the last two B-entries // set to the zero vector. Vector<N, T> boundary0{}, boundary1{}; boundary0.MakeZero(); boundary1.MakeZero(); Matrix4x4<T> R{}; int32_t const numBElements = 4 * numPm1; std::vector<Vector<N, T>> B(numBElements); OnPresolve(numPoints, f0, f1, boundary0, boundary1, R, B); T const r1 = static_cast<T>(1); T const r3 = static_cast<T>(3); T const r4 = static_cast<T>(4); T const r6 = static_cast<T>(6); T const r10 = static_cast<T>(10); if (isFree) { R(2, 1) = r1; R(2, 2) = r4; R(2, 3) = r10; Solve(0, 1, numPoints, f0, f1, R, B); } else // is closed { int32_t const numPm2 = numPoints - 2; T lambda = mDelta[0] / mDelta[numPm2]; T lambdasqr = lambda * lambda; T lambdacub = lambdasqr * lambda; R(2, 0) = -lambdasqr; R(2, 1) = -r3 * lambdasqr; R(2, 2) = -r6 * lambdasqr; R(2, 3) = -r10 * lambdasqr; R(3, 1) = -r1 * lambdacub; R(3, 2) = -r4 * lambdacub; R(3, 3) = -r10 * lambdacub; Solve(1, 1, numPoints, f0, f1, R, B); } this->mConstructed = true; } NaturalQuinticSpline(bool isFree, std::vector<Vector<N, T>> const& f0, std::vector<Vector<N, T>> const& f1, std::vector<T> const& times) : NaturalQuinticSpline(isFree, static_cast<int32_t>(f0.size()), f0.data(), f1.data(), times.data()) { } // Construct a clamped spline. NaturalQuinticSpline(int32_t numPoints, Vector<N, T> const* f0, Vector<N, T> const* f1, T const* times, Vector<N, T> const& derivative0, Vector<N, T> const& derivative1) : ParametricCurve<N, T>(numPoints - 1, times), mPolynomials{}, mDelta{} { LogAssert( numPoints >= 2 && f0 != nullptr && f1 != nullptr && times != nullptr, "Invalid input."); int32_t numPm1 = numPoints - 1; mPolynomials.resize(numPm1); mDelta.resize(numPm1); for (int32_t i0 = 0, i1 = 1; i1 < numPoints; i0 = i1++) { mDelta[i0] = times[i1] - times[i0]; } int32_t const numPm2 = numPoints - 2; T const rHalf = static_cast<T>(0.5); T coeff0 = rHalf * mDelta[0] * mDelta[0]; T coeff1 = rHalf * mDelta[numPm2] * mDelta[numPm2]; Vector<N, T> boundary0 = coeff0 * derivative0; Vector<N, T> boundary1 = coeff1 * derivative1; Matrix4x4<T> R{}; int32_t const numBElements = 4 * numPm1; std::vector<Vector<N, T>> B(numBElements); OnPresolve(numPoints, f0, f1, boundary0, boundary1, R, B); T const r1 = static_cast<T>(1); T const r3 = static_cast<T>(3); T const r6 = static_cast<T>(6); T const r10 = static_cast<T>(10); R(3, 0) = r1; R(3, 1) = r3; R(3, 2) = r6; R(3, 3) = r10; Solve(1, 0, numPoints, f0, f1, R, B); this->mConstructed = true; } NaturalQuinticSpline(std::vector<Vector<N, T>> const& f0, std::vector<Vector<N, T>> const& f1, std::vector<T> const& times, Vector<N, T> const& derivative0, Vector<N, T> const& derivative1) : NaturalQuinticSpline(static_cast<int32_t>(f0.size()), f0.data(), f1.data(), times.data(), derivative0, derivative1) { } virtual ~NaturalQuinticSpline() = default; using Polynomial = std::array<Vector<N, T>, 6>; inline std::vector<Polynomial> const& GetPolynomials() const { return mPolynomials; } // Evaluation of the function and its derivatives through order 5. If // you want only the position, pass in order 0. If you want the // position and first derivative, pass in order of 1 and so on. The // output array 'jet' must have 'order + 1' elements. The values are // ordered as position, first derivative, second derivative and so on. virtual void Evaluate(T t, uint32_t order, Vector<N, T>* jet) const override { if (!this->mConstructed) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i <= order; ++i) { jet[i].MakeZero(); } return; } size_t key = 0; T u = static_cast<T>(0); GetKeyInfo(t, key, u); auto const& poly = mPolynomials[key]; // Compute position. jet[0] = poly[0] + u * (poly[1] + u * (poly[2] + u * (poly[3] + u * (poly[4] + u * poly[5])))); if (order >= 1) { // Compute first derivative. T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); T const r4 = static_cast<T>(4); T const r5 = static_cast<T>(5); T denom = mDelta[key]; jet[1] = (poly[1] + u * (r2 * poly[2] + u * (r3 * poly[3] + u * (r4 * poly[4] + u * (r5 * poly[5]))))) / denom; if (order >= 2) { // Compute second derivative. T const r6 = static_cast<T>(6); T const r12 = static_cast<T>(12); T const r20 = static_cast<T>(20); denom *= mDelta[key]; jet[2] = (r2 * poly[2] + u * (r6 * poly[3] + u * (r12 * poly[4] + u * (r20 * poly[5])))) / denom; if (order >= 3) { // Compute third derivative. T const r24 = static_cast<T>(24); T const r60 = static_cast<T>(60); denom *= mDelta[key]; jet[3] = (r6 * poly[3] + u * (r24 * poly[4] + u * (r60 * poly[5]))) / denom; if (order >= 4) { // Compute fourth derivative. denom *= mDelta[key]; jet[4] = (r24 * poly[4] + u * (r60 * poly[5])) / denom; if (order >= 5) { // Compute fifth derivative. denom *= mDelta[key]; jet[5] = (r60 * poly[5]) / denom; for (uint32_t i = 6; i <= order; ++i) { // Derivatives of order 6 and higher are zero. jet[i].MakeZero(); } } } } } } } private: void OnPresolve(int32_t numPoints, Vector<N, T> const* f0, Vector<N, T> const* f1, Vector<N, T> const& boundary0, Vector<N, T> const& boundary1, Matrix4x4<T>& R, std::vector<Vector<N, T>>& B) { int32_t const numPm1 = numPoints - 1; int32_t const numPm2 = numPoints - 2; int32_t const numPm3 = numPoints - 3; T const r1 = static_cast<T>(1); T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); T const r4 = static_cast<T>(4); T const r5 = static_cast<T>(5); T const r6 = static_cast<T>(6); T const r10 = static_cast<T>(10); T const r11 = static_cast<T>(11); T const r14 = static_cast<T>(14); T const r15 = static_cast<T>(15); T const r20 = static_cast<T>(20); std::array<T, 4> coeff0{ r10, -r20, r15, -r4 }; std::array<T, 4> coeff1{ -r6, r14, -r11, r3 }; for (int32_t i0 = 0, i1 = 1; i0 <= numPm3; i0 = i1++) { Vector<N, T> diff0 = f0[i1] - f0[i0] - mDelta[i0] * f1[i0]; Vector<N, T> diff1 = mDelta[i0] * (f1[i1] - f1[i0]); for (int32_t j = 0, k = 4 * i0; j < 4; ++j, ++k) { B[k] = coeff0[j] * diff0 + coeff1[j] * diff1; } } B[B.size() - 4] = f0[numPm1] - f0[numPm2] - mDelta[numPm2] * f1[numPm2]; B[B.size() - 3] = mDelta[numPm2] * (f1[numPm1] - f1[numPm2]); B[B.size() - 2] = boundary0; B[B.size() - 1] = boundary1; R(0, 0) = r1; R(0, 1) = r1; R(0, 2) = r1; R(0, 3) = r1; R(1, 0) = r2; R(1, 1) = r3; R(1, 2) = r4; R(1, 3) = r5; } void Solve(int32_t ell20, int32_t ell31, int32_t numPoints, Vector<N, T> const* f0, Vector<N, T> const* f1, Matrix4x4<T>& R, std::vector<Vector<N, T>>& B) { RowReduce(ell20, ell31, numPoints, R, B); BackSubstitute(f0, f1, R, B); } void RowReduce(int32_t ell20, int32_t ell31, int32_t numPoints, Matrix4x4<T>& R, std::vector<Vector<N, T>>& B) { // Apply the row reductions to convert the matrix system to // upper-triangular block-matrix system. T const r1 = static_cast<T>(1); T const r3 = static_cast<T>(3); T const r8 = static_cast<T>(8); int32_t const numPm3 = numPoints - 3; if (ell20 == 1) { Vector<N, T>& Btrg = B[B.size() - 2]; Btrg -= B[0]; T sigma = mDelta[0] / mDelta[1]; T sigmasqr = sigma * sigma; T sigmacub = sigmasqr * sigma; T LUProd0 = -r3 * sigmasqr, LUProd1 = sigmacub; T sign = -r1; for (int32_t i = 1; i <= numPm3; ++i) { Btrg -= sign * (LUProd0 * B[4 * i] + LUProd1 * B[4 * i + 1]); sigma = mDelta[i] / mDelta[i + 1]; sigmasqr = sigma * sigma; sigmacub = sigmasqr * sigma; T temp0 = sigmasqr * (-r3 * LUProd0 + r8 * LUProd1); T temp1 = sigmacub * (LUProd0 - r3 * LUProd1); LUProd0 = temp0; LUProd1 = temp1; sign = -sign; } R(2, 0) += sign * LUProd0; R(2, 1) += sign * LUProd1; } if (ell31 == 1) { Vector<N, T>& Btrg = B[B.size() - 1]; Btrg -= B[1]; T sigma = mDelta[0] / mDelta[1]; T sigmasqr = sigma * sigma; T sigmacub = sigmasqr * sigma; T LUProd0 = r8 * sigmasqr, LUProd1 = -r3 * sigmacub; T sign = -r1; for (int32_t i = 1; i <= numPm3; ++i) { Btrg -= sign * (LUProd0 * B[4 * i] + LUProd1 * B[4 * i + 1]); sigma = mDelta[i] / mDelta[i + 1]; sigmasqr = sigma * sigma; sigmacub = sigmasqr * sigma; T temp0 = sigmasqr * (-r3 * LUProd0 + r8 * LUProd1); T temp1 = sigmacub * (LUProd0 - r3 * LUProd1); LUProd0 = temp0; LUProd1 = temp1; sign = -sign; } R(3, 0) += sign * LUProd0; R(3, 1) += sign * LUProd1; } } void BackSubstitute(Vector<N, T> const* f0, Vector<N, T> const* f1, Matrix4x4<T> const& R, std::vector<Vector<N, T>> const& B) { bool invertible = false; Matrix4x4<T> invR = Inverse(R, &invertible); LogAssert( invertible, "R matrix is not invertible."); auto& poly = mPolynomials.back(); size_t j0 = B.size() - 4; size_t j1 = j0 + 1; size_t j2 = j0 + 2; size_t j3 = j0 + 3; poly[0] = f0[mPolynomials.size() - 1]; poly[1] = f1[mPolynomials.size() - 1] * mDelta[mPolynomials.size() - 1]; poly[2] = invR(0, 0) * B[j0] + invR(0, 1) * B[j1] + invR(0, 2) * B[j2] + invR(0, 3) * B[j3]; poly[3] = invR(1, 0) * B[j0] + invR(1, 1) * B[j1] + invR(1, 2) * B[j2] + invR(1, 3) * B[j3]; poly[4] = invR(2, 0) * B[j0] + invR(2, 1) * B[j1] + invR(2, 2) * B[j2] + invR(2, 3) * B[j3]; poly[5] = invR(3, 0) * B[j0] + invR(3, 1) * B[j1] + invR(3, 2) * B[j2] + invR(3, 3) * B[j3]; T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); T const r7 = static_cast<T>(7); T const r8 = static_cast<T>(8); int32_t const numPolynomials = static_cast<int32_t>(mPolynomials.size()); for (int32_t i1 = numPolynomials - 2, i0 = i1 + 1; i1 >= 0; i0 = i1--) { auto const& prev = mPolynomials[i0]; auto& curr = mPolynomials[i1]; T sigma = mDelta[i1] / mDelta[i0]; T sigmasqr = sigma * sigma; T sigmacub = sigmasqr * sigma; T u00 = -r3 * sigmasqr; T u01 = sigmacub; T u10 = r8 * sigmasqr; T u11 = -r3 * sigmacub; T u20 = -r7 * sigmasqr; T u21 = r3 * sigmacub; T u30 = r2 * sigmasqr; T u31 = -sigmacub; j0 -= 4; j1 -= 4; j2 -= 4; j3 -= 4; curr[0] = f0[i1]; curr[1] = f1[i1] * mDelta[i1]; curr[2] = B[j0] - (u00 * prev[2] + u01 * prev[3]); curr[3] = B[j1] - (u10 * prev[2] + u11 * prev[3]); curr[4] = B[j2] - (u20 * prev[2] + u21 * prev[3]); curr[5] = B[j3] - (u30 * prev[2] + u31 * prev[3]); } } // Determine the index key for which times[key] <= t < times[key+1]. // Return u = (t - times[key]) / delta[key] which is in [0,1]. void GetKeyInfo(T const& t, size_t& key, T& u) const { size_t const numSegments = static_cast<size_t>(this->GetNumSegments()); if (t > this->mTime[0]) { if (t < this->mTime[numSegments]) { for (size_t i = 0, ip1 = 1; i < numSegments; i = ip1++) { if (t < this->mTime[ip1]) { key = i; u = (t - this->mTime[i]) / mDelta[i]; break; } } } else { key = numSegments - 1; u = static_cast<T>(1); } } else { key = 0; u = static_cast<T>(0); } } std::vector<Polynomial> mPolynomials; std::vector<T> mDelta; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ExtremalQuery3PRJ.h
.h
1,966
61
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ExtremalQuery3.h> namespace gte { template <typename Real> class ExtremalQuery3PRJ : public ExtremalQuery3<Real> { public: // Construction. ExtremalQuery3PRJ(Polyhedron3<Real> const& polytope) : ExtremalQuery3<Real>(polytope) { mCentroid = this->mPolytope.ComputeVertexAverage(); } // Disallow copying and assignment. ExtremalQuery3PRJ(ExtremalQuery3PRJ const&) = delete; ExtremalQuery3PRJ& operator=(ExtremalQuery3PRJ const&) = delete; // Compute the extreme vertices in the specified direction and return // the indices of the vertices in the polyhedron vertex array. virtual void GetExtremeVertices(Vector3<Real> const& direction, int32_t& positiveDirection, int32_t& negativeDirection) override { Real minValue = std::numeric_limits<Real>::max(), maxValue = -minValue; negativeDirection = -1; positiveDirection = -1; auto vertexPool = this->mPolytope.GetVertexPool(); for (auto i : this->mPolytope.GetUniqueIndices()) { Vector3<Real> diff = vertexPool.get()->at(i) - mCentroid; Real dot = Dot(direction, diff); if (dot < minValue) { negativeDirection = i; minValue = dot; } if (dot > maxValue) { positiveDirection = i; maxValue = dot; } } } private: Vector3<Real> mCentroid; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Capsule3.h
.h
13,177
347
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/DistLineSegment.h> #include <Mathematics/Capsule.h> #include <Mathematics/Vector3.h> // The queries consider the capsule to be a solid. // // The test-intersection queries are based on distance computations. namespace gte { template <typename T> class TIQuery<T, Line3<T>, Capsule3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line3<T> const& line, Capsule3<T> const& capsule) { Result result{}; DCPQuery<T, Line3<T>, Segment3<T>> lsQuery{}; auto lsResult = lsQuery(line, capsule.segment); result.intersect = (lsResult.distance <= capsule.radius); return result; } }; template <typename T> class FIQuery<T, Line3<T>, Capsule3<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } bool intersect; size_t numIntersections; std::array<T, 2> parameter; std::array<Vector3<T>, 2> point; }; Result operator()(Line3<T> const& line, Capsule3<T> const& capsule) { Result result{}; DoQuery(line.origin, line.direction, capsule, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& lineOrigin, Vector3<T> const& lineDirection, Capsule3<T> const& capsule, Result& result) { // Create a coordinate system for the capsule. In this system, // the capsule segment center C is the origin and the capsule axis // direction W is the z-axis. U and V are the other coordinate // axis directions. If P = x*U+y*V+z*W, the cylinder containing // the capsule wall is x^2 + y^2 = r^2, where r is the capsule // radius. The finite cylinder that makes up the capsule minus // its hemispherical end caps has z-values |z| <= e, where e is // the extent of the capsule segment. The top hemisphere cap is // x^2+y^2+(z-e)^2 = r^2 for z >= e and the bottom hemisphere cap // is x^2+y^2+(z+e)^2 = r^2 for z <= -e. Vector3<T> segOrigin{}; // P Vector3<T> segDirection{}; // D T segExtent{}; // e capsule.segment.GetCenteredForm(segOrigin, segDirection, segExtent); std::array<Vector3<T>, 3> basis{}; // {W, U, V} basis[0] = segDirection; ComputeOrthogonalComplement(1, basis.data()); T rSqr = capsule.radius * capsule.radius; Vector3<T> const& W = basis[0]; Vector3<T> const& U = basis[1]; Vector3<T> const& V = basis[2]; // Convert incoming line origin to capsule coordinates. Vector3<T> diff = lineOrigin - segOrigin; Vector3<T> P{ Dot(U, diff), Dot(V, diff), Dot(W, diff) }; // Get the z-value, in capsule coordinates, of the incoming line's // unit-length direction. T const zero = static_cast<T>(0); T dz = Dot(W, lineDirection); if (std::fabs(dz) == static_cast<T>(1)) { // The line is parallel to the capsule axis. Determine // whether the line intersects the capsule hemispheres. T radialSqrDist = rSqr - P[0] * P[0] - P[1] * P[1]; if (radialSqrDist >= zero) { // The line intersects the hemispherical caps. result.intersect = true; result.numIntersections = 2; T zOffset = std::sqrt(radialSqrDist) + segExtent; if (dz > zero) { result.parameter[0] = -P[2] - zOffset; result.parameter[1] = -P[2] + zOffset; } else { result.parameter[0] = P[2] - zOffset; result.parameter[1] = P[2] + zOffset; } } // else: The line outside the capsule's cylinder, no // intersection. return; } // Convert the incoming line unit-length direction to capsule // coordinates. Vector3<T> D{ Dot(U, lineDirection), Dot(V, lineDirection), dz }; // Test intersection of line P+t*D with infinite cylinder // x^2+y^2 = r^2. This reduces to computing the roots of a // quadratic equation. If P = (px,py,pz) and D = (dx,dy,dz), then // the quadratic equation is // (dx^2+dy^2)*t^2 + 2*(px*dx+py*dy)*t + (px^2+py^2-r^2) = 0 T a0 = P[0] * P[0] + P[1] * P[1] - rSqr; T a1 = P[0] * D[0] + P[1] * D[1]; T a2 = D[0] * D[0] + D[1] * D[1]; T discr = a1 * a1 - a0 * a2; if (discr < zero) { // The line does not intersect the infinite cylinder, so it // cannot intersect the capsule. return; } T root, tValue, zValue; if (discr > zero) { // The line intersects the infinite cylinder in two places. root = std::sqrt(discr); tValue = (-a1 - root) / a2; zValue = P[2] + tValue * D[2]; if (std::fabs(zValue) <= segExtent) { result.intersect = true; result.parameter[result.numIntersections++] = tValue; } tValue = (-a1 + root) / a2; zValue = P[2] + tValue * D[2]; if (std::fabs(zValue) <= segExtent) { result.intersect = true; result.parameter[result.numIntersections++] = tValue; } if (result.numIntersections == 2) { // The line intersects the capsule wall in two places. return; } } else { // The line is tangent to the infinite cylinder but intersects // the cylinder in a single point. tValue = -a1 / a2; zValue = P[2] + tValue * D[2]; if (std::fabs(zValue) <= segExtent) { result.intersect = true; result.numIntersections = 1; result.parameter[0] = tValue; result.parameter[1] = result.parameter[0]; return; } } // Test intersection with bottom hemisphere. The quadratic // equation is // t^2 + 2*(px*dx+py*dy+(pz+e)*dz)*t // + (px^2+py^2+(pz+e)^2-r^2) = 0 // Use the fact that currently a1 = px*dx+py*dy and // a0 = px^2+py^2-r^2. The leading coefficient is a2 = 1, so no // need to include in the construction. T PZpE = P[2] + segExtent; a1 += PZpE * D[2]; a0 += PZpE * PZpE; discr = a1 * a1 - a0; if (discr > zero) { root = std::sqrt(discr); tValue = -a1 - root; zValue = P[2] + tValue * D[2]; if (zValue <= -segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } tValue = -a1 + root; zValue = P[2] + tValue * D[2]; if (zValue <= -segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } } else if (discr == zero) { tValue = -a1; zValue = P[2] + tValue * D[2]; if (zValue <= -segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } } // Test intersection with top hemisphere. The quadratic equation // is // t^2 + 2*(px*dx+py*dy+(pz-e)*dz)*t // + (px^2+py^2+(pz-e)^2-r^2) = 0 // Use the fact that currently a1 = px*dx+py*dy+(pz+e)*dz and // a0 = px^2+py^2+(pz+e)^2-r^2. The leading coefficient is a2 = 1, // so no need to include in the construction. a1 -= static_cast<T>(2) * segExtent * D[2]; a0 -= static_cast<T>(4) * segExtent * P[2]; discr = a1 * a1 - a0; if (discr > zero) { root = std::sqrt(discr); tValue = -a1 - root; zValue = P[2] + tValue * D[2]; if (zValue >= segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } tValue = -a1 + root; zValue = P[2] + tValue * D[2]; if (zValue >= segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } } else if (discr == zero) { tValue = -a1; zValue = P[2] + tValue * D[2]; if (zValue >= segExtent) { result.parameter[result.numIntersections++] = tValue; if (result.numIntersections == 2) { result.intersect = true; if (result.parameter[0] > result.parameter[1]) { std::swap(result.parameter[0], result.parameter[1]); } return; } } } if (result.numIntersections == 1) { result.parameter[1] = result.parameter[0]; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay2AlignedBox2.h
.h
4,641
140
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine2AlignedBox2.h> #include <Mathematics/Ray.h> #include <Mathematics/Vector2.h> // The queries consider the box to be a solid. // // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the four // edges of the box. namespace gte { template <typename T> class TIQuery<T, Ray2<T>, AlignedBox2<T>> : public TIQuery<T, Line2<T>, AlignedBox2<T>> { public: struct Result : public TIQuery<T, Line2<T>, AlignedBox2<T>>::Result { Result() : TIQuery<T, Line2<T>, AlignedBox2<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray2<T> const& ray, AlignedBox2<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<T>::Unit(d). Vector2<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the ray to the aligned-box coordinate system. Vector2<T> rayOrigin = ray.origin - boxCenter; Result result{}; DoQuery(rayOrigin, ray.direction, boxExtent, result); return result; } protected: void DoQuery(Vector2<T> const& rayOrigin, Vector2<T> const& rayDirection, Vector2<T> const& boxExtent, Result& result) { for (int32_t i = 0; i < 2; ++i) { if (std::fabs(rayOrigin[i]) > boxExtent[i] && rayOrigin[i] * rayDirection[i] >= (T)0) { result.intersect = false; return; } } TIQuery<T, Line2<T>, AlignedBox2<T>>::DoQuery(rayOrigin, rayDirection, boxExtent, result); } }; template <typename T> class FIQuery<T, Ray2<T>, AlignedBox2<T>> : public FIQuery<T, Line2<T>, AlignedBox2<T>> { public: struct Result : public FIQuery<T, Line2<T>, AlignedBox2<T>>::Result { Result() : FIQuery<T, Line2<T>, AlignedBox2<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray2<T> const& ray, AlignedBox2<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<T>::Unit(d). Vector2<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the ray to the aligned-box coordinate system. Vector2<T> rayOrigin = ray.origin - boxCenter; Result result{}; DoQuery(rayOrigin, ray.direction, boxExtent, result); for (int32_t i = 0; i < result.numIntersections; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } return result; } protected: void DoQuery(Vector2<T> const& rayOrigin, Vector2<T> const& rayDirection, Vector2<T> const& boxExtent, Result& result) { FIQuery<T, Line2<T>, AlignedBox2<T>>::DoQuery(rayOrigin, rayDirection, boxExtent, result); if (result.intersect) { // The line containing the ray intersects the box; the // t-interval is [t0,t1]. The ray intersects the box as long // as [t0,t1] overlaps the ray t-interval [0,+infinity). std::array<T, 2> rayInterval = { (T)0, std::numeric_limits<T>::max() }; FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(result.parameter, rayInterval); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/UnsymmetricEigenvalues.h
.h
14,122
383
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> #include <algorithm> #include <array> #include <cstdint> #include <cstring> #include <functional> #include <vector> // An implementation of the QR algorithm described in "Matrix Computations, // 2nd edition" by G. H. Golub and C. F. Van Loan, The Johns Hopkins // University Press, Baltimore MD, Fourth Printing 1993. In particular, // the implementation is based on Chapter 7 (The Unsymmetric Eigenvalue // Problem), Section 7.5 (The Practical QR Algorithm). namespace gte { template <typename Real> class UnsymmetricEigenvalues { public: // The solver processes NxN matrices (not necessarily symmetric), // where N >= 3 ('size' is N) and the matrix is stored in row-major // order. The maximum number of iterations ('maxIterations') must // be specified for reducing an upper Hessenberg matrix to an upper // quasi-triangular matrix (upper triangular matrix of blocks where // the diagonal blocks are 1x1 or 2x2). The goal is to compute the // real-valued eigenvalues. UnsymmetricEigenvalues(int32_t size, uint32_t maxIterations) : mSize(0), mSizeM1(0), mMaxIterations(0), mMatrix{}, mX{}, mV{}, mScaledV{}, mW{}, mFlagStorage{}, mSubdiagonalFlag(nullptr), mNumEigenvalues(0), mEigenvalues{} { if (size >= 3 && maxIterations > 0) { mSize = size; mSizeM1 = size - 1; mMaxIterations = maxIterations; mMatrix.resize(static_cast<size_t>(size) * static_cast<size_t>(size)); mX.resize(size); mV.resize(size); mScaledV.resize(size); mW.resize(size); mFlagStorage.resize(static_cast<size_t>(size) + 1); std::fill(mFlagStorage.begin(), mFlagStorage.end(), 0); mSubdiagonalFlag = &mFlagStorage[1]; mEigenvalues.resize(mSize); } } // A copy of the NxN input is made internally. The order of the // eigenvalues is specified by sortType: -1 (decreasing), 0 (no // sorting), or +1 (increasing). When sorted, the eigenvectors are // ordered accordingly. The return value is the number of iterations // consumed when convergence occurred, 0xFFFFFFFF when convergence did // not occur, or 0 when N <= 1 was passed to the constructor. uint32_t Solve(Real const* input, int32_t sortType) { if (mSize > 0) { std::copy(input, input + static_cast<size_t>(mSize) * static_cast<size_t>(mSize), mMatrix.begin()); ReduceToUpperHessenberg(); std::array<int32_t, 2> block; bool found = GetBlock(block); uint32_t numIterations; for (numIterations = 0; numIterations < mMaxIterations; ++numIterations) { if (found) { // Solve the current subproblem. FrancisQRStep(block[0], block[1] + 1); // Find another subproblem (if any). found = GetBlock(block); } else { break; } } // The matrix is fully uncoupled, upper Hessenberg with 1x1 or // 2x2 diagonal blocks. Golub and Van Loan call this "upper // quasi-triangular". mNumEigenvalues = 0; std::fill(mEigenvalues.begin(), mEigenvalues.end(), (Real)0); for (int32_t i = 0; i < mSizeM1; ++i) { if (mSubdiagonalFlag[i] == 0) { if (mSubdiagonalFlag[i - 1] == 0) { // We have a 1x1 block with a real eigenvalue. mEigenvalues[mNumEigenvalues++] = A(i, i); } } else { if (mSubdiagonalFlag[i - 1] == 0 && mSubdiagonalFlag[i + 1] == 0) { // We have a 2x2 block that might have real // eigenvalues. Real a00 = A(i, i); Real a01 = A(i, i + 1); Real a10 = A(i + 1, i); Real a11 = A(i + 1, i + 1); Real tr = a00 + a11; Real det = a00 * a11 - a01 * a10; Real halfTr = tr * (Real)0.5; Real discr = halfTr * halfTr - det; if (discr >= (Real)0) { Real rootDiscr = std::sqrt(discr); mEigenvalues[mNumEigenvalues++] = halfTr - rootDiscr; mEigenvalues[mNumEigenvalues++] = halfTr + rootDiscr; } } // else: // The QR iteration failed to converge at this block. // It must also be the case that // numIterations == mMaxIterations. TODO: The caller // will be aware of this when testing the returned // numIterations. Is there a remedy for such a case? // This happened with root finding using the companion // matrix of a polynomial.) } } if (sortType != 0 && mNumEigenvalues > 1) { if (sortType > 0) { std::sort(mEigenvalues.begin(), mEigenvalues.begin() + mNumEigenvalues, std::less<Real>()); } else { std::sort(mEigenvalues.begin(), mEigenvalues.begin() + mNumEigenvalues, std::greater<Real>()); } } return numIterations; } return 0; } // Get the real-valued eigenvalues of the matrix passed to Solve(...). // The input 'eigenvalues' must have at least N elements. void GetEigenvalues(uint32_t& numEigenvalues, Real* eigenvalues) const { if (mSize > 0) { numEigenvalues = mNumEigenvalues; std::memcpy(eigenvalues, mEigenvalues.data(), numEigenvalues * sizeof(Real)); } else { numEigenvalues = 0; } } private: // 2D accessors to elements of mMatrix[]. inline Real const& A(int32_t r, int32_t c) const { return mMatrix[c + r * static_cast<size_t>(mSize)]; } inline Real& A(int32_t r, int32_t c) { return mMatrix[c + r * static_cast<size_t>(mSize)]; } // Compute the Householder vector for (X[rmin],...,x[rmax]). The // input vector is stored in mX in the index range [rmin,rmax]. The // output vector V is stored in mV in the index range [rmin,rmax]. // The scaled vector is S = (-2/Dot(V,V))*V and is stored in mScaledV // in the index range [rmin,rmax]. void House(int32_t rmin, int32_t rmax) { Real length = (Real)0; for (int32_t r = rmin; r <= rmax; ++r) { length += mX[r] * mX[r]; } length = std::sqrt(length); if (length != (Real)0) { Real sign = (mX[rmin] >= (Real)0 ? (Real)1 : (Real)-1); Real invDenom = (Real)1 / (mX[rmin] + sign * length); for (int32_t r = rmin + 1; r <= rmax; ++r) { mV[r] = mX[r] * invDenom; } } mV[rmin] = (Real)1; Real dot = (Real)1; for (int32_t r = rmin + 1; r <= rmax; ++r) { dot += mV[r] * mV[r]; } Real scale = (Real)-2 / dot; for (int32_t r = rmin; r <= rmax; ++r) { mScaledV[r] = scale * mV[r]; } } // Support for replacing matrix A by P^T*A*P, where P is a Householder // reflection computed using House(...). void RowHouse(int32_t rmin, int32_t rmax, int32_t cmin, int32_t cmax) { for (int32_t c = cmin; c <= cmax; ++c) { mW[c] = (Real)0; for (int32_t r = rmin; r <= rmax; ++r) { mW[c] += mScaledV[r] * A(r, c); } } for (int32_t r = rmin; r <= rmax; ++r) { for (int32_t c = cmin; c <= cmax; ++c) { A(r, c) += mV[r] * mW[c]; } } } void ColHouse(int32_t rmin, int32_t rmax, int32_t cmin, int32_t cmax) { for (int32_t r = rmin; r <= rmax; ++r) { mW[r] = (Real)0; for (int32_t c = cmin; c <= cmax; ++c) { mW[r] += mScaledV[c] * A(r, c); } } for (int32_t r = rmin; r <= rmax; ++r) { for (int32_t c = cmin; c <= cmax; ++c) { A(r, c) += mW[r] * mV[c]; } } } void ReduceToUpperHessenberg() { for (int32_t c = 0, cp1 = 1; c <= mSize - 3; ++c, ++cp1) { for (int32_t r = cp1; r <= mSizeM1; ++r) { mX[r] = A(r, c); } House(cp1, mSizeM1); RowHouse(cp1, mSizeM1, c, mSizeM1); ColHouse(0, mSizeM1, cp1, mSizeM1); } } void FrancisQRStep(int32_t rmin, int32_t rmax) { // Apply the double implicit shift step. int32_t const i0 = rmax - 1, i1 = rmax; Real a00 = A(i0, i0); Real a01 = A(i0, i1); Real a10 = A(i1, i0); Real a11 = A(i1, i1); Real tr = a00 + a11; Real det = a00 * a11 - a01 * a10; int32_t const j0 = rmin, j1 = j0 + 1, j2 = j1 + 1; Real b00 = A(j0, j0); Real b01 = A(j0, j1); Real b10 = A(j1, j0); Real b11 = A(j1, j1); Real b21 = A(j2, j1); mX[rmin] = b00 * (b00 - tr) + b01 * b10 + det; mX[static_cast<size_t>(rmin) + 1] = b10 * (b00 + b11 - tr); mX[static_cast<size_t>(rmin) + 2] = b10 * b21; House(rmin, rmin + 2); RowHouse(rmin, rmin + 2, rmin, rmax); ColHouse(rmin, std::min(rmax, rmin + 3), rmin, rmin + 2); // Apply Householder reflections to restore the matrix to upper // Hessenberg form. for (int32_t c = 0, cp1 = 1; c <= mSize - 3; ++c, ++cp1) { int32_t kmax = std::min(cp1 + 2, mSizeM1); for (int32_t r = cp1; r <= kmax; ++r) { mX[r] = A(r, c); } House(cp1, kmax); RowHouse(cp1, kmax, c, mSizeM1); ColHouse(0, mSizeM1, cp1, kmax); } } bool GetBlock(std::array<int32_t, 2>& block) { for (int32_t i = 0; i < mSizeM1; ++i) { Real a00 = A(i, i); Real a11 = A(i + 1, i + 1); Real a21 = A(i + 1, i); Real sum0 = a00 + a11; Real sum1 = sum0 + a21; mSubdiagonalFlag[i] = (sum1 != sum0 ? 1 : 0); } for (int32_t i = 0; i < mSizeM1; ++i) { if (mSubdiagonalFlag[i] == 1) { block = { i, -1 }; while (i < mSizeM1 && mSubdiagonalFlag[i] == 1) { block[1] = i++; } if (block[1] != block[0]) { return true; } } } return false; } // The number N of rows and columns of the matrices to be processed. int32_t mSize, mSizeM1; // The maximum number of iterations for reducing the tridiagonal // matrix to a diagonal matrix. uint32_t mMaxIterations; // The internal copy of a matrix passed to the solver. std::vector<Real> mMatrix; // NxN elements // Temporary storage to compute Householder reflections. std::vector<Real> mX, mV, mScaledV, mW; // N elements // Flags about the zeroness of the subdiagonal entries. This is used // to detect uncoupled submatrices and apply the QR algorithm to the // corresponding subproblems. The storage is padded on both ends with // zeros to avoid additional code logic when packing the eigenvalues // for access by the caller. std::vector<int32_t> mFlagStorage; int32_t* mSubdiagonalFlag; int32_t mNumEigenvalues; std::vector<Real> mEigenvalues; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IndexAttribute.h
.h
2,638
86
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> // The IndexAttribute class represents an array of triples of indices into a // vertex array for an indexed triangle mesh. For now, the source must be // either uint16_t or uint32_t. namespace gte { struct IndexAttribute { // Construction. inline IndexAttribute(void* inSource = nullptr, size_t inSize = 0) : source(inSource), size(inSize) { } // Triangle access. inline void SetTriangle(uint32_t t, uint32_t v0, uint32_t v1, uint32_t v2) { if (size == sizeof(uint32_t)) { uint32_t* index = reinterpret_cast<uint32_t*>(source) + 3 * static_cast<size_t>(t); index[0] = v0; index[1] = v1; index[2] = v2; return; } if (size == sizeof(uint16_t)) { uint16_t* index = reinterpret_cast<uint16_t*>(source) + 3 * static_cast<size_t>(t); index[0] = static_cast<uint16_t>(v0); index[1] = static_cast<uint16_t>(v1); index[2] = static_cast<uint16_t>(v2); return; } // Unsupported type. } inline void GetTriangle(uint32_t t, uint32_t& v0, uint32_t& v1, uint32_t& v2) const { if (size == sizeof(uint32_t)) { uint32_t* index = reinterpret_cast<uint32_t*>(source) + 3 * static_cast<size_t>(t); v0 = index[0]; v1 = index[1]; v2 = index[2]; return; } if (size == sizeof(uint16_t)) { uint16_t* index = reinterpret_cast<uint16_t*>(source) + 3 * static_cast<size_t>(t); v0 = static_cast<uint32_t>(index[0]); v1 = static_cast<uint32_t>(index[1]); v2 = static_cast<uint32_t>(index[2]); return; } // Unsupported type. v0 = 0; v1 = 0; v2 = 0; } // The source pointer must be 4-byte aligned, which is guaranteed on // 32-bit and 64-bit architectures. The size is the number of bytes // per index. void* source; size_t size; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ASinEstimate.h
.h
1,025
33
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.08 #pragma once #include <Mathematics/ACosEstimate.h> // Approximations to asin(x) of the form f(x) = pi/2 - sqrt(1-x)*p(x) // where the polynomial p(x) of degree D minimizes the quantity // maximum{|acos(x)/sqrt(1-x) - p(x)| : x in [0,1]} over all // polynomials of degree D. We use the identity asin(x) = pi/2 - acos(x). namespace gte { template <typename Real> class ASinEstimate { public: // The input constraint is x in [0,1]. For example, // float x; // in [0,1] // float result = ASinEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return (Real)GTE_C_HALF_PI - ACosEstimate<Real>::template Degree<D>(x); } }; }
Unknown