Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

manifold: Update to 3.5.2

Jakub Marcowski5158fbdb32e4
diff --git a/COPYRIGHT.txt b/COPYRIGHT.txt
index 09e779a251d..b18c237d4b2 100644
--- a/COPYRIGHT.txt
+++ b/COPYRIGHT.txt
@@ -422,7 +422,7 @@ License: BSD-3-clause
Files: thirdparty/manifold/*
Comment: Manifold
-Copyright: 2020-2025, The Manifold Authors
+Copyright: 2020-2026, The Manifold Authors
License: Apache-2.0
Files: thirdparty/mbedtls/*
diff --git a/modules/csg/SCsub b/modules/csg/SCsub
index 147e96970e5..1b945d85c32 100644
--- a/modules/csg/SCsub
+++ b/modules/csg/SCsub
@@ -19,9 +19,11 @@ thirdparty_sources = [
"src/constructors.cpp",
"src/csg_tree.cpp",
"src/edge_op.cpp",
+ "src/execution_impl.cpp",
"src/face_op.cpp",
"src/impl.cpp",
"src/manifold.cpp",
+ "src/minkowski.cpp",
"src/polygon.cpp",
"src/properties.cpp",
"src/quickhull.cpp",
diff --git a/thirdparty/README.md b/thirdparty/README.md
index fbc5cd4fb7a..a0e5ca1625c 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -667,14 +667,18 @@ See `linuxbsd_headers/README.md`.
## manifold
- Upstream: https://github.com/elalish/manifold
-- Version: 3.3.2 (798d83c8d7fabcddd23c1617097b95ba40f2597c, 2025)
+- Version: 3.5.2 (11235e6b8ebea2dbed8aec4285685aafd3d95667, 2026)
- License: Apache 2.0
File extracted from upstream source:
-- `src/` and `include/`, except from `CMakeLists.txt`, `cross_section.h` and `meshIO.{cpp,h}`
+- `src/` and `include/`, except from `CMakeLists.txt`, `cross_section.h`
- `AUTHORS`, `LICENSE`
+Patches:
+
+- `0001-missing-include.patch` ([GH-120018](https://github.com/godotengine/godot/pull/120018))
+
## mbedtls
diff --git a/thirdparty/manifold/include/manifold/common.h b/thirdparty/manifold/include/manifold/common.h
index d48cf4d2ebc..1e890f1de27 100644
--- a/thirdparty/manifold/include/manifold/common.h
+++ b/thirdparty/manifold/include/manifold/common.h
@@ -1,4 +1,4 @@
-// Copyright 2021 The Manifold Authors.
+// Copyright 2026 The Manifold Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -13,17 +13,31 @@
// limitations under the License.
#pragma once
+#include <cmath>
+#include <functional>
#include <limits>
+#include <memory>
#include <vector>
-#ifdef MANIFOLD_DEBUG
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
#include <chrono>
+#include <iostream>
#endif
+#include "./math.h"
#include "linalg.h"
-#include "optional_assert.h"
namespace manifold {
+
+// Forward decls for ExecutionContext factory methods (full defs in
+// manifold.h / mesh.h).
+class Manifold;
+template <typename Precision, typename I = uint32_t>
+struct MeshGLP;
+using MeshGL = MeshGLP<float>;
+using MeshGL64 = MeshGLP<double, uint64_t>;
+struct Box; // defined below; needed by ExecutionContext::LevelSet
+
/** @addtogroup Math
* @ingroup Core
* @brief Simple math operations.
@@ -93,19 +107,20 @@ constexpr double smoothstep(double edge0, double edge1, double a) {
* @param x Angle in degrees.
*/
inline double sind(double x) {
- if (!la::isfinite(x)) return sin(x);
+ if (!la::isfinite(x)) return NAN;
if (x < 0.0) return -sind(-x);
int quo;
- x = remquo(fabs(x), 90.0, &quo);
+ x = std::remquo(std::fabs(x), 90.0, &quo);
+ const double xr = radians(x);
switch (quo % 4) {
case 0:
- return sin(radians(x));
+ return math::sin(xr);
case 1:
- return cos(radians(x));
+ return math::cos(xr);
case 2:
- return -sin(radians(x));
+ return -math::sin(xr);
case 3:
- return -cos(radians(x));
+ return -math::cos(xr);
}
return 0.0;
}
@@ -152,6 +167,131 @@ struct Smoothness {
double smoothness;
};
+/**
+ * @brief Result of a ray cast query against a Manifold.
+ */
+struct RayHit {
+ /// The triangle index that was hit.
+ uint64_t faceID = 0;
+ /// The parametric distance along the ray segment in the closed interval
+ /// [0, 1], where 0 is the origin and 1 is the endpoint. Hits exactly at
+ /// the origin or endpoint are included.
+ double distance = 0;
+ /// The 3D position of the hit point.
+ vec3 position = vec3(0.0);
+ /// The geometric face normal at the hit.
+ vec3 normal = vec3(0.0);
+};
+
+/**
+ * @brief Observe and control a long-running Manifold evaluation.
+ *
+ * Attach to a Manifold via Manifold::WithContext(ctx); the next *eager* op
+ * invoked on the result (Status, Refine / RefineToLength / RefineToTolerance,
+ * Hull, MinkowskiSum / MinkowskiDifference) snapshots the ctx and reports
+ * progress and observes cancellation through it. Safe to read/write from any
+ * thread.
+ *
+ * Copyable and movable: copies share the same underlying state via a
+ * shared_ptr, so one thread can evaluate while another holds a copy and
+ * observes Progress() or calls Cancel(). Use a separate context per
+ * evaluation; passing the same context (or a copy of it) to two concurrent
+ * eager ops produces meaningless progress values because both calls reset
+ * and mutate the same counters.
+ *
+ * Cancellation is permanent for a Manifold: once requested and detected,
+ * the Manifold's status becomes Error::Cancelled and stays Cancelled. To
+ * retry, construct a new Manifold. A context, however, is reusable: each
+ * evaluation through it resets the progress counters, but it does NOT
+ * clear the cancel flag -- once Cancel() has been called on a context,
+ * every subsequent evaluation with that context (or any copy of it) will
+ * short-circuit to Error::Cancelled. Construct a fresh context to make a
+ * new evaluation cancellable independently.
+ *
+ * Cancellation granularity varies by op: Boolean trees check per
+ * sub-boolean (so a single very large boolean may run to completion
+ * before the next check); Hull checks at the boundaries of its main
+ * phases (post-buildMesh and post-SortGeometry); Minkowski checks per
+ * face of the first input and per internal BatchBoolean batch.
+ *
+ * Example: cancel a long-running BatchBoolean from an observer thread.
+ * @code
+ * ExecutionContext ctx;
+ * Manifold big = Manifold::BatchBoolean(items, OpType::Add).WithContext(ctx);
+ * std::thread eval([&] {
+ * if (big.Status() == Manifold::Error::Cancelled) {
+ * // evaluation was cancelled
+ * }
+ * });
+ * // ...later, from the UI thread:
+ * ctx.Cancel();
+ * eval.join();
+ * @endcode
+ *
+ * Example: cancel a Minkowski sum mid-evaluation.
+ * @code
+ * ExecutionContext ctx;
+ * std::thread eval([&] {
+ * if (a.WithContext(ctx).MinkowskiSum(b).Status() ==
+ * Manifold::Error::Cancelled) {
+ * // evaluation was cancelled
+ * }
+ * });
+ * ctx.Cancel();
+ * eval.join();
+ * @endcode
+ */
+class ExecutionContext {
+ public:
+ ExecutionContext();
+ ~ExecutionContext();
+ ExecutionContext(const ExecutionContext&);
+ ExecutionContext(ExecutionContext&&) noexcept;
+ ExecutionContext& operator=(const ExecutionContext&);
+ ExecutionContext& operator=(ExecutionContext&&) noexcept;
+
+ /// Request cancellation. Can be called from any thread. Idempotent.
+ void Cancel();
+ /// Has cancellation been requested?
+ bool Cancelled() const;
+ /// Normalized progress in [0, 1]. Monotonically increases during
+ /// evaluation. Returns 1.0 when no work has been scheduled (interpreted
+ /// as trivially complete -- e.g. a single-leaf manifold has nothing to
+ /// evaluate, and `Progress()` called before any `Status(ctx)` reflects
+ /// the same "no pending work" state).
+ double Progress() const;
+
+ /// Eager ctx-aware `Manifold(MeshGL)`. The heavy ingest steps check
+ /// cancel and credit `Progress()` between phases. Precedence: a
+ /// Cancel() before this call wins over empty/malformed input;
+ /// validation errors win over a Cancel() that races in after that.
+ /// Concurrent calls on the same ctx produce undefined progress
+ /// values; the returned Manifolds remain valid.
+ Manifold FromMeshGL(const MeshGL& mesh);
+ Manifold FromMeshGL(const MeshGL64& mesh);
+
+ /// Eager ctx-aware `Manifold::Smooth(MeshGL[64])`. The ingest phases
+ /// plus the tangent-creation phases check cancel and credit
+ /// `Progress()` between phases. Same cancel-vs-validation precedence
+ /// as `FromMeshGL`.
+ Manifold Smooth(const MeshGL& mesh,
+ const std::vector<Smoothness>& sharpenedEdges = {});
+ Manifold Smooth(const MeshGL64& mesh,
+ const std::vector<Smoothness>& sharpenedEdges = {});
+
+ /// Eager ctx-aware `Manifold::LevelSet`. The voxel-sampling and
+ /// mesh-extraction phases check cancel and credit `Progress()` between
+ /// phases. A Cancel() before or during the call yields a Cancelled result.
+ Manifold LevelSet(std::function<double(vec3)> sdf, Box bounds,
+ double edgeLength, double level = 0, double tolerance = -1,
+ bool canParallel = true);
+
+ /// @internal Opaque implementation. Defined in src/execution_impl.h;
+ /// accessible only to internal code that includes that header.
+ struct Impl;
+ std::shared_ptr<Impl> impl_;
+};
+
/**
* @brief Axis-aligned 3D box, primarily for bounding.
*/
@@ -206,6 +346,18 @@ struct Box {
la::all(la::gequal(max, box.max));
}
+ /**
+ * Does this box equal the given box exactly?
+ */
+ constexpr bool operator==(const Box& box) const {
+ return la::all(la::equal(box.min, min)) && la::all(la::equal(max, box.max));
+ }
+
+ /**
+ * Does this box not equal the given box exactly?
+ */
+ constexpr bool operator!=(const Box& box) const { return !(*this == box); }
+
/**
* Expand this box to include the given point.
*/
@@ -380,7 +532,7 @@ struct Rect {
/**
* Is the rectangle empty (containing no space)?
*/
- constexpr bool IsEmpty() const { return max.y <= min.y || max.x <= min.x; };
+ constexpr bool IsEmpty() const { return max.y <= min.y || max.x <= min.x; }
/**
* Does this recangle have finite bounds?
@@ -471,7 +623,7 @@ struct Rect {
* @brief Boolean operation type: Add (Union), Subtract (Difference), and
* Intersect.
*/
-enum class OpType { Add, Subtract, Intersect };
+enum class OpType : char { Add, Subtract, Intersect };
constexpr int DEFAULT_SEGMENTS = 0;
constexpr double DEFAULT_ANGLE = 10.0;
@@ -487,7 +639,6 @@ constexpr double DEFAULT_LENGTH = 1.0;
* must be specified.
*/
class Quality {
- private:
public:
static void SetMinCircularAngle(double angle);
static void SetMinCircularEdgeLength(double length);
@@ -524,9 +675,8 @@ struct ExecutionParams {
bool cleanupTriangles = true;
/// Verbose level:
/// - 0 for no verbose output
- /// - 1 for verbose output for the Boolean, including timing info and vector
- /// sizes.
- /// - 2 for verbose output with triangulator action as well.
+ /// - 1 for Boolean debug dumps on failures and invalid intermediate meshes.
+ /// - 2 for Boolean timing and size statistics, plus triangulator action.
int verbose = 0;
};
/** @} */
@@ -534,13 +684,11 @@ struct ExecutionParams {
#ifdef MANIFOLD_DEBUG
inline std::ostream& operator<<(std::ostream& stream, const Box& box) {
- return stream << "min: " << box.min << ", "
- << "max: " << box.max;
+ return stream << "min: " << box.min << ", " << "max: " << box.max;
}
inline std::ostream& operator<<(std::ostream& stream, const Rect& box) {
- return stream << "min: " << box.min << ", "
- << "max: " << box.max;
+ return stream << "min: " << box.min << ", " << "max: " << box.max;
}
inline std::ostream& operator<<(std::ostream& stream, const Smoothness& s) {
@@ -576,6 +724,9 @@ void Diff(const std::vector<T>& a, const std::vector<T>& b) {
std::cout << std::endl;
}
+#endif
+
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
struct Timer {
std::chrono::high_resolution_clock::time_point start, end;
diff --git a/thirdparty/manifold/include/manifold/linalg.h b/thirdparty/manifold/include/manifold/linalg.h
index 2b82421abc7..e2a5a508426 100644
--- a/thirdparty/manifold/include/manifold/linalg.h
+++ b/thirdparty/manifold/include/manifold/linalg.h
@@ -1,4 +1,4 @@
-// Copyright 2024 The Manifold Authors.
+// Copyright 2026 The Manifold Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -41,6 +41,8 @@
#include <functional> // For std::hash declaration
#include <type_traits> // For std::enable_if, std::is_same, std::declval
+#include "./math.h"
+
// In Visual Studio 2015, `constexpr` applied to a member function implies
// `const`, which causes ambiguous overload resolution
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
@@ -617,42 +619,6 @@ struct std_abs {
return std::abs(a);
}
};
-struct std_floor {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::floor(a)) {
- return std::floor(a);
- }
-};
-struct std_ceil {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::ceil(a)) {
- return std::ceil(a);
- }
-};
-struct std_exp {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::exp(a)) {
- return std::exp(a);
- }
-};
-struct std_log {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::log(a)) {
- return std::log(a);
- }
-};
-struct std_log2 {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::log2(a)) {
- return std::log2(a);
- }
-};
-struct std_log10 {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::log10(a)) {
- return std::log10(a);
- }
-};
struct std_sqrt {
template <class A>
constexpr auto operator()(A a) const -> decltype(std::sqrt(a)) {
@@ -660,81 +626,26 @@ struct std_sqrt {
}
};
struct std_sin {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::sin(a)) {
- return std::sin(a);
- }
+ double operator()(double a) const { return manifold::math::sin(a); }
};
struct std_cos {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::cos(a)) {
- return std::cos(a);
- }
+ double operator()(double a) const { return manifold::math::cos(a); }
};
struct std_tan {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::tan(a)) {
- return std::tan(a);
- }
+ double operator()(double a) const { return manifold::math::tan(a); }
};
struct std_asin {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::asin(a)) {
- return std::asin(a);
- }
+ double operator()(double a) const { return manifold::math::asin(a); }
};
struct std_acos {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::acos(a)) {
- return std::acos(a);
- }
+ double operator()(double a) const { return manifold::math::acos(a); }
};
struct std_atan {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::atan(a)) {
- return std::atan(a);
- }
-};
-struct std_sinh {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::sinh(a)) {
- return std::sinh(a);
- }
-};
-struct std_cosh {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::cosh(a)) {
- return std::cosh(a);
- }
-};
-struct std_tanh {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::tanh(a)) {
- return std::tanh(a);
- }
-};
-struct std_round {
- template <class A>
- constexpr auto operator()(A a) const -> decltype(std::round(a)) {
- return std::round(a);
- }
-};
-struct std_fmod {
- template <class A, class B>
- constexpr auto operator()(A a, B b) const -> decltype(std::fmod(a, b)) {
- return std::fmod(a, b);
- }
-};
-struct std_pow {
- template <class A, class B>
- constexpr auto operator()(A a, B b) const -> decltype(std::pow(a, b)) {
- return std::pow(a, b);
- }
+ double operator()(double a) const { return manifold::math::atan(a); }
};
struct std_atan2 {
- template <class A, class B>
- constexpr auto operator()(A a, B b) const -> decltype(std::atan2(a, b)) {
- return std::atan2(a, b);
+ double operator()(double a, double b) const {
+ return manifold::math::atan2(a, b);
}
};
struct std_copysign {
@@ -908,10 +819,8 @@ struct vec<T, 3> {
LINALG_CONSTEXPR14 T& operator[](int i) {
return i == 0 ? x : i == 1 ? y : z;
}
- constexpr const vec<T, 2>& xy() const {
- return *reinterpret_cast<const vec<T, 2>*>(this);
- }
- vec<T, 2>& xy() { return *reinterpret_cast<vec<T, 2>*>(this); }
+ constexpr vec<T, 2> xy() const { return vec<T, 2>(x, y); }
+ constexpr vec<T, 2> yz() const { return vec<T, 2>(y, z); }
template <class U, class = detail::conv_t<vec, U>>
constexpr vec(const U& u) : vec(converter<vec, U>{}(u)) {}
@@ -946,14 +855,8 @@ struct vec<T, 4> {
LINALG_CONSTEXPR14 T& operator[](int i) {
return i == 0 ? x : i == 1 ? y : i == 2 ? z : w;
}
- constexpr const vec<T, 2>& xy() const {
- return *reinterpret_cast<const vec<T, 2>*>(this);
- }
- constexpr const vec<T, 3>& xyz() const {
- return *reinterpret_cast<const vec<T, 3>*>(this);
- }
- vec<T, 2>& xy() { return *reinterpret_cast<vec<T, 2>*>(this); }
- vec<T, 3>& xyz() { return *reinterpret_cast<vec<T, 3>*>(this); }
+ constexpr vec<T, 2> xy() const { return vec<T, 2>(x, y); }
+ constexpr vec<T, 3> xyz() const { return vec<T, 3>(x, y, z); }
template <class U, class = detail::conv_t<vec, U>>
constexpr vec(const U& u) : vec(converter<vec, U>{}(u)) {}
@@ -1554,30 +1457,6 @@ constexpr apply_t<detail::std_abs, A> abs(const A& a) {
return apply(detail::std_abs{}, a);
}
template <class A>
-constexpr apply_t<detail::std_floor, A> floor(const A& a) {
- return apply(detail::std_floor{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_ceil, A> ceil(const A& a) {
- return apply(detail::std_ceil{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_exp, A> exp(const A& a) {
- return apply(detail::std_exp{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_log, A> log(const A& a) {
- return apply(detail::std_log{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_log2, A> log2(const A& a) {
- return apply(detail::std_log2{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_log10, A> log10(const A& a) {
- return apply(detail::std_log10{}, a);
-}
-template <class A>
constexpr apply_t<detail::std_sqrt, A> sqrt(const A& a) {
return apply(detail::std_sqrt{}, a);
}
@@ -1605,22 +1484,6 @@ template <class A>
constexpr apply_t<detail::std_atan, A> atan(const A& a) {
return apply(detail::std_atan{}, a);
}
-template <class A>
-constexpr apply_t<detail::std_sinh, A> sinh(const A& a) {
- return apply(detail::std_sinh{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_cosh, A> cosh(const A& a) {
- return apply(detail::std_cosh{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_tanh, A> tanh(const A& a) {
- return apply(detail::std_tanh{}, a);
-}
-template <class A>
-constexpr apply_t<detail::std_round, A> round(const A& a) {
- return apply(detail::std_round{}, a);
-}
/** @} */
/** @addtogroup binary_STL
@@ -1630,14 +1493,6 @@ constexpr apply_t<detail::std_round, A> round(const A& a) {
* @{
*/
template <class A, class B>
-constexpr apply_t<detail::std_fmod, A, B> fmod(const A& a, const B& b) {
- return apply(detail::std_fmod{}, a, b);
-}
-template <class A, class B>
-constexpr apply_t<detail::std_pow, A, B> pow(const A& a, const B& b) {
- return apply(detail::std_pow{}, a, b);
-}
-template <class A, class B>
constexpr apply_t<detail::std_atan2, A, B> atan2(const A& a, const B& b) {
return apply(detail::std_atan2{}, a, b);
}
@@ -1809,7 +1664,7 @@ T distance(const vec<T, M>& a, const vec<T, M>& b) {
template <class T, int M>
T uangle(const vec<T, M>& a, const vec<T, M>& b) {
T d = dot(a, b);
- return d > 1 ? 0 : std::acos(d < -1 ? -1 : d);
+ return d > 1 ? 0 : linalg::acos(d < -1 ? -1 : d);
}
/**
* @brief Return the angle in radians between two non-unit vectors.
@@ -1824,7 +1679,7 @@ T angle(const vec<T, M>& a, const vec<T, M>& b) {
*/
template <class T>
vec<T, 2> rot(T a, const vec<T, 2>& v) {
- const T s = std::sin(a), c = std::cos(a);
+ const T s = linalg::sin(a), c = linalg::cos(a);
return {v.x * c - v.y * s, v.x * s + v.y * c};
}
/**
@@ -1833,7 +1688,7 @@ vec<T, 2> rot(T a, const vec<T, 2>& v) {
*/
template <class T>
vec<T, 3> rotx(T a, const vec<T, 3>& v) {
- const T s = std::sin(a), c = std::cos(a);
+ const T s = linalg::sin(a), c = linalg::cos(a);
return {v.x, v.y * c - v.z * s, v.y * s + v.z * c};
}
/**
@@ -1842,7 +1697,7 @@ vec<T, 3> rotx(T a, const vec<T, 3>& v) {
*/
template <class T>
vec<T, 3> roty(T a, const vec<T, 3>& v) {
- const T s = std::sin(a), c = std::cos(a);
+ const T s = linalg::sin(a), c = linalg::cos(a);
return {v.x * c + v.z * s, v.y, -v.x * s + v.z * c};
}
/**
@@ -1851,7 +1706,7 @@ vec<T, 3> roty(T a, const vec<T, 3>& v) {
*/
template <class T>
vec<T, 3> rotz(T a, const vec<T, 3>& v) {
- const T s = std::sin(a), c = std::cos(a);
+ const T s = linalg::sin(a), c = linalg::cos(a);
return {v.x * c - v.y * s, v.x * s + v.y * c, v.z};
}
/**
@@ -1870,8 +1725,8 @@ template <class T, int M>
vec<T, M> slerp(const vec<T, M>& a, const vec<T, M>& b, T t) {
T th = uangle(a, b);
return th == 0 ? a
- : a * (std::sin(th * (1 - t)) / std::sin(th)) +
- b * (std::sin(th * t) / std::sin(th));
+ : a * (linalg::sin(th * (1 - t)) / linalg::sin(th)) +
+ b * (linalg::sin(th * t) / linalg::sin(th));
}
/** @} */
@@ -1909,7 +1764,7 @@ vec<T, 4> qexp(const vec<T, 4>& q) {
const auto v = q.xyz();
const auto vv = length(v);
return std::exp(q.w) *
- vec<T, 4>{v * (vv > 0 ? std::sin(vv) / vv : 0), std::cos(vv)};
+ vec<T, 4>{v * (vv > 0 ? linalg::sin(vv) / vv : 0), linalg::cos(vv)};
}
/**
* @brief
@@ -1920,7 +1775,7 @@ template <class T>
vec<T, 4> qlog(const vec<T, 4>& q) {
const auto v = q.xyz();
const auto vv = length(v), qq = length(q);
- return {v * (vv > 0 ? std::acos(q.w / qq) / vv : 0), std::log(qq)};
+ return {v * (vv > 0 ? linalg::acos(q.w / qq) / vv : 0), std::log(qq)};
}
/**
* @brief quaternion `q` raised to the exponent `p`
@@ -1928,9 +1783,10 @@ vec<T, 4> qlog(const vec<T, 4>& q) {
template <class T>
vec<T, 4> qpow(const vec<T, 4>& q, const T& p) {
const auto v = q.xyz();
- const auto vv = length(v), qq = length(q), th = std::acos(q.w / qq);
+ const auto vv = length(v), qq = length(q), th = linalg::acos(q.w / qq);
return std::pow(qq, p) *
- vec<T, 4>{v * (vv > 0 ? std::sin(p * th) / vv : 0), std::cos(p * th)};
+ vec<T, 4>{v * (vv > 0 ? linalg::sin(p * th) / vv : 0),
+ linalg::cos(p * th)};
}
/**
* @brief [Hamilton
@@ -2003,7 +1859,7 @@ constexpr vec<T, 3> qrot(const vec<T, 4>& q, const vec<T, 3>& v) {
*/
template <class T>
T qangle(const vec<T, 4>& q) {
- return std::atan2(length(q.xyz()), q.w) * 2;
+ return linalg::atan2(length(q.xyz()), q.w) * 2;
}
/**
* @brief Return the normalized axis of the axis-angle representation of the
@@ -2034,7 +1890,7 @@ vec<T, 4> qslerp(const vec<T, 4>& a, const vec<T, 4>& b, T t) {
*/
template <class T>
vec<T, 4> constexpr rotation_quat(const vec<T, 3>& axis, T angle) {
- return {axis * std::sin(angle / 2), std::cos(angle / 2)};
+ return {axis * linalg::sin(angle / 2), linalg::cos(angle / 2)};
}
/**
* @brief Returns a normalized quaternion representing the shortest rotation
@@ -2305,7 +2161,7 @@ mat<T, 4, 4> frustum_matrix(T x0, T x1, T y0, T y1, T n, T f,
template <class T>
mat<T, 4, 4> perspective_matrix(T fovy, T aspect, T n, T f, fwd_axis a = neg_z,
z_range z = neg_one_to_one) {
- T y = n * std::tan(fovy / 2), x = y * aspect;
+ T y = n * linalg::tan(fovy / 2), x = y * aspect;
return frustum_matrix(-x, x, -y, y, n, f, a, z);
}
/** @} */
diff --git a/thirdparty/manifold/include/manifold/manifold.h b/thirdparty/manifold/include/manifold/manifold.h
index 1e4b20116d1..ff4e04b86dd 100644
--- a/thirdparty/manifold/include/manifold/manifold.h
+++ b/thirdparty/manifold/include/manifold/manifold.h
@@ -16,8 +16,10 @@
#include <cstdint> // uint32_t, uint64_t
#include <functional>
#include <memory> // needed for shared_ptr
+#include <mutex>
#include "manifold/common.h"
+#include "manifold/mesh.h"
#include "manifold/vec_view.h"
namespace manifold {
@@ -39,197 +41,6 @@ class CsgLeafNode;
* @{
*/
-/**
- * @brief Mesh input/output suitable for pushing directly into graphics
- * libraries.
- *
- * The core (non-optional) parts of MeshGL are the triVerts indices buffer and
- * the vertProperties interleaved vertex buffer, which follow the conventions of
- * OpenGL (and other graphic libraries') buffers and are therefore generally
- * easy to map directly to other applications' data structures.
- *
- * The triVerts vector has a stride of 3 and specifies triangles as
- * vertex indices. For triVerts = [2, 4, 5, 3, 1, 6, ...], the triangles are [2,
- * 4, 5], [3, 1, 6], etc. and likewise the halfedges are [2, 4], [4, 5], [5, 2],
- * [3, 1], [1, 6], [6, 3], etc.
- *
- * The triVerts indices should form a manifold mesh: each of the 3 halfedges of
- * each triangle should have exactly one paired halfedge in the list, defined as
- * having the first index of one equal to the second index of the other and
- * vice-versa. However, this is not always possible - consider e.g. a cube with
- * normal-vector properties. Shared vertices would turn the cube into a ball by
- * interpolating normals - the common solution is to duplicate each corner
- * vertex into 3, each with the same position, but different normals
- * corresponding to each face. This is exactly what should be done in MeshGL,
- * however we request two additional vectors in this case: mergeFromVert and
- * mergeToVert. Each vertex mergeFromVert[i] is merged into vertex
- * mergeToVert[i], avoiding unreliable floating-point comparisons to recover the
- * manifold topology. These merges are simply a union, so which is from and to
- * doesn't matter.
- *
- * If you don't have merge vectors, you can create them with the Merge() method,
- * however this will fail if the mesh is not already manifold within the set
- * tolerance. For maximum reliability, always store the merge vectors with the
- * mesh, e.g. using the EXT_mesh_manifold extension in glTF.
- *
- * You can have any number of arbitrary floating-point properties per vertex,
- * and they will all be interpolated as necessary during operations. It is up to
- * you to keep track of which channel represents what type of data. A few of
- * Manifold's methods allow you to specify the channel where normals data
- * starts, in order to update it automatically for transforms and such. This
- * will be easier if your meshes all use the same channels for properties, but
- * this is not a requirement. Operations between meshes with different numbers
- * of peroperties will simply use the larger numProp and pad the smaller one
- * with zeroes.
- *
- * On output, the triangles are sorted into runs (runIndex, runOriginalID,
- * runTransform) that correspond to different mesh inputs. Other 3D libraries
- * may refer to these runs as primitives of a mesh (as in glTF) or draw calls,
- * as they often represent different materials on different parts of the mesh.
- * It is generally a good idea to maintain a map of OriginalIDs to materials to
- * make it easy to reapply them after a set of Boolean operations. These runs
- * can also be used as input, and thus also ensure a lossless roundtrip of data
- * through MeshGL.
- *
- * As an example, with runIndex = [0, 6, 18, 21] and runOriginalID = [1, 3, 3],
- * there are 7 triangles, where the first two are from the input mesh with ID 1,
- * the next 4 are from an input mesh with ID 3, and the last triangle is from a
- * different copy (instance) of the input mesh with ID 3. These two instances
- * can be distinguished by their different runTransform matrices.
- *
- * You can reconstruct polygonal faces by assembling all the triangles that are
- * from the same run and share the same faceID. These faces will be planar
- * within the output tolerance.
- *
- * The halfedgeTangent vector is used to specify the weighted tangent vectors of
- * each halfedge for the purpose of using the Refine methods to create a
- * smoothly-interpolated surface. They can also be output when calculated
- * automatically by the Smooth functions.
- *
- * MeshGL is an alias for the standard single-precision version. Use MeshGL64 to
- * output the full double precision that Manifold uses internally.
- */
-template <typename Precision, typename I = uint32_t>
-struct MeshGLP {
- /// Number of property vertices
- I NumVert() const { return vertProperties.size() / numProp; };
- /// Number of triangles
- I NumTri() const { return triVerts.size() / 3; };
- /// Number of properties per vertex, always >= 3.
- I numProp = 3;
- /// Flat, GL-style interleaved list of all vertex properties: propVal =
- /// vertProperties[vert * numProp + propIdx]. The first three properties are
- /// always the position x, y, z. The stride of the array is numProp.
- std::vector<Precision> vertProperties;
- /// The vertex indices of the three triangle corners in CCW (from the outside)
- /// order, for each triangle.
- std::vector<I> triVerts;
- /// Optional: A list of only the vertex indicies that need to be merged to
- /// reconstruct the manifold.
- std::vector<I> mergeFromVert;
- /// Optional: The same length as mergeFromVert, and the corresponding value
- /// contains the vertex to merge with. It will have an identical position, but
- /// the other properties may differ.
- std::vector<I> mergeToVert;
- /// Optional: Indicates runs of triangles that correspond to a particular
- /// input mesh instance. The runs encompass all of triVerts and are sorted
- /// by runOriginalID. Run i begins at triVerts[runIndex[i]] and ends at
- /// triVerts[runIndex[i+1]]. All runIndex values are divisible by 3. Returned
- /// runIndex will always be 1 longer than runOriginalID, but same length is
- /// also allowed as input: triVerts.size() will be automatically appended in
- /// this case.
- std::vector<I> runIndex;
- /// Optional: The OriginalID of the mesh this triangle run came from. This ID
- /// is ideal for reapplying materials to the output mesh. Multiple runs may
- /// have the same ID, e.g. representing different copies of the same input
- /// mesh. If you create an input MeshGL that you want to be able to reference
- /// as one or more originals, be sure to set unique values from ReserveIDs().
- std::vector<uint32_t> runOriginalID;
- /// Optional: For each run, a 3x4 transform is stored representing how the
- /// corresponding original mesh was transformed to create this triangle run.
- /// This matrix is stored in column-major order and the length of the overall
- /// vector is 12 * runOriginalID.size().
- std::vector<Precision> runTransform;
- /// Optional: Length NumTri, contains the source face ID this triangle comes
- /// from. Simplification will maintain all edges between triangles with
- /// different faceIDs. Input faceIDs will be maintained to the outputs, but if
- /// none are given, they will be filled in with Manifold's coplanar face
- /// calculation based on mesh tolerance.
- std::vector<I> faceID;
- /// Optional: The X-Y-Z-W weighted tangent vectors for smooth Refine(). If
- /// non-empty, must be exactly four times as long as Mesh.triVerts. Indexed
- /// as 4 * (3 * tri + i) + j, i < 3, j < 4, representing the tangent value
- /// Mesh.triVerts[tri][i] along the CCW edge. If empty, mesh is faceted.
- std::vector<Precision> halfedgeTangent;
- /// Tolerance for mesh simplification. When creating a Manifold, the tolerance
- /// used will be the maximum of this and a baseline tolerance from the size of
- /// the bounding box. Any edge shorter than tolerance may be collapsed.
- /// Tolerance may be enlarged when floating point error accumulates.
- Precision tolerance = 0;
-
- MeshGLP() = default;
-
- /**
- * Updates the mergeFromVert and mergeToVert vectors in order to create a
- * manifold solid. If the MeshGL is already manifold, no change will occur and
- * the function will return false. Otherwise, this will merge verts along open
- * edges within tolerance (the maximum of the MeshGL tolerance and the
- * baseline bounding-box tolerance), keeping any from the existing merge
- * vectors, and return true.
- *
- * There is no guarantee the result will be manifold - this is a best-effort
- * helper function designed primarily to aid in the case where a manifold
- * multi-material MeshGL was produced, but its merge vectors were lost due to
- * a round-trip through a file format. Constructing a Manifold from the result
- * will report an error status if it is not manifold.
- */
- bool Merge();
-
- /**
- * Returns the x, y, z position of the ith vertex.
- *
- * @param v vertex index.
- */
- la::vec<Precision, 3> GetVertPos(size_t v) const {
- size_t offset = v * numProp;
- return la::vec<Precision, 3>(vertProperties[offset],
- vertProperties[offset + 1],
- vertProperties[offset + 2]);
- }
-
- /**
- * Returns the three vertex indices of the ith triangle.
- *
- * @param t triangle index.
- */
- la::vec<I, 3> GetTriVerts(size_t t) const {
- size_t offset = 3 * t;
- return la::vec<I, 3>(triVerts[offset], triVerts[offset + 1],
- triVerts[offset + 2]);
- }
-
- /**
- * Returns the x, y, z, w tangent of the ith halfedge.
- *
- * @param h halfedge index (3 * triangle_index + [0|1|2]).
- */
- la::vec<Precision, 4> GetTangent(size_t h) const {
- size_t offset = 4 * h;
- return la::vec<Precision, 4>(
- halfedgeTangent[offset], halfedgeTangent[offset + 1],
- halfedgeTangent[offset + 2], halfedgeTangent[offset + 3]);
- }
-};
-
-/**
- * @brief Single-precision - ideal for most uses, especially graphics.
- */
-using MeshGL = MeshGLP<float>;
-/**
- * @brief Double-precision, 64-bit indices - best for huge meshes.
- */
-using MeshGL64 = MeshGLP<double, uint64_t>;
-
/**
* @brief This library's internal representation of an oriented, 2-manifold,
* triangle mesh - a simple boundary-representation of a solid object. Use this
@@ -282,6 +93,8 @@ class Manifold {
*/
///@{
std::vector<Manifold> Decompose() const;
+ [[deprecated(
+ "Compose is deprecated, use BatchBoolean with OpType::Add instead.")]]
static Manifold Compose(const std::vector<Manifold>&);
static Manifold Tetrahedron();
static Manifold Cube(vec3 size = vec3(1.0), bool center = false);
@@ -322,6 +135,8 @@ class Manifold {
FaceIDWrongLength,
InvalidConstruction,
ResultTooLarge,
+ InvalidTangents,
+ Cancelled,
};
/** @name Information
@@ -329,6 +144,32 @@ class Manifold {
*/
///@{
Error Status() const;
+
+ /// Returns a copy of this Manifold with the given ExecutionContext attached.
+ /// The attachment is consumed only by `Status()` (for deferred CSG trees)
+ /// and the eager ops (`Refine` / `RefineToLength` / `RefineToTolerance`,
+ /// `Hull`, `MinkowskiSum` / `MinkowskiDifference`); those snapshot the ctx
+ /// and report progress / observe cancellation through it. Other queries
+ /// that force evaluation (`Volume`, `GetMeshGL`, `BoundingBox`, etc.) do
+ /// not currently observe attached ctx.
+ ///
+ /// Deferred ops (Boolean operators, Translate / Rotate / Scale / Transform
+ /// / Mirror / Warp / SetTolerance / Simplify, BatchBoolean, the
+ /// vector-of-Manifold Hull) ignore any attached ctx and produce a result
+ /// with no attached ctx. Inputs are not mutated. The idiom for observing a
+ /// deferred tree is therefore:
+ ///
+ /// (a + b - c).WithContext(ctx).Status();
+ ///
+ /// while the idiom for observing an eager op is:
+ ///
+ /// m.WithContext(ctx).Refine(n);
+ /// m.WithContext(ctx).MinkowskiSum(other);
+ ///
+ /// Raw copy / assignment preserves the attachment (it's the same logical
+ /// Manifold). Only ops that derive a *new* Manifold drop the attachment.
+ Manifold WithContext(const ExecutionContext& ctx) const;
+
bool IsEmpty() const;
size_t NumVert() const;
size_t NumEdge() const;
@@ -346,6 +187,7 @@ class Manifold {
double SurfaceArea() const;
double Volume() const;
double MinGap(const Manifold& other, double searchLength) const;
+ std::vector<RayHit> RayCast(vec3 origin, vec3 endpoint) const;
///@}
/** @name Mesh ID
@@ -391,6 +233,8 @@ class Manifold {
std::pair<Manifold, Manifold> SplitByPlane(vec3 normal,
double originOffset) const;
Manifold TrimByPlane(vec3 normal, double originOffset) const;
+ Manifold MinkowskiSum(const Manifold&) const;
+ Manifold MinkowskiDifference(const Manifold&) const;
///@}
/** @name Properties
@@ -401,7 +245,8 @@ class Manifold {
int numProp,
std::function<void(double*, vec3, const double*)> propFunc) const;
Manifold CalculateCurvature(int gaussianIdx, int meanIdx) const;
- Manifold CalculateNormals(int normalIdx, double minSharpAngle = 60) const;
+ Manifold CalculateNormals(int normalIdx = 0,
+ double minSharpAngle = 52.5) const;
///@}
/** @name Smoothing
@@ -412,8 +257,9 @@ class Manifold {
Manifold Refine(int) const;
Manifold RefineToLength(double) const;
Manifold RefineToTolerance(double) const;
- Manifold SmoothByNormals(int normalIdx) const;
- Manifold SmoothOut(double minSharpAngle = 60, double minSmoothness = 0) const;
+ Manifold SmoothByNormals(int normalIdx = 0) const;
+ Manifold SmoothOut(double minSharpAngle = 52.5,
+ double minSmoothness = 0) const;
static Manifold Smooth(const MeshGL&,
const std::vector<Smoothness>& sharpenedEdges = {});
static Manifold Smooth(const MeshGL64&,
@@ -428,21 +274,10 @@ class Manifold {
static Manifold Hull(const std::vector<vec3>& pts);
///@}
- /** @name Debugging I/O
+ /** @name I/O
* Self-contained mechanism for reading and writing high precision Manifold
* data. Write function creates special-purpose OBJ files, and Read function
- * reads them in. Be warned these are not (and not intended to be)
- * full-featured OBJ importers/exporters. Their primary use is to extract
- * accurate Manifold data for debugging purposes - writing out any info
- * needed to accurately reproduce a problem case's state. Consequently, they
- * may store and process additional data in comments that other OBJ parsing
- * programs won't understand.
- *
- * The "format" read and written by these functions is not guaranteed to be
- * stable from release to release - it will be modified as needed to ensure
- * it captures information needed for debugging. The only API guarantee is
- * that the ReadOBJ method in a given build/release will read in the output
- * of the WriteOBJ method produced by that release.
+ * reads them in.
*
* To work with a file, the caller should prepare the ifstream/ostream
* themselves, as follows:
@@ -456,7 +291,7 @@ class Manifold {
* ifile.close();
* if (obj_m.Status() != Manifold::Error::NoError) {
* std::cerr << "Failed reading " << filename << ":\n";
- * std::cerr << Manifold::ToString(ob_m.Status()) << "\n";
+ * std::cerr << Manifold::ToString(obj_m.Status()) << "\n";
* }
* ifile.close();
* }
@@ -474,7 +309,7 @@ class Manifold {
* ofile.close();
* @endcode
*/
-#ifdef MANIFOLD_DEBUG
+#ifndef MANIFOLD_NO_IOSTREAM
static Manifold ReadOBJ(std::istream& stream);
bool WriteOBJ(std::ostream& stream) const;
#endif
@@ -490,13 +325,39 @@ class Manifold {
struct Impl;
+ /// @internal Wrap a fully-built Impl into a leaf-node Manifold.
+ /// Caller is responsible for the invariants the public ctors enforce
+ /// (in particular, calling `MakeEmpty(status)` on error). Used by
+ /// ctx-aware static factories on `ExecutionContext`.
+ static Manifold FromImpl(std::shared_ptr<Impl> pImpl);
+
private:
Manifold(std::shared_ptr<CsgNode> pNode_);
Manifold(std::shared_ptr<Impl> pImpl_);
static Manifold Invalid();
+ static Manifold PropagateStatus(Error status);
+ mutable std::shared_ptr<std::mutex> pNodeMutex_ =
+ std::make_shared<std::mutex>();
mutable std::shared_ptr<CsgNode> pNode_;
-
- CsgLeafNode& GetCsgLeafNode() const;
+ // Optional attached ExecutionContext. shared_ptr so the Impl outlives
+ // the user's ExecutionContext if a ctx-attached Manifold survives it.
+ // Propagates through copy ctor / op= (raw copy preserves the attachment).
+ // Manifold-returning ops do *not* propagate it: derived Manifolds get a
+ // null ctx_. Eager ops (Status, Refine family) snapshot ctx_ to observe
+ // their in-call work; the snapshot uses std::atomic_load, which pins the
+ // Impl across long-running evaluations even if a concurrent op= reseats
+ // ctx_ mid-eval.
+ //
+ // Accessed only via std::atomic_load / std::atomic_store: no const method
+ // mutates ctx_, but op= and the copy ctor write it on a Manifold that
+ // may be concurrently observed by const methods on other threads. The
+ // atomic-shared-ptr free functions give a torn-read-free snapshot
+ // without taking a lock. (pNode_ uses a mutex instead because lazy CSG
+ // eval mutates it through const methods, which atomic_load can't model.)
+ std::shared_ptr<ExecutionContext::Impl> ctx_;
+
+ std::shared_ptr<CsgNode> LoadPNode() const;
+ CsgLeafNode& GetCsgLeafNode(ExecutionContext::Impl* ctx = nullptr) const;
};
/** @} */
@@ -537,6 +398,10 @@ inline std::string ToString(const Manifold::Error& error) {
return "Invalid Construction";
case Manifold::Error::ResultTooLarge:
return "Result Too Large";
+ case Manifold::Error::InvalidTangents:
+ return "Invalid Tangents";
+ case Manifold::Error::Cancelled:
+ return "Cancelled";
default:
return "Unknown Error";
};
diff --git a/thirdparty/manifold/include/manifold/math.h b/thirdparty/manifold/include/manifold/math.h
new file mode 100644
index 00000000000..7a0b10aa9a5
--- /dev/null
+++ b/thirdparty/manifold/include/manifold/math.h
@@ -0,0 +1,527 @@
+// Copyright 2026 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Deterministic trigonometric helpers.
+//
+// Adapted from FreeBSD msun implementations via musl libc sources:
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/__sin.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/__cos.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/__tan.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/__rem_pio2.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/e_acos.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/atan.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/atan2.c
+// - https://git.musl-libc.org/cgit/musl/plain/src/math/tan.c
+//
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+// Developed at SunPro/SunSoft, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this software is freely
+// granted, provided that this notice is preserved.
+#pragma once
+
+#include <cfloat>
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+
+namespace manifold {
+namespace math {
+inline uint64_t AsUint64(double x) {
+ uint64_t u;
+ std::memcpy(&u, &x, sizeof(u));
+ return u;
+}
+
+inline double FromUint64(uint64_t u) {
+ double x;
+ std::memcpy(&x, &u, sizeof(x));
+ return x;
+}
+
+inline uint32_t HighWord(double x) {
+ return static_cast<uint32_t>(AsUint64(x) >> 32);
+}
+
+inline uint32_t LowWord(double x) { return static_cast<uint32_t>(AsUint64(x)); }
+
+inline double WithLowWord(double x, uint32_t low) {
+ uint64_t u = AsUint64(x);
+ u = (u & 0xffffffff00000000ULL) | static_cast<uint64_t>(low);
+ return FromUint64(u);
+}
+
+constexpr inline double SinKernel(double x, double y, int iy) {
+ constexpr double S1 = -1.66666666666666324348e-01;
+ constexpr double S2 = 8.33333333332248946124e-03;
+ constexpr double S3 = -1.98412698298579493134e-04;
+ constexpr double S4 = 2.75573137070700676789e-06;
+ constexpr double S5 = -2.50507602534068634195e-08;
+ constexpr double S6 = 1.58969099521155010221e-10;
+
+ const double z = x * x;
+ const double w = z * z;
+ const double r = S2 + z * (S3 + z * S4) + z * w * (S5 + z * S6);
+ const double v = z * x;
+ if (iy == 0) return x + v * (S1 + z * r);
+ return x - ((z * (0.5 * y - v * r) - y) - v * S1);
+}
+
+constexpr inline double CosKernel(double x, double y) {
+ constexpr double C1 = 4.16666666666666019037e-02;
+ constexpr double C2 = -1.38888888888741095749e-03;
+ constexpr double C3 = 2.48015872894767294178e-05;
+ constexpr double C4 = -2.75573143513906633035e-07;
+ constexpr double C5 = 2.08757232129817482790e-09;
+ constexpr double C6 = -1.13596475577881948265e-11;
+
+ const double z = x * x;
+ const double w = z * z;
+ const double r =
+ z * (C1 + z * (C2 + z * C3)) + w * w * (C4 + z * (C5 + z * C6));
+ const double hz = 0.5 * z;
+ const double w1 = 1.0 - hz;
+ return w1 + (((1.0 - w1) - hz) + (z * r - x * y));
+}
+
+inline double TanKernel(double x, double y, int odd) {
+ constexpr double T[] = {
+ 3.33333333333334091986e-01, 1.33333333333201242699e-01,
+ 5.39682539762260521377e-02, 2.18694882948595424599e-02,
+ 8.86323982359930005737e-03, 3.59207910759131235356e-03,
+ 1.45620945432529025516e-03, 5.88041240820264096874e-04,
+ 2.46463134818469906812e-04, 7.81794442939557092300e-05,
+ 7.14072491382608190305e-05, -1.85586374855275456654e-05,
+ 2.59073051863633712884e-05,
+ };
+ constexpr double pio4 = 7.85398163397448278999e-01;
+ constexpr double pio4lo = 3.06161699786838301793e-17;
+
+ const uint32_t hx = HighWord(x);
+ const bool big = (hx & 0x7fffffff) >= 0x3FE59428; // |x| >= 0.6744
+ bool sign = false;
+ if (big) {
+ sign = (hx >> 31) != 0;
+ if (sign) {
+ x = -x;
+ y = -y;
+ }
+ x = (pio4 - x) + (pio4lo - y);
+ y = 0.0;
+ }
+
+ const double z = x * x;
+ const double w = z * z;
+ const double r =
+ T[1] + w * (T[3] + w * (T[5] + w * (T[7] + w * (T[9] + w * T[11]))));
+ const double v =
+ z *
+ (T[2] + w * (T[4] + w * (T[6] + w * (T[8] + w * (T[10] + w * T[12])))));
+ const double s = z * x;
+ const double rr = y + z * (s * (r + v) + y) + s * T[0];
+ const double ww = x + rr;
+ if (big) {
+ const double s2 = 1 - 2 * odd;
+ const double vv = s2 - 2.0 * (x + (rr - ww * ww / (ww + s2)));
+ return sign ? -vv : vv;
+ }
+ if (!odd) return ww;
+ // Compute -1/(x+r) with reduced cancellation error.
+ const double w0 = WithLowWord(ww, 0);
+ const double vv = rr - (w0 - x);
+ const double aa = -1.0 / ww;
+ const double a0 = WithLowWord(aa, 0);
+ return a0 + aa * (1.0 + a0 * w0 + a0 * vv);
+}
+
+inline double acos(double x) {
+ constexpr double pio2_hi = 1.57079632679489655800e+00;
+ constexpr double pio2_lo = 6.12323399573676603587e-17;
+ constexpr double pS0 = 1.66666666666666657415e-01;
+ constexpr double pS1 = -3.25565818622400915405e-01;
+ constexpr double pS2 = 2.01212532134862925881e-01;
+ constexpr double pS3 = -4.00555345006794114027e-02;
+ constexpr double pS4 = 7.91534994289814532176e-04;
+ constexpr double pS5 = 3.47933107596021167570e-05;
+ constexpr double qS1 = -2.40339491173441421878e+00;
+ constexpr double qS2 = 2.02094576023350569471e+00;
+ constexpr double qS3 = -6.88283971605453293030e-01;
+ constexpr double qS4 = 7.70381505559019352791e-02;
+ auto R = [=](double z) {
+ const double p =
+ z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))));
+ const double q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)));
+ return p / q;
+ };
+ double z, w, s, c, df;
+ uint64_t xx;
+ uint32_t hx, lx, ix;
+ std::memcpy(&xx, &x, sizeof(xx));
+ hx = xx >> 32;
+ ix = hx & 0x7fffffff;
+ if (ix >= 0x3ff00000) {
+ lx = xx;
+ if (((ix - 0x3ff00000) | lx) == 0) {
+ if (hx >> 31) return 2 * pio2_hi + 0x1p-120f;
+ return 0;
+ }
+ return 0 / (x - x);
+ }
+ if (ix < 0x3fe00000) {
+ if (ix <= 0x3c600000) return pio2_hi + 0x1p-120f;
+ return pio2_hi - (x - (pio2_lo - x * R(x * x)));
+ }
+ if (hx >> 31) {
+ z = (1.0 + x) * 0.5;
+ s = std::sqrt(z);
+ w = R(z) * s - pio2_lo;
+ return 2 * (pio2_hi - (s + w));
+ }
+ z = (1.0 - x) * 0.5;
+ s = std::sqrt(z);
+ std::memcpy(&xx, &s, sizeof(xx));
+ xx &= 0xffffffff00000000;
+ std::memcpy(&df, &xx, sizeof(xx));
+ c = (z - df * df) / (s + df);
+ w = R(z) * s + c;
+ return 2 * (df + w);
+}
+
+inline int RemPio2(double x, double y[2]) {
+ constexpr double half_pi = 1.57079632679489661923132169163975144;
+ constexpr double toint = 1.5 / DBL_EPSILON;
+ constexpr double pio4 = 0x1.921fb54442d18p-1;
+ constexpr double invpio2 = 6.36619772367581382433e-01;
+ constexpr double pio2_1 = 1.57079632673412561417e+00;
+ constexpr double pio2_1t = 6.07710050650619224932e-11;
+ constexpr double pio2_2 = 6.07710050630396597660e-11;
+ constexpr double pio2_2t = 2.02226624879595063154e-21;
+ constexpr double pio2_3 = 2.02226624871116645580e-21;
+ constexpr double pio2_3t = 8.47842766036889956997e-32;
+
+ uint64_t ux;
+ std::memcpy(&ux, &x, sizeof(ux));
+ const bool sign = (ux >> 63) != 0;
+ const uint32_t ix = static_cast<uint32_t>((ux >> 32) & 0x7fffffff);
+
+ if (ix <= 0x400f6a7a) { // |x| ~<= 5pi/4
+ if ((ix & 0xfffff) == 0x921fb) goto medium;
+ if (ix <= 0x4002d97c) { // |x| ~<= 3pi/4
+ if (!sign) {
+ const double z = x - pio2_1;
+ y[0] = z - pio2_1t;
+ y[1] = (z - y[0]) - pio2_1t;
+ return 1;
+ }
+ const double z = x + pio2_1;
+ y[0] = z + pio2_1t;
+ y[1] = (z - y[0]) + pio2_1t;
+ return -1;
+ }
+ if (!sign) {
+ const double z = x - 2 * pio2_1;
+ y[0] = z - 2 * pio2_1t;
+ y[1] = (z - y[0]) - 2 * pio2_1t;
+ return 2;
+ }
+ const double z = x + 2 * pio2_1;
+ y[0] = z + 2 * pio2_1t;
+ y[1] = (z - y[0]) + 2 * pio2_1t;
+ return -2;
+ }
+ if (ix <= 0x401c463b) { // |x| ~<= 9pi/4
+ if (ix <= 0x4015fdbc) { // |x| ~<= 7pi/4
+ if (ix == 0x4012d97c) goto medium;
+ if (!sign) {
+ const double z = x - 3 * pio2_1;
+ y[0] = z - 3 * pio2_1t;
+ y[1] = (z - y[0]) - 3 * pio2_1t;
+ return 3;
+ }
+ const double z = x + 3 * pio2_1;
+ y[0] = z + 3 * pio2_1t;
+ y[1] = (z - y[0]) + 3 * pio2_1t;
+ return -3;
+ }
+ if (ix == 0x401921fb) goto medium;
+ if (!sign) {
+ const double z = x - 4 * pio2_1;
+ y[0] = z - 4 * pio2_1t;
+ y[1] = (z - y[0]) - 4 * pio2_1t;
+ return 4;
+ }
+ const double z = x + 4 * pio2_1;
+ y[0] = z + 4 * pio2_1t;
+ y[1] = (z - y[0]) + 4 * pio2_1t;
+ return -4;
+ }
+
+ if (ix < 0x413921fb) { // |x| ~< 2^20*(pi/2), medium size
+ medium:
+ double fn = x * invpio2 + toint - toint;
+ int n = static_cast<int32_t>(fn);
+ double r = x - fn * pio2_1;
+ double w = fn * pio2_1t;
+ if (r - w < -pio4) {
+ n--;
+ fn--;
+ r = x - fn * pio2_1;
+ w = fn * pio2_1t;
+ } else if (r - w > pio4) {
+ n++;
+ fn++;
+ r = x - fn * pio2_1;
+ w = fn * pio2_1t;
+ }
+ y[0] = r - w;
+ uint64_t uy0;
+ std::memcpy(&uy0, &y[0], sizeof(uy0));
+ const int ey = static_cast<int>((uy0 >> 52) & 0x7ff);
+ const int ex = static_cast<int>(ix >> 20);
+ if (ex - ey > 16) {
+ const double t = r;
+ w = fn * pio2_2;
+ r = t - w;
+ w = fn * pio2_2t - ((t - r) - w);
+ y[0] = r - w;
+ std::memcpy(&uy0, &y[0], sizeof(uy0));
+ const int ey2 = static_cast<int>((uy0 >> 52) & 0x7ff);
+ if (ex - ey2 > 49) {
+ const double t2 = r;
+ w = fn * pio2_3;
+ r = t2 - w;
+ w = fn * pio2_3t - ((t2 - r) - w);
+ y[0] = r - w;
+ }
+ }
+ y[1] = (r - y[0]) - w;
+ return n;
+ }
+
+ if (ix >= 0x7ff00000) {
+ y[0] = y[1] = x - x;
+ return 0;
+ }
+
+ int q;
+ y[0] = std::remquo(x, half_pi, &q);
+ y[1] = 0.0;
+ return q;
+}
+
+inline double sin(double x) {
+ uint64_t ux;
+ std::memcpy(&ux, &x, sizeof(ux));
+ const uint32_t ix = static_cast<uint32_t>((ux >> 32) & 0x7fffffff);
+ if (ix <= 0x3fe921fb) {
+ if (ix < 0x3e500000) return x;
+ return SinKernel(x, 0.0, 0);
+ }
+ if (ix >= 0x7ff00000) return x - x;
+ double y[2];
+ const int n = RemPio2(x, y);
+ switch (n & 3) {
+ case 0:
+ return SinKernel(y[0], y[1], 1);
+ case 1:
+ return CosKernel(y[0], y[1]);
+ case 2:
+ return -SinKernel(y[0], y[1], 1);
+ default:
+ return -CosKernel(y[0], y[1]);
+ }
+}
+
+inline double cos(double x) {
+ uint64_t ux;
+ std::memcpy(&ux, &x, sizeof(ux));
+ const uint32_t ix = static_cast<uint32_t>((ux >> 32) & 0x7fffffff);
+ if (ix <= 0x3fe921fb) {
+ if (ix < 0x3e46a09e) return 1.0;
+ return CosKernel(x, 0.0);
+ }
+ if (ix >= 0x7ff00000) return x - x;
+ double y[2];
+ const int n = RemPio2(x, y);
+ switch (n & 3) {
+ case 0:
+ return CosKernel(y[0], y[1]);
+ case 1:
+ return -SinKernel(y[0], y[1], 1);
+ case 2:
+ return -CosKernel(y[0], y[1]);
+ default:
+ return SinKernel(y[0], y[1], 1);
+ }
+}
+
+inline double tan(double x) {
+ const uint32_t ix = HighWord(x) & 0x7fffffff;
+ if (ix <= 0x3fe921fb) {
+ if (ix < 0x3e400000) return x;
+ return TanKernel(x, 0.0, 0);
+ }
+ if (ix >= 0x7ff00000) return x - x;
+ double y[2];
+ const int n = RemPio2(x, y);
+ return TanKernel(y[0], y[1], n & 1);
+}
+
+inline double asin(double x) {
+ constexpr double half_pi = 1.57079632679489661923132169163975144;
+ if (!std::isfinite(x) || x < -1.0 || x > 1.0) return NAN;
+ if (x == 1.0) return half_pi;
+ if (x == -1.0) return -half_pi;
+ return half_pi - acos(x);
+}
+
+inline double atan(double x) {
+ constexpr double atanhi[] = {
+ 4.63647609000806093515e-01, 7.85398163397448278999e-01,
+ 9.82793723247329054082e-01, 1.57079632679489655800e+00};
+ constexpr double atanlo[] = {
+ 2.26987774529616870924e-17, 3.06161699786838301793e-17,
+ 1.39033110312309984516e-17, 6.12323399573676603587e-17};
+ constexpr double aT[] = {
+ 3.33333333333329318027e-01, -1.99999999998764832476e-01,
+ 1.42857142725034663711e-01, -1.11111104054623557880e-01,
+ 9.09088713343650656196e-02, -7.69187620504482999495e-02,
+ 6.66107313738753120669e-02, -5.83357013379057348645e-02,
+ 4.97687799461593236017e-02, -3.65315727442169155270e-02,
+ 1.62858201153657823623e-02};
+
+ uint32_t ix = HighWord(x);
+ const uint32_t sign = ix >> 31;
+ ix &= 0x7fffffff;
+ int id;
+
+ if (ix >= 0x44100000) { // |x| >= 2^66
+ if (std::isnan(x)) return x;
+ const double z = atanhi[3] + 0x1p-120f;
+ return sign ? -z : z;
+ }
+ if (ix < 0x3fdc0000) { // |x| < 0.4375
+ if (ix < 0x3e400000) return x; // |x| < 2^-27
+ id = -1;
+ } else {
+ x = std::fabs(x);
+ if (ix < 0x3ff30000) { // |x| < 1.1875
+ if (ix < 0x3fe60000) { // 7/16 <= |x| < 11/16
+ id = 0;
+ x = (2.0 * x - 1.0) / (2.0 + x);
+ } else { // 11/16 <= |x| < 19/16
+ id = 1;
+ x = (x - 1.0) / (x + 1.0);
+ }
+ } else {
+ if (ix < 0x40038000) { // |x| < 2.4375
+ id = 2;
+ x = (x - 1.5) / (1.0 + 1.5 * x);
+ } else { // 2.4375 <= |x| < 2^66
+ id = 3;
+ x = -1.0 / x;
+ }
+ }
+ }
+
+ const double z = x * x;
+ const double w = z * z;
+ const double s1 =
+ z * (aT[0] +
+ w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10])))));
+ const double s2 =
+ w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9]))));
+ if (id < 0) return x - x * (s1 + s2);
+ const double zz = atanhi[id] - (x * (s1 + s2) - atanlo[id] - x);
+ return sign ? -zz : zz;
+}
+
+inline double atan2(double y, double x) {
+ constexpr double pi = 3.1415926535897931160E+00;
+ constexpr double pi_lo = 1.2246467991473531772E-16;
+
+ if (std::isnan(x) || std::isnan(y)) return x + y;
+ uint32_t ix = HighWord(x);
+ uint32_t iy = HighWord(y);
+ const uint32_t lx = LowWord(x);
+ const uint32_t ly = LowWord(y);
+
+ if (((ix - 0x3ff00000) | lx) == 0) return atan(y); // x = 1.0
+
+ const uint32_t m = ((iy >> 31) & 1) | ((ix >> 30) & 2);
+ ix &= 0x7fffffff;
+ iy &= 0x7fffffff;
+
+ if ((iy | ly) == 0) { // y = 0
+ switch (m) {
+ case 0:
+ case 1:
+ return y;
+ case 2:
+ return pi;
+ default:
+ return -pi;
+ }
+ }
+ if ((ix | lx) == 0) return (m & 1) ? -pi / 2 : pi / 2; // x = 0
+
+ if (ix == 0x7ff00000) { // x is INF
+ if (iy == 0x7ff00000) {
+ switch (m) {
+ case 0:
+ return pi / 4;
+ case 1:
+ return -pi / 4;
+ case 2:
+ return 3 * pi / 4;
+ default:
+ return -3 * pi / 4;
+ }
+ }
+ switch (m) {
+ case 0:
+ return 0.0;
+ case 1:
+ return -0.0;
+ case 2:
+ return pi;
+ default:
+ return -pi;
+ }
+ }
+
+ if (ix + (64 << 20) < iy || iy == 0x7ff00000) {
+ return (m & 1) ? -pi / 2 : pi / 2; // |y/x| > 2^64
+ }
+
+ double z;
+ if ((m & 2) && iy + (64 << 20) < ix) {
+ z = 0; // |y/x| < 2^-64 and x < 0
+ } else {
+ z = atan(std::fabs(y / x));
+ }
+
+ switch (m) {
+ case 0:
+ return z;
+ case 1:
+ return -z;
+ case 2:
+ return pi - (z - pi_lo);
+ default:
+ return (z - pi_lo) - pi;
+ }
+}
+
+} // namespace math
+} // namespace manifold
diff --git a/thirdparty/manifold/include/manifold/mesh.h b/thirdparty/manifold/include/manifold/mesh.h
new file mode 100644
index 00000000000..9402c9c99aa
--- /dev/null
+++ b/thirdparty/manifold/include/manifold/mesh.h
@@ -0,0 +1,277 @@
+// Copyright 2021 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+#include <cstdint>
+#include <istream>
+#include <type_traits>
+#include <vector>
+
+#include "manifold/common.h"
+
+namespace manifold {
+
+/** @addtogroup Core
+ * @{
+ */
+
+/**
+ * @brief Mesh input/output suitable for pushing directly into graphics
+ * libraries.
+ *
+ * The core (non-optional) parts of MeshGL are the triVerts indices buffer and
+ * the vertProperties interleaved vertex buffer, which follow the conventions of
+ * OpenGL (and other graphic libraries') buffers and are therefore generally
+ * easy to map directly to other applications' data structures.
+ *
+ * The triVerts vector has a stride of 3 and specifies triangles as
+ * vertex indices. For triVerts = [2, 4, 5, 3, 1, 6, ...], the triangles are [2,
+ * 4, 5], [3, 1, 6], etc. and likewise the halfedges are [2, 4], [4, 5], [5, 2],
+ * [3, 1], [1, 6], [6, 3], etc.
+ *
+ * The triVerts indices should form a manifold mesh: each of the 3 halfedges of
+ * each triangle should have exactly one paired halfedge in the list, defined as
+ * having the first index of one equal to the second index of the other and
+ * vice-versa. However, this is not always possible - consider e.g. a cube with
+ * normal-vector properties. Shared vertices would turn the cube into a ball by
+ * interpolating normals - the common solution is to duplicate each corner
+ * vertex into 3, each with the same position, but different normals
+ * corresponding to each face. This is exactly what should be done in MeshGL,
+ * however we request two additional vectors in this case: mergeFromVert and
+ * mergeToVert. Each vertex mergeFromVert[i] is merged into vertex
+ * mergeToVert[i], avoiding unreliable floating-point comparisons to recover the
+ * manifold topology. These merges are simply a union, so which is from and to
+ * doesn't matter.
+ *
+ * If you don't have merge vectors, you can create them with the Merge() method,
+ * however this will fail if the mesh is not already manifold within the set
+ * tolerance. For maximum reliability, always store the merge vectors with the
+ * mesh, e.g. using the EXT_mesh_manifold extension in glTF.
+ *
+ * You can have any number of arbitrary floating-point properties per vertex,
+ * and they will all be interpolated as necessary during operations. It is up to
+ * you to keep track of which channel represents what type of data. A few of
+ * Manifold's methods allow you to specify the channel where normals data
+ * starts, in order to update it automatically for transforms and such. This
+ * will be easier if your meshes all use the same channels for properties, but
+ * this is not a requirement. Operations between meshes with different numbers
+ * of properties will simply use the larger numProp and pad the smaller one
+ * with zeroes.
+ *
+ * On output, the triangles are sorted into runs (runIndex, runOriginalID,
+ * runTransform) that correspond to different mesh inputs. Other 3D libraries
+ * may refer to these runs as primitives of a mesh (as in glTF) or draw calls,
+ * as they often represent different materials on different parts of the mesh.
+ * It is generally a good idea to maintain a map of OriginalIDs to materials to
+ * make it easy to reapply them after a set of Boolean operations. These runs
+ * can also be used as input, and thus also ensure a lossless roundtrip of data
+ * through MeshGL.
+ *
+ * As an example, with runIndex = [0, 6, 18, 21] and runOriginalID = [1, 3, 3],
+ * there are 7 triangles, where the first two are from the input mesh with ID 1,
+ * the next 4 are from an input mesh with ID 3, and the last triangle is from a
+ * different copy (instance) of the input mesh with ID 3. These two instances
+ * can be distinguished by their different runTransform matrices.
+ *
+ * You can reconstruct polygonal faces by assembling all the triangles that are
+ * from the same run and share the same faceID. These faces will be planar
+ * within the output tolerance.
+ *
+ * The halfedgeTangent vector is used to specify the weighted tangent vectors of
+ * each halfedge for the purpose of using the Refine methods to create a
+ * smoothly-interpolated surface. They can also be output when calculated
+ * automatically by the Smooth functions.
+ *
+ * MeshGL is an alias for the standard single-precision version. Use MeshGL64 to
+ * output the full double precision that Manifold uses internally.
+ */
+// MeshGLP / MeshGL / MeshGL64 are forward-declared in common.h; the
+// default `I = uint32_t` lives on the forward decl.
+template <typename Precision, typename I>
+struct MeshGLP {
+ /// Number of property vertices
+ I NumVert() const { return vertProperties.size() / numProp; };
+ /// Number of triangles
+ I NumTri() const { return triVerts.size() / 3; };
+ /// Number of triangle runs
+ I NumRun() const { return runOriginalID.size(); };
+ /// Number of properties per vertex, always >= 3.
+ I numProp = 3;
+ /// Flat, GL-style interleaved list of all vertex properties: propVal =
+ /// vertProperties[vert * numProp + propIdx]. The first three properties are
+ /// always the position x, y, z. The stride of the array is numProp.
+ std::vector<Precision> vertProperties;
+ /// The vertex indices of the three triangle corners in CCW (from the outside)
+ /// order, for each triangle.
+ std::vector<I> triVerts;
+ /// Optional: A list of only the vertex indicies that need to be merged to
+ /// reconstruct the manifold.
+ std::vector<I> mergeFromVert;
+ /// Optional: The same length as mergeFromVert, and the corresponding value
+ /// contains the vertex to merge with. It will have an identical position, but
+ /// the other properties may differ.
+ std::vector<I> mergeToVert;
+ /// Optional: Indicates runs of triangles that correspond to a particular
+ /// input mesh instance. The runs encompass all of triVerts and are sorted
+ /// by runOriginalID. Run i begins at triVerts[runIndex[i]] and ends at
+ /// triVerts[runIndex[i+1]]. All runIndex values are divisible by 3. Returned
+ /// runIndex will always be 1 longer than runOriginalID, but same length is
+ /// also allowed as input: triVerts.size() will be automatically appended in
+ /// this case.
+ std::vector<I> runIndex;
+ /// Optional: The OriginalID of the mesh this triangle run came from. This ID
+ /// is ideal for reapplying materials to the output mesh. Multiple runs may
+ /// have the same ID, e.g. representing different copies of the same input
+ /// mesh. If you create an input MeshGL that you want to be able to reference
+ /// as one or more originals, be sure to set unique values from ReserveIDs().
+ std::vector<uint32_t> runOriginalID;
+ /// Optional: For each run, a 3x4 transform is stored representing how the
+ /// corresponding original mesh was transformed to create this triangle run.
+ /// This matrix is stored in column-major order and the length of the overall
+ /// vector is 12 * runOriginalID.size().
+ std::vector<Precision> runTransform;
+ /// Optional: For each run, defines a set of flags giving extra information
+ /// about the run. See the corresponding getter functions for details on the
+ /// specific flags. These are primarily used on output.
+ std::vector<uint8_t> runFlags;
+ /// Optional: Length NumTri, contains the source face ID this triangle comes
+ /// from. Simplification will maintain all edges between triangles with
+ /// different faceIDs. Input faceIDs will be maintained to the outputs, but if
+ /// none are given, they will be filled in with Manifold's coplanar face
+ /// calculation based on mesh tolerance.
+ std::vector<I> faceID;
+ /// Optional: The X-Y-Z-W weighted tangent vectors for smooth Refine(). If
+ /// non-empty, must be exactly four times as long as Mesh.triVerts. Indexed
+ /// as 4 * (3 * tri + i) + j, i < 3, j < 4, representing the tangent value
+ /// Mesh.triVerts[tri][i] along the CCW edge. If empty, mesh is faceted.
+ std::vector<Precision> halfedgeTangent;
+ /// Tolerance for mesh simplification. When creating a Manifold, the tolerance
+ /// used will be the maximum of this and a baseline tolerance from the size of
+ /// the bounding box. Any edge shorter than tolerance may be collapsed.
+ /// Tolerance may be enlarged when floating point error accumulates.
+ Precision tolerance = 0;
+
+ MeshGLP() = default;
+
+ /**
+ * Updates the mergeFromVert and mergeToVert vectors in order to create a
+ * manifold solid. If the MeshGL is already manifold, no change will occur
+ * and the function will return false. Otherwise, this will merge verts
+ * along open edges within tolerance (the maximum of the MeshGL tolerance
+ * and the baseline bounding-box tolerance), keeping any from the existing
+ * merge vectors, and return true.
+ *
+ * There is no guarantee the result will be manifold - this is a
+ * best-effort helper function designed primarily to aid in the case where
+ * a manifold multi-material MeshGL was produced, but its merge vectors
+ * were lost due to a round-trip through a file format. Constructing a
+ * Manifold from the result will report an error status if it is not
+ * manifold.
+ */
+ bool Merge();
+
+ /**
+ * Returns the x, y, z position of the ith vertex.
+ *
+ * @param v vertex index.
+ */
+ la::vec<Precision, 3> GetVertPos(size_t v) const {
+ size_t offset = v * numProp;
+ return la::vec<Precision, 3>(vertProperties[offset],
+ vertProperties[offset + 1],
+ vertProperties[offset + 2]);
+ }
+
+ /**
+ * Returns the three vertex indices of the ith triangle.
+ *
+ * @param t triangle index.
+ */
+ la::vec<I, 3> GetTriVerts(size_t t) const {
+ size_t offset = 3 * t;
+ return la::vec<I, 3>(triVerts[offset], triVerts[offset + 1],
+ triVerts[offset + 2]);
+ }
+
+ /**
+ * Returns the x, y, z, w tangent of the ith halfedge.
+ *
+ * @param h halfedge index (3 * triangle_index + [0|1|2]).
+ */
+ la::vec<Precision, 4> GetTangent(size_t h) const {
+ size_t offset = 4 * h;
+ return la::vec<Precision, 4>(
+ halfedgeTangent[offset], halfedgeTangent[offset + 1],
+ halfedgeTangent[offset + 2], halfedgeTangent[offset + 3]);
+ }
+
+ /**
+ * Returns the transformation matrix for the specified run.
+ *
+ * @param run The index of the triangle run (0 <= run < runOriginalID.size()).
+ */
+ mat3x4 GetRunTransform(size_t run) const {
+ size_t offset = 12 * run;
+ if (offset + 12 > runTransform.size()) {
+ return la::identity;
+ }
+ return mat3x4(la::mat<Precision, 3, 4>(&runTransform[offset]));
+ }
+
+ /**
+ * Returns true if this triangle run is on the backside compared to the
+ * original mesh, e.g. from a subtraction. Informational only - the framework
+ * already orients stored normals so the standard `getMesh()` flow returns
+ * world-frame values regardless of this bit.
+ *
+ * @param run The index of the triangle run (0 <= run < runFlags.size()).
+ */
+ bool Backside(size_t run) const {
+ return run < runFlags.size() && (runFlags[run] & 1) != 0;
+ }
+
+ /**
+ * Returns true if the first three extra-property channels (slots 3, 4, 5)
+ * of this run carry world-frame vertex normals (set by
+ * `Manifold::CalculateNormals(0)` and round-tripped via `runFlags` bit 1).
+ * Consumers should treat the slot as normals and skip re-applying
+ * `runTransform` to it.
+ *
+ * hasNormals is per-run, so different runs may set it differently.
+ * Behavior is undefined when a single propVert is shared by triangles
+ * from runs that disagree - the slot has one interpretation, and a
+ * Transform rotates it for hasNormals=true and clobbers any
+ * hasNormals=false sharer. Standard `CalculateNormals` / Boolean /
+ * Compose outputs never produce that shape.
+ *
+ * @param run The index of the triangle run (0 <= run < runFlags.size()).
+ */
+ bool HasNormals(size_t run) const {
+ return run < runFlags.size() && (runFlags[run] & 2) != 0;
+ }
+};
+
+// MeshGL / MeshGL64 aliases live in common.h. Pin the default template
+// arg so dropping `I = uint32_t` breaks the build instead of silently
+// changing MeshGL's index type.
+static_assert(std::is_same<MeshGL, MeshGLP<float, uint32_t>>::value,
+ "MeshGL default index type must stay uint32_t");
+
+#ifndef MANIFOLD_NO_IOSTREAM
+MeshGL64 ReadOBJ(std::istream& stream);
+bool WriteOBJ(std::ostream& stream, const MeshGL64& mesh);
+#endif
+/** @} */
+} // namespace manifold
\ No newline at end of file
diff --git a/thirdparty/manifold/patches/0001-missing-include.patch b/thirdparty/manifold/patches/0001-missing-include.patch
new file mode 100644
index 00000000000..6e5b47444a5
--- /dev/null
+++ b/thirdparty/manifold/patches/0001-missing-include.patch
@@ -0,0 +1,12 @@
+diff --git a/thirdparty/manifold/include/manifold/mesh.h b/thirdparty/manifold/include/manifold/mesh.h
+index 984af936d3..9402c9c99a 100644
+--- a/thirdparty/manifold/include/manifold/mesh.h
++++ b/thirdparty/manifold/include/manifold/mesh.h
+@@ -15,6 +15,7 @@
+ #pragma once
+
+ #include <cstdint>
++#include <istream>
+ #include <type_traits>
+ #include <vector>
+
diff --git a/thirdparty/manifold/src/boolean3.cpp b/thirdparty/manifold/src/boolean3.cpp
index 571ca995aeb..96a410fe460 100644
--- a/thirdparty/manifold/src/boolean3.cpp
+++ b/thirdparty/manifold/src/boolean3.cpp
@@ -28,92 +28,90 @@ using namespace manifold;
namespace {
-// These two functions (Interpolate and Intersect) are the only places where
-// floating-point operations take place in the whole Boolean function. These
-// are carefully designed to minimize rounding error and to eliminate it at edge
-// cases to ensure consistency.
-
-vec2 Interpolate(vec3 pL, vec3 pR, double x) {
- const double dxL = x - pL.x;
- const double dxR = x - pR.x;
- DEBUG_ASSERT(dxL * dxR <= 0, logicErr,
- "Boolean manifold error: not in domain");
- const bool useL = fabs(dxL) < fabs(dxR);
- const vec3 dLR = pR - pL;
- const double lambda = (useL ? dxL : dxR) / dLR.x;
- if (!std::isfinite(lambda) || !std::isfinite(dLR.y) || !std::isfinite(dLR.z))
- return vec2(pL.y, pL.z);
- vec2 yz;
- yz[0] = lambda * dLR.y + (useL ? pL.y : pR.y);
- yz[1] = lambda * dLR.z + (useL ? pL.z : pR.z);
- return yz;
-}
+// `Intersect` stays local to the Boolean3 kernel cascade; the lower-level
+// symbolic perturbation primitives it uses live in shared.h.
-vec4 Intersect(const vec3& pL, const vec3& pR, const vec3& qL, const vec3& qR) {
- const double dyL = qL.y - pL.y;
- const double dyR = qR.y - pR.y;
+vec4 Intersect(const vec3& aL, const vec3& aR, const vec3& bL, const vec3& bR) {
+ const double dyL = bL.y - aL.y;
+ const double dyR = bR.y - aR.y;
DEBUG_ASSERT(dyL * dyR <= 0, logicErr,
"Boolean manifold error: no intersection");
const bool useL = fabs(dyL) < fabs(dyR);
- const double dx = pR.x - pL.x;
+ const double dx = aR.x - aL.x;
double lambda = (useL ? dyL : dyR) / (dyL - dyR);
if (!std::isfinite(lambda)) lambda = 0.0;
vec4 xyzz;
- xyzz.x = lambda * dx + (useL ? pL.x : pR.x);
- const double pDy = pR.y - pL.y;
- const double qDy = qR.y - qL.y;
- const bool useP = fabs(pDy) < fabs(qDy);
- xyzz.y = lambda * (useP ? pDy : qDy) +
- (useL ? (useP ? pL.y : qL.y) : (useP ? pR.y : qR.y));
- xyzz.z = lambda * (pR.z - pL.z) + (useL ? pL.z : pR.z);
- xyzz.w = lambda * (qR.z - qL.z) + (useL ? qL.z : qR.z);
+ xyzz.x = lambda * dx + (useL ? aL.x : aR.x);
+ const double aDy = aR.y - aL.y;
+ const double bDy = bR.y - bL.y;
+ const bool useA = fabs(aDy) < fabs(bDy);
+ xyzz.y = lambda * (useA ? aDy : bDy) +
+ (useL ? (useA ? aL.y : bL.y) : (useA ? aR.y : bR.y));
+ xyzz.z = lambda * (aR.z - aL.z) + (useL ? aL.z : aR.z);
+ xyzz.w = lambda * (bR.z - bL.z) + (useL ? bL.z : bR.z);
return xyzz;
}
-inline bool Shadows(double p, double q, double dir) {
- return p == q ? dir < 0 : p < q;
+struct FaceEdge {
+ int edge;
+ int start;
+ int end;
+ bool isForward;
+};
+
+inline void LoadFaceEdges(const Halfedges& halfedges, int tri,
+ FaceEdge edge[3]) {
+ for (const int i : {0, 1, 2}) {
+ const int halfedge = 3 * tri + i;
+ const int start = halfedges.Start(halfedge);
+ const int end = halfedges.Start(3 * tri + Next3(i));
+ if (start < end) {
+ edge[i] = {halfedge, start, end, true};
+ } else {
+ edge[i] = {halfedges.Pair(halfedge), end, start, false};
+ }
+ }
}
-inline std::pair<int, vec2> Shadow01(
- const int p0, const int q1, VecView<const vec3> vertPosP,
- VecView<const vec3> vertPosQ, VecView<const Halfedge> halfedgeQ,
- const double expandP, VecView<const vec3> normal, const bool reverse) {
- const int q1s = halfedgeQ[q1].startVert;
- const int q1e = halfedgeQ[q1].endVert;
- const double p0x = vertPosP[p0].x;
- const double q1sx = vertPosQ[q1s].x;
- const double q1ex = vertPosQ[q1e].x;
- int s01 = reverse ? Shadows(q1sx, p0x, expandP * normal[q1s].x) -
- Shadows(q1ex, p0x, expandP * normal[q1e].x)
- : Shadows(p0x, q1ex, expandP * normal[p0].x) -
- Shadows(p0x, q1sx, expandP * normal[p0].x);
+template <bool expandP, bool forward>
+inline std::pair<int, vec2> Shadow01(const int a0, const int b1, const int b1s,
+ const int b1e, const Manifold::Impl& inA,
+ const Manifold::Impl& inB) {
+ const double a0x = inA.vertPos_[a0].x;
+ const double b1sx = inB.vertPos_[b1s].x;
+ const double b1ex = inB.vertPos_[b1e].x;
+ const double a0xp = inA.vertNormal_[a0].x;
+ const double b1sxp = inB.vertNormal_[b1s].x;
+ const double b1exp = inB.vertNormal_[b1e].x;
+ int s01 = forward ? Shadows(a0x, b1ex, withSign(expandP, a0xp) - b1exp) -
+ Shadows(a0x, b1sx, withSign(expandP, a0xp) - b1sxp)
+ : Shadows(b1sx, a0x, withSign(expandP, b1sxp) - a0xp) -
+ Shadows(b1ex, a0x, withSign(expandP, b1exp) - a0xp);
vec2 yz01(NAN);
if (s01 != 0) {
- yz01 = Interpolate(vertPosQ[q1s], vertPosQ[q1e], vertPosP[p0].x);
- if (reverse) {
- vec3 diff = vertPosQ[q1s] - vertPosP[p0];
- const double start2 = la::dot(diff, diff);
- diff = vertPosQ[q1e] - vertPosP[p0];
- const double end2 = la::dot(diff, diff);
- const double dir = start2 < end2 ? normal[q1s].y : normal[q1e].y;
- if (!Shadows(yz01[0], vertPosP[p0].y, expandP * dir)) s01 = 0;
+ yz01 =
+ Interpolate(inB.vertPos_[b1s], inB.vertPos_[b1e], inA.vertPos_[a0].x);
+ const int b1pair = inB.halfedge_.Pair(b1);
+ const double dir =
+ inB.faceNormal_[b1 / 3].y + inB.faceNormal_[b1pair / 3].y;
+ if (forward) {
+ if (!Shadows(inA.vertPos_[a0].y, yz01[0], -dir)) s01 = 0;
} else {
- if (!Shadows(vertPosP[p0].y, yz01[0], expandP * normal[p0].y)) s01 = 0;
+ if (!Shadows(yz01[0], inA.vertPos_[a0].y, withSign(expandP, dir)))
+ s01 = 0;
}
}
return std::make_pair(s01, yz01);
}
+template <bool expandP>
struct Kernel11 {
- VecView<const vec3> vertPosP;
- VecView<const vec3> vertPosQ;
- VecView<const Halfedge> halfedgeP;
- VecView<const Halfedge> halfedgeQ;
- const double expandP;
- VecView<const vec3> normalP;
-
- std::pair<int, vec4> operator()(int p1, int q1) {
+ const Manifold::Impl& inP;
+ const Manifold::Impl& inQ;
+
+ std::pair<int, vec4> operator()(int p1, int p1s, int p1e, int q1, int q1s,
+ int q1e) {
vec4 xyzz11 = vec4(NAN);
int s11 = 0;
@@ -125,32 +123,32 @@ struct Kernel11 {
bool shadows = false;
s11 = 0;
- const int p0[2] = {halfedgeP[p1].startVert, halfedgeP[p1].endVert};
+ const int p0[2] = {p1s, p1e};
for (int i : {0, 1}) {
- const auto [s01, yz01] = Shadow01(p0[i], q1, vertPosP, vertPosQ,
- halfedgeQ, expandP, normalP, false);
+ const auto [s01, yz01] =
+ Shadow01<expandP, true>(p0[i], q1, q1s, q1e, inP, inQ);
// If the value is NaN, then these do not overlap.
if (std::isfinite(yz01[0])) {
s11 += s01 * (i == 0 ? -1 : 1);
if (k < 2 && (k == 0 || (s01 != 0) != shadows)) {
shadows = s01 != 0;
- pRL[k] = vertPosP[p0[i]];
+ pRL[k] = inP.vertPos_[p0[i]];
qRL[k] = vec3(pRL[k].x, yz01.x, yz01.y);
++k;
}
}
}
- const int q0[2] = {halfedgeQ[q1].startVert, halfedgeQ[q1].endVert};
+ const int q0[2] = {q1s, q1e};
for (int i : {0, 1}) {
- const auto [s10, yz10] = Shadow01(q0[i], p1, vertPosQ, vertPosP,
- halfedgeP, expandP, normalP, true);
+ const auto [s10, yz10] =
+ Shadow01<expandP, false>(q0[i], p1, p1s, p1e, inQ, inP);
// If the value is NaN, then these do not overlap.
if (std::isfinite(yz10[0])) {
s11 += s10 * (i == 0 ? -1 : 1);
if (k < 2 && (k == 0 || (s10 != 0) != shadows)) {
shadows = s10 != 0;
- qRL[k] = vertPosQ[q0[i]];
+ qRL[k] = inQ.vertPos_[q0[i]];
pRL[k] = vec3(qRL[k].x, yz10.x, yz10.y);
++k;
}
@@ -163,30 +161,31 @@ struct Kernel11 {
DEBUG_ASSERT(k == 2, logicErr, "Boolean manifold error: s11");
xyzz11 = Intersect(pRL[0], pRL[1], qRL[0], qRL[1]);
- const int p1s = halfedgeP[p1].startVert;
- const int p1e = halfedgeP[p1].endVert;
- vec3 diff = vertPosP[p1s] - vec3(xyzz11);
- const double start2 = la::dot(diff, diff);
- diff = vertPosP[p1e] - vec3(xyzz11);
- const double end2 = la::dot(diff, diff);
- const double dir = start2 < end2 ? normalP[p1s].z : normalP[p1e].z;
-
- if (!Shadows(xyzz11.z, xyzz11.w, expandP * dir)) s11 = 0;
+ const int p1pair = inP.halfedge_.Pair(p1);
+ const double dirP =
+ inP.faceNormal_[p1 / 3].z + inP.faceNormal_[p1pair / 3].z;
+ const int q1pair = inQ.halfedge_.Pair(q1);
+ const double dirQ =
+ inQ.faceNormal_[q1 / 3].z + inQ.faceNormal_[q1pair / 3].z;
+ if (!Shadows(xyzz11.z, xyzz11.w, withSign(expandP, dirP) - dirQ)) s11 = 0;
}
return std::make_pair(s11, xyzz11);
}
};
+template <bool expandP, bool forward>
struct Kernel02 {
- VecView<const vec3> vertPosP;
- VecView<const Halfedge> halfedgeQ;
- VecView<const vec3> vertPosQ;
- const double expandP;
- VecView<const vec3> vertNormalP;
- const bool forward;
-
- std::pair<int, double> operator()(int p0, int q2) {
+ const Manifold::Impl& inA;
+ const Manifold::Impl& inB;
+
+ std::pair<int, double> operator()(int a0, int b2) {
+ FaceEdge edgeB[3];
+ LoadFaceEdges(inB.halfedge_, b2, edgeB);
+ return (*this)(a0, b2, edgeB);
+ }
+
+ std::pair<int, double> operator()(int a0, int b2, const FaceEdge edgeB[3]) {
int s02 = 0;
double z02 = 0.0;
@@ -196,33 +195,15 @@ struct Kernel02 {
// Either the left or right must shadow, but not both. This ensures the
// intersection is between the left and right.
bool shadows = false;
- int closestVert = -1;
- double minMetric = std::numeric_limits<double>::infinity();
- s02 = 0;
- const vec3 posP = vertPosP[p0];
for (const int i : {0, 1, 2}) {
- const int q1 = 3 * q2 + i;
- const Halfedge edge = halfedgeQ[q1];
- const int q1F = edge.IsForward() ? q1 : edge.pairedHalfedge;
-
- if (!forward) {
- const int qVert = halfedgeQ[q1F].startVert;
- const vec3 diff = posP - vertPosQ[qVert];
- const double metric = la::dot(diff, diff);
- if (metric < minMetric) {
- minMetric = metric;
- closestVert = qVert;
- }
- }
-
- const auto syz01 = Shadow01(p0, q1F, vertPosP, vertPosQ, halfedgeQ,
- expandP, vertNormalP, !forward);
+ const auto syz01 = Shadow01<expandP, forward>(
+ a0, edgeB[i].edge, edgeB[i].start, edgeB[i].end, inA, inB);
const int s01 = syz01.first;
const vec2 yz01 = syz01.second;
// If the value is NaN, then these do not overlap.
if (std::isfinite(yz01[0])) {
- s02 += s01 * (forward == edge.IsForward() ? -1 : 1);
+ s02 += s01 * (forward == edgeB[i].isForward ? -1 : 1);
if (k < 2 && (k == 0 || (s01 != 0) != shadows)) {
shadows = s01 != 0;
yzzRL[k++] = vec3(yz01[0], yz01[1], yz01[1]);
@@ -234,13 +215,12 @@ struct Kernel02 {
z02 = NAN;
} else {
DEBUG_ASSERT(k == 2, logicErr, "Boolean manifold error: s02");
- vec3 vertPos = vertPosP[p0];
- z02 = Interpolate(yzzRL[0], yzzRL[1], vertPos.y)[1];
+ vec3 vertPosA = inA.vertPos_[a0];
+ z02 = Interpolate(yzzRL[0], yzzRL[1], vertPosA.y)[1];
if (forward) {
- if (!Shadows(vertPos.z, z02, expandP * vertNormalP[p0].z)) s02 = 0;
+ if (!Shadows(vertPosA.z, z02, -inB.faceNormal_[b2].z)) s02 = 0;
} else {
- // DEBUG_ASSERT(closestVert != -1, topologyErr, "No closest vert");
- if (!Shadows(z02, vertPos.z, expandP * vertNormalP[closestVert].z))
+ if (!Shadows(z02, vertPosA.z, withSign(expandP, inB.faceNormal_[b2].z)))
s02 = 0;
}
}
@@ -248,15 +228,14 @@ struct Kernel02 {
}
};
+template <bool expandP, bool forward>
struct Kernel12 {
- VecView<const Halfedge> halfedgesP;
- VecView<const Halfedge> halfedgesQ;
- VecView<const vec3> vertPosP;
- const bool forward;
- Kernel02 k02;
- Kernel11 k11;
-
- std::pair<int, vec3> operator()(int p1, int q2) {
+ const Manifold::Impl& inA;
+ const Manifold::Impl& inB;
+ Kernel02<expandP, forward> k02;
+ Kernel11<expandP> k11;
+
+ std::pair<int, vec3> operator()(int a1, int b2) {
int x12 = 0;
vec3 v12 = vec3(NAN);
@@ -269,15 +248,18 @@ struct Kernel12 {
bool shadows = false;
x12 = 0;
- const Halfedge edge = halfedgesP[p1];
+ const int edgeAStart = inA.halfedge_.Start(a1);
+ const int edgeAEnd = inA.halfedge_.End(a1);
+ FaceEdge edgeB[3];
+ LoadFaceEdges(inB.halfedge_, b2, edgeB);
- for (int vert : {edge.startVert, edge.endVert}) {
- const auto [s, z] = k02(vert, q2);
+ for (int vertA : {edgeAStart, edgeAEnd}) {
+ const auto [s, z] = k02(vertA, b2, edgeB);
if (std::isfinite(z)) {
- x12 += s * ((vert == edge.startVert) == forward ? 1 : -1);
+ x12 += s * ((vertA == edgeAStart) == forward ? 1 : -1);
if (k < 2 && (k == 0 || (s != 0) != shadows)) {
shadows = s != 0;
- xzyLR0[k] = vertPosP[vert];
+ xzyLR0[k] = inA.vertPos_[vertA];
std::swap(xzyLR0[k].y, xzyLR0[k].z);
xzyLR1[k] = xzyLR0[k];
xzyLR1[k][1] = z;
@@ -287,12 +269,13 @@ struct Kernel12 {
}
for (const int i : {0, 1, 2}) {
- const int q1 = 3 * q2 + i;
- const Halfedge edge = halfedgesQ[q1];
- const int q1F = edge.IsForward() ? q1 : edge.pairedHalfedge;
- const auto [s, xyzz] = forward ? k11(p1, q1F) : k11(q1F, p1);
+ const auto [s, xyzz] = forward
+ ? k11(a1, edgeAStart, edgeAEnd, edgeB[i].edge,
+ edgeB[i].start, edgeB[i].end)
+ : k11(edgeB[i].edge, edgeB[i].start,
+ edgeB[i].end, a1, edgeAStart, edgeAEnd);
if (std::isfinite(xyzz[0])) {
- x12 -= s * (edge.IsForward() ? 1 : -1);
+ x12 -= s * (edgeB[i].isForward ? 1 : -1);
if (k < 2 && (k == 0 || (s != 0) != shadows)) {
shadows = s != 0;
xzyLR0[k][0] = xyzz.x;
@@ -319,22 +302,16 @@ struct Kernel12 {
}
};
-struct Kernel12Tmp {
- Vec<std::array<int, 2>> p1q2_;
- Vec<int> x12_;
- Vec<vec3> v12_;
-};
-
+template <bool expandP, bool forward>
struct Kernel12Recorder {
- using Local = Kernel12Tmp;
- Kernel12& k12;
- bool forward;
+ using Local = Intersections;
+ Kernel12<expandP, forward>& k12;
#if MANIFOLD_PAR == 1
- tbb::combinable<Kernel12Tmp> store;
+ tbb::combinable<Intersections> store;
Local& local() { return store.local(); }
#else
- Kernel12Tmp localStore;
+ Intersections localStore;
Local& local() { return localStore; }
#endif
@@ -342,36 +319,36 @@ struct Kernel12Recorder {
const auto [x12, v12] = k12(queryIdx, leafIdx);
if (std::isfinite(v12[0])) {
if (forward)
- tmp.p1q2_.push_back({queryIdx, leafIdx});
+ tmp.p1q2.push_back({queryIdx, leafIdx});
else
- tmp.p1q2_.push_back({leafIdx, queryIdx});
- tmp.x12_.push_back(x12);
- tmp.v12_.push_back(v12);
+ tmp.p1q2.push_back({leafIdx, queryIdx});
+ tmp.x12.push_back(x12);
+ tmp.v12.push_back(v12);
}
}
- Kernel12Tmp get() {
+ Intersections get() {
#if MANIFOLD_PAR == 1
- Kernel12Tmp result;
- std::vector<Kernel12Tmp> tmps;
+ Intersections result;
+ std::vector<Intersections> tmps;
store.combine_each(
- [&](Kernel12Tmp& data) { tmps.emplace_back(std::move(data)); });
+ [&](Intersections& data) { tmps.emplace_back(std::move(data)); });
std::vector<size_t> sizes;
size_t total_size = 0;
for (const auto& tmp : tmps) {
sizes.push_back(total_size);
- total_size += tmp.x12_.size();
+ total_size += tmp.x12.size();
}
- result.p1q2_.resize(total_size);
- result.x12_.resize(total_size);
- result.v12_.resize(total_size);
+ result.p1q2.resize(total_size);
+ result.x12.resize(total_size);
+ result.v12.resize(total_size);
for_each_n(ExecutionPolicy::Seq, countAt(0), tmps.size(), [&](size_t i) {
- std::copy(tmps[i].p1q2_.begin(), tmps[i].p1q2_.end(),
- result.p1q2_.begin() + sizes[i]);
- std::copy(tmps[i].x12_.begin(), tmps[i].x12_.end(),
- result.x12_.begin() + sizes[i]);
- std::copy(tmps[i].v12_.begin(), tmps[i].v12_.end(),
- result.v12_.begin() + sizes[i]);
+ std::copy(tmps[i].p1q2.begin(), tmps[i].p1q2.end(),
+ result.p1q2.begin() + sizes[i]);
+ std::copy(tmps[i].x12.begin(), tmps[i].x12.end(),
+ result.x12.begin() + sizes[i]);
+ std::copy(tmps[i].v12.begin(), tmps[i].v12.end(),
+ result.v12.begin() + sizes[i]);
});
return result;
#else
@@ -380,84 +357,94 @@ struct Kernel12Recorder {
}
};
-std::tuple<Vec<int>, Vec<vec3>> Intersect12(const Manifold::Impl& inP,
- const Manifold::Impl& inQ,
- Vec<std::array<int, 2>>& p1q2,
- double expandP, bool forward) {
+template <bool expandP, bool forward>
+Intersections Intersect12_(const Manifold::Impl& inP, const Manifold::Impl& inQ,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
// a: 1 (edge), b: 2 (face)
const Manifold::Impl& a = forward ? inP : inQ;
const Manifold::Impl& b = forward ? inQ : inP;
- Kernel02 k02{a.vertPos_, b.halfedge_, b.vertPos_,
- expandP, inP.vertNormal_, forward};
- Kernel11 k11{inP.vertPos_, inQ.vertPos_, inP.halfedge_,
- inQ.halfedge_, expandP, inP.vertNormal_};
+ Kernel02<expandP, forward> k02{a, b};
+ Kernel11<expandP> k11{inP, inQ};
- Kernel12 k12{a.halfedge_, b.halfedge_, a.vertPos_, forward, k02, k11};
- Kernel12Recorder recorder{k12, forward, {}};
+ Kernel12<expandP, forward> k12{a, b, k02, k11};
+ Kernel12Recorder<expandP, forward> recorder{k12, {}};
auto f = [&a](int i) {
- return a.halfedge_[i].IsForward()
- ? Box(a.vertPos_[a.halfedge_[i].startVert],
- a.vertPos_[a.halfedge_[i].endVert])
- : Box();
+ const int start = a.halfedge_.Start(i);
+ const int end = a.halfedge_.End(i);
+ return start < end ? Box(a.vertPos_[start], a.vertPos_[end]) : Box();
};
- b.collider_.Collisions<false, decltype(f), Kernel12Recorder>(
- f, a.halfedge_.size(), recorder);
+ b.collider_.Collisions<false>(recorder, f, a.halfedge_.size(), true, ctx);
+ if (IsCancelled(ctx)) return Intersections{};
- Kernel12Tmp result = recorder.get();
- p1q2 = std::move(result.p1q2_);
- auto x12 = std::move(result.x12_);
- auto v12 = std::move(result.v12_);
+ Intersections result = recorder.get();
+ auto& p1q2 = result.p1q2;
// sort p1q2 according to edges
Vec<size_t> i12(p1q2.size());
sequence(i12.begin(), i12.end());
int index = forward ? 0 : 1;
- stable_sort(i12.begin(), i12.end(), [&](int a, int b) {
+ stable_sort(i12.begin(), i12.end(), [&](auto a, auto b) {
return p1q2[a][index] < p1q2[b][index] ||
(p1q2[a][index] == p1q2[b][index] &&
p1q2[a][1 - index] < p1q2[b][1 - index]);
});
Permute(p1q2, i12);
- Permute(x12, i12);
- Permute(v12, i12);
- return std::make_tuple(x12, v12);
+ Permute(result.x12, i12);
+ Permute(result.v12, i12);
+ return result;
};
-Vec<int> Winding03(const Manifold::Impl& inP, const Manifold::Impl& inQ,
- const VecView<std::array<int, 2>> p1q2, double expandP,
- bool forward) {
+template <bool forward>
+Intersections Intersect12(const Manifold::Impl& inP, const Manifold::Impl& inQ,
+ bool expandP, ExecutionContext::Impl* ctx) {
+ if (expandP)
+ return Intersect12_<true, forward>(inP, inQ, ctx);
+ else
+ return Intersect12_<false, forward>(inP, inQ, ctx);
+}
+
+template <bool expandP, bool forward>
+Vec<int> Winding03_(const Manifold::Impl& inP, const Manifold::Impl& inQ,
+ const VecView<std::array<int, 2>> p1q2,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // a: 0 (vert), b: 2 (face)
const Manifold::Impl& a = forward ? inP : inQ;
const Manifold::Impl& b = forward ? inQ : inP;
Vec<int> brokenHalfedges;
int index = forward ? 0 : 1;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
DisjointSets uA(a.vertPos_.size());
for_each(autoPolicy(a.halfedge_.size()), countAt(0),
- countAt(a.halfedge_.size()), [&](int edge) {
- const Halfedge& he = a.halfedge_[edge];
- if (!he.IsForward()) return;
+ countAt(static_cast<int>(a.halfedge_.size())), ctx, [&](int edge) {
+ const int start = a.halfedge_.Start(edge);
+ const int end = a.halfedge_.End(edge);
+ if (start >= end) return;
// check if the edge is broken
auto it = std::lower_bound(
p1q2.begin(), p1q2.end(), edge,
[index](const std::array<int, 2>& collisionPair, int e) {
return collisionPair[index] < e;
});
- if (it == p1q2.end() || (*it)[index] != edge)
- uA.unite(he.startVert, he.endVert);
+ if (it == p1q2.end() || (*it)[index] != edge) uA.unite(start, end);
});
+ if (IsCancelled(ctx)) return Vec<int>{};
// find components, the hope is the number of components should be small
- std::unordered_set<int> components;
+ std::unordered_set<size_t> components;
#if (MANIFOLD_PAR == 1)
if (a.vertPos_.size() > 1e5) {
- tbb::combinable<std::unordered_set<int>> componentsShared;
- for_each(autoPolicy(a.vertPos_.size()), countAt(0),
- countAt(a.vertPos_.size()),
- [&](int v) { componentsShared.local().insert(uA.find(v)); });
- componentsShared.combine_each([&](const std::unordered_set<int>& data) {
+ tbb::combinable<std::unordered_set<size_t>> componentsShared;
+ for_each(autoPolicy(a.vertPos_.size()), countAt(0_uz),
+ countAt(a.vertPos_.size()), ctx,
+ [&](size_t v) { componentsShared.local().insert(uA.find(v)); });
+ componentsShared.combine_each([&](const std::unordered_set<size_t>& data) {
components.insert(data.begin(), data.end());
});
} else
@@ -466,39 +453,56 @@ Vec<int> Winding03(const Manifold::Impl& inP, const Manifold::Impl& inQ,
for (size_t v = 0; v < a.vertPos_.size(); v++)
components.insert(uA.find(v));
}
+ if (IsCancelled(ctx)) return Vec<int>{};
Vec<int> verts;
verts.reserve(components.size());
- for (int c : components) verts.push_back(c);
+ for (size_t c : components) verts.push_back(static_cast<int>(c));
Vec<int> w03(a.NumVert(), 0);
- Kernel02 k02{a.vertPos_, b.halfedge_, b.vertPos_,
- expandP, inP.vertNormal_, forward};
+ Kernel02<expandP, forward> k02{a, b};
auto recorderf = [&](int i, int b) {
const auto [s02, z02] = k02(verts[i], b);
- if (std::isfinite(z02)) w03[verts[i]] += s02 * (!forward ? -1 : 1);
+ // note that i is distinct on each thread, and verts contains unique
+ // elements, so this does not require atomics
+ if (std::isfinite(z02)) w03[verts[i]] += s02 * (forward ? 1 : -1);
};
auto recorder = MakeSimpleRecorder(recorderf);
auto f = [&](int i) { return a.vertPos_[verts[i]]; };
- b.collider_.Collisions<false, decltype(f), decltype(recorder)>(
- f, verts.size(), recorder);
+ b.collider_.Collisions<false>(recorder, f, verts.size(), true, ctx);
+ if (IsCancelled(ctx)) return Vec<int>{};
// flood fill
- for_each(autoPolicy(w03.size()), countAt(0), countAt(w03.size()),
+ for_each(autoPolicy(w03.size()), countAt(0_uz), countAt(w03.size()), ctx,
[&](size_t i) {
size_t root = uA.find(i);
if (root == i) return;
w03[i] = w03[root];
});
+ if (IsCancelled(ctx)) return Vec<int>{};
return w03;
}
+
+template <bool forward>
+Vec<int> Winding03(const Manifold::Impl& inP, const Manifold::Impl& inQ,
+ const VecView<std::array<int, 2>> p1q2, bool expandP,
+ ExecutionContext::Impl* ctx) {
+ if (expandP)
+ return Winding03_<true, forward>(inP, inQ, p1q2, ctx);
+ else
+ return Winding03_<false, forward>(inP, inQ, p1q2, ctx);
+}
} // namespace
namespace manifold {
Boolean3::Boolean3(const Manifold::Impl& inP, const Manifold::Impl& inQ,
- OpType op)
- : inP_(inP), inQ_(inQ), expandP_(op == OpType::Add ? 1.0 : -1.0) {
+ OpType op, ExecutionContext::Impl* ctx)
+ : inP_(inP), inQ_(inQ), expandP_(op == OpType::Add), ctx_(ctx) {
+ ZoneScoped;
// Symbolic perturbation:
- // Union -> expand inP
- // Difference, Intersection -> contract inP
+ // Union -> expand inP, expand inQ
+ // Difference, Intersection -> contract inP, expand inQ
+ // Technically Intersection should contract inQ, but doing it this way makes
+ // Split faster and any suboptimal cases seem pretty rare.
+
constexpr size_t INT_MAX_SZ =
static_cast<size_t>(std::numeric_limits<int>::max());
@@ -509,37 +513,128 @@ Boolean3::Boolean3(const Manifold::Impl& inP, const Manifold::Impl& inQ,
return;
}
-#ifdef MANIFOLD_DEBUG
+ // Phase-boundary fast-path: skip launching the next phase if cancel fired
+ // between phases. The per-phase invariant is enforced inside the called
+ // functions (Intersect12_, Winding03_).
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
Timer intersections;
intersections.Start();
+ Timer intersect12P, intersect12Q, winding03P, winding03Q;
+ intersect12P.Start();
#endif
// Level 3
// Build up the intersection of the edges and triangles, keeping only those
// that intersect, and record the direction the edge is passing through the
// triangle.
- std::tie(x12_, v12_) = Intersect12(inP, inQ, p1q2_, expandP_, true);
- PRINT("x12 size = " << x12_.size());
-
- std::tie(x21_, v21_) = Intersect12(inP, inQ, p2q1_, expandP_, false);
- PRINT("x21 size = " << x21_.size());
+ if (IsCancelled(ctx_)) return;
+ xv12_ = Intersect12<true>(inP, inQ, expandP_, ctx_);
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ intersect12P.Stop();
+ intersect12Q.Start();
+#endif
+ if (IsCancelled(ctx_)) return;
+ xv21_ = Intersect12<false>(inP, inQ, expandP_, ctx_);
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ intersect12Q.Stop();
+#endif
- if (x12_.size() > INT_MAX_SZ || x21_.size() > INT_MAX_SZ) {
+ if (xv12_.x12.size() > INT_MAX_SZ || xv21_.x12.size() > INT_MAX_SZ) {
valid = false;
return;
}
// Compute winding numbers of all vertices using flood fill
// Vertices on the same connected component have the same winding number
- w03_ = Winding03(inP, inQ, p1q2_, expandP_, true);
- w30_ = Winding03(inP, inQ, p2q1_, expandP_, false);
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ winding03P.Start();
+#endif
+ if (IsCancelled(ctx_)) return;
+ w03_ = Winding03<true>(inP, inQ, xv12_.p1q2, expandP_, ctx_);
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ winding03P.Stop();
+ winding03Q.Start();
+#endif
+ if (IsCancelled(ctx_)) return;
+ w30_ = Winding03<false>(inP, inQ, xv21_.p1q2, expandP_, ctx_);
+ // No trailing check: Winding03_ already returns empty on cancel and
+ // Boolean3::Result re-checks on entry.
-#ifdef MANIFOLD_DEBUG
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ winding03Q.Stop();
intersections.Stop();
- if (ManifoldParams().verbose) {
- intersections.Print("Intersections");
+ if (ManifoldParams().verbose >= 2) {
+ intersect12P.Print(" Intersect12 P->Q");
+ intersect12Q.Print(" Intersect12 Q->P");
+ winding03P.Print(" Winding03 P");
+ winding03Q.Print(" Winding03 Q");
+ intersections.Print("Intersections (total)");
}
#endif
}
+std::vector<RayHit> Manifold::Impl::RayCast(vec3 origin, vec3 endpoint) const {
+ ZoneScoped;
+ if (IsEmpty()) return {};
+ const vec3 dir = endpoint - origin;
+ if (la::dot(dir, dir) == 0.0) return {};
+
+ // Build a minimal single-edge Impl representing the ray segment.
+ // Kernel12 treats inA as an edge mesh. Halfedges derives endVert from the
+ // next edge in a triangle, so this helper uses a padded degenerate face:
+ // edge 0 is the forward ray, edge 1 is its reverse, and edge 2 only closes
+ // the local storage loop. Zero vertex normals and face normal mean the ray
+ // contributes nothing to perturbation tiebreakers; consistency at shared
+ // edges/vertices depends entirely on the mesh's own normals.
+ Impl rayImpl;
+ rayImpl.vertPos_.resize(2);
+ rayImpl.vertPos_[0] = origin;
+ rayImpl.vertPos_[1] = endpoint;
+ rayImpl.vertNormal_.resize(2);
+ rayImpl.vertNormal_[0] = vec3(0.0);
+ rayImpl.vertNormal_[1] = vec3(0.0);
+ rayImpl.halfedge_.resize(3);
+ rayImpl.halfedge_.Set(0, 0, 1, 0); // forward: vert 0 → 1
+ rayImpl.halfedge_.Set(1, 1, 0, 0); // backward: vert 1 → 0
+ rayImpl.halfedge_.Set(2, -1, -1, 0);
+ rayImpl.faceNormal_.resize(1);
+ rayImpl.faceNormal_[0] = vec3(0.0);
+
+ // expandP=false with zero vertNormal means the ray-side perturbation is
+ // zero. forward=true means we project along +Z for the lower-dimensional
+ // kernel cascade (Shadow01 → Kernel02 → Kernel11 → Kernel12).
+ Kernel02<false, true> k02{rayImpl, *this};
+ Kernel11<false> k11{rayImpl, *this};
+ Kernel12<false, true> k12{rayImpl, *this, k02, k11};
+
+ // Use the component with largest magnitude for stable t computation.
+ const vec3 absDir = la::abs(dir);
+ const int tAxis = absDir.x > absDir.y && absDir.x > absDir.z ? 0
+ : absDir.y > absDir.z ? 1
+ : 2;
+
+ std::vector<RayHit> hits;
+ // Query the BVH with the ray's AABB.
+ const Box rayBox(la::min(origin, endpoint), la::max(origin, endpoint));
+ auto recorderf = [&](int /*queryIdx*/, int tri) {
+ const auto [s, v] = k12(0, tri); // halfedge 0 vs triangle tri
+ if (s != 0 && std::isfinite(v.x)) {
+ // v is the 3D intersection point computed by Kernel12.
+ // Compute parametric t ∈ [0,1] along the ray segment.
+ const double t = (v[tAxis] - origin[tAxis]) / dir[tAxis];
+ if (t >= 0.0 && t <= 1.0) {
+ hits.push_back({static_cast<uint64_t>(tri), t, v, faceNormal_[tri]});
+ }
+ }
+ };
+ auto recorder = MakeSimpleRecorder(recorderf);
+ auto f = [&rayBox](int) { return rayBox; };
+ collider_.Collisions<false>(recorder, f, 1, false);
+
+ std::sort(hits.begin(), hits.end(), [](const RayHit& a, const RayHit& b) {
+ return a.distance < b.distance;
+ });
+ return hits;
+}
+
} // namespace manifold
diff --git a/thirdparty/manifold/src/boolean3.h b/thirdparty/manifold/src/boolean3.h
index b9d872ddf94..e5014ffc1db 100644
--- a/thirdparty/manifold/src/boolean3.h
+++ b/thirdparty/manifold/src/boolean3.h
@@ -13,11 +13,12 @@
// limitations under the License.
#pragma once
+#include "execution_impl.h"
#include "impl.h"
#ifdef MANIFOLD_DEBUG
#define PRINT(msg) \
- if (ManifoldParams().verbose > 0) std::cout << msg << std::endl;
+ if (ManifoldParams().verbose >= 2) std::cout << msg << std::endl;
#else
#define PRINT(msg)
#endif
@@ -44,17 +45,28 @@
namespace manifold {
/** @ingroup Private */
+
+// In forward mode, stores the intersections of edges of P with faces of Q.
+// In reverse mode, stores the intersections of faces of P with edges of Q.
+// In reverse, p1q2 -> p2q1, x12 -> x21, v12 -> v21.
+struct Intersections {
+ Vec<std::array<int, 2>> p1q2;
+ Vec<int> x12;
+ Vec<vec3> v12;
+};
+
class Boolean3 {
public:
- Boolean3(const Manifold::Impl& inP, const Manifold::Impl& inQ, OpType op);
+ Boolean3(const Manifold::Impl& inP, const Manifold::Impl& inQ, OpType op,
+ ExecutionContext::Impl* ctx = nullptr);
Manifold::Impl Result(OpType op) const;
private:
const Manifold::Impl &inP_, &inQ_;
- const double expandP_;
- Vec<std::array<int, 2>> p1q2_, p2q1_;
- Vec<int> x12_, x21_, w03_, w30_;
- Vec<vec3> v12_, v21_;
+ const bool expandP_;
+ Intersections xv12_, xv21_;
+ Vec<int> w03_, w30_;
bool valid = true;
+ ExecutionContext::Impl* ctx_ = nullptr;
};
} // namespace manifold
diff --git a/thirdparty/manifold/src/boolean_result.cpp b/thirdparty/manifold/src/boolean_result.cpp
index 7eacf3c4de0..eb19641e183 100644
--- a/thirdparty/manifold/src/boolean_result.cpp
+++ b/thirdparty/manifold/src/boolean_result.cpp
@@ -15,6 +15,7 @@
#include <algorithm>
#include <array>
#include <map>
+#include <optional>
#include "boolean3.h"
#include "parallel.h"
@@ -64,17 +65,14 @@ struct DuplicateVerts {
}
};
-template <bool atomic>
struct CountVerts {
- VecView<Halfedge> halfedges;
+ const Halfedges& halfedges;
VecView<int> count;
VecView<const int> inclusion;
void operator()(size_t i) {
- if (atomic)
- AtomicAdd(count[i / 3], std::abs(inclusion[halfedges[i].startVert]));
- else
- count[i / 3] += std::abs(inclusion[halfedges[i].startVert]);
+ for (size_t j : {0, 1, 2})
+ count[i] += std::abs(inclusion[halfedges.Start(3 * i + j)]);
}
};
@@ -84,7 +82,7 @@ struct CountNewVerts {
VecView<int> countQ;
VecView<const int> i12;
const Vec<std::array<int, 2>>& pq;
- VecView<const Halfedge> halfedges;
+ const Halfedges& halfedges;
void operator()(const int idx) {
int edgeP = pq[idx][inverted ? 1 : 0];
@@ -93,14 +91,12 @@ struct CountNewVerts {
if (atomic) {
AtomicAdd(countQ[faceQ], inclusion);
- const Halfedge half = halfedges[edgeP];
AtomicAdd(countP[edgeP / 3], inclusion);
- AtomicAdd(countP[half.pairedHalfedge / 3], inclusion);
+ AtomicAdd(countP[halfedges.Pair(edgeP) / 3], inclusion);
} else {
countQ[faceQ] += inclusion;
- const Halfedge half = halfedges[edgeP];
countP[edgeP / 3] += inclusion;
- countP[half.pairedHalfedge / 3] += inclusion;
+ countP[halfedges.Pair(edgeP) / 3] += inclusion;
}
}
};
@@ -109,41 +105,39 @@ std::tuple<Vec<int>, Vec<int>> SizeOutput(
Manifold::Impl& outR, const Manifold::Impl& inP, const Manifold::Impl& inQ,
const Vec<int>& i03, const Vec<int>& i30, const Vec<int>& i12,
const Vec<int>& i21, const Vec<std::array<int, 2>>& p1q2,
- const Vec<std::array<int, 2>>& p2q1, bool invertQ) {
+ const Vec<std::array<int, 2>>& p2q1, bool invertQ,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
Vec<int> sidesPerFacePQ(inP.NumTri() + inQ.NumTri(), 0);
// note: numFaceR <= facePQ2R.size() = sidesPerFacePQ.size() + 1
auto sidesPerFaceP = sidesPerFacePQ.view(0, inP.NumTri());
auto sidesPerFaceQ = sidesPerFacePQ.view(inP.NumTri(), inQ.NumTri());
- if (inP.halfedge_.size() >= 1e5) {
- for_each(ExecutionPolicy::Par, countAt(0_uz), countAt(inP.halfedge_.size()),
- CountVerts<true>({inP.halfedge_, sidesPerFaceP, i03}));
- for_each(ExecutionPolicy::Par, countAt(0_uz), countAt(inQ.halfedge_.size()),
- CountVerts<true>({inQ.halfedge_, sidesPerFaceQ, i30}));
- } else {
- for_each(ExecutionPolicy::Seq, countAt(0_uz), countAt(inP.halfedge_.size()),
- CountVerts<false>({inP.halfedge_, sidesPerFaceP, i03}));
- for_each(ExecutionPolicy::Seq, countAt(0_uz), countAt(inQ.halfedge_.size()),
- CountVerts<false>({inQ.halfedge_, sidesPerFaceQ, i30}));
- }
+ auto policy = autoPolicy(inP.halfedge_.size());
+ for_each(policy, countAt(0_uz), countAt(inP.halfedge_.size() / 3), ctx,
+ CountVerts{inP.halfedge_, sidesPerFaceP, i03});
+ for_each(policy, countAt(0_uz), countAt(inQ.halfedge_.size() / 3), ctx,
+ CountVerts{inQ.halfedge_, sidesPerFaceQ, i30});
if (i12.size() >= 1e5) {
- for_each_n(ExecutionPolicy::Par, countAt(0), i12.size(),
- CountNewVerts<false, true>(
- {sidesPerFaceP, sidesPerFaceQ, i12, p1q2, inP.halfedge_}));
- for_each_n(ExecutionPolicy::Par, countAt(0), i21.size(),
- CountNewVerts<true, true>(
- {sidesPerFaceQ, sidesPerFaceP, i21, p2q1, inQ.halfedge_}));
+ for_each_n(ExecutionPolicy::Par, countAt(0), i12.size(), ctx,
+ CountNewVerts<false, true>{sidesPerFaceP, sidesPerFaceQ, i12,
+ p1q2, inP.halfedge_});
+ for_each_n(ExecutionPolicy::Par, countAt(0), i21.size(), ctx,
+ CountNewVerts<true, true>{sidesPerFaceQ, sidesPerFaceP, i21,
+ p2q1, inQ.halfedge_});
} else {
- for_each_n(ExecutionPolicy::Seq, countAt(0), i12.size(),
- CountNewVerts<false, false>(
- {sidesPerFaceP, sidesPerFaceQ, i12, p1q2, inP.halfedge_}));
- for_each_n(ExecutionPolicy::Seq, countAt(0), i21.size(),
- CountNewVerts<true, false>(
- {sidesPerFaceQ, sidesPerFaceP, i21, p2q1, inQ.halfedge_}));
+ for_each_n(ExecutionPolicy::Seq, countAt(0), i12.size(), ctx,
+ CountNewVerts<false, false>{sidesPerFaceP, sidesPerFaceQ, i12,
+ p1q2, inP.halfedge_});
+ for_each_n(ExecutionPolicy::Seq, countAt(0), i21.size(), ctx,
+ CountNewVerts<true, false>{sidesPerFaceQ, sidesPerFaceP, i21,
+ p2q1, inQ.halfedge_});
}
+ if (IsCancelled(ctx)) return std::make_tuple(Vec<int>{}, Vec<int>{});
Vec<int> facePQ2R(inP.NumTri() + inQ.NumTri() + 1, 0);
auto keepFace = TransformIterator(sidesPerFacePQ.begin(),
@@ -157,13 +151,13 @@ std::tuple<Vec<int>, Vec<int>> SizeOutput(
outR.faceNormal_.resize_nofill(numFaceR);
Vec<size_t> tmpBuffer(outR.faceNormal_.size());
- auto faceIds = TransformIterator(countAt(0_uz), [&sidesPerFacePQ](size_t i) {
+ auto faceIdsP = TransformIterator(countAt(0_uz), [&sidesPerFacePQ](size_t i) {
if (sidesPerFacePQ[i] > 0) return i;
return std::numeric_limits<size_t>::max();
});
auto next =
- copy_if(faceIds, faceIds + inP.faceNormal_.size(), tmpBuffer.begin(),
+ copy_if(faceIdsP, faceIdsP + inP.faceNormal_.size(), tmpBuffer.begin(),
[](size_t v) { return v != std::numeric_limits<size_t>::max(); });
gather(tmpBuffer.begin(), next, inP.faceNormal_.begin(),
@@ -190,9 +184,8 @@ std::tuple<Vec<int>, Vec<int>> SizeOutput(
auto newEnd = remove(sidesPerFacePQ.begin(), sidesPerFacePQ.end(), 0);
Vec<int> faceEdge(newEnd - sidesPerFacePQ.begin() + 1, 0);
inclusive_scan(sidesPerFacePQ.begin(), newEnd, faceEdge.begin() + 1);
- outR.halfedge_.resize(faceEdge.back());
- return std::make_tuple(faceEdge, facePQ2R);
+ return std::make_tuple(std::move(faceEdge), std::move(facePQ2R));
}
struct EdgePos {
@@ -200,22 +193,24 @@ struct EdgePos {
int vert;
int collisionId;
bool isStart;
+
+ bool operator<(const EdgePos& other) const {
+ return edgePos < other.edgePos ||
+ // we also sort by collisionId to make things deterministic
+ (edgePos == other.edgePos && collisionId < other.collisionId);
+ }
};
-// thread sanitizer doesn't really know how to check when there are too many
-// mutex
-#if defined(__has_feature)
-#if __has_feature(thread_sanitizer)
-__attribute__((no_sanitize("thread")))
-#endif
-#endif
void AddNewEdgeVerts(
// we need concurrent_map because we will be adding things concurrently
- concurrent_map<int, std::vector<EdgePos>> &edgesP,
- concurrent_map<std::pair<int, int>, std::vector<EdgePos>> &edgesNew,
- const Vec<std::array<int, 2>> &p1q2, const Vec<int> &i12, const Vec<int> &v12R,
- const Vec<Halfedge> &halfedgeP, bool forward, size_t offset) {
+ concurrent_map<int, std::vector<EdgePos>>& edgesP,
+ concurrent_map<std::pair<int, int>, std::vector<EdgePos>>& edgesNew,
+ const Vec<std::array<int, 2>>& p1q2, const Vec<int>& i12,
+ const Vec<int>& v12R, const Halfedges& halfedgeP, bool forward,
+ size_t offset, ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
// For each edge of P that intersects a face of Q (p1q2), add this vertex to
// P's corresponding edge vector and to the two new edges, which are
// intersections between the face of Q and the two faces of P attached to the
@@ -228,8 +223,7 @@ void AddNewEdgeVerts(
const int vert = v12R[i];
const int inclusion = i12[i];
- Halfedge halfedge = halfedgeP[edgeP];
- std::pair<int, int> keyRight = {halfedge.pairedHalfedge / 3, faceQ};
+ std::pair<int, int> keyRight = {halfedgeP.Pair(edgeP) / 3, faceQ};
if (!forward) std::swap(keyRight.first, keyRight.second);
std::pair<int, int> keyLeft = {edgeP / 3, faceQ};
@@ -259,7 +253,9 @@ void AddNewEdgeVerts(
// ideally we should have 1 mutex per key, but kParallelThreshold is enough
// to avoid contention for most of the cases
std::array<std::mutex, kParallelThreshold> mutexes;
- static tbb::affinity_partitioner ap;
+ // thread_local: affinity_partitioner isn't safe for concurrent use
+ // (internal state mutated by parallel_for without synchronization).
+ thread_local tbb::affinity_partitioner ap;
auto processFun = std::bind(
process, [&](size_t hash) { mutexes[hash % mutexes.size()].lock(); },
[&](size_t hash) { mutexes[hash % mutexes.size()].unlock(); },
@@ -267,18 +263,26 @@ void AddNewEdgeVerts(
tbb::parallel_for(
tbb::blocked_range<size_t>(0_uz, p1q2.size(), 32),
[&](const tbb::blocked_range<size_t>& range) {
+ if (IsCancelled(ctx)) return;
for (size_t i = range.begin(); i != range.end(); i++) processFun(i);
},
ap);
return;
}
#endif
+ if (IsCancelled(ctx)) return;
auto processFun =
std::bind(process, [](size_t) {}, [](size_t) {}, std::placeholders::_1);
- for (size_t i = 0; i < p1q2.size(); ++i) processFun(i);
+ // Per-iter cancel check; the caller's post-call IsCancelled discards the
+ // partial edgesP/edgesNew.
+ for (size_t i = 0; i < p1q2.size(); ++i) {
+ if (IsCancelled(ctx)) return;
+ processFun(i);
+ }
}
-std::vector<Halfedge> PairUp(std::vector<EdgePos>& edgePos) {
+template <typename F>
+void PairUp(std::vector<EdgePos>& edgePos, F f) {
// Pair start vertices with end vertices to form edges. The choice of pairing
// is arbitrary for the manifoldness guarantee, but must be ordered to be
// geometrically valid. If the order does not go start-end-start-end... then
@@ -291,45 +295,42 @@ std::vector<Halfedge> PairUp(std::vector<EdgePos>& edgePos) {
[](EdgePos x) { return x.isStart; });
DEBUG_ASSERT(static_cast<size_t>(middle - edgePos.begin()) == nEdges,
topologyErr, "Non-manifold edge!");
- auto cmp = [](EdgePos a, EdgePos b) {
- return a.edgePos < b.edgePos ||
- // we also sort by collisionId to make things deterministic
- (a.edgePos == b.edgePos && a.collisionId < b.collisionId);
- };
- std::stable_sort(edgePos.begin(), middle, cmp);
- std::stable_sort(middle, edgePos.end(), cmp);
- std::vector<Halfedge> edges;
+ std::stable_sort(edgePos.begin(), middle);
+ std::stable_sort(middle, edgePos.end());
for (size_t i = 0; i < nEdges; ++i)
- edges.push_back({edgePos[i].vert, edgePos[i + nEdges].vert, -1});
- return edges;
+ f(Halfedge{edgePos[i].vert, edgePos[i + nEdges].vert, -1});
}
-void AppendPartialEdges(Manifold::Impl& outR, Vec<char>& wholeHalfedgeP,
- Vec<int>& facePtrR,
+void AppendPartialEdges(Manifold::Impl& outR, Vec<Halfedge>& halfedgeR,
+ Vec<char>& wholeHalfedgeP, Vec<int>& facePtrR,
concurrent_map<int, std::vector<EdgePos>>& edgesP,
Vec<TriRef>& halfedgeRef, const Manifold::Impl& inP,
const Vec<int>& i03, const Vec<int>& vP2R,
- const Vec<int>::IterC faceP2R, bool forward) {
+ const Vec<int>::IterC faceP2R, bool forward,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
// Each edge in the map is partially retained; for each of these, look up
// their original verts and include them based on their winding number (i03),
// while remapping them to the output using vP2R. Use the verts position
// projected along the edge vector to pair them up, then distribute these
// edges to their faces.
- Vec<Halfedge>& halfedgeR = outR.halfedge_;
const Vec<vec3>& vertPosP = inP.vertPos_;
- const Vec<Halfedge>& halfedgeP = inP.halfedge_;
+ const Halfedges& halfedgeP = inP.halfedge_;
+ // Per-iter cancel check; the caller's post-call IsCancelled discards the
+ // partial outR.
for (auto& value : edgesP) {
+ if (IsCancelled(ctx)) return;
const int edgeP = value.first;
- std::vector<EdgePos>& edgePosP = value.second;
+ std::vector<EdgePos> edgePosP = value.second;
+ std::stable_sort(edgePosP.begin(), edgePosP.end());
- const Halfedge& halfedge = halfedgeP[edgeP];
+ const int pairP = halfedgeP.Pair(edgeP);
wholeHalfedgeP[edgeP] = false;
- wholeHalfedgeP[halfedge.pairedHalfedge] = false;
+ wholeHalfedgeP[pairP] = false;
- const int vStart = halfedge.startVert;
- const int vEnd = halfedge.endVert;
+ const int vStart = halfedgeP.Start(edgeP);
+ const int vEnd = halfedgeP.End(edgeP);
const vec3 edgeVec = vertPosP[vEnd] - vertPosP[vStart];
// Fill in the edge positions of the old points.
for (EdgePos& edge : edgePosP) {
@@ -353,13 +354,10 @@ void AppendPartialEdges(Manifold::Impl& outR, Vec<char>& wholeHalfedgeP,
++edgePos.vert;
}
- // sort edges into start/end pairs along length
- std::vector<Halfedge> edges = PairUp(edgePosP);
-
// add halfedges to result
const int faceLeftP = edgeP / 3;
const int faceLeft = faceP2R[faceLeftP];
- const int faceRightP = halfedge.pairedHalfedge / 3;
+ const int faceRightP = pairP / 3;
const int faceRight = faceP2R[faceRightP];
// Negative inclusion means the halfedges are reversed, which means our
// reference is now to the endVert instead of the startVert, which is one
@@ -368,7 +366,7 @@ void AppendPartialEdges(Manifold::Impl& outR, Vec<char>& wholeHalfedgeP,
const TriRef forwardRef = {forward ? 0 : 1, -1, faceLeftP, -1};
const TriRef backwardRef = {forward ? 0 : 1, -1, faceRightP, -1};
- for (Halfedge e : edges) {
+ PairUp(edgePosP, [&](Halfedge e) {
const int forwardEdge = facePtrR[faceLeft]++;
const int backwardEdge = facePtrR[faceRight]++;
@@ -380,23 +378,27 @@ void AppendPartialEdges(Manifold::Impl& outR, Vec<char>& wholeHalfedgeP,
e.pairedHalfedge = forwardEdge;
halfedgeR[backwardEdge] = e;
halfedgeRef[backwardEdge] = backwardRef;
- }
+ });
}
}
void AppendNewEdges(
- Manifold::Impl& outR, Vec<int>& facePtrR,
+ Manifold::Impl& outR, Vec<Halfedge>& halfedgeR, Vec<int>& facePtrR,
concurrent_map<std::pair<int, int>, std::vector<EdgePos>>& edgesNew,
- Vec<TriRef>& halfedgeRef, const Vec<int>& facePQ2R, const int numFaceP) {
+ Vec<TriRef>& halfedgeRef, const Vec<int>& facePQ2R, const int numFaceP,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
// Pair up each edge's verts and distribute to faces based on indices in key.
- Vec<Halfedge>& halfedgeR = outR.halfedge_;
Vec<vec3>& vertPosR = outR.vertPos_;
+ // Per-iter cancel check; the caller's post-call IsCancelled discards the
+ // partial outR.
for (auto& value : edgesNew) {
+ if (IsCancelled(ctx)) return;
const int faceP = value.first.first;
const int faceQ = value.first.second;
std::vector<EdgePos>& edgePos = value.second;
+ std::stable_sort(edgePos.begin(), edgePos.end());
Box bbox;
for (auto edge : edgePos) {
@@ -411,15 +413,12 @@ void AppendNewEdges(
edge.edgePos = vertPosR[edge.vert][i];
}
- // sort edges into start/end pairs along length.
- std::vector<Halfedge> edges = PairUp(edgePos);
-
// add halfedges to result
const int faceLeft = facePQ2R[faceP];
const int faceRight = facePQ2R[numFaceP + faceQ];
const TriRef forwardRef = {0, -1, faceP, -1};
const TriRef backwardRef = {1, -1, faceQ, -1};
- for (Halfedge e : edges) {
+ PairUp(edgePos, [&](Halfedge e) {
const int forwardEdge = facePtrR[faceLeft]++;
const int backwardEdge = facePtrR[faceRight]++;
@@ -431,7 +430,7 @@ void AppendNewEdges(
e.pairedHalfedge = forwardEdge;
halfedgeR[backwardEdge] = e;
halfedgeRef[backwardEdge] = backwardRef;
- }
+ });
}
}
@@ -440,7 +439,7 @@ struct DuplicateHalfedges {
VecView<TriRef> halfedgeRef;
VecView<int> facePtr;
VecView<const char> wholeHalfedgeP;
- VecView<const Halfedge> halfedgesP;
+ const Halfedges& halfedgesP;
VecView<const int> i03;
VecView<const int> vP2R;
VecView<const int> faceP2R;
@@ -448,19 +447,23 @@ struct DuplicateHalfedges {
void operator()(const int idx) {
if (!wholeHalfedgeP[idx]) return;
- Halfedge halfedge = halfedgesP[idx];
- if (!halfedge.IsForward()) return;
- const int inclusion = i03[halfedge.startVert];
+ int startVert = halfedgesP.Start(idx);
+ int endVert = halfedgesP.Start(NextHalfedge(idx));
+ if (startVert >= endVert) return;
+ const int inclusion = i03[startVert];
if (inclusion == 0) return;
if (inclusion < 0) { // reverse
- std::swap(halfedge.startVert, halfedge.endVert);
+ std::swap(startVert, endVert);
}
- halfedge.startVert = vP2R[halfedge.startVert];
- halfedge.endVert = vP2R[halfedge.endVert];
+ startVert = vP2R[startVert];
+ endVert = vP2R[endVert];
+ const int propVert = halfedgesP.Prop(idx);
+ const int pair = halfedgesP.Pair(idx);
+ const int pairPropVert = halfedgesP.Prop(pair);
const int faceLeftP = idx / 3;
const int newFace = faceP2R[faceLeftP];
- const int faceRightP = halfedge.pairedHalfedge / 3;
+ const int faceRightP = pair / 3;
const int faceRight = faceP2R[faceRightP];
// Negative inclusion means the halfedges are reversed, which means our
// reference is now to the endVert instead of the startVert, which is one
@@ -471,30 +474,32 @@ struct DuplicateHalfedges {
for (int i = 0; i < std::abs(inclusion); ++i) {
int forwardEdge = AtomicAdd(facePtr[newFace], 1);
int backwardEdge = AtomicAdd(facePtr[faceRight], 1);
- halfedge.pairedHalfedge = backwardEdge;
- halfedgesR[forwardEdge] = halfedge;
- halfedgesR[backwardEdge] = {halfedge.endVert, halfedge.startVert,
- forwardEdge};
+ halfedgesR[forwardEdge] = {startVert, endVert, backwardEdge, propVert};
+ halfedgesR[backwardEdge] = {endVert, startVert, forwardEdge,
+ pairPropVert};
halfedgeRef[forwardEdge] = forwardRef;
halfedgeRef[backwardEdge] = backwardRef;
- ++halfedge.startVert;
- ++halfedge.endVert;
+ ++startVert;
+ ++endVert;
}
}
};
void AppendWholeEdges(Manifold::Impl& outR, Vec<int>& facePtrR,
- Vec<TriRef>& halfedgeRef, const Manifold::Impl& inP,
- const Vec<char> wholeHalfedgeP, const Vec<int>& i03,
- const Vec<int>& vP2R, VecView<const int> faceP2R,
- bool forward) {
+ Vec<Halfedge>& halfedgesR, Vec<TriRef>& halfedgeRef,
+ const Manifold::Impl& inP, const Vec<char> wholeHalfedgeP,
+ const Vec<int>& i03, const Vec<int>& vP2R,
+ VecView<const int> faceP2R, bool forward,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
for_each_n(
- autoPolicy(inP.halfedge_.size()), countAt(0), inP.halfedge_.size(),
- DuplicateHalfedges({outR.halfedge_, halfedgeRef, facePtrR, wholeHalfedgeP,
- inP.halfedge_, i03, vP2R, faceP2R, forward}));
+ autoPolicy(inP.halfedge_.size()), countAt(0), inP.halfedge_.size(), ctx,
+ DuplicateHalfedges{halfedgesR, halfedgeRef, facePtrR, wholeHalfedgeP,
+ inP.halfedge_, i03, vP2R, faceP2R, forward});
}
struct MapTriRef {
@@ -511,12 +516,16 @@ struct MapTriRef {
};
void UpdateReference(Manifold::Impl& outR, const Manifold::Impl& inP,
- const Manifold::Impl& inQ, bool invertQ) {
+ const Manifold::Impl& inQ, bool invertQ,
+ ExecutionContext::Impl* ctx) {
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const int offsetQ = Manifold::Impl::meshIDCounter_;
for_each_n(
autoPolicy(outR.NumTri(), 1e5), outR.meshRelation_.triRef.begin(),
- outR.NumTri(),
+ outR.NumTri(), ctx,
MapTriRef({inP.meshRelation_.triRef, inQ.meshRelation_.triRef, offsetQ}));
+ if (IsCancelled(ctx)) return;
for (const auto& pair : inP.meshRelation_.meshIDtransform) {
outR.meshRelation_.meshIDtransform[pair.first] = pair.second;
@@ -534,14 +543,14 @@ struct Barycentric {
VecView<const vec3> vertPosP;
VecView<const vec3> vertPosQ;
VecView<const vec3> vertPosR;
- VecView<const Halfedge> halfedgeP;
- VecView<const Halfedge> halfedgeQ;
- VecView<const Halfedge> halfedgeR;
+ const Halfedges& halfedgeP;
+ const Halfedges& halfedgeQ;
+ const Halfedges& halfedgeR;
const double epsilon;
void operator()(const int tri) {
const TriRef refPQ = ref[tri];
- if (halfedgeR[3 * tri].startVert < 0) return;
+ if (halfedgeR.Start(3 * tri) < 0) return;
const int triPQ = refPQ.faceID;
const bool PQ = refPQ.meshID == 0;
@@ -550,18 +559,21 @@ struct Barycentric {
mat3 triPos;
for (const int j : {0, 1, 2})
- triPos[j] = vertPos[halfedge[3 * triPQ + j].startVert];
+ triPos[j] = vertPos[halfedge.Start(3 * triPQ + j)];
for (const int i : {0, 1, 2}) {
- const int vert = halfedgeR[3 * tri + i].startVert;
+ const int vert = halfedgeR.Start(3 * tri + i);
uvw[3 * tri + i] = GetBarycentric(vertPosR[vert], triPos, epsilon);
}
}
};
void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
- const Manifold::Impl& inQ) {
+ const Manifold::Impl& inQ, bool invertQ,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const int numPropP = inP.NumProp();
const int numPropQ = inQ.NumProp();
const int numProp = std::max(numPropP, numPropQ);
@@ -570,10 +582,11 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
const int numTri = outR.NumTri();
Vec<vec3> bary(outR.halfedge_.size());
- for_each_n(autoPolicy(numTri, 1e4), countAt(0), numTri,
- Barycentric({bary, outR.meshRelation_.triRef, inP.vertPos_,
- inQ.vertPos_, outR.vertPos_, inP.halfedge_,
- inQ.halfedge_, outR.halfedge_, outR.epsilon_}));
+ for_each_n(autoPolicy(numTri, 1e4), countAt(0), numTri, ctx,
+ Barycentric{bary, outR.meshRelation_.triRef, inP.vertPos_,
+ inQ.vertPos_, outR.vertPos_, inP.halfedge_,
+ inQ.halfedge_, outR.halfedge_, outR.epsilon_});
+ if (IsCancelled(ctx)) return;
using Entry = std::pair<ivec3, int>;
int idMissProp = outR.NumVert();
@@ -586,8 +599,9 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
int idx = 0;
for (int tri = 0; tri < numTri; ++tri) {
+ if (IsCancelled(ctx)) return;
// Skip collapsed triangles
- if (outR.halfedge_[3 * tri].startVert < 0) continue;
+ if (outR.halfedge_.Start(3 * tri) < 0) continue;
const TriRef ref = outR.meshRelation_.triRef[tri];
const bool PQ = ref.meshID == 0;
@@ -595,8 +609,17 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
const auto& properties = PQ ? inP.properties_ : inQ.properties_;
const auto& halfedge = PQ ? inP.halfedge_ : inQ.halfedge_;
+ // For Subtract, Q's triangles are flipped in the result, so Q's
+ // world-frame vertex normals (slot 0..2 when hasNormals) need a sign
+ // flip to point outward from the result's solid (into the cavity).
+ // Check is per-source-triangle, not whole input - inQ may be a mixed
+ // Boolean result.
+ const bool negateNormals =
+ !PQ && invertQ && oldNumProp >= 3 &&
+ Manifold::Impl::TriHasNormals(inQ.meshRelation_, ref.faceID);
+
for (const int i : {0, 1, 2}) {
- const int vert = outR.halfedge_[3 * tri + i].startVert;
+ const int vert = outR.halfedge_.Start(3 * tri + i);
const vec3& uvw = bary[3 * tri + i];
ivec4 key(PQ, idMissProp, -1, -1);
@@ -605,7 +628,7 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
for (const int j : {0, 1, 2}) {
if (uvw[j] == 1) {
// On a retained vert, the propVert must also match
- key[2] = halfedge[3 * ref.faceID + j].propVert;
+ key[2] = halfedge.Prop(3 * ref.faceID + j);
edge = -1;
break;
}
@@ -613,8 +636,8 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
}
if (edge >= 0) {
// On an edge, both propVerts must match
- const int p0 = halfedge[3 * ref.faceID + Next3(edge)].propVert;
- const int p1 = halfedge[3 * ref.faceID + Prev3(edge)].propVert;
+ const int p0 = halfedge.Prop(3 * ref.faceID + Next3(edge));
+ const int p1 = halfedge.Prop(3 * ref.faceID + Prev3(edge));
key[1] = vert;
key[2] = std::min(p0, p1);
key[3] = std::max(p0, p1);
@@ -627,7 +650,7 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
// only key.x/key.z matters
auto& entry = propMissIdx[key.x][key.z];
if (entry >= 0) {
- outR.halfedge_[3 * tri + i].propVert = entry;
+ outR.halfedge_.SetProp(3 * tri + i, entry);
continue;
}
entry = idx;
@@ -637,7 +660,7 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
for (const auto& b : bin) {
if (b.first == ivec3(key.x, key.z, key.w)) {
bFound = true;
- outR.halfedge_[3 * tri + i].propVert = b.second;
+ outR.halfedge_.SetProp(3 * tri + i, b.second);
break;
}
}
@@ -645,15 +668,16 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
bin.push_back(std::make_pair(ivec3(key.x, key.z, key.w), idx));
}
- outR.halfedge_[3 * tri + i].propVert = idx++;
+ outR.halfedge_.SetProp(3 * tri + i, idx++);
for (int p = 0; p < numProp; ++p) {
if (p < oldNumProp) {
vec3 oldProps;
for (const int j : {0, 1, 2})
oldProps[j] =
- properties[oldNumProp * halfedge[3 * ref.faceID + j].propVert +
- p];
- outR.properties_.push_back(la::dot(uvw, oldProps));
+ properties[oldNumProp * halfedge.Prop(3 * ref.faceID + j) + p];
+ double val = la::dot(uvw, oldProps);
+ if (negateNormals && p < 3) val = -val;
+ outR.properties_.push_back(val);
} else {
outR.properties_.push_back(0);
}
@@ -662,55 +686,52 @@ void CreateProperties(Manifold::Impl& outR, const Manifold::Impl& inP,
}
}
-void ReorderHalfedges(VecView<Halfedge>& halfedges) {
- ZoneScoped;
- // halfedges in the same face are added in non-deterministic order, so we have
- // to reorder them for determinism
-
- // step 1: reorder within the same face, such that the halfedge with the
- // smallest starting vertex is placed first
- for_each(autoPolicy(halfedges.size() / 3), countAt(0),
- countAt(halfedges.size() / 3), [&halfedges](size_t tri) {
- std::array<Halfedge, 3> face = {halfedges[tri * 3],
- halfedges[tri * 3 + 1],
- halfedges[tri * 3 + 2]};
- int index = 0;
- for (int i : {1, 2})
- if (face[i].startVert < face[index].startVert) index = i;
- for (int i : {0, 1, 2})
- halfedges[tri * 3 + i] = face[(index + i) % 3];
- });
- // step 2: fix paired halfedge
- for_each(autoPolicy(halfedges.size() / 3), countAt(0),
- countAt(halfedges.size() / 3), [&halfedges](size_t tri) {
- for (int i : {0, 1, 2}) {
- Halfedge& curr = halfedges[tri * 3 + i];
- int oppositeFace = curr.pairedHalfedge / 3;
- int index = -1;
- for (int j : {0, 1, 2})
- if (curr.startVert == halfedges[oppositeFace * 3 + j].endVert)
- index = j;
- curr.pairedHalfedge = oppositeFace * 3 + index;
- }
- });
-}
-
} // namespace
namespace manifold {
Manifold::Impl Boolean3::Result(OpType op) const {
-#ifdef MANIFOLD_DEBUG
- Timer assemble;
- assemble.Start();
+ ZoneScoped;
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ // Per-Result local timing baseline, kept off the shared ctx so concurrent
+ // booleans in a CSG tree don't clobber it; the uid tags each printed phase
+ // line so interleaved parallel output can be split apart. Replaces the old
+ // per-stage Timers.
+ LocalPhaseTiming phaseTiming = BeginLocalPhaseTiming();
#endif
- DEBUG_ASSERT((expandP_ > 0) == (op == OpType::Add), logicErr,
+ DEBUG_ASSERT(expandP_ == (op == OpType::Add), logicErr,
"Result op type not compatible with constructor op type.");
const int c1 = op == OpType::Intersect ? 0 : 1;
const int c2 = op == OpType::Add ? 1 : 0;
const int c3 = op == OpType::Intersect ? 1 : -1;
+ // Sub-Boolean progress accounting. `phase()` advances `donePhases` by 1
+ // and checks cancel; `balance` (declared just below) tops up `donePhases`
+ // to `kPhasesPerBoolean` on any non-cancelled return so `Progress()`
+ // reaches 1.0 even after early-exit paths (status errors, empty/degenerate
+ // inputs) that skip most or all of the phase sites.
+ struct PhaseBalance {
+ ExecutionContext::Impl* ctx;
+ int published = 0;
+ bool fullPath = false;
+ ~PhaseBalance() {
+ if (!ctx) return;
+ if (IsCancelled(ctx)) return; // partial publication is intentional
+ if (fullPath) {
+ DEBUG_ASSERT(published == kPhasesPerBoolean, logicErr,
+ "Boolean3::Result phase count drift; "
+ "update kPhasesPerBoolean to match phase() site count");
+ return;
+ }
+ if (published < kPhasesPerBoolean) {
+ ctx->donePhases.fetch_add(kPhasesPerBoolean - published,
+ std::memory_order_relaxed);
+ }
+ }
+ };
+ PhaseBalance balance{ctx_};
+
if (inP_.status_ != Manifold::Error::NoError) {
auto impl = Manifold::Impl();
impl.status_ = inP_.status_;
@@ -734,6 +755,26 @@ Manifold::Impl Boolean3::Result(OpType op) const {
return inP_;
}
+ auto phase = [&](int line) -> std::optional<Manifold::Impl> {
+ if (ctx_) ctx_->donePhases.fetch_add(1, std::memory_order_relaxed);
+ ++balance.published;
+ if (IsCancelled(ctx_)) {
+ auto impl = Manifold::Impl();
+ impl.status_ = Manifold::Error::Cancelled;
+ return impl;
+ }
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ // Record this boundary against the per-Result baseline; `line` is the call
+ // site so each phase reports its own location (the lambda body has one).
+ if (ctx_) RecordPhase(phaseTiming, balance.published, __FILE__, line);
+#endif
+ return std::nullopt;
+ };
+
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
+ if (auto c = phase(__LINE__)) return *c;
+
if (!valid) {
auto impl = Manifold::Impl();
impl.status_ = Manifold::Error::ResultTooLarge;
@@ -743,14 +784,14 @@ Manifold::Impl Boolean3::Result(OpType op) const {
const bool invertQ = op == OpType::Subtract;
// Convert winding numbers to inclusion values based on operation type.
- Vec<int> i12(x12_.size());
- Vec<int> i21(x21_.size());
+ Vec<int> i12(xv12_.x12.size());
+ Vec<int> i21(xv21_.x12.size());
Vec<int> i03(w03_.size());
Vec<int> i30(w30_.size());
- transform(x12_.begin(), x12_.end(), i12.begin(),
+ transform(xv12_.x12.begin(), xv12_.x12.end(), i12.begin(),
[c3](int v) { return c3 * v; });
- transform(x21_.begin(), x21_.end(), i21.begin(),
+ transform(xv21_.x12.begin(), xv21_.x12.end(), i21.begin(),
[c3](int v) { return c3 * v; });
transform(w03_.begin(), w03_.end(), i03.begin(),
[c1, c3](int v) { return c1 + c3 * v; });
@@ -767,15 +808,15 @@ Manifold::Impl Boolean3::Result(OpType op) const {
numVertR = AbsSum()(vQ2R.back(), i30.back());
const int nQv = numVertR - nPv;
- Vec<int> v12R(v12_.size());
- if (v12_.size() > 0) {
+ Vec<int> v12R(xv12_.v12.size());
+ if (xv12_.v12.size() > 0) {
exclusive_scan(i12.begin(), i12.end(), v12R.begin(), numVertR, AbsSum());
numVertR = AbsSum()(v12R.back(), i12.back());
}
const int n12 = numVertR - nPv - nQv;
- Vec<int> v21R(v21_.size());
- if (v21_.size() > 0) {
+ Vec<int> v21R(xv21_.v12.size());
+ if (xv21_.v12.size() > 0) {
exclusive_scan(i21.begin(), i21.end(), v21R.begin(), numVertR, AbsSum());
numVertR = AbsSum()(v21R.back(), i21.back());
}
@@ -784,7 +825,9 @@ Manifold::Impl Boolean3::Result(OpType op) const {
// Create the output Manifold
Manifold::Impl outR;
- if (numVertR == 0) return outR;
+ if (numVertR == 0) {
+ return outR;
+ }
outR.epsilon_ = std::max(inP_.epsilon_, inQ_.epsilon_);
outR.tolerance_ = std::max(inP_.tolerance_, inQ_.tolerance_);
@@ -792,15 +835,16 @@ Manifold::Impl Boolean3::Result(OpType op) const {
outR.vertPos_.resize_nofill(numVertR);
// Add vertices, duplicating for inclusion numbers not in [-1, 1].
// Retained vertices from P and Q:
- for_each_n(autoPolicy(inP_.NumVert(), 1e4), countAt(0), inP_.NumVert(),
+ for_each_n(autoPolicy(inP_.NumVert(), 1e4), countAt(0), inP_.NumVert(), ctx_,
DuplicateVerts({outR.vertPos_, i03, vP2R, inP_.vertPos_}));
- for_each_n(autoPolicy(inQ_.NumVert(), 1e4), countAt(0), inQ_.NumVert(),
+ for_each_n(autoPolicy(inQ_.NumVert(), 1e4), countAt(0), inQ_.NumVert(), ctx_,
DuplicateVerts({outR.vertPos_, i30, vQ2R, inQ_.vertPos_}));
// New vertices created from intersections:
- for_each_n(autoPolicy(i12.size(), 1e4), countAt(0), i12.size(),
- DuplicateVerts({outR.vertPos_, i12, v12R, v12_}));
- for_each_n(autoPolicy(i21.size(), 1e4), countAt(0), i21.size(),
- DuplicateVerts({outR.vertPos_, i21, v21R, v21_}));
+ for_each_n(autoPolicy(i12.size(), 1e4), countAt(0), i12.size(), ctx_,
+ DuplicateVerts({outR.vertPos_, i12, v12R, xv12_.v12}));
+ for_each_n(autoPolicy(i21.size(), 1e4), countAt(0), i21.size(), ctx_,
+ DuplicateVerts({outR.vertPos_, i21, v21R, xv21_.v12}));
+ if (auto c = phase(__LINE__)) return *c;
PRINT(nPv << " verts from inP");
PRINT(nQv << " verts from inQ");
@@ -818,9 +862,11 @@ Manifold::Impl Boolean3::Result(OpType op) const {
// This key is the face index of <P, Q>
concurrent_map<std::pair<int, int>, std::vector<EdgePos>> edgesNew;
- AddNewEdgeVerts(edgesP, edgesNew, p1q2_, i12, v12R, inP_.halfedge_, true, 0);
- AddNewEdgeVerts(edgesQ, edgesNew, p2q1_, i21, v21R, inQ_.halfedge_, false,
- p1q2_.size());
+ AddNewEdgeVerts(edgesP, edgesNew, xv12_.p1q2, i12, v12R, inP_.halfedge_, true,
+ 0, ctx_);
+ AddNewEdgeVerts(edgesQ, edgesNew, xv21_.p1q2, i21, v21R, inQ_.halfedge_,
+ false, xv12_.p1q2.size(), ctx_);
+ if (auto c = phase(__LINE__)) return *c;
v12R.clear();
v21R.clear();
@@ -829,7 +875,9 @@ Manifold::Impl Boolean3::Result(OpType op) const {
Vec<int> faceEdge;
Vec<int> facePQ2R;
std::tie(faceEdge, facePQ2R) =
- SizeOutput(outR, inP_, inQ_, i03, i30, i12, i21, p1q2_, p2q1_, invertQ);
+ SizeOutput(outR, inP_, inQ_, i03, i30, i12, i21, xv12_.p1q2, xv21_.p1q2,
+ invertQ, ctx_);
+ if (auto c = phase(__LINE__)) return *c;
i12.clear();
i21.clear();
@@ -842,25 +890,36 @@ Manifold::Impl Boolean3::Result(OpType op) const {
Vec<char> wholeHalfedgeQ(inQ_.halfedge_.size(), true);
// The halfedgeRef contains the data that will become triRef once the faces
// are triangulated.
- Vec<TriRef> halfedgeRef(2 * outR.NumEdge());
-
- AppendPartialEdges(outR, wholeHalfedgeP, facePtrR, edgesP, halfedgeRef, inP_,
- i03, vP2R, facePQ2R.begin(), true);
- AppendPartialEdges(outR, wholeHalfedgeQ, facePtrR, edgesQ, halfedgeRef, inQ_,
- i30, vQ2R, facePQ2R.begin() + inP_.NumTri(), false);
+ Vec<TriRef> halfedgeRef(faceEdge.back());
+ // Note that we are working with Vec<Halfedge> instead of Halfedges here,
+ // since the faces can be arbitrary polygons before feeding into the
+ // triangulator.
+ Vec<Halfedge> faceHalfedges(faceEdge.back());
+
+ AppendPartialEdges(outR, faceHalfedges, wholeHalfedgeP, facePtrR, edgesP,
+ halfedgeRef, inP_, i03, vP2R, facePQ2R.begin(), true,
+ ctx_);
+ AppendPartialEdges(outR, faceHalfedges, wholeHalfedgeQ, facePtrR, edgesQ,
+ halfedgeRef, inQ_, i30, vQ2R,
+ facePQ2R.begin() + inP_.NumTri(), false, ctx_);
+ if (auto c = phase(__LINE__)) return *c;
edgesP.clear();
edgesQ.clear();
- AppendNewEdges(outR, facePtrR, edgesNew, halfedgeRef, facePQ2R,
- inP_.NumTri());
+ AppendNewEdges(outR, faceHalfedges, facePtrR, edgesNew, halfedgeRef, facePQ2R,
+ inP_.NumTri(), ctx_);
+ if (auto c = phase(__LINE__)) return *c;
edgesNew.clear();
- AppendWholeEdges(outR, facePtrR, halfedgeRef, inP_, wholeHalfedgeP, i03, vP2R,
- facePQ2R.cview(0, inP_.NumTri()), true);
- AppendWholeEdges(outR, facePtrR, halfedgeRef, inQ_, wholeHalfedgeQ, i30, vQ2R,
- facePQ2R.cview(inP_.NumTri(), inQ_.NumTri()), false);
+ AppendWholeEdges(outR, facePtrR, faceHalfedges, halfedgeRef, inP_,
+ wholeHalfedgeP, i03, vP2R, facePQ2R.cview(0, inP_.NumTri()),
+ true, ctx_);
+ AppendWholeEdges(outR, facePtrR, faceHalfedges, halfedgeRef, inQ_,
+ wholeHalfedgeQ, i30, vQ2R,
+ facePQ2R.cview(inP_.NumTri(), inQ_.NumTri()), false, ctx_);
+ if (auto c = phase(__LINE__)) return *c;
wholeHalfedgeP.clear();
wholeHalfedgeQ.clear();
@@ -871,32 +930,25 @@ Manifold::Impl Boolean3::Result(OpType op) const {
vP2R.clear();
vQ2R.clear();
-#ifdef MANIFOLD_DEBUG
- assemble.Stop();
- Timer triangulate;
- triangulate.Start();
-#endif
-
// Level 6
- outR.Face2Tri(faceEdge, halfedgeRef);
+ outR.Face2Tri(faceEdge, faceHalfedges, halfedgeRef, /*allowConvex=*/false,
+ ctx_);
halfedgeRef.clear();
+ faceHalfedges.clear();
faceEdge.clear();
- ReorderHalfedges(outR.halfedge_);
-
-#ifdef MANIFOLD_DEBUG
- triangulate.Stop();
- Timer simplify;
- simplify.Start();
-#endif
+ outR.ReorderHalfedges(ctx_);
+ if (auto c = phase(__LINE__)) return *c;
if (ManifoldParams().intermediateChecks)
DEBUG_ASSERT(outR.IsManifold(), logicErr,
"triangulated mesh is not manifold!");
- CreateProperties(outR, inP_, inQ_);
+ CreateProperties(outR, inP_, inQ_, invertQ, ctx_);
+ if (auto c = phase(__LINE__)) return *c;
- UpdateReference(outR, inP_, inQ_, invertQ);
+ UpdateReference(outR, inP_, inQ_, invertQ, ctx_);
+ if (auto c = phase(__LINE__)) return *c;
outR.SimplifyTopology(nPv + nQv);
outR.RemoveUnreferencedVerts();
@@ -905,27 +957,22 @@ Manifold::Impl Boolean3::Result(OpType op) const {
DEBUG_ASSERT(outR.Is2Manifold(), logicErr,
"simplified mesh is not 2-manifold!");
-#ifdef MANIFOLD_DEBUG
- simplify.Stop();
- Timer sort;
- sort.Start();
-#endif
-
- outR.Finish();
+ outR.CalculateBBox();
+ outR.SortGeometry(ctx_);
outR.IncrementMeshIDs();
-
-#ifdef MANIFOLD_DEBUG
- sort.Stop();
- if (ManifoldParams().verbose) {
- assemble.Print("Assembly");
- triangulate.Print("Triangulation");
- simplify.Print("Simplification");
- sort.Print("Sorting");
- std::cout << outR.NumVert() << " verts and " << outR.NumTri() << " tris"
- << std::endl;
+ if (auto c = phase(__LINE__)) return *c;
+
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ // Per-stage timing now comes from the phase() boundaries above (verbose >= 2,
+ // ctx attached); this keeps the result-size summary, tagged with the same uid
+ // so it groups with this boolean's phase lines.
+ if (ManifoldParams().verbose >= 2) {
+ std::cout << " [b" << phaseTiming.uid << "] " << outR.NumVert()
+ << " verts and " << outR.NumTri() << " tris" << std::endl;
}
#endif
+ balance.fullPath = true;
return outR;
}
diff --git a/thirdparty/manifold/src/collider.h b/thirdparty/manifold/src/collider.h
index 4c02b98033a..da3834ed6fd 100644
--- a/thirdparty/manifold/src/collider.h
+++ b/thirdparty/manifold/src/collider.h
@@ -13,6 +13,7 @@
// limitations under the License.
#pragma once
+#include "execution_impl.h"
#include "manifold/common.h"
#include "parallel.h"
#include "utils.h"
@@ -166,8 +167,10 @@ struct FindCollision {
using Local = typename Recorder::Local;
- inline int RecordCollision(int node, const int queryIdx, Local& local) {
- bool overlaps = nodeBBox_[node].DoesOverlap(f(queryIdx));
+ inline int RecordCollision(std::invoke_result_t<F, const int> query, int node,
+ const int queryIdx, Local& local) {
+ auto box = nodeBBox_[node];
+ bool overlaps = box.DoesOverlap(query);
if (overlaps && IsLeaf(node)) {
int leafIdx = Node2Leaf(node);
if (!selfCollision || leafIdx != queryIdx) {
@@ -178,6 +181,13 @@ struct FindCollision {
}
void operator()(const int queryIdx) {
+ auto query = f(queryIdx);
+
+ // early exit for empty boxes
+ if constexpr (std::is_same_v<std::remove_cv_t<decltype(query)>, Box>) {
+ if (query.min.x == std::numeric_limits<double>::infinity()) return;
+ }
+
// stack cannot overflow because radix tree has max depth 30 (Morton code) +
// 32 (index).
int stack[64];
@@ -190,8 +200,8 @@ struct FindCollision {
int child1 = internalChildren_[internal].first;
int child2 = internalChildren_[internal].second;
- int traverse1 = RecordCollision(child1, queryIdx, local);
- int traverse2 = RecordCollision(child2, queryIdx, local);
+ int traverse1 = RecordCollision(query, child1, queryIdx, local);
+ int traverse2 = RecordCollision(query, child2, queryIdx, local);
if (!traverse1 && !traverse2) {
if (top < 0) break; // done
@@ -224,11 +234,6 @@ struct BuildInternalBoxes {
}
};
-struct TransformBox {
- const mat3x4 transform;
- void operator()(Box& box) { box = box.Transform(transform); }
-};
-
constexpr inline uint32_t SpreadBits3(uint32_t v) {
v = 0xFF0000FFu & (v * 0x00010001u);
v = 0x0F00F00Fu & (v * 0x00000101u);
@@ -264,6 +269,7 @@ class Collider {
ZoneScoped;
DEBUG_ASSERT(leafBB.size() == leafMorton.size(), userErr,
"vectors must be the same length");
+ if (leafBB.size() == 0) return;
int num_nodes = 2 * leafBB.size() - 1;
// assign and allocate members
nodeBBox_.resize_nofill(num_nodes);
@@ -276,22 +282,9 @@ class Collider {
UpdateBoxes(leafBB);
}
- bool Transform(mat3x4 transform) {
- ZoneScoped;
- bool axisAligned = true;
- for (int row : {0, 1, 2}) {
- int count = 0;
- for (int col : {0, 1, 2}) {
- if (transform[col][row] == 0.0) ++count;
- }
- if (count != 2) axisAligned = false;
- }
- if (axisAligned) {
- for_each(autoPolicy(nodeBBox_.size(), 1e5), nodeBBox_.begin(),
- nodeBBox_.end(),
- [transform](Box& box) { box = box.Transform(transform); });
- }
- return axisAligned;
+ Box GetBoundingBox() const {
+ if (nodeBBox_.empty()) return Box();
+ return nodeBBox_[collider_internal::Internal2Node(0)];
}
void UpdateBoxes(const VecView<const Box>& leafBB) {
@@ -309,42 +302,46 @@ class Collider {
{nodeBBox_, counter, nodeParent_, internalChildren_}));
}
- // This function iterates over queriesIn and calls recorder.record(queryIdx,
- // leafIdx, local) for each collision it found.
- // If selfCollisionl is true, it will skip the case where queryIdx == leafIdx.
- // The recorder should provide a local() method that returns a Recorder::Local
- // type, representing thread local storage. By default, recorder.record can
- // run in parallel and the thread local storage can be combined at the end.
- // If parallel is false, the function will run in sequential mode.
- //
- // If thread local storage is not needed, use SimpleRecorder.
- template <const bool selfCollision = false, typename T, typename Recorder>
- void Collisions(const VecView<const T>& queriesIn, Recorder& recorder,
- bool parallel = true) const {
+ void Transform(const mat3x4& transform) {
ZoneScoped;
- using collider_internal::FindCollision;
- if (internalChildren_.empty()) return;
- auto f = [queriesIn](const int i) { return queriesIn[i]; };
- for_each_n(parallel ? autoPolicy(queriesIn.size(),
- collider_internal::kSequentialThreshold)
- : ExecutionPolicy::Seq,
- countAt(0), queriesIn.size(),
- FindCollision<decltype(f), selfCollision, Recorder>{
- f, nodeBBox_, internalChildren_, recorder});
+ DEBUG_ASSERT(IsAxisAligned(transform), userErr,
+ "transform must be axis-aligned");
+ for_each(autoPolicy(nodeBBox_.size()), countAt(0_uz),
+ countAt(nodeBBox_.size()), [&transform, this](size_t i) {
+ nodeBBox_[i] = nodeBBox_[i].Transform(transform);
+ });
}
template <const bool selfCollision = false, typename F, typename Recorder>
- void Collisions(F f, int n, Recorder& recorder, bool parallel = true) const {
+ void Collisions(Recorder& recorder, F f, int n, bool parallel = true,
+ ExecutionContext::Impl* ctx = nullptr) const {
ZoneScoped;
using collider_internal::FindCollision;
if (internalChildren_.empty()) return;
for_each_n(parallel ? autoPolicy(n, collider_internal::kSequentialThreshold)
: ExecutionPolicy::Seq,
- countAt(0), n,
+ countAt(0), n, ctx,
FindCollision<decltype(f), selfCollision, Recorder>{
f, nodeBBox_, internalChildren_, recorder});
}
+ // This function iterates over queriesIn and calls recorder.record(queryIdx,
+ // leafIdx, local) for each collision it found.
+ // If selfCollisionl is true, it will skip the case where queryIdx == leafIdx.
+ // The recorder should provide a local() method that returns a Recorder::Local
+ // type, representing thread local storage. By default, recorder.record can
+ // run in parallel and the thread local storage can be combined at the end.
+ // If parallel is false, the function will run in sequential mode.
+ //
+ // If thread local storage is not needed, use SimpleRecorder.
+ template <const bool selfCollision = false, typename T, typename Recorder>
+ void Collisions(Recorder& recorder, const VecView<const T>& queriesIn,
+ bool parallel = true,
+ ExecutionContext::Impl* ctx = nullptr) const {
+ auto f = [queriesIn](const int i) { return queriesIn[i]; };
+ Collisions<selfCollision>(recorder, f, queriesIn.size(), parallel, ctx);
+ }
+
static uint32_t MortonCode(vec3 position, Box bBox) {
using collider_internal::SpreadBits3;
vec3 xyz = (position - bBox.min) / (bBox.max - bBox.min);
@@ -355,6 +352,17 @@ class Collider {
return x * 4 + y * 2 + z;
}
+ static bool IsAxisAligned(const mat3x4& transform) {
+ for (int row : {0, 1, 2}) {
+ int count = 0;
+ for (int col : {0, 1, 2}) {
+ if (transform[col][row] == 0.0) ++count;
+ }
+ if (count != 2) return false;
+ }
+ return true;
+ }
+
private:
Vec<Box> nodeBBox_;
Vec<int> nodeParent_;
diff --git a/thirdparty/manifold/src/constructors.cpp b/thirdparty/manifold/src/constructors.cpp
index c7c2aacd5ac..d94f9cb685a 100644
--- a/thirdparty/manifold/src/constructors.cpp
+++ b/thirdparty/manifold/src/constructors.cpp
@@ -1,4 +1,4 @@
-// Copyright 2021 The Manifold Authors.
+// Copyright 2026 The Manifold Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -19,38 +19,6 @@
#include "manifold/polygon.h"
#include "parallel.h"
-namespace {
-using namespace manifold;
-
-template <typename P, typename I>
-std::shared_ptr<Manifold::Impl> SmoothImpl(
- const MeshGLP<P, I>& meshGL,
- const std::vector<Smoothness>& sharpenedEdges) {
- DEBUG_ASSERT(meshGL.halfedgeTangent.empty(), std::runtime_error,
- "when supplying tangents, the normal constructor should be used "
- "rather than Smooth().");
-
- MeshGLP<P, I> meshTmp = meshGL;
- meshTmp.faceID.resize(meshGL.NumTri());
- std::iota(meshTmp.faceID.begin(), meshTmp.faceID.end(), 0);
-
- std::shared_ptr<Manifold::Impl> impl =
- std::make_shared<Manifold::Impl>(meshTmp);
- impl->CreateTangents(impl->UpdateSharpenedEdges(sharpenedEdges));
- // Restore the original faceID
- const size_t numTri = impl->NumTri();
- for (size_t i = 0; i < numTri; ++i) {
- if (meshGL.faceID.size() == numTri) {
- impl->meshRelation_.triRef[i].faceID =
- meshGL.faceID[impl->meshRelation_.triRef[i].faceID];
- } else {
- impl->meshRelation_.triRef[i].faceID = -1;
- }
- }
- return impl;
-}
-} // namespace
-
namespace manifold {
/**
* Constructs a smooth version of the input mesh by creating tangents; this
@@ -82,7 +50,7 @@ namespace manifold {
*/
Manifold Manifold::Smooth(const MeshGL& meshGL,
const std::vector<Smoothness>& sharpenedEdges) {
- return Manifold(SmoothImpl(meshGL, sharpenedEdges));
+ return Manifold(MakeSmoothImpl(meshGL, sharpenedEdges));
}
/**
@@ -115,7 +83,7 @@ Manifold Manifold::Smooth(const MeshGL& meshGL,
*/
Manifold Manifold::Smooth(const MeshGL64& meshGL64,
const std::vector<Smoothness>& sharpenedEdges) {
- return Manifold(SmoothImpl(meshGL64, sharpenedEdges));
+ return Manifold(MakeSmoothImpl(meshGL64, sharpenedEdges));
}
/**
@@ -148,7 +116,8 @@ Manifold Manifold::Cube(vec3 size, bool center) {
* form cones if both radii are specified.
*
* @param height Z-extent
- * @param radiusLow Radius of bottom circle. Must be positive.
+ * @param radiusLow Radius of bottom circle. Must be non-negative. If zero,
+ * radiusHigh must be positive and a cone with apex at the bottom is created.
* @param radiusHigh Radius of top circle. Can equal zero. Default is equal to
* radiusLow.
* @param circularSegments How many line segments to use around the circle.
@@ -158,9 +127,20 @@ Manifold Manifold::Cube(vec3 size, bool center) {
*/
Manifold Manifold::Cylinder(double height, double radiusLow, double radiusHigh,
int circularSegments, bool center) {
- if (height <= 0.0 || radiusLow <= 0.0) {
+ if (height <= 0.0 || radiusLow < 0.0) {
return Invalid();
}
+ if (radiusLow == 0.0) {
+ if (radiusHigh <= 0.0) {
+ return Invalid();
+ }
+ // Cone with apex at bottom: create the centered apex-at-top version and
+ // mirror it
+ Manifold cone = Cylinder(height, radiusHigh, 0.0, circularSegments, true);
+ cone = cone.Mirror(vec3(0.0, 0.0, 1.0));
+ if (!center) cone = cone.Translate(vec3(0.0, 0.0, height / 2.0));
+ return cone.AsOriginal();
+ }
const double scale = radiusHigh >= 0.0 ? radiusHigh / radiusLow : 1.0;
const double radius = fmax(radiusLow, radiusHigh);
const int n = circularSegments > 2 ? circularSegments
@@ -198,13 +178,18 @@ Manifold Manifold::Sphere(double radius, int circularSegments) {
pImpl_->Subdivide([n](vec3, vec4, vec4) { return n - 1; });
for_each_n(autoPolicy(pImpl_->NumVert(), 1e5), pImpl_->vertPos_.begin(),
pImpl_->NumVert(), [radius](vec3& v) {
- v = la::cos(kHalfPi * (1.0 - v));
+ v = vec3(la::cos(kHalfPi * (1.0 - v.x)),
+ la::cos(kHalfPi * (1.0 - v.y)),
+ la::cos(kHalfPi * (1.0 - v.z)));
v = radius * la::normalize(v);
if (std::isnan(v.x)) v = vec3(0.0);
});
- pImpl_->Finish();
// Ignore preceding octahedron.
pImpl_->InitializeOriginal();
+ pImpl_->CalculateBBox();
+ pImpl_->SetEpsilon();
+ pImpl_->SortGeometry();
+ pImpl_->SetNormalsAndCoplanar();
return Manifold(pImpl_);
}
@@ -296,9 +281,11 @@ Manifold Manifold::Extrude(const Polygons& crossSection, double height,
}
pImpl_->CreateHalfedges(triVertsDH);
- pImpl_->Finish();
pImpl_->InitializeOriginal();
- pImpl_->MarkCoplanar();
+ pImpl_->CalculateBBox();
+ pImpl_->SetEpsilon();
+ pImpl_->SortGeometry();
+ pImpl_->SetNormalsAndCoplanar();
return Manifold(pImpl_);
}
@@ -439,13 +426,17 @@ Manifold Manifold::Revolve(const Polygons& crossSection, int circularSegments,
}
pImpl_->CreateHalfedges(triVertsDH);
- pImpl_->Finish();
pImpl_->InitializeOriginal();
- pImpl_->MarkCoplanar();
+ pImpl_->CalculateBBox();
+ pImpl_->SetEpsilon();
+ pImpl_->SortGeometry();
+ pImpl_->SetNormalsAndCoplanar();
return Manifold(pImpl_);
}
/**
+ * Deprecated: Use BatchBoolean with OpType::Add instead.
+ *
* Constructs a new manifold from a vector of other manifolds. This is a purely
* topological operation, so care should be taken to avoid creating
* overlapping results. It is the inverse operation of Decompose().
@@ -453,11 +444,7 @@ Manifold Manifold::Revolve(const Polygons& crossSection, int circularSegments,
* @param manifolds A vector of Manifolds to lazy-union together.
*/
Manifold Manifold::Compose(const std::vector<Manifold>& manifolds) {
- std::vector<std::shared_ptr<CsgLeafNode>> children;
- for (const auto& manifold : manifolds) {
- children.push_back(manifold.pNode_->ToLeafNode());
- }
- return Manifold(CsgLeafNode::Compose(children));
+ return BatchBoolean(manifolds, OpType::Add);
}
/**
@@ -467,11 +454,15 @@ Manifold Manifold::Compose(const std::vector<Manifold>& manifolds) {
*/
std::vector<Manifold> Manifold::Decompose() const {
ZoneScoped;
- DisjointSets uf(NumVert());
- // Graph graph;
auto pImpl_ = GetCsgLeafNode().GetImpl();
- for (const Halfedge& halfedge : pImpl_->halfedge_) {
- if (halfedge.IsForward()) uf.unite(halfedge.startVert, halfedge.endVert);
+ if (pImpl_->status_ != Error::NoError) {
+ return {PropagateStatus(pImpl_->status_)};
+ }
+ DisjointSets uf(NumVert());
+ for (size_t edge = 0; edge < pImpl_->halfedge_.size(); ++edge) {
+ if (pImpl_->halfedge_.IsForward(edge)) {
+ uf.unite(pImpl_->halfedge_.Start(edge), pImpl_->halfedge_.End(edge));
+ }
}
std::vector<int> componentIndices;
const int numComponents = uf.connectedComponents(componentIndices);
@@ -497,25 +488,28 @@ std::vector<Manifold> Manifold::Decompose() const {
[i, &vertLabel](int v) { return vertLabel[v] == i; }) -
vertNew2Old.begin();
impl->vertPos_.resize(nVert);
+ impl->vertNormal_.resize(nVert);
vertNew2Old.resize(nVert);
gather(vertNew2Old.begin(), vertNew2Old.end(), pImpl_->vertPos_.begin(),
impl->vertPos_.begin());
+ gather(vertNew2Old.begin(), vertNew2Old.end(), pImpl_->vertNormal_.begin(),
+ impl->vertNormal_.begin());
- Vec<int> faceNew2Old(NumTri());
+ Vec<int> faceNew2Old;
+ faceNew2Old.reserve(NumTri());
const auto& halfedge = pImpl_->halfedge_;
- const int nFace =
- copy_if(countAt(0_uz), countAt(NumTri()), faceNew2Old.begin(),
- [i, &vertLabel, &halfedge](int face) {
- return vertLabel[halfedge[3 * face].startVert] == i;
- }) -
- faceNew2Old.begin();
+ for (size_t face = 0; face < NumTri(); ++face) {
+ if (vertLabel[halfedge.Start(static_cast<int>(3 * face))] == i) {
+ faceNew2Old.push_back(static_cast<int>(face));
+ }
+ }
- if (nFace == 0) continue;
- faceNew2Old.resize(nFace);
+ if (faceNew2Old.empty()) continue;
impl->GatherFaces(*pImpl_, faceNew2Old);
impl->ReindexVerts(vertNew2Old, pImpl_->NumVert());
- impl->Finish();
+ impl->CalculateBBox();
+ impl->SortGeometry();
meshes.push_back(Manifold(impl));
}
diff --git a/thirdparty/manifold/src/cross_section/cross_section.cpp b/thirdparty/manifold/src/cross_section/cross_section.cpp
index 5864806c6fc..68d875901c4 100644
--- a/thirdparty/manifold/src/cross_section/cross_section.cpp
+++ b/thirdparty/manifold/src/cross_section/cross_section.cpp
@@ -228,12 +228,14 @@ CrossSection& CrossSection::operator=(CrossSection&&) noexcept = default;
* const methods.
*/
CrossSection::CrossSection(const CrossSection& other) {
+ std::lock_guard<std::mutex> lock(*other.pathsMutex_);
paths_ = other.paths_;
transform_ = other.transform_;
}
CrossSection& CrossSection::operator=(const CrossSection& other) {
if (this != &other) {
+ std::scoped_lock lock(*pathsMutex_, *other.pathsMutex_);
paths_ = other.paths_;
transform_ = other.transform_;
}
@@ -295,6 +297,7 @@ CrossSection::CrossSection(const Rect& rect) {
// All access to paths_ should be done through the GetPaths() method, which
// applies the accumulated transform_
std::shared_ptr<const PathImpl> CrossSection::GetPaths() const {
+ std::lock_guard<std::mutex> lock(*pathsMutex_);
if (transform_ == mat2x3(la::identity)) {
return paths_;
}
@@ -556,6 +559,7 @@ CrossSection CrossSection::Mirror(const vec2 ax) const {
* @param m The affine transform matrix to apply to all the vertices.
*/
CrossSection CrossSection::Transform(const mat2x3& m) const {
+ std::lock_guard<std::mutex> lock(*pathsMutex_);
auto transformed = CrossSection();
transformed.transform_ = m * Mat3(transform_);
transformed.paths_ = paths_;
@@ -678,7 +682,7 @@ CrossSection CrossSection::Offset(double delta, JoinType jointype,
// (radius) in order to get back the same number of segments in Clipper2:
// steps_per_360 = PI / acos(1 - arc_tol / abs_delta)
const double abs_delta = std::fabs(delta);
- arc_tol = (std::cos(Clipper2Lib::PI / n) - 1) * -abs_delta;
+ arc_tol = (math::cos(Clipper2Lib::PI / n) - 1) * -abs_delta;
}
auto ps =
C2::InflatePaths(GetPaths()->paths_, delta, jt(jointype),
diff --git a/thirdparty/manifold/src/cross_section/cross_section_boolean2.cpp b/thirdparty/manifold/src/cross_section/cross_section_boolean2.cpp
new file mode 100644
index 00000000000..1091555dc19
--- /dev/null
+++ b/thirdparty/manifold/src/cross_section/cross_section_boolean2.cpp
@@ -0,0 +1,225 @@
+// Copyright 2026 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "manifold/cross_section.h"
+
+// Temporary backend-selection placeholder. The boolean2 implementation lands
+// in the follow-up backend PR; this file intentionally returns empty
+// CrossSection results so the staged backend cannot appear partially correct.
+
+using namespace manifold;
+
+namespace manifold {
+struct PathImpl {
+ PathImpl(Polygons paths) : paths_(std::move(paths)) {}
+ operator const Polygons&() const { return paths_; }
+ const Polygons paths_;
+};
+} // namespace manifold
+
+namespace {
+std::shared_ptr<const PathImpl> empty_paths() {
+ return std::make_shared<const PathImpl>(Polygons{});
+}
+} // namespace
+
+namespace manifold {
+
+CrossSection::CrossSection() : paths_(empty_paths()) {}
+
+CrossSection::~CrossSection() = default;
+CrossSection::CrossSection(CrossSection&&) noexcept = default;
+CrossSection& CrossSection::operator=(CrossSection&&) noexcept = default;
+
+CrossSection::CrossSection(const CrossSection& other) {
+ (void)other;
+ paths_ = empty_paths();
+}
+
+CrossSection& CrossSection::operator=(const CrossSection& other) {
+ (void)other;
+ paths_ = empty_paths();
+ transform_ = la::identity;
+ return *this;
+}
+
+CrossSection::CrossSection(std::shared_ptr<const PathImpl> paths)
+ : paths_(empty_paths()) {
+ (void)paths;
+}
+
+CrossSection::CrossSection(const SimplePolygon& contour, FillRule fillrule) {
+ (void)contour;
+ (void)fillrule;
+ paths_ = empty_paths();
+}
+
+CrossSection::CrossSection(const Polygons& contours, FillRule fillrule) {
+ (void)contours;
+ (void)fillrule;
+ paths_ = empty_paths();
+}
+
+CrossSection::CrossSection(const Rect& rect) {
+ (void)rect;
+ paths_ = empty_paths();
+}
+
+std::shared_ptr<const PathImpl> CrossSection::GetPaths() const {
+ std::lock_guard<std::mutex> lock(*pathsMutex_);
+ return paths_;
+}
+
+CrossSection CrossSection::Square(const vec2 size, bool center) {
+ (void)size;
+ (void)center;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Circle(double radius, int circularSegments) {
+ (void)radius;
+ (void)circularSegments;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Boolean(const CrossSection& second,
+ OpType op) const {
+ (void)second;
+ (void)op;
+ return CrossSection();
+}
+
+CrossSection CrossSection::BatchBoolean(
+ const std::vector<CrossSection>& crossSections, OpType op) {
+ (void)crossSections;
+ (void)op;
+ return CrossSection();
+}
+
+CrossSection CrossSection::operator+(const CrossSection& other) const {
+ return Boolean(other, OpType::Add);
+}
+
+CrossSection& CrossSection::operator+=(const CrossSection& other) {
+ *this = *this + other;
+ return *this;
+}
+
+CrossSection CrossSection::operator-(const CrossSection& other) const {
+ return Boolean(other, OpType::Subtract);
+}
+
+CrossSection& CrossSection::operator-=(const CrossSection& other) {
+ *this = *this - other;
+ return *this;
+}
+
+CrossSection CrossSection::operator^(const CrossSection& other) const {
+ return Boolean(other, OpType::Intersect);
+}
+
+CrossSection& CrossSection::operator^=(const CrossSection& other) {
+ *this = *this ^ other;
+ return *this;
+}
+
+CrossSection CrossSection::Compose(
+ const std::vector<CrossSection>& crossSections) {
+ (void)crossSections;
+ return CrossSection();
+}
+
+std::vector<CrossSection> CrossSection::Decompose() const { return {}; }
+
+CrossSection CrossSection::Translate(const vec2 v) const {
+ (void)v;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Rotate(double degrees) const {
+ (void)degrees;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Scale(const vec2 scale) const {
+ (void)scale;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Mirror(const vec2 ax) const {
+ (void)ax;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Transform(const mat2x3& m) const {
+ (void)m;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Warp(std::function<void(vec2&)> warpFunc) const {
+ (void)warpFunc;
+ return CrossSection();
+}
+
+CrossSection CrossSection::WarpBatch(
+ std::function<void(VecView<vec2>)> warpFunc) const {
+ (void)warpFunc;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Simplify(double epsilon) const {
+ (void)epsilon;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Offset(double delta, JoinType jt, double miterLimit,
+ int circularSegments) const {
+ (void)delta;
+ (void)jt;
+ (void)miterLimit;
+ (void)circularSegments;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Hull(
+ const std::vector<CrossSection>& crossSections) {
+ (void)crossSections;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Hull() const { return CrossSection(); }
+
+CrossSection CrossSection::Hull(SimplePolygon pts) {
+ (void)pts;
+ return CrossSection();
+}
+
+CrossSection CrossSection::Hull(const Polygons polys) {
+ (void)polys;
+ return CrossSection();
+}
+
+double CrossSection::Area() const { return 0.0; }
+
+size_t CrossSection::NumVert() const { return 0; }
+
+size_t CrossSection::NumContour() const { return 0; }
+
+bool CrossSection::IsEmpty() const { return true; }
+
+Rect CrossSection::Bounds() const { return {}; }
+
+Polygons CrossSection::ToPolygons() const { return {}; }
+
+} // namespace manifold
diff --git a/thirdparty/manifold/src/csg_tree.cpp b/thirdparty/manifold/src/csg_tree.cpp
index 35585a6103f..78417dea1bc 100644
--- a/thirdparty/manifold/src/csg_tree.cpp
+++ b/thirdparty/manifold/src/csg_tree.cpp
@@ -17,19 +17,27 @@
#endif
#include <algorithm>
+#include <cstdint>
#include "boolean3.h"
#include "csg_tree.h"
+#include "execution_impl.h"
#include "impl.h"
#include "mesh_fixes.h"
#include "parallel.h"
namespace {
using namespace manifold;
+
struct MeshCompare {
- bool operator()(const std::shared_ptr<CsgLeafNode>& a,
- const std::shared_ptr<CsgLeafNode>& b) {
- return a->GetImpl()->NumVert() < b->GetImpl()->NumVert();
+ bool operator()(const std::pair<std::shared_ptr<CsgLeafNode>, uint64_t>& a,
+ const std::pair<std::shared_ptr<CsgLeafNode>, uint64_t>& b) {
+ // Use NumVert() which doesn't trigger transform application.
+ const size_t aVert = a.first->NumVert();
+ const size_t bVert = b.first->NumVert();
+ if (aVert != bVert) return aVert < bVert;
+ // Tie-break by insertion order so heap behavior is deterministic across
+ return a.second < b.second;
}
};
@@ -86,7 +94,14 @@ CsgLeafNode::CsgLeafNode(std::shared_ptr<const Manifold::Impl> pImpl_,
mat3x4 transform_)
: pImpl_(pImpl_), transform_(transform_) {}
+CsgLeafNode::CsgLeafNode(const CsgLeafNode& other) {
+ std::lock_guard<std::mutex> lock(other.mutex_);
+ pImpl_ = other.pImpl_;
+ transform_ = other.transform_;
+}
+
std::shared_ptr<const Manifold::Impl> CsgLeafNode::GetImpl() const {
+ std::lock_guard<std::mutex> lock(mutex_);
if (transform_ == mat3x4(la::identity)) return pImpl_;
pImpl_ =
std::make_shared<const Manifold::Impl>(pImpl_->Transform(transform_));
@@ -94,22 +109,67 @@ std::shared_ptr<const Manifold::Impl> CsgLeafNode::GetImpl() const {
return pImpl_;
}
-std::shared_ptr<CsgLeafNode> CsgLeafNode::ToLeafNode() const {
+std::shared_ptr<CsgLeafNode> CsgLeafNode::ToLeafNode(
+ ExecutionContext::Impl*) const {
return std::make_shared<CsgLeafNode>(*this);
}
std::shared_ptr<CsgNode> CsgLeafNode::Transform(const mat3x4& m) const {
+ std::lock_guard<std::mutex> lock(mutex_);
return std::make_shared<CsgLeafNode>(pImpl_, m * Mat4(transform_));
}
CsgNodeType CsgLeafNode::GetNodeType() const { return CsgNodeType::Leaf; }
+Box CsgLeafNode::GetBoundingBox() const {
+ // Compute transformed bounding box without triggering full mesh transform.
+ // This is an approximation - the actual bounding box of the transformed mesh
+ // may be tighter, but this is sufficient for overlap checks.
+ std::lock_guard<std::mutex> lock(mutex_);
+ const Box& box = pImpl_->bBox_;
+ if (transform_ == mat3x4(la::identity)) {
+ return box;
+ }
+
+ // Arvo's algorithm for transforming AABBs efficiently.
+ // Instead of transforming all 8 corners, we compute min/max directly
+ // from the matrix elements based on their signs.
+ vec3 newMin = transform_[3]; // translation component
+ vec3 newMax = newMin;
+
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ const auto a = transform_[j][i] * box.min[j];
+ const auto b = transform_[j][i] * box.max[j];
+ newMin[i] += std::min(a, b);
+ newMax[i] += std::max(a, b);
+ }
+ }
+ return Box{newMin, newMax};
+}
+
+size_t CsgLeafNode::NumVert() const {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return pImpl_->NumVert();
+}
+
std::shared_ptr<CsgLeafNode> ImplToLeaf(Manifold::Impl&& impl) {
- return std::make_shared<CsgLeafNode>(std::make_shared<Manifold::Impl>(impl));
+ return std::make_shared<CsgLeafNode>(
+ std::make_shared<Manifold::Impl>(std::move(impl)));
+}
+
+// Build a leaf with the given error status — used to short-circuit boolean
+// evaluation on cancellation.
+std::shared_ptr<CsgLeafNode> ErrorLeaf(Manifold::Error err) {
+ Manifold::Impl impl;
+ impl.status_ = err;
+ return ImplToLeaf(std::move(impl));
}
std::shared_ptr<CsgLeafNode> SimpleBoolean(const Manifold::Impl& a,
- const Manifold::Impl& b, OpType op) {
+ const Manifold::Impl& b, OpType op,
+ ExecutionContext::Impl* ctx) {
+ if (IsCancelled(ctx)) return ErrorLeaf(Manifold::Error::Cancelled);
#ifdef MANIFOLD_DEBUG
auto dump = [&]() {
dump_lock.lock();
@@ -117,7 +177,6 @@ std::shared_ptr<CsgLeafNode> SimpleBoolean(const Manifold::Impl& a,
<< std::endl;
std::cout << "RHS self-intersecting: " << b.IsSelfIntersecting()
<< std::endl;
-#ifdef MANIFOLD_EXPORT
if (ManifoldParams().verbose) {
if (op == OpType::Add)
std::cout << "Add";
@@ -129,11 +188,10 @@ std::shared_ptr<CsgLeafNode> SimpleBoolean(const Manifold::Impl& a,
std::cout << a;
std::cout << b;
}
-#endif
dump_lock.unlock();
};
try {
- Boolean3 boolean(a, b, op);
+ Boolean3 boolean(a, b, op, ctx);
auto impl = boolean.Result(op);
if (ManifoldParams().selfIntersectionChecks && impl.IsSelfIntersecting()) {
dump_lock.lock();
@@ -141,6 +199,7 @@ std::shared_ptr<CsgLeafNode> SimpleBoolean(const Manifold::Impl& a,
dump_lock.unlock();
throw logicErr("self intersection detected");
}
+ if (ctx) ctx->doneBooleans.fetch_add(1, std::memory_order_relaxed);
return ImplToLeaf(std::move(impl));
} catch (logicErr& err) {
dump();
@@ -150,7 +209,9 @@ std::shared_ptr<CsgLeafNode> SimpleBoolean(const Manifold::Impl& a,
throw err;
}
#else
- return ImplToLeaf(Boolean3(a, b, op).Result(op));
+ auto leaf = ImplToLeaf(Boolean3(a, b, op, ctx).Result(op));
+ if (ctx) ctx->doneBooleans.fetch_add(1, std::memory_order_relaxed);
+ return leaf;
#endif
}
@@ -162,6 +223,7 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
ZoneScoped;
double epsilon = -1;
double tolerance = -1;
+ Box bbox;
int numVert = 0;
int numEdge = 0;
int numTri = 0;
@@ -186,6 +248,7 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
if (!std::isfinite(nodeEpsilon)) nodeEpsilon = -1;
epsilon = std::max(epsilon, nodeEpsilon);
tolerance = std::max(tolerance, node->pImpl_->tolerance_);
+ bbox = bbox.Union(node->GetBoundingBox());
vertIndices.push_back(numVert);
edgeIndices.push_back(numEdge * 2);
@@ -203,7 +266,9 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
Manifold::Impl combined;
combined.epsilon_ = epsilon;
combined.tolerance_ = tolerance;
+ combined.bBox_ = bbox;
combined.vertPos_.resize_nofill(numVert);
+ combined.vertNormal_.resize_nofill(numVert);
combined.halfedge_.resize_nofill(2 * numEdge);
combined.faceNormal_.resize_nofill(numTri);
combined.halfedgeTangent_.resize(2 * numEdge);
@@ -219,11 +284,15 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
if (nodes.size() > 1 && policy == ExecutionPolicy::Par)
policy = ExecutionPolicy::Seq;
+ // Snapshot once and reuse for both shifts; two reads can disagree under
+ // cross-thread CSG and leave triRef.meshID values not in meshIDtransform.
+ const uint32_t meshIDCounterSnapshot = Manifold::Impl::meshIDCounter_;
+
for_each_n(
nodes.size() > 1 ? ExecutionPolicy::Par : ExecutionPolicy::Seq,
countAt(0), nodes.size(),
[&nodes, &vertIndices, &edgeIndices, &triIndices, &propVertIndices,
- numPropOut, &combined, policy](int i) {
+ numPropOut, &combined, policy, meshIDCounterSnapshot](int i) {
auto& node = nodes[i];
copy(node->pImpl_->halfedgeTangent_.begin(),
node->pImpl_->halfedgeTangent_.end(),
@@ -231,16 +300,19 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
const int nextVert = vertIndices[i];
const int nextEdge = edgeIndices[i];
const int nextProp = propVertIndices[i];
- transform(node->pImpl_->halfedge_.begin(),
- node->pImpl_->halfedge_.end(),
- combined.halfedge_.begin() + edgeIndices[i],
- [nextVert, nextEdge, nextProp](Halfedge edge) {
- edge.startVert += nextVert;
- edge.endVert += nextVert;
- edge.pairedHalfedge += nextEdge;
- edge.propVert += nextProp;
- return edge;
- });
+ const bool hasProp = node->pImpl_->NumProp() > 0;
+ for_each_n(
+ policy, countAt(0), node->pImpl_->halfedge_.size(), [&](int edge) {
+ const int newEdge = edgeIndices[i] + edge;
+ combined.halfedge_.SetStart(
+ newEdge, node->pImpl_->halfedge_.Start(edge) + nextVert);
+ combined.halfedge_.SetPair(
+ newEdge, node->pImpl_->halfedge_.Pair(edge) + nextEdge);
+ const int propVert =
+ hasProp ? node->pImpl_->halfedge_.Prop(edge) + nextProp
+ : nextProp;
+ combined.halfedge_.SetProp(newEdge, propVert);
+ });
if (node->pImpl_->NumProp() > 0) {
const int numProp = node->pImpl_->NumProp();
@@ -254,11 +326,26 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
newProp.end(), numPropOut);
copy(oldRange.begin(), oldRange.end(), newRange.begin());
}
+ // Properties copy above doesn't go through the on-the-fly transform
+ // applied to vertPos_/faceNormal_ below; eager-transform slot 0..2
+ // per-meshID so world-frame normals stay in sync. Covers mixed
+ // input nodes (some meshIDs with hasNormals, some without).
+ if (numProp >= 3 && node->transform_ != mat3x4(la::identity)) {
+ const mat3 normalTransform =
+ la::inverse(la::transpose(mat3(node->transform_)));
+ Manifold::Impl::EagerTransformPropNormals(
+ node->pImpl_->halfedge_, node->pImpl_->meshRelation_,
+ normalTransform, newProp, oldProp.size() / numProp, numPropOut,
+ propVertIndices[i]);
+ }
}
if (node->transform_ == mat3x4(la::identity)) {
copy(node->pImpl_->vertPos_.begin(), node->pImpl_->vertPos_.end(),
combined.vertPos_.begin() + vertIndices[i]);
+ copy(node->pImpl_->vertNormal_.begin(),
+ node->pImpl_->vertNormal_.end(),
+ combined.vertNormal_.begin() + vertIndices[i]);
copy(node->pImpl_->faceNormal_.begin(),
node->pImpl_->faceNormal_.end(),
combined.faceNormal_.begin() + triIndices[i]);
@@ -272,11 +359,16 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
});
mat3 normalTransform =
la::inverse(la::transpose(mat3(node->transform_)));
+ auto vertNormalBegin =
+ TransformIterator(node->pImpl_->vertNormal_.begin(),
+ TransformNormals({normalTransform}));
auto faceNormalBegin =
TransformIterator(node->pImpl_->faceNormal_.begin(),
TransformNormals({normalTransform}));
copy_n(vertPosBegin, node->pImpl_->vertPos_.size(),
combined.vertPos_.begin() + vertIndices[i]);
+ copy_n(vertNormalBegin, node->pImpl_->vertNormal_.size(),
+ combined.vertNormal_.begin() + vertIndices[i]);
copy_n(faceNormalBegin, node->pImpl_->faceNormal_.size(),
combined.faceNormal_.begin() + triIndices[i]);
@@ -288,12 +380,12 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
node->pImpl_->halfedge_});
if (invert)
for_each_n(policy, countAt(triIndices[i]), node->pImpl_->NumTri(),
- FlipTris({combined.halfedge_}));
+ FlipTris{combined.halfedge_});
}
// Since the nodes may be copies containing the same meshIDs, it is
// important to add an offset so that each node instance gets
// unique meshIDs.
- const int offset = i * Manifold::Impl::meshIDCounter_;
+ const int offset = i * meshIDCounterSnapshot;
transform(node->pImpl_->meshRelation_.triRef.begin(),
node->pImpl_->meshRelation_.triRef.end(),
combined.meshRelation_.triRef.begin() + triIndices[i],
@@ -305,16 +397,23 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
for (size_t i = 0; i < nodes.size(); i++) {
auto& node = nodes[i];
- const int offset = i * Manifold::Impl::meshIDCounter_;
+ const int offset = i * meshIDCounterSnapshot;
for (const auto& pair : node->pImpl_->meshRelation_.meshIDtransform) {
- combined.meshRelation_.meshIDtransform[pair.first + offset] = pair.second;
+ Manifold::Impl::Relation rel = pair.second;
+ // Apply the node's transform to the mesh relation if not identity.
+ // This is necessary because we may not have called GetImpl() which would
+ // have applied the transform to the mesh relations.
+ if (node->transform_ != mat3x4(la::identity)) {
+ rel.transform = node->transform_ * Mat4(rel.transform);
+ }
+ combined.meshRelation_.meshIDtransform[pair.first + offset] = rel;
}
}
// required to remove parts that are smaller than the tolerance
combined.RemoveDegenerates();
- combined.Finish();
+ combined.SortGeometry();
combined.IncrementMeshIDs();
return ImplToLeaf(std::move(combined));
}
@@ -324,7 +423,8 @@ std::shared_ptr<CsgLeafNode> CsgLeafNode::Compose(
* operation. Only supports union and intersection.
*/
std::shared_ptr<CsgLeafNode> BatchBoolean(
- OpType operation, std::vector<std::shared_ptr<CsgLeafNode>>& results) {
+ OpType operation, std::vector<std::shared_ptr<CsgLeafNode>>& results,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
DEBUG_ASSERT(operation != OpType::Subtract, logicErr,
"BatchBoolean doesn't support Difference.");
@@ -333,48 +433,62 @@ std::shared_ptr<CsgLeafNode> BatchBoolean(
if (results.size() == 1) return results.front();
if (results.size() == 2)
return SimpleBoolean(*results[0]->GetImpl(), *results[1]->GetImpl(),
- operation);
+ operation, ctx);
+ std::vector<std::pair<std::shared_ptr<CsgLeafNode>, uint64_t>> heapNodes;
+ heapNodes.reserve(results.size());
+ for (size_t i = 0; i < results.size(); ++i) {
+ heapNodes.emplace_back(std::move(results[i]), i);
+ }
+ results.clear();
+ uint64_t nextSerial = heapNodes.size();
+
// apply boolean operations starting from smaller meshes
// the assumption is that boolean operations on smaller meshes is faster,
// due to less data being copied and processed
auto cmpFn = MeshCompare();
- std::make_heap(results.begin(), results.end(), cmpFn);
- std::vector<std::shared_ptr<CsgLeafNode>> tmp;
+ std::make_heap(heapNodes.begin(), heapNodes.end(), cmpFn);
+ std::vector<std::pair<std::shared_ptr<CsgLeafNode>, uint64_t>> tmp;
#if MANIFOLD_PAR == 1
tbb::task_group group;
// make sure the order of result is deterministic
std::vector<std::shared_ptr<CsgLeafNode>> parallelTmp;
+ std::vector<uint64_t> parallelSerial;
for (int i = 0; i < 4; i++) parallelTmp.push_back(nullptr);
+ for (int i = 0; i < 4; i++) parallelSerial.push_back(0);
#endif
- while (results.size() > 1) {
- for (size_t i = 0; i < 4 && results.size() > 1; i++) {
- std::pop_heap(results.begin(), results.end(), cmpFn);
- auto a = std::move(results.back());
- results.pop_back();
- std::pop_heap(results.begin(), results.end(), cmpFn);
- auto b = std::move(results.back());
- results.pop_back();
+ while (heapNodes.size() > 1) {
+ if (IsCancelled(ctx)) return ErrorLeaf(Manifold::Error::Cancelled);
+ for (size_t i = 0; i < 4 && heapNodes.size() > 1; i++) {
+ std::pop_heap(heapNodes.begin(), heapNodes.end(), cmpFn);
+ auto a = std::move(heapNodes.back());
+ heapNodes.pop_back();
+ std::pop_heap(heapNodes.begin(), heapNodes.end(), cmpFn);
+ auto b = std::move(heapNodes.back());
+ heapNodes.pop_back();
#if MANIFOLD_PAR == 1
- group.run([&, i, a, b]() {
- parallelTmp[i] = SimpleBoolean(*a->GetImpl(), *b->GetImpl(), operation);
+ parallelSerial[i] = nextSerial++;
+ group.run([&, i, a = std::move(a.first), b = std::move(b.first)]() {
+ parallelTmp[i] =
+ SimpleBoolean(*a->GetImpl(), *b->GetImpl(), operation, ctx);
});
#else
- auto result = SimpleBoolean(*a->GetImpl(), *b->GetImpl(), operation);
- tmp.push_back(result);
+ auto result = SimpleBoolean(*a.first->GetImpl(), *b.first->GetImpl(),
+ operation, ctx);
+ tmp.emplace_back(std::move(result), nextSerial++);
#endif
}
#if MANIFOLD_PAR == 1
group.wait();
for (int i = 0; i < 4 && parallelTmp[i]; i++)
- tmp.emplace_back(std::move(parallelTmp[i]));
+ tmp.emplace_back(std::move(parallelTmp[i]), parallelSerial[i]);
#endif
- for (auto result : tmp) {
- results.push_back(result);
- std::push_heap(results.begin(), results.end(), cmpFn);
+ for (auto& result : tmp) {
+ heapNodes.push_back(std::move(result));
+ std::push_heap(heapNodes.begin(), heapNodes.end(), cmpFn);
}
tmp.clear();
}
- return results.front();
+ return heapNodes.front().first;
}
/**
@@ -382,7 +496,8 @@ std::shared_ptr<CsgLeafNode> BatchBoolean(
* possible.
*/
std::shared_ptr<CsgLeafNode> BatchUnion(
- std::vector<std::shared_ptr<CsgLeafNode>>& children) {
+ std::vector<std::shared_ptr<CsgLeafNode>>& children,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
// INVARIANT: children_ is a vector of leaf nodes
// this kMaxUnionSize is a heuristic to avoid the pairwise disjoint check
@@ -393,13 +508,14 @@ std::shared_ptr<CsgLeafNode> BatchUnion(
DEBUG_ASSERT(!children.empty(), logicErr,
"BatchUnion should not have empty children");
while (children.size() > 1) {
+ if (IsCancelled(ctx)) return ErrorLeaf(Manifold::Error::Cancelled);
const size_t start = (children.size() > kMaxUnionSize)
? (children.size() - kMaxUnionSize)
: 0;
Vec<Box> boxes;
boxes.reserve(children.size() - start);
for (size_t i = start; i < children.size(); i++) {
- boxes.push_back(children[i]->GetImpl()->bBox_);
+ boxes.push_back(children[i]->GetBoundingBox());
}
// partition the children into a set of disjoint sets
// each set contains a set of children that are pairwise disjoint
@@ -428,11 +544,19 @@ std::shared_ptr<CsgLeafNode> BatchUnion(
tmp.push_back(children[start + j]);
}
impls.push_back(CsgLeafNode::Compose(tmp));
+ // Compose absorbs set.size() leaves into 1 leaf, which is
+ // set.size() - 1 leaf-reductions toward the final result.
+ if (ctx) {
+ const int reductions = static_cast<int>(set.size() - 1);
+ ctx->doneBooleans.fetch_add(reductions, std::memory_order_relaxed);
+ ctx->donePhases.fetch_add(reductions * kPhasesPerBoolean,
+ std::memory_order_relaxed);
+ }
}
}
children.erase(children.begin() + start, children.end());
- children.push_back(BatchBoolean(OpType::Add, impls));
+ children.push_back(BatchBoolean(OpType::Add, impls, ctx));
// move it to the front as we process from the back, and the newly added
// child should be quite complicated
std::swap(children.front(), children.back());
@@ -465,7 +589,10 @@ CsgOpNode::~CsgOpNode() {
while (!toProcess.empty()) {
auto child = std::move(toProcess.back());
toProcess.pop_back();
- if (impl_.UseCount() == 1) {
+ // Only empty the child's impl if we are its last holder. Otherwise
+ // another live tree still references this CsgOpNode and may later
+ // try to evaluate it, which requires its impl intact.
+ if (child.use_count() == 1 && child->impl_.UseCount() == 1) {
auto childImpl = child->impl_.GetGuard();
handleChildren(*childImpl);
}
@@ -513,8 +640,15 @@ struct CsgStackFrame {
op_node(op_node) {}
};
-std::shared_ptr<CsgLeafNode> CsgOpNode::ToLeafNode() const {
- if (cache_ != nullptr) return cache_;
+std::shared_ptr<CsgLeafNode> CsgOpNode::ToLeafNode(
+ ExecutionContext::Impl* ctx) const {
+ ZoneScoped;
+ {
+ // cache_ is published under impl_'s guard below; read it under the same
+ // lock so a concurrent eval of a shared op node can't tear it.
+ auto guard = impl_.GetGuard();
+ if (cache_ != nullptr) return cache_;
+ }
// Note: We do need a pointer here to avoid vector pointers from being
// invalidated after pushing elements into the explicit stack.
@@ -615,16 +749,31 @@ std::shared_ptr<CsgLeafNode> CsgOpNode::ToLeafNode() const {
// destination->push_back(node->cache_->Transform(transform));
// }
while (!stack.empty()) {
+ if (IsCancelled(ctx)) {
+ // Poison every op_node currently on the stack, not just `this`.
+ // Sub-ops may have had their impl_ partially mutated during finalize
+ // (children replaced with an intermediate result); leaving cache_
+ // unset would let a later evaluation of a shared sub-op run against
+ // a partially-reduced tree. Shared cache ensures any subsequent
+ // eval of any op on the stack returns Cancelled.
+ auto cancelled = ErrorLeaf(Manifold::Error::Cancelled);
+ for (auto& frame : stack) {
+ if (!frame->op_node->cache_) frame->op_node->cache_ = cancelled;
+ }
+ cache_ = cancelled;
+ return cache_;
+ }
std::shared_ptr<CsgStackFrame> frame = stack.back();
auto impl = frame->op_node->impl_.GetGuard();
if (frame->finalize) {
if (!frame->op_node->cache_) {
switch (frame->op_node->op_) {
case OpType::Add:
- *impl = {BatchUnion(frame->positive_children)};
+ *impl = {BatchUnion(frame->positive_children, ctx)};
break;
case OpType::Intersect: {
- *impl = {BatchBoolean(OpType::Intersect, frame->positive_children)};
+ *impl = {
+ BatchBoolean(OpType::Intersect, frame->positive_children, ctx)};
break;
};
case OpType::Subtract:
@@ -632,14 +781,15 @@ std::shared_ptr<CsgLeafNode> CsgOpNode::ToLeafNode() const {
// nothing to subtract from, so the result is empty.
*impl = {std::make_shared<CsgLeafNode>()};
} else {
- auto positive = BatchUnion(frame->positive_children);
+ auto positive = BatchUnion(frame->positive_children, ctx);
if (frame->negative_children.empty()) {
// nothing to subtract, result equal to the LHS.
*impl = {frame->positive_children[0]};
} else {
- auto negative = BatchUnion(frame->negative_children);
+ auto negative = BatchUnion(frame->negative_children, ctx);
*impl = {SimpleBoolean(*positive->GetImpl(),
- *negative->GetImpl(), OpType::Subtract)};
+ *negative->GetImpl(), OpType::Subtract,
+ ctx)};
}
}
break;
@@ -710,4 +860,32 @@ CsgNodeType CsgOpNode::GetNodeType() const {
return CsgNodeType::Leaf;
}
+size_t CsgOpNode::NumLeaves() const {
+ // An already-evaluated CsgOpNode counts as a single leaf for the purposes
+ // of estimating remaining boolean work. Iterative walk: `+=` chains can
+ // produce very deep CsgOpNode trees that would blow the call stack if
+ // this were recursive.
+ if (cache_ != nullptr) return 1;
+ size_t total = 0;
+ std::vector<const CsgOpNode*> stack;
+ stack.push_back(this);
+ while (!stack.empty()) {
+ const CsgOpNode* op = stack.back();
+ stack.pop_back();
+ if (op->cache_ != nullptr) {
+ total += 1;
+ continue;
+ }
+ auto impl = op->impl_.GetGuard();
+ for (const auto& child : *impl) {
+ if (child->GetNodeType() == CsgNodeType::Leaf) {
+ total += 1;
+ } else {
+ stack.push_back(static_cast<const CsgOpNode*>(child.get()));
+ }
+ }
+ }
+ return total;
+}
+
} // namespace manifold
diff --git a/thirdparty/manifold/src/csg_tree.h b/thirdparty/manifold/src/csg_tree.h
index fa5d22382da..0337e69485d 100644
--- a/thirdparty/manifold/src/csg_tree.h
+++ b/thirdparty/manifold/src/csg_tree.h
@@ -13,6 +13,8 @@
// limitations under the License.
#pragma once
+#include <mutex>
+
#include "manifold/manifold.h"
#include "utils.h"
@@ -24,9 +26,14 @@ class CsgLeafNode;
class CsgNode : public std::enable_shared_from_this<CsgNode> {
public:
- virtual std::shared_ptr<CsgLeafNode> ToLeafNode() const = 0;
+ virtual std::shared_ptr<CsgLeafNode> ToLeafNode(
+ ExecutionContext::Impl* ctx = nullptr) const = 0;
virtual std::shared_ptr<CsgNode> Transform(const mat3x4& m) const = 0;
virtual CsgNodeType GetNodeType() const = 0;
+ /// Count the leaves in the subtree rooted at this node. A CsgOpNode with
+ /// a cached evaluation counts as a single leaf. Used for pre-pass progress
+ /// denominator: a CSG tree with N leaves reduces to 1 result in N-1 ops.
+ virtual size_t NumLeaves() const = 0;
virtual std::shared_ptr<CsgNode> Boolean(
const std::shared_ptr<CsgNode>& second, OpType op);
@@ -42,21 +49,36 @@ class CsgLeafNode final : public CsgNode {
CsgLeafNode();
CsgLeafNode(std::shared_ptr<const Manifold::Impl> pImpl_);
CsgLeafNode(std::shared_ptr<const Manifold::Impl> pImpl_, mat3x4 transform_);
+ // mutex_ is not copyable; snapshot the source under its lock.
+ CsgLeafNode(const CsgLeafNode& other);
std::shared_ptr<const Manifold::Impl> GetImpl() const;
- std::shared_ptr<CsgLeafNode> ToLeafNode() const override;
+ std::shared_ptr<CsgLeafNode> ToLeafNode(
+ ExecutionContext::Impl* ctx = nullptr) const override;
std::shared_ptr<CsgNode> Transform(const mat3x4& m) const override;
CsgNodeType GetNodeType() const override;
+ size_t NumLeaves() const override { return 1; }
+
static std::shared_ptr<CsgLeafNode> Compose(
const std::vector<std::shared_ptr<CsgLeafNode>>& nodes);
+ // Returns the bounding box without triggering eager transform application.
+ // This is more efficient for overlap checks when we don't need the full mesh.
+ Box GetBoundingBox() const;
+
+ // Returns the number of vertices without triggering eager transform.
+ size_t NumVert() const;
+
private:
mutable std::shared_ptr<const Manifold::Impl> pImpl_;
mutable mat3x4 transform_ = la::identity;
+ // Lazy realization mutates these through const accessors on a shared node,
+ // so every access takes mutex_.
+ mutable std::mutex mutex_;
};
class CsgOpNode final : public CsgNode {
@@ -70,10 +92,13 @@ class CsgOpNode final : public CsgNode {
std::shared_ptr<CsgNode> Transform(const mat3x4& m) const override;
- std::shared_ptr<CsgLeafNode> ToLeafNode() const override;
+ std::shared_ptr<CsgLeafNode> ToLeafNode(
+ ExecutionContext::Impl* ctx = nullptr) const override;
CsgNodeType GetNodeType() const override;
+ size_t NumLeaves() const override;
+
~CsgOpNode();
private:
diff --git a/thirdparty/manifold/src/disjoint_sets.h b/thirdparty/manifold/src/disjoint_sets.h
index f85476fc9ff..f8f23776613 100644
--- a/thirdparty/manifold/src/disjoint_sets.h
+++ b/thirdparty/manifold/src/disjoint_sets.h
@@ -21,42 +21,43 @@
//
#pragma once
#include <atomic>
+#include <cassert>
#include <cstddef>
#include <cstdint>
+#include <limits>
#include <unordered_map>
#include <vector>
+#include "parallel.h"
+
class DisjointSets {
public:
- DisjointSets(uint32_t size) : mData(size) {
- for (uint32_t i = 0; i < size; ++i) mData[i] = (uint32_t)i;
+ DisjointSets(size_t size) : mData(size) {
+ assert(size <= std::numeric_limits<uint32_t>::max());
+ using namespace manifold;
+ for_each(autoPolicy(size), countAt(0_uz), countAt(size),
+ [this](size_t i) { mData[i] = static_cast<uint32_t>(i); });
}
- uint32_t find(uint32_t id) const {
- while (id != parent(id)) {
- uint64_t value = mData[id];
- uint32_t new_parent = parent((uint32_t)value);
- uint64_t new_value = (value & 0xFFFFFFFF00000000ULL) | new_parent;
- /* Try to update parent (may fail, that's ok) */
- if (value != new_value) mData[id].compare_exchange_weak(value, new_value);
- id = new_parent;
- }
- return id;
- }
+ size_t find(size_t id) const { return findImpl(ToIndex(id)); }
- bool same(uint32_t id1, uint32_t id2) const {
+ bool same(size_t id1In, size_t id2In) const {
+ uint32_t id1 = ToIndex(id1In);
+ uint32_t id2 = ToIndex(id2In);
for (;;) {
- id1 = find(id1);
- id2 = find(id2);
+ id1 = findImpl(id1);
+ id2 = findImpl(id2);
if (id1 == id2) return true;
if (parent(id1) == id1) return false;
}
}
- uint32_t unite(uint32_t id1, uint32_t id2) {
+ size_t unite(size_t id1In, size_t id2In) {
+ uint32_t id1 = ToIndex(id1In);
+ uint32_t id2 = ToIndex(id2In);
for (;;) {
- id1 = find(id1);
- id2 = find(id2);
+ id1 = findImpl(id1);
+ id2 = findImpl(id2);
if (id1 == id2) return id1;
@@ -85,7 +86,7 @@ class DisjointSets {
return id2;
}
- uint32_t size() const { return (uint32_t)mData.size(); }
+ size_t size() const { return mData.size(); }
uint32_t rank(uint32_t id) const {
return ((uint32_t)(mData[id] >> 32)) & 0x7FFFFFFFu;
@@ -100,7 +101,7 @@ class DisjointSets {
for (size_t i = 0; i < mData.size(); ++i) {
// we optimize for connected component of size 1
// no need to put them into the hashmap
- auto iParent = find(i);
+ uint32_t iParent = findImpl(ToIndex(i));
if (rank(iParent) == 0) {
components[i] = static_cast<int>(toLabel.size()) + lonelyNodes++;
continue;
@@ -118,4 +119,22 @@ class DisjointSets {
}
mutable std::vector<std::atomic<uint64_t>> mData;
+
+ private:
+ static uint32_t ToIndex(size_t id) {
+ assert(id <= std::numeric_limits<uint32_t>::max());
+ return static_cast<uint32_t>(id);
+ }
+
+ uint32_t findImpl(uint32_t id) const {
+ while (id != parent(id)) {
+ uint64_t value = mData[id];
+ uint32_t new_parent = parent((uint32_t)value);
+ uint64_t new_value = (value & 0xFFFFFFFF00000000ULL) | new_parent;
+ /* Try to update parent (may fail, that's ok) */
+ if (value != new_value) mData[id].compare_exchange_weak(value, new_value);
+ id = new_parent;
+ }
+ return id;
+ }
};
diff --git a/thirdparty/manifold/src/edge_op.cpp b/thirdparty/manifold/src/edge_op.cpp
index ae038896349..0587b4672a1 100644
--- a/thirdparty/manifold/src/edge_op.cpp
+++ b/thirdparty/manifold/src/edge_op.cpp
@@ -13,6 +13,7 @@
// limitations under the License.
#include <unordered_map>
+#include <unordered_set>
#include "impl.h"
#include "parallel.h"
@@ -36,106 +37,11 @@ bool Is01Longest(vec2 v0, vec2 v1, vec2 v2) {
return l[0] > l[1] && l[0] > l[2];
}
-struct DuplicateEdge {
- const Halfedge* sortedHalfedge;
-
- bool operator()(int edge) {
- const Halfedge& halfedge = sortedHalfedge[edge];
- const Halfedge& nextHalfedge = sortedHalfedge[edge + 1];
- return halfedge.startVert == nextHalfedge.startVert &&
- halfedge.endVert == nextHalfedge.endVert;
- }
-};
-
-struct ShortEdge {
- VecView<const Halfedge> halfedge;
- VecView<const vec3> vertPos;
- const double epsilon;
- const int firstNewVert;
-
- bool operator()(int edge) const {
- const Halfedge& half = halfedge[edge];
- if (half.pairedHalfedge < 0 ||
- (half.startVert < firstNewVert && half.endVert < firstNewVert))
- return false;
- // Flag short edges
- const vec3 delta = vertPos[half.endVert] - vertPos[half.startVert];
- return la::dot(delta, delta) < epsilon * epsilon;
- }
-};
-
-struct FlagEdge {
- VecView<const Halfedge> halfedge;
- VecView<const TriRef> triRef;
- const int firstNewVert;
-
- bool operator()(int edge) const {
- const Halfedge& half = halfedge[edge];
- if (half.pairedHalfedge < 0 || half.startVert < firstNewVert) return false;
- // Flag redundant edges - those where the startVert is surrounded by only
- // two original triangles.
- const TriRef ref0 = triRef[edge / 3];
- int current = NextHalfedge(half.pairedHalfedge);
- TriRef ref1 = triRef[current / 3];
- bool ref1Updated = !ref0.SameFace(ref1);
- while (current != edge) {
- current = NextHalfedge(halfedge[current].pairedHalfedge);
- int tri = current / 3;
- const TriRef ref = triRef[tri];
- if (!ref.SameFace(ref0) && !ref.SameFace(ref1)) {
- if (!ref1Updated) {
- ref1 = ref;
- ref1Updated = true;
- } else {
- return false;
- }
- }
- }
- return true;
- }
-};
-
-struct SwappableEdge {
- VecView<const Halfedge> halfedge;
- VecView<const vec3> vertPos;
- VecView<const vec3> triNormal;
- const double tolerance;
- const int firstNewVert;
-
- bool operator()(int edge) const {
- const Halfedge& half = halfedge[edge];
- if (half.pairedHalfedge < 0) return false;
- if (half.startVert < firstNewVert && half.endVert < firstNewVert &&
- halfedge[NextHalfedge(edge)].endVert < firstNewVert &&
- halfedge[NextHalfedge(half.pairedHalfedge)].endVert < firstNewVert)
- return false;
-
- int tri = edge / 3;
- ivec3 triEdge = TriOf(edge);
- mat2x3 projection = GetAxisAlignedProjection(triNormal[tri]);
- vec2 v[3];
- for (int i : {0, 1, 2})
- v[i] = projection * vertPos[halfedge[triEdge[i]].startVert];
- if (CCW(v[0], v[1], v[2], tolerance) > 0 || !Is01Longest(v[0], v[1], v[2]))
- return false;
-
- // Switch to neighbor's projection.
- edge = half.pairedHalfedge;
- tri = edge / 3;
- triEdge = TriOf(edge);
- projection = GetAxisAlignedProjection(triNormal[tri]);
- for (int i : {0, 1, 2})
- v[i] = projection * vertPos[halfedge[triEdge[i]].startVert];
- return CCW(v[0], v[1], v[2], tolerance) > 0 ||
- Is01Longest(v[0], v[1], v[2]);
- }
-};
-
struct FlagStore {
#if MANIFOLD_PAR == 1
- tbb::combinable<std::vector<size_t>> store;
+ tbb::combinable<Vec<size_t>> store;
#endif
- std::vector<size_t> s;
+ Vec<size_t> s;
template <typename Pred, typename F>
void run_seq(size_t n, Pred pred, F f) {
@@ -155,16 +61,15 @@ struct FlagStore {
tbb::parallel_for(tbb::blocked_range<size_t>(0, n),
[&store, &pred](const auto& r) {
auto& local = store.local();
- for (auto i = r.begin(); i < r.end(); ++i) {
+ for (auto i = r.begin(); i < r.end(); i++)
if (pred(i)) local.push_back(i);
- }
});
- std::vector<std::vector<size_t>> stores;
- std::vector<size_t> result;
+ std::vector<Vec<size_t>> stores;
+ Vec<size_t> result;
store.combine_each(
[&](auto& data) { stores.emplace_back(std::move(data)); });
- std::vector<size_t> sizes;
+ Vec<size_t> sizes;
size_t total_size = 0;
for (const auto& tmp : stores) {
sizes.push_back(total_size);
@@ -203,6 +108,7 @@ namespace manifold {
void Manifold::Impl::CleanupTopology() {
if (!halfedge_.size()) return;
DEBUG_ASSERT(IsManifold(), logicErr, "polygon mesh is not manifold!");
+ halfedge_.MakeUnique();
// In the case of a very bad triangulation, it is possible to create pinched
// verts. They must be removed before edge collapse.
@@ -234,19 +140,25 @@ void Manifold::Impl::CleanupTopology() {
*/
void Manifold::Impl::SimplifyTopology(int firstNewVert) {
if (!halfedge_.size()) return;
+ halfedge_.MakeUnique();
CleanupTopology();
CollapseShortEdges(firstNewVert);
CollapseColinearEdges(firstNewVert);
SwapDegenerates(firstNewVert);
+ // Merging verts causes their normals to change
+ CalculateVertNormals();
}
void Manifold::Impl::RemoveDegenerates(int firstNewVert) {
if (!halfedge_.size()) return;
+ halfedge_.MakeUnique();
CleanupTopology();
CollapseShortEdges(firstNewVert);
SwapDegenerates(firstNewVert);
+ // Merging verts causes their normals to change
+ CalculateVertNormals();
}
void Manifold::Impl::CollapseShortEdges(int firstNewVert) {
@@ -255,21 +167,41 @@ void Manifold::Impl::CollapseShortEdges(int firstNewVert) {
size_t numFlagged = 0;
const size_t nbEdges = halfedge_.size();
- std::vector<int> scratchBuffer;
+ Vec<int> scratchBuffer;
scratchBuffer.reserve(10);
// Short edges get to skip several checks and hence remove more classes of
// degenerate triangles than flagged edges do, but this could in theory lead
// to error stacking where a vertex moves too far. For this reason this is
- // restricted to epsilon, rather than tolerance.
- ShortEdge se{halfedge_, vertPos_, epsilon_, firstNewVert};
- s.run(nbEdges, se, [&](size_t i) {
- const bool didCollapse = CollapseEdge(i, scratchBuffer);
+ // restricted to epsilon, rather than tolerance. However, in the case of a
+ // Boolean operation, we set firstNewVert in order to only operate on
+ // newly-created verts, which means error stacking is not a concern, so we
+ // allow collapsing up to tolerance in that case.
+ const double tol = firstNewVert == 0 ? epsilon_ : tolerance_;
+
+ auto shortEdge = [&](int edge) {
+ const int pair = halfedge_.Pair(edge);
+ if (pair < 0) return false;
+ const int start = halfedge_.Start(edge);
+ const int end = halfedge_.End(edge);
+ if (start < firstNewVert && end < firstNewVert) return false;
+ // Flag short edges
+ const vec3 delta = vertPos_[end] - vertPos_[start];
+ const double lenSq = la::dot(delta, delta);
+ // To ensure tolerance_-scale errors don't stack, only collapse these edges
+ // if they connect a new vert to an old vert, since old verts are only
+ // allowed to move by epsilon_.
+ const double maxLen = end < firstNewVert ? tol * tol : epsilon_ * epsilon_;
+ return lenSq < maxLen;
+ };
+
+ s.run(nbEdges, shortEdge, [&](size_t i) {
+ const bool didCollapse = CollapseEdge(i, scratchBuffer, tol, firstNewVert);
if (didCollapse) numFlagged++;
scratchBuffer.resize(0);
});
#ifdef MANIFOLD_DEBUG
- if (ManifoldParams().verbose > 0 && numFlagged > 0) {
+ if (ManifoldParams().verbose >= 2 && numFlagged > 0) {
std::cout << "collapsed " << numFlagged << " short edges" << std::endl;
}
#endif
@@ -279,7 +211,7 @@ void Manifold::Impl::CollapseColinearEdges(int firstNewVert) {
FlagStore s;
size_t numFlagged = 0;
const size_t nbEdges = halfedge_.size();
- std::vector<int> scratchBuffer;
+ Vec<int> scratchBuffer;
scratchBuffer.reserve(10);
while (1) {
ZoneScopedN("CollapseFlaggedEdge");
@@ -290,8 +222,32 @@ void Manifold::Impl::CollapseColinearEdges(int firstNewVert) {
// non-intersecting parts of the input meshes. Colinear is defined not by a
// local check, but by the global MarkCoplanar function, which keeps this
// from being vulnerable to error stacking.
- FlagEdge se{halfedge_, meshRelation_.triRef, firstNewVert};
- s.run(nbEdges, se, [&](size_t i) {
+ auto colinearEdge = [&](int edge) {
+ const int pair = halfedge_.Pair(edge);
+ if (pair < 0 || halfedge_.Start(edge) < firstNewVert) return false;
+ // Flag redundant edges - those where the startVert is surrounded by only
+ // two original triangles.
+ const TriRef ref0 = meshRelation_.triRef[edge / 3];
+ int current = NextHalfedge(pair);
+ TriRef ref1 = meshRelation_.triRef[current / 3];
+ bool ref1Updated = !ref0.SameFace(ref1);
+ while (current != edge) {
+ current = NextHalfedge(halfedge_.Pair(current));
+ int tri = current / 3;
+ const TriRef ref = meshRelation_.triRef[tri];
+ if (!ref.SameFace(ref0) && !ref.SameFace(ref1)) {
+ if (!ref1Updated) {
+ ref1 = ref;
+ ref1Updated = true;
+ } else {
+ return false;
+ }
+ }
+ }
+ return true;
+ };
+
+ s.run(nbEdges, colinearEdge, [&](size_t i) {
const bool didCollapse = CollapseEdge(i, scratchBuffer);
if (didCollapse) numFlagged++;
scratchBuffer.resize(0);
@@ -299,7 +255,7 @@ void Manifold::Impl::CollapseColinearEdges(int firstNewVert) {
if (numFlagged == 0) break;
#ifdef MANIFOLD_DEBUG
- if (ManifoldParams().verbose > 0 && numFlagged > 0) {
+ if (ManifoldParams().verbose >= 2 && numFlagged > 0) {
std::cout << "collapsed " << numFlagged << " colinear edges" << std::endl;
}
#endif
@@ -311,14 +267,42 @@ void Manifold::Impl::SwapDegenerates(int firstNewVert) {
FlagStore s;
size_t numFlagged = 0;
const size_t nbEdges = halfedge_.size();
- std::vector<int> scratchBuffer;
+ Vec<int> scratchBuffer;
scratchBuffer.reserve(10);
- SwappableEdge se{halfedge_, vertPos_, faceNormal_, tolerance_, firstNewVert};
- std::vector<int> edgeSwapStack;
- std::vector<int> visited(halfedge_.size(), -1);
+ auto swappableEdge = [&](int edge) {
+ const int pair = halfedge_.Pair(edge);
+ if (pair < 0) return false;
+ const ivec3 triEdge = TriOf(edge);
+ const ivec3 pairTriEdge = TriOf(pair);
+ if (halfedge_.Start(triEdge[0]) < firstNewVert &&
+ halfedge_.Start(triEdge[1]) < firstNewVert &&
+ halfedge_.Start(triEdge[2]) < firstNewVert &&
+ halfedge_.Start(pairTriEdge[2]) < firstNewVert)
+ return false;
+
+ int tri = edge / 3;
+ mat2x3 projection = GetAxisAlignedProjection(faceNormal_[tri]);
+ vec2 v[3];
+ for (int i : {0, 1, 2})
+ v[i] = projection * vertPos_[halfedge_.Start(triEdge[i])];
+ if (CCW(v[0], v[1], v[2], tolerance_) > 0 || !Is01Longest(v[0], v[1], v[2]))
+ return false;
+
+ // Switch to neighbor's projection.
+ edge = pair;
+ tri = edge / 3;
+ projection = GetAxisAlignedProjection(faceNormal_[tri]);
+ for (int i : {0, 1, 2})
+ v[i] = projection * vertPos_[halfedge_.Start(pairTriEdge[i])];
+ return CCW(v[0], v[1], v[2], tolerance_) > 0 ||
+ Is01Longest(v[0], v[1], v[2]);
+ };
+
+ Vec<int> edgeSwapStack;
+ Vec<int> visited(halfedge_.size(), -1);
int tag = 0;
- s.run(nbEdges, se, [&](size_t i) {
+ s.run(nbEdges, swappableEdge, [&](size_t i) {
numFlagged++;
tag++;
RecursiveEdgeSwap(i, tag, visited, edgeSwapStack, scratchBuffer);
@@ -330,7 +314,7 @@ void Manifold::Impl::SwapDegenerates(int firstNewVert) {
});
#ifdef MANIFOLD_DEBUG
- if (ManifoldParams().verbose > 0 && numFlagged > 0) {
+ if (ManifoldParams().verbose >= 2 && numFlagged > 0) {
std::cout << "swapped " << numFlagged << " edges" << std::endl;
}
#endif
@@ -340,30 +324,30 @@ void Manifold::Impl::SwapDegenerates(int firstNewVert) {
// edges distinct. Also duplicates startVert if it becomes pinched.
void Manifold::Impl::DedupeEdge(const int edge) {
// Orbit endVert
- const int startVert = halfedge_[edge].startVert;
- const int endVert = halfedge_[edge].endVert;
- const int endProp = halfedge_[NextHalfedge(edge)].propVert;
- int current = halfedge_[NextHalfedge(edge)].pairedHalfedge;
+ const int nextEdge = NextHalfedge(edge);
+ const int startVert = halfedge_.Start(edge);
+ const int endVert = halfedge_.Start(nextEdge);
+ const int endProp = halfedge_.Prop(nextEdge);
+ int current = halfedge_.Pair(nextEdge);
while (current != edge) {
- const int vert = halfedge_[current].startVert;
+ const int vert = halfedge_.Start(current);
if (vert == startVert) {
// Single topological unit needs 2 faces added to be split
const int newVert = vertPos_.size();
vertPos_.push_back(vertPos_[endVert]);
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
- current = halfedge_[NextHalfedge(current)].pairedHalfedge;
- const int opposite = halfedge_[NextHalfedge(edge)].pairedHalfedge;
+ current = halfedge_.Pair(NextHalfedge(current));
+ const int opposite = halfedge_.Pair(nextEdge);
UpdateVert(newVert, current, opposite);
int newHalfedge = halfedge_.size();
int oldFace = current / 3;
- int outsideVert = halfedge_[current].startVert;
- halfedge_.push_back({endVert, newVert, -1, endProp});
- halfedge_.push_back({newVert, outsideVert, -1, endProp});
- halfedge_.push_back(
- {outsideVert, endVert, -1, halfedge_[current].propVert});
- PairUp(newHalfedge + 2, halfedge_[current].pairedHalfedge);
+ int outsideVert = halfedge_.Start(current);
+ halfedge_.push_back(endVert, -1, endProp);
+ halfedge_.push_back(newVert, -1, endProp);
+ halfedge_.push_back(outsideVert, -1, halfedge_.Prop(current));
+ PairUp(newHalfedge + 2, halfedge_.Pair(current));
PairUp(newHalfedge + 1, current);
if (meshRelation_.triRef.size() > 0)
meshRelation_.triRef.push_back(meshRelation_.triRef[oldFace]);
@@ -371,12 +355,11 @@ void Manifold::Impl::DedupeEdge(const int edge) {
newHalfedge += 3;
oldFace = opposite / 3;
- outsideVert = halfedge_[opposite].startVert;
- halfedge_.push_back({newVert, endVert, -1, endProp}); // fix prop
- halfedge_.push_back({endVert, outsideVert, -1, endProp});
- halfedge_.push_back(
- {outsideVert, newVert, -1, halfedge_[opposite].propVert});
- PairUp(newHalfedge + 2, halfedge_[opposite].pairedHalfedge);
+ outsideVert = halfedge_.Start(opposite);
+ halfedge_.push_back(newVert, -1, endProp); // fix prop
+ halfedge_.push_back(endVert, -1, endProp);
+ halfedge_.push_back(outsideVert, -1, halfedge_.Prop(opposite));
+ PairUp(newHalfedge + 2, halfedge_.Pair(opposite));
PairUp(newHalfedge + 1, opposite);
PairUp(newHalfedge, newHalfedge - 3);
if (meshRelation_.triRef.size() > 0)
@@ -386,7 +369,7 @@ void Manifold::Impl::DedupeEdge(const int edge) {
break;
}
- current = halfedge_[NextHalfedge(current)].pairedHalfedge;
+ current = halfedge_.Pair(NextHalfedge(current));
}
if (current == edge) {
@@ -396,20 +379,20 @@ void Manifold::Impl::DedupeEdge(const int edge) {
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
ForVert(NextHalfedge(current), [this, newVert](int e) {
- halfedge_[e].startVert = newVert;
- halfedge_[halfedge_[e].pairedHalfedge].endVert = newVert;
+ halfedge_.SetStart(e, newVert);
+ halfedge_.SetEnd(halfedge_.Pair(e), newVert);
});
}
// Orbit startVert
- const int pair = halfedge_[edge].pairedHalfedge;
- current = halfedge_[NextHalfedge(pair)].pairedHalfedge;
+ const int pair = halfedge_.Pair(edge);
+ current = halfedge_.Pair(NextHalfedge(pair));
while (current != pair) {
- const int vert = halfedge_[current].startVert;
+ const int vert = halfedge_.Start(current);
if (vert == endVert) {
break; // Connected: not a pinched vert
}
- current = halfedge_[NextHalfedge(current)].pairedHalfedge;
+ current = halfedge_.Pair(NextHalfedge(current));
}
if (current == pair) {
@@ -419,15 +402,15 @@ void Manifold::Impl::DedupeEdge(const int edge) {
if (vertNormal_.size() > 0) vertNormal_.push_back(vertNormal_[endVert]);
ForVert(NextHalfedge(current), [this, newVert](int e) {
- halfedge_[e].startVert = newVert;
- halfedge_[halfedge_[e].pairedHalfedge].endVert = newVert;
+ halfedge_.SetStart(e, newVert);
+ halfedge_.SetEnd(halfedge_.Pair(e), newVert);
});
}
}
void Manifold::Impl::PairUp(int edge0, int edge1) {
- halfedge_[edge0].pairedHalfedge = edge1;
- halfedge_[edge1].pairedHalfedge = edge0;
+ halfedge_.SetPair(edge0, edge1);
+ halfedge_.SetPair(edge1, edge0);
}
// Traverses CW around startEdge.endVert from startEdge to endEdge
@@ -436,10 +419,10 @@ void Manifold::Impl::PairUp(int edge0, int edge1) {
void Manifold::Impl::UpdateVert(int vert, int startEdge, int endEdge) {
int current = startEdge;
while (current != endEdge) {
- halfedge_[current].endVert = vert;
+ halfedge_.SetEnd(current, vert);
current = NextHalfedge(current);
- halfedge_[current].startVert = vert;
- current = halfedge_[current].pairedHalfedge;
+ halfedge_.SetStart(current, vert);
+ current = halfedge_.Pair(current);
DEBUG_ASSERT(current != startEdge, logicErr, "infinite loop in decimator!");
}
}
@@ -449,59 +432,54 @@ void Manifold::Impl::UpdateVert(int vert, int startEdge, int endEdge) {
// across this edge.
void Manifold::Impl::FormLoop(int current, int end) {
int startVert = vertPos_.size();
- vertPos_.push_back(vertPos_[halfedge_[current].startVert]);
+ vertPos_.push_back(vertPos_[halfedge_.Start(current)]);
int endVert = vertPos_.size();
- vertPos_.push_back(vertPos_[halfedge_[current].endVert]);
+ vertPos_.push_back(vertPos_[halfedge_.End(current)]);
- int oldMatch = halfedge_[current].pairedHalfedge;
- int newMatch = halfedge_[end].pairedHalfedge;
+ int oldMatch = halfedge_.Pair(current);
+ int newMatch = halfedge_.Pair(end);
UpdateVert(startVert, oldMatch, newMatch);
UpdateVert(endVert, end, current);
- halfedge_[current].pairedHalfedge = newMatch;
- halfedge_[newMatch].pairedHalfedge = current;
- halfedge_[end].pairedHalfedge = oldMatch;
- halfedge_[oldMatch].pairedHalfedge = end;
+ PairUp(current, newMatch);
+ PairUp(end, oldMatch);
RemoveIfFolded(end);
}
void Manifold::Impl::CollapseTri(const ivec3& triEdge) {
- if (halfedge_[triEdge[1]].pairedHalfedge == -1) return;
- int pair1 = halfedge_[triEdge[1]].pairedHalfedge;
- int pair2 = halfedge_[triEdge[2]].pairedHalfedge;
- halfedge_[pair1].pairedHalfedge = pair2;
- halfedge_[pair2].pairedHalfedge = pair1;
+ if (halfedge_.Pair(triEdge[1]) == -1) return;
+ int pair1 = halfedge_.Pair(triEdge[1]);
+ int pair2 = halfedge_.Pair(triEdge[2]);
+ PairUp(pair1, pair2);
for (int i : {0, 1, 2}) {
- halfedge_[triEdge[i]] = {-1, -1, -1, halfedge_[triEdge[i]].propVert};
+ halfedge_.Set(triEdge[i], -1, -1, halfedge_.Prop(triEdge[i]));
}
}
void Manifold::Impl::RemoveIfFolded(int edge) {
const ivec3 tri0edge = TriOf(edge);
- const ivec3 tri1edge = TriOf(halfedge_[edge].pairedHalfedge);
- if (halfedge_[tri0edge[1]].pairedHalfedge == -1) return;
- if (halfedge_[tri0edge[1]].endVert == halfedge_[tri1edge[1]].endVert) {
- if (halfedge_[tri0edge[1]].pairedHalfedge == tri1edge[2]) {
- if (halfedge_[tri0edge[2]].pairedHalfedge == tri1edge[1]) {
+ const ivec3 tri1edge = TriOf(halfedge_.Pair(edge));
+ if (halfedge_.Pair(tri0edge[1]) == -1) return;
+ if (halfedge_.Start(tri0edge[2]) == halfedge_.Start(tri1edge[2])) {
+ if (halfedge_.Pair(tri0edge[1]) == tri1edge[2]) {
+ if (halfedge_.Pair(tri0edge[2]) == tri1edge[1]) {
for (int i : {0, 1, 2})
- vertPos_[halfedge_[tri0edge[i]].startVert] = vec3(NAN);
+ vertPos_[halfedge_.Start(tri0edge[i])] = vec3(NAN);
} else {
- vertPos_[halfedge_[tri0edge[1]].startVert] = vec3(NAN);
+ vertPos_[halfedge_.Start(tri0edge[1])] = vec3(NAN);
}
} else {
- if (halfedge_[tri0edge[2]].pairedHalfedge == tri1edge[1]) {
- vertPos_[halfedge_[tri1edge[1]].startVert] = vec3(NAN);
+ if (halfedge_.Pair(tri0edge[2]) == tri1edge[1]) {
+ vertPos_[halfedge_.Start(tri1edge[1])] = vec3(NAN);
}
}
- PairUp(halfedge_[tri0edge[1]].pairedHalfedge,
- halfedge_[tri1edge[2]].pairedHalfedge);
- PairUp(halfedge_[tri0edge[2]].pairedHalfedge,
- halfedge_[tri1edge[1]].pairedHalfedge);
+ PairUp(halfedge_.Pair(tri0edge[1]), halfedge_.Pair(tri1edge[2]));
+ PairUp(halfedge_.Pair(tri0edge[2]), halfedge_.Pair(tri1edge[1]));
for (int i : {0, 1, 2}) {
- halfedge_[tri0edge[i]] = {-1, -1, -1};
- halfedge_[tri1edge[i]] = {-1, -1, -1};
+ halfedge_.Set(tri0edge[i], -1, -1, -1);
+ halfedge_.Set(tri1edge[i], -1, -1, -1);
}
}
}
@@ -511,31 +489,40 @@ void Manifold::Impl::RemoveIfFolded(int edge) {
// have resulted in a 4-manifold edge. Do not collapse an edge if startVert is
// pinched - the vert would be marked NaN, but other edges could still be
// pointing to it.
-bool Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
+bool Manifold::Impl::CollapseEdge(const int edge, Vec<int>& edges, double tol,
+ int firstNewVert) {
Vec<TriRef>& triRef = meshRelation_.triRef;
+ if (tol < 0) tol = epsilon_;
- const Halfedge toRemove = halfedge_[edge];
- if (toRemove.pairedHalfedge < 0) return false;
+ const int pair = halfedge_.Pair(edge);
+ if (pair < 0) return false;
- const int endVert = toRemove.endVert;
const ivec3 tri0edge = TriOf(edge);
- const ivec3 tri1edge = TriOf(toRemove.pairedHalfedge);
+ const ivec3 tri1edge = TriOf(pair);
+ const int startVert = halfedge_.Start(tri0edge[0]);
+ const int endVert = halfedge_.Start(tri0edge[1]);
const vec3 pNew = vertPos_[endVert];
- const vec3 pOld = vertPos_[toRemove.startVert];
+ const vec3 pOld = vertPos_[startVert];
const vec3 delta = pNew - pOld;
- const bool shortEdge = la::dot(delta, delta) < epsilon_ * epsilon_;
+ // We don't check that startVert is still new here - it may have been
+ // collapsed to a different neighbor. However, it's still fine to collapse it
+ // further, as it's still only collapsing its own original neighbors together,
+ // which can't stack errors arbitrarily far.
+ const double maxLen =
+ endVert < firstNewVert ? tol * tol : epsilon_ * epsilon_;
+ const bool shortEdge = la::dot(delta, delta) < maxLen;
// Orbit startVert
- int start = halfedge_[tri1edge[1]].pairedHalfedge;
+ int start = halfedge_.Pair(tri1edge[1]);
int current = tri1edge[2];
if (!shortEdge) {
current = start;
- TriRef refCheck = triRef[toRemove.pairedHalfedge / 3];
- vec3 pLast = vertPos_[halfedge_[tri1edge[1]].endVert];
+ TriRef refCheck = triRef[pair / 3];
+ vec3 pLast = vertPos_[halfedge_.Start(tri1edge[2])];
while (current != tri1edge[0]) {
current = NextHalfedge(current);
- vec3 pNext = vertPos_[halfedge_[current].endVert];
+ vec3 pNext = vertPos_[halfedge_.End(current)];
const int tri = current / 3;
const TriRef ref = triRef[tri];
const mat2x3 projection = GetAxisAlignedProjection(faceNormal_[tri]);
@@ -548,13 +535,12 @@ bool Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
return false;
}
if (ref.meshID != oldRef.meshID || ref.faceID != oldRef.faceID ||
- la::dot(faceNormal_[toRemove.pairedHalfedge / 3],
- faceNormal_[tri]) < -0.5) {
+ la::dot(faceNormal_[pair / 3], faceNormal_[tri]) < -0.5) {
// Restrict collapse to colinear edges when the edge separates faces
// or the edge is sharp. This ensures large shifts are not introduced
// parallel to the tangent plane.
if (CCW(projection * pLast, projection * pOld, projection * pNew,
- epsilon_) != 0)
+ tol) != 0)
return false;
}
}
@@ -565,27 +551,27 @@ bool Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
return false;
pLast = pNext;
- current = halfedge_[current].pairedHalfedge;
+ current = halfedge_.Pair(current);
}
}
// Orbit endVert
{
- int current = halfedge_[tri0edge[1]].pairedHalfedge;
+ int current = halfedge_.Pair(tri0edge[1]);
while (current != tri1edge[2]) {
current = NextHalfedge(current);
edges.push_back(current);
- current = halfedge_[current].pairedHalfedge;
+ current = halfedge_.Pair(current);
}
}
// Remove toRemove.startVert and replace with endVert.
- vertPos_[toRemove.startVert] = vec3(NAN);
+ vertPos_[startVert] = vec3(NAN);
CollapseTri(tri1edge);
// Orbit startVert
const int tri0 = edge / 3;
- const int tri1 = toRemove.pairedHalfedge / 3;
+ const int tri1 = pair / 3;
current = start;
while (current != tri0edge[2]) {
current = NextHalfedge(current);
@@ -594,17 +580,16 @@ bool Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
// Update the shifted triangles to the vertBary of endVert
const int tri = current / 3;
if (triRef[tri].SameFace(triRef[tri0])) {
- halfedge_[current].propVert = halfedge_[NextHalfedge(edge)].propVert;
+ halfedge_.SetProp(current, halfedge_.Prop(NextHalfedge(edge)));
} else if (triRef[tri].SameFace(triRef[tri1])) {
- halfedge_[current].propVert =
- halfedge_[toRemove.pairedHalfedge].propVert;
+ halfedge_.SetProp(current, halfedge_.Prop(pair));
}
}
- const int vert = halfedge_[current].endVert;
- const int next = halfedge_[current].pairedHalfedge;
+ const int vert = halfedge_.End(current);
+ const int next = halfedge_.Pair(current);
for (size_t i = 0; i < edges.size(); ++i) {
- if (vert == halfedge_[edges[i]].endVert) {
+ if (vert == halfedge_.End(edges[i])) {
FormLoop(edges[i], current);
start = next;
edges.resize(i);
@@ -621,13 +606,13 @@ bool Manifold::Impl::CollapseEdge(const int edge, std::vector<int>& edges) {
}
void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
- std::vector<int>& visited,
- std::vector<int>& edgeSwapStack,
- std::vector<int>& edges) {
+ Vec<int>& visited,
+ Vec<int>& edgeSwapStack,
+ Vec<int>& edges) {
Vec<TriRef>& triRef = meshRelation_.triRef;
if (edge < 0) return;
- const int pair = halfedge_[edge].pairedHalfedge;
+ const int pair = halfedge_.Pair(edge);
if (pair < 0) return;
// avoid infinite recursion
@@ -639,7 +624,7 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
mat2x3 projection = GetAxisAlignedProjection(faceNormal_[edge / 3]);
vec2 v[4];
for (int i : {0, 1, 2})
- v[i] = projection * vertPos_[halfedge_[tri0edge[i]].startVert];
+ v[i] = projection * vertPos_[halfedge_.Start(tri0edge[i])];
// Only operate on the long edge of a degenerate triangle.
if (CCW(v[0], v[1], v[2], tolerance_) > 0 || !Is01Longest(v[0], v[1], v[2]))
return;
@@ -647,19 +632,19 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
// Switch to neighbor's projection.
projection = GetAxisAlignedProjection(faceNormal_[pair / 3]);
for (int i : {0, 1, 2})
- v[i] = projection * vertPos_[halfedge_[tri0edge[i]].startVert];
- v[3] = projection * vertPos_[halfedge_[tri1edge[2]].startVert];
+ v[i] = projection * vertPos_[halfedge_.Start(tri0edge[i])];
+ v[3] = projection * vertPos_[halfedge_.Start(tri1edge[2])];
auto SwapEdge = [&]() {
// The 0-verts are swapped to the opposite 2-verts.
- const int v0 = halfedge_[tri0edge[2]].startVert;
- const int v1 = halfedge_[tri1edge[2]].startVert;
- halfedge_[tri0edge[0]].startVert = v1;
- halfedge_[tri0edge[2]].endVert = v1;
- halfedge_[tri1edge[0]].startVert = v0;
- halfedge_[tri1edge[2]].endVert = v0;
- PairUp(tri0edge[0], halfedge_[tri1edge[2]].pairedHalfedge);
- PairUp(tri1edge[0], halfedge_[tri0edge[2]].pairedHalfedge);
+ const int v0 = halfedge_.Start(tri0edge[2]);
+ const int v1 = halfedge_.Start(tri1edge[2]);
+ halfedge_.SetStart(tri0edge[0], v1);
+ halfedge_.SetEnd(tri0edge[2], v1);
+ halfedge_.SetStart(tri1edge[0], v0);
+ halfedge_.SetEnd(tri1edge[2], v0);
+ PairUp(tri0edge[0], halfedge_.Pair(tri1edge[2]));
+ PairUp(tri1edge[0], halfedge_.Pair(tri0edge[2]));
PairUp(tri0edge[2], tri1edge[2]);
// Both triangles are now subsets of the neighboring triangle.
const int tri0 = tri0edge[0] / 3;
@@ -672,32 +657,32 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
// Update properties if applicable
if (properties_.size() > 0) {
Vec<double>& prop = properties_;
- halfedge_[tri0edge[1]].propVert = halfedge_[tri1edge[0]].propVert;
- halfedge_[tri0edge[0]].propVert = halfedge_[tri1edge[2]].propVert;
- halfedge_[tri0edge[2]].propVert = halfedge_[tri1edge[2]].propVert;
+ halfedge_.SetProp(tri0edge[1], halfedge_.Prop(tri1edge[0]));
+ halfedge_.SetProp(tri0edge[0], halfedge_.Prop(tri1edge[2]));
+ halfedge_.SetProp(tri0edge[2], halfedge_.Prop(tri1edge[2]));
const int numProp = NumProp();
const int newProp = prop.size() / numProp;
- const int propIdx0 = halfedge_[tri1edge[0]].propVert;
- const int propIdx1 = halfedge_[tri1edge[1]].propVert;
+ const int propIdx0 = halfedge_.Prop(tri1edge[0]);
+ const int propIdx1 = halfedge_.Prop(tri1edge[1]);
for (int p = 0; p < numProp; ++p) {
prop.push_back(a * prop[numProp * propIdx0 + p] +
(1 - a) * prop[numProp * propIdx1 + p]);
}
- halfedge_[tri1edge[0]].propVert = newProp;
- halfedge_[tri0edge[2]].propVert = newProp;
+ halfedge_.SetProp(tri1edge[0], newProp);
+ halfedge_.SetProp(tri0edge[2], newProp);
}
// if the new edge already exists, duplicate the verts and split the mesh.
- int current = halfedge_[tri1edge[0]].pairedHalfedge;
- const int endVert = halfedge_[tri1edge[1]].endVert;
+ int current = halfedge_.Pair(tri1edge[0]);
+ const int endVert = halfedge_.End(tri1edge[1]);
while (current != tri0edge[1]) {
current = NextHalfedge(current);
- if (halfedge_[current].endVert == endVert) {
+ if (halfedge_.End(current) == endVert) {
FormLoop(tri0edge[2], current);
RemoveIfFolded(tri0edge[2]);
return;
}
- current = halfedge_[current].pairedHalfedge;
+ current = halfedge_.Pair(current);
}
};
@@ -714,8 +699,8 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
} else {
visited[edge] = tag;
visited[pair] = tag;
- edgeSwapStack.insert(edgeSwapStack.end(), {tri1edge[1], tri1edge[0],
- tri0edge[1], tri0edge[0]});
+ for (auto edge : {tri1edge[1], tri1edge[0], tri0edge[1], tri0edge[0]})
+ edgeSwapStack.push_back(edge);
}
return;
} else if (CCW(v[0], v[3], v[2], tolerance_) <= 0 ||
@@ -726,9 +711,8 @@ void Manifold::Impl::RecursiveEdgeSwap(const int edge, int& tag,
SwapEdge();
visited[edge] = tag;
visited[pair] = tag;
- edgeSwapStack.insert(edgeSwapStack.end(),
- {halfedge_[tri1edge[0]].pairedHalfedge,
- halfedge_[tri0edge[1]].pairedHalfedge});
+ for (auto edge : {halfedge_.Pair(tri1edge[0]), halfedge_.Pair(tri0edge[1])})
+ edgeSwapStack.push_back(edge);
}
void Manifold::Impl::SplitPinchedVerts() {
@@ -744,7 +728,7 @@ void Manifold::Impl::SplitPinchedVerts() {
// The idea here is to identify cycles of halfedges that can be iterated
// through using ForVert. Pinched verts are vertices where there are
// multiple cycles associated with the vertex. Each cycle is identified with
- // the largest halfedge index within the cycle, and when there are multiple
+ // the smallest halfedge index within the cycle, and when there are multiple
// cycles associated with the same starting vertex but with different ids,
// it means we have a pinched vertex. This check is done by using a single
// atomic cas operation, the expected case is either invalid id (the vertex
@@ -755,7 +739,7 @@ void Manifold::Impl::SplitPinchedVerts() {
// halfedges because it is thread local. This is why we need a vector to
// deduplicate the probematic halfedges we found.
std::vector<std::atomic<size_t>> largestEdge(NumVert());
- for_each(ExecutionPolicy::Par, countAt(0), countAt(NumVert()),
+ for_each(ExecutionPolicy::Par, countAt(0_uz), countAt(NumVert()),
[&largestEdge](size_t i) {
largestEdge[i].store(std::numeric_limits<size_t>::max());
});
@@ -769,18 +753,20 @@ void Manifold::Impl::SplitPinchedVerts() {
for (auto i = r.begin(); i < r.end(); ++i) {
if (local[i]) continue;
local[i] = true;
- const int vert = halfedge_[i].startVert;
+ const int vert = halfedge_.Start(i);
if (vert == -1) continue;
- size_t largest = i;
- ForVert(i, [&local, &largest](int current) {
+ size_t smallest = i;
+ ForVert(i, [&local, &smallest](int current) {
local[current] = true;
- largest = std::max(largest, static_cast<size_t>(current));
+ smallest = std::min(smallest, static_cast<size_t>(current));
});
- size_t expected = std::numeric_limits<size_t>::max();
- if (!largestEdge[vert].compare_exchange_strong(expected, largest) &&
- expected != largest) {
+ size_t got = std::numeric_limits<size_t>::max();
+ if (!largestEdge[vert].compare_exchange_strong(got, smallest) &&
+ got != smallest) {
// we know that there is another loop...
- pinchedLocal.push_back(largest);
+ // put all to pinched
+ pinchedLocal.push_back(smallest);
+ pinchedLocal.push_back(got);
}
}
if (!pinchedLocal.empty()) {
@@ -791,15 +777,20 @@ void Manifold::Impl::SplitPinchedVerts() {
});
manifold::stable_sort(pinched.begin(), pinched.end());
- std::vector<bool> halfedgeProcessed(nbEdges, false);
+ pinched.resize(std::distance(
+ pinched.begin(), manifold::unique(pinched.begin(), pinched.end())));
+ std::unordered_set<int> processedVerts;
for (size_t i : pinched) {
- if (halfedgeProcessed[i]) continue;
- vertPos_.push_back(vertPos_[halfedge_[i].startVert]);
+ const int startVert = halfedge_.Start(i);
+ if (processedVerts.find(startVert) == processedVerts.end()) {
+ processedVerts.insert(startVert);
+ continue;
+ }
+ vertPos_.push_back(vertPos_[startVert]);
const int vert = NumVert() - 1;
- ForVert(i, [this, vert, &halfedgeProcessed](int current) {
- halfedgeProcessed[current] = true;
- halfedge_[current].startVert = vert;
- halfedge_[halfedge_[current].pairedHalfedge].endVert = vert;
+ ForVert(i, [this, vert](int current) {
+ halfedge_.SetStart(current, vert);
+ halfedge_.SetEnd(halfedge_.Pair(current), vert);
});
}
} else
@@ -809,19 +800,22 @@ void Manifold::Impl::SplitPinchedVerts() {
std::vector<bool> halfedgeProcessed(nbEdges, false);
for (size_t i = 0; i < nbEdges; ++i) {
if (halfedgeProcessed[i]) continue;
- int vert = halfedge_[i].startVert;
+ int vert = halfedge_.Start(i);
if (vert == -1) continue;
if (vertProcessed[vert]) {
vertPos_.push_back(vertPos_[vert]);
vert = NumVert() - 1;
+ ForVert(i, [this, &halfedgeProcessed, vert](int current) {
+ halfedgeProcessed[current] = true;
+ halfedge_.SetStart(current, vert);
+ halfedge_.SetEnd(halfedge_.Pair(current), vert);
+ });
} else {
vertProcessed[vert] = true;
+ ForVert(i, [this, &halfedgeProcessed, vert](int current) {
+ halfedgeProcessed[current] = true;
+ });
}
- ForVert(i, [this, &halfedgeProcessed, vert](int current) {
- halfedgeProcessed[current] = true;
- halfedge_[current].startVert = vert;
- halfedge_[halfedge_[current].pairedHalfedge].endVert = vert;
- });
}
}
}
@@ -851,9 +845,10 @@ void Manifold::Impl::DedupeEdges() {
Vec<std::pair<int, int>> endVerts;
std::unordered_map<int, int> endVertSet;
for (auto i = start; i < end; ++i) {
- if (local[i] || halfedge_[i].startVert == -1 ||
- halfedge_[i].endVert == -1)
- continue;
+ if (local[i]) continue;
+ const int startVert = halfedge_.Start(i);
+ const int endVert = halfedge_.End(i);
+ if (startVert == -1 || endVert == -1) continue;
// we want to keep the allocation
endVerts.clear(false);
endVertSet.clear();
@@ -862,11 +857,9 @@ void Manifold::Impl::DedupeEdges() {
// this makes sure we always report the same set of entries
ForVert(i, [&local, &endVerts, &endVertSet, this](int current) {
local[current] = true;
- if (halfedge_[current].startVert == -1 ||
- halfedge_[current].endVert == -1) {
- return;
- }
- int endV = halfedge_[current].endVert;
+ const int startVert = halfedge_.Start(current);
+ const int endV = halfedge_.End(current);
+ if (startVert == -1 || endV == -1) return;
if (endVertSet.empty()) {
auto iter = std::find_if(endVerts.begin(), endVerts.end(),
[endV](const std::pair<int, int>& pair) {
@@ -891,11 +884,9 @@ void Manifold::Impl::DedupeEdges() {
// we always report the same set of duplicates, excluding the smallest
// halfedge in the set of duplicates
ForVert(i, [&endVerts, &endVertSet, &results, this](int current) {
- if (halfedge_[current].startVert == -1 ||
- halfedge_[current].endVert == -1) {
- return;
- }
- int endV = halfedge_[current].endVert;
+ const int startVert = halfedge_.Start(current);
+ const int endV = halfedge_.End(current);
+ if (startVert == -1 || endV == -1) return;
if (endVertSet.empty()) {
auto iter = std::find_if(endVerts.begin(), endVerts.end(),
[endV](const std::pair<int, int>& pair) {
@@ -946,7 +937,7 @@ void Manifold::Impl::DedupeEdges() {
if (numFlagged == 0) break;
#ifdef MANIFOLD_DEBUG
- if (ManifoldParams().verbose > 0) {
+ if (ManifoldParams().verbose >= 2) {
std::cout << "found " << numFlagged << " duplicate edges to split"
<< std::endl;
}
diff --git a/thirdparty/manifold/src/execution_impl.cpp b/thirdparty/manifold/src/execution_impl.cpp
new file mode 100644
index 00000000000..062639fe38a
--- /dev/null
+++ b/thirdparty/manifold/src/execution_impl.cpp
@@ -0,0 +1,141 @@
+// Copyright 2026 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "execution_impl.h"
+
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+#include <chrono>
+#include <cstring>
+#include <iostream>
+#endif
+
+#include "impl.h"
+#include "manifold/manifold.h"
+#include "manifold/mesh.h"
+
+namespace {
+using namespace manifold;
+
+// Reset progress counters at the start of an eager static-factory call.
+// Done counters reset before totals so an observer never reads
+// Progress > 1.0 (it may briefly read 0). Cancel is intentionally
+// preserved - sticky across ops per the ExecutionContext contract.
+void ResetForStaticFactory(ExecutionContext::Impl* ctx, int totalPhases) {
+ ctx->doneBooleans.store(0, std::memory_order_relaxed);
+ ctx->donePhases.store(0, std::memory_order_relaxed);
+ ctx->totalBooleans.store(0, std::memory_order_relaxed);
+ ctx->totalPhases.store(totalPhases, std::memory_order_relaxed);
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ ctx->lastPhase = std::chrono::high_resolution_clock::now();
+#endif
+}
+
+} // namespace
+namespace manifold {
+
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+void RecordPhase(ExecutionContext::Impl* ctx, const char* file, int line) {
+ const auto now = std::chrono::high_resolution_clock::now();
+ if (ManifoldParams().verbose >= 2) {
+ const double ms =
+ std::chrono::duration<double, std::milli>(now - ctx->lastPhase).count();
+ const char* slash = std::strrchr(file, '/');
+ std::cout << " phase " << ctx->donePhases.load(std::memory_order_relaxed)
+ << " (" << (slash ? slash + 1 : file) << ":" << line
+ << ") = " << ms << " ms" << std::endl;
+ }
+ ctx->lastPhase = now;
+}
+
+LocalPhaseTiming BeginLocalPhaseTiming() {
+ static std::atomic<int> counter{0};
+ return {std::chrono::high_resolution_clock::now(),
+ counter.fetch_add(1, std::memory_order_relaxed)};
+}
+
+void RecordPhase(LocalPhaseTiming& timing, int phase, const char* file,
+ int line) {
+ const auto now = std::chrono::high_resolution_clock::now();
+ if (ManifoldParams().verbose >= 2) {
+ const double ms =
+ std::chrono::duration<double, std::milli>(now - timing.last).count();
+ const char* slash = std::strrchr(file, '/');
+ std::cout << " [b" << timing.uid << "] phase " << phase << " ("
+ << (slash ? slash + 1 : file) << ":" << line << ") = " << ms
+ << " ms" << std::endl;
+ }
+ timing.last = now;
+}
+#endif
+
+ExecutionContext::ExecutionContext() : impl_(std::make_shared<Impl>()) {}
+ExecutionContext::~ExecutionContext() = default;
+ExecutionContext::ExecutionContext(const ExecutionContext&) = default;
+ExecutionContext::ExecutionContext(ExecutionContext&&) noexcept = default;
+ExecutionContext& ExecutionContext::operator=(const ExecutionContext&) =
+ default;
+ExecutionContext& ExecutionContext::operator=(ExecutionContext&&) noexcept =
+ default;
+
+void ExecutionContext::Cancel() {
+ impl_->cancel.store(true, std::memory_order_relaxed);
+}
+
+bool ExecutionContext::Cancelled() const { return IsCancelled(impl_.get()); }
+
+double ExecutionContext::Progress() const {
+ const int total = impl_->totalPhases.load(std::memory_order_relaxed);
+ // Zero-work case: no phases scheduled (single-leaf manifold, or
+ // pre-evaluation). Treat as complete -- "no work to do" maps to 100%
+ // more naturally than 0%, and matches the user expectation that a
+ // returned `Status() == NoError` means the operation is done.
+ if (total == 0) return 1.0;
+ return double(impl_->donePhases.load(std::memory_order_relaxed)) / total;
+}
+
+Manifold ExecutionContext::FromMeshGL(const MeshGL& mesh) {
+ ResetForStaticFactory(impl_.get(), kPhasesPerFromMesh);
+ return Manifold::FromImpl(
+ std::make_shared<Manifold::Impl>(mesh, impl_.get()));
+}
+
+Manifold ExecutionContext::FromMeshGL(const MeshGL64& mesh) {
+ ResetForStaticFactory(impl_.get(), kPhasesPerFromMesh);
+ return Manifold::FromImpl(
+ std::make_shared<Manifold::Impl>(mesh, impl_.get()));
+}
+
+Manifold ExecutionContext::Smooth(
+ const MeshGL& mesh, const std::vector<Smoothness>& sharpenedEdges) {
+ ResetForStaticFactory(impl_.get(), kPhasesPerSmooth);
+ return Manifold::FromImpl(MakeSmoothImpl(mesh, sharpenedEdges, impl_.get()));
+}
+
+Manifold ExecutionContext::Smooth(
+ const MeshGL64& mesh, const std::vector<Smoothness>& sharpenedEdges) {
+ ResetForStaticFactory(impl_.get(), kPhasesPerSmooth);
+ return Manifold::FromImpl(MakeSmoothImpl(mesh, sharpenedEdges, impl_.get()));
+}
+
+Manifold ExecutionContext::LevelSet(std::function<double(vec3)> sdf, Box bounds,
+ double edgeLength, double level,
+ double tolerance, bool canParallel) {
+ ResetForStaticFactory(impl_.get(), kPhasesPerLevelSet);
+ auto pImpl = std::make_shared<Manifold::Impl>();
+ pImpl->CreateLevelSet(sdf, bounds, edgeLength, level, tolerance, canParallel,
+ impl_.get());
+ return Manifold::FromImpl(pImpl);
+}
+
+} // namespace manifold
diff --git a/thirdparty/manifold/src/execution_impl.h b/thirdparty/manifold/src/execution_impl.h
new file mode 100644
index 00000000000..e3608743e7e
--- /dev/null
+++ b/thirdparty/manifold/src/execution_impl.h
@@ -0,0 +1,160 @@
+// Copyright 2026 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+#include <atomic>
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+#include <chrono>
+#endif
+
+#include "manifold/common.h"
+
+namespace manifold {
+
+inline bool IsCancelled(ExecutionContext::Impl* ctx);
+
+/** @ingroup Private
+ *
+ * Number of progress phases per `Boolean3::Result`. Must equal the count of
+ * `phase()` sites in `boolean_result.cpp`'s `Boolean3::Result` (asserted on
+ * the happy-path return). Bump in lockstep when adding/removing a site.
+ */
+constexpr int kPhasesPerBoolean = 11;
+
+/** @ingroup Private
+ *
+ * Heavy phases in the `Manifold::Impl::Impl(MeshGLP, ctx)` ingest;
+ * credit is published only after a phase completes successfully. Bump
+ * in lockstep with the `donePhases.fetch_add(1, ...)` sites in the
+ * ctor body.
+ */
+constexpr int kPhasesPerFromMesh = 7;
+
+/** @ingroup Private
+ *
+ * Heavy phases in `ExecutionContext::Smooth(MeshGL[64])`: the
+ * `kPhasesPerFromMesh` ingest phases followed by 7 tangent-creation
+ * phases in `Manifold::Impl::CreateTangents(sharpenedEdges, ctx)`.
+ * Bump in lockstep with `ADVANCE_PHASE_OR_RETURN(ctx)` sites in that
+ * function.
+ */
+constexpr int kPhasesPerSmooth = kPhasesPerFromMesh + 7;
+
+/** @ingroup Private
+ *
+ * Heavy phases in `Manifold::Impl::CreateLevelSet(...)`: the four grid
+ * loops (voxel SDF sampling, NearSurface, ComputeVerts, BuildTris)
+ * followed by one lumped finalize phase (CreateHalfedges through
+ * SetNormalsAndCoplanar). The NearSurface hash-table resize loop may
+ * re-run NearSurface, but counts as a single phase regardless. Bump in
+ * lockstep with `ADVANCE_PHASE_OR_RETURN(ctx)` sites in CreateLevelSet.
+ */
+constexpr int kPhasesPerLevelSet = 5;
+
+/** @ingroup Private
+ *
+ * Pimpl for ExecutionContext. `cancel` is private; use `IsCancelled(ctx)`
+ * to read it -- this is the canonical reader, enforced by the type system.
+ * `totalBooleans`, `doneBooleans`, `totalPhases`, and `donePhases` are
+ * public for progress reporting and test introspection.
+ *
+ * `Progress() = donePhases / totalPhases`. `totalPhases` is the canonical
+ * progress denominator across op types; for Boolean trees it is set at
+ * `GetCsgLeafNode` to `totalBooleans * kPhasesPerBoolean`. Future
+ * non-Boolean ops (Hull, LevelSet, Refine, ...) can add to `totalPhases`
+ * and increment `donePhases` independently using the same mechanism.
+ *
+ * `totalBooleans`/`doneBooleans` are kept as introspection counters for
+ * tests and tools; they are not used in `Progress()`.
+ */
+struct ExecutionContext::Impl {
+ public:
+ std::atomic<int> totalBooleans{0};
+ std::atomic<int> doneBooleans{0};
+ std::atomic<int> totalPhases{0};
+ std::atomic<int> donePhases{0};
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+ // Wall-clock of the last phase boundary, for per-phase timing via
+ // ADVANCE_PHASE_OR_RETURN. Stamped at the static-factory reset; touched only
+ // by the op's own thread.
+ std::chrono::high_resolution_clock::time_point lastPhase{};
+#endif
+
+ private:
+ std::atomic<bool> cancel{false};
+
+ friend bool IsCancelled(Impl*);
+ friend class manifold::ExecutionContext;
+};
+
+/** @ingroup Private
+ *
+ * Canonical reader for the cancel flag. The only path to observe cancel
+ * state from internal code -- `Impl::cancel` is private and friended only
+ * to this function and `ExecutionContext` (for its public `Cancel`/`Cancelled`
+ * members). The ctx-aware overloads in `parallel.h` go through here.
+ *
+ * Returns false if `ctx` is nullptr (no-cancellation calls), otherwise
+ * loads `cancel` with `memory_order_relaxed` (cancel is advisory; we
+ * don't need synchronization with other operations).
+ */
+inline bool IsCancelled(ExecutionContext::Impl* ctx) {
+ return ctx && ctx->cancel.load(std::memory_order_relaxed);
+}
+
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+// Times the span since the previous phase boundary (or the static-factory
+// reset) and prints it when verbose >= 2. Called by ADVANCE_PHASE_OR_RETURN;
+// defined in execution_impl.cpp so <chrono>/<iostream> stay out of this
+// widely-included header.
+void RecordPhase(ExecutionContext::Impl* ctx, const char* file, int line);
+
+// Per-op local phase-timing state. Boolean3::Result keeps this on its own
+// stack rather than on the shared ctx, so concurrent booleans in a CSG tree
+// don't clobber each other's baseline. `uid` tags the printed lines so the
+// interleaved output of parallel booleans can be split apart.
+struct LocalPhaseTiming {
+ std::chrono::high_resolution_clock::time_point last;
+ int uid;
+};
+LocalPhaseTiming BeginLocalPhaseTiming();
+void RecordPhase(LocalPhaseTiming& timing, int phase, const char* file,
+ int line);
+#endif
+
+} // namespace manifold
+
+/** @ingroup Private
+ *
+ * Phase-boundary checkpoint for `Manifold::Impl` methods (relies on
+ * `this->MakeEmpty`). Call count must equal the method's `kPhasesPer*`.
+ */
+#if defined(MANIFOLD_DEBUG) || defined(MANIFOLD_TIMING)
+#define MANIFOLD_RECORD_PHASE(ctx) \
+ manifold::RecordPhase((ctx), __FILE__, __LINE__)
+#else
+#define MANIFOLD_RECORD_PHASE(ctx) ((void)0)
+#endif
+
+#define ADVANCE_PHASE_OR_RETURN(ctx) \
+ do { \
+ if (manifold::IsCancelled(ctx)) { \
+ MakeEmpty(manifold::Manifold::Error::Cancelled); \
+ return; \
+ } \
+ if (ctx) { \
+ (ctx)->donePhases.fetch_add(1, std::memory_order_relaxed); \
+ MANIFOLD_RECORD_PHASE(ctx); \
+ } \
+ } while (0)
diff --git a/thirdparty/manifold/src/face_op.cpp b/thirdparty/manifold/src/face_op.cpp
index 5e826dd73b3..9ada39bdd5c 100644
--- a/thirdparty/manifold/src/face_op.cpp
+++ b/thirdparty/manifold/src/face_op.cpp
@@ -12,12 +12,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+#include <array>
#include <unordered_set>
#include "impl.h"
#include "manifold/common.h"
#include "manifold/polygon.h"
#include "parallel.h"
+#include "polygon_internal.h"
#include "shared.h"
#if (MANIFOLD_PAR == 1) && __has_include(<tbb/concurrent_map.h>)
@@ -68,7 +70,7 @@ std::vector<std::vector<int>> AssembleHalfedges(VecView<Halfedge>::IterC start,
* Add the vertex position projection to the indexed polygons.
*/
PolygonsIdx ProjectPolygons(const std::vector<std::vector<int>>& polys,
- const Vec<Halfedge>& halfedge,
+ const VecView<const Halfedge>& halfedge,
const Vec<vec3>& vertPos, mat2x3 projection) {
PolygonsIdx polygons;
for (const auto& poly : polys) {
@@ -80,13 +82,98 @@ PolygonsIdx ProjectPolygons(const std::vector<std::vector<int>>& polys,
} // for poly
return polygons;
}
+
+void WriteLocalTriangles(Halfedges& output, VecView<int> contour2Tri,
+ const VecView<const Halfedge>& faceHalfedge,
+ size_t firstTri, const ivec3* triangles, int numTri) {
+ DEBUG_ASSERT(numTri <= 2, logicErr,
+ "local face path only handles tris/quads");
+ std::array<ivec3, 6> localEdges;
+ const int firstOut = 3 * firstTri;
+ int numEdge = 0;
+ for (int tri = 0; tri < numTri; ++tri) {
+ for (const int i : {0, 1, 2}) {
+ const int out = firstOut + numEdge;
+ const int start = triangles[tri][i];
+ const int end = triangles[tri][Next3(i)];
+ localEdges[numEdge] = {start, end, out};
+ output.SetStart(out, faceHalfedge[start].startVert);
+ output.SetProp(out, faceHalfedge[start].propVert);
+ output.SetPair(out, -1);
+ ++numEdge;
+ }
+ }
+
+ for (int i = 0; i < numEdge; ++i) {
+ const ivec3 edge = localEdges[i];
+ int pair = -1;
+ for (int j = 0; j < numEdge; ++j) {
+ if (localEdges[j][0] == edge[1] && localEdges[j][1] == edge[0]) {
+ pair = localEdges[j][2];
+ break;
+ }
+ }
+ if (pair >= 0) {
+ output.SetPair(edge[2], pair);
+ } else {
+ contour2Tri[edge[0]] = edge[2];
+ }
+ }
+}
+
+void WriteGeneralTriangulation(Halfedges& output, VecView<int> contour2Tri,
+ const VecView<const Halfedge>& faceHalfedge,
+ size_t firstTri,
+ const HalfedgeTriangulation& triangulation,
+ ExecutionContext::Impl* ctx) {
+ const int firstOut = 3 * firstTri;
+ const size_t numTriHalfedge = 3 * triangulation.NumTri();
+ for_each_n(
+ autoPolicy(numTriHalfedge, 1e5), countAt(0_uz), numTriHalfedge, ctx,
+ [&](size_t local) {
+ const int out = firstOut + local;
+ const Halfedge& edge =
+ triangulation.halfedges[triangulation.contourEnd + local];
+ output.SetStart(out, faceHalfedge[edge.startVert].startVert);
+ output.SetProp(out, faceHalfedge[edge.startVert].propVert);
+ if (edge.pairedHalfedge >= static_cast<int>(triangulation.contourEnd)) {
+ output.SetPair(out, firstOut + edge.pairedHalfedge -
+ static_cast<int>(triangulation.contourEnd));
+ } else {
+ output.SetPair(out, -1);
+ }
+ });
+
+ for_each_n(autoPolicy(triangulation.contourEnd, 1e5), countAt(0_uz),
+ triangulation.contourEnd, ctx, [&](size_t contour) {
+ const Halfedge& edge = triangulation.halfedges[contour];
+ if (edge.pairedHalfedge < 0) return;
+ DEBUG_ASSERT(edge.pairedHalfedge >=
+ static_cast<int>(triangulation.contourEnd),
+ topologyErr, "contour paired to another contour");
+ const int boundary = edge.endVert;
+ DEBUG_ASSERT(boundary >= 0 &&
+ boundary < static_cast<int>(contour2Tri.size()),
+ topologyErr, "contour edge index out of bounds");
+ contour2Tri[boundary] =
+ firstOut + edge.pairedHalfedge -
+ static_cast<int>(triangulation.contourEnd);
+ });
+}
+
+void WriteTriRefs(VecView<vec3> triNormal, VecView<TriRef> triRef,
+ size_t firstTri, size_t numTri, vec3 normal, TriRef ref,
+ ExecutionContext::Impl* ctx) {
+ for_each_n(autoPolicy(numTri, 1e5), countAt(0_uz), numTri, ctx,
+ [&](size_t tri) {
+ triNormal[firstTri + tri] = normal;
+ triRef[firstTri + tri] = ref;
+ });
+}
} // namespace
namespace manifold {
-using GeneralTriangulation = std::function<std::vector<ivec3>(int)>;
-using AddTriangle = std::function<void(int, ivec3, vec3, TriRef)>;
-
/**
* Triangulates the faces. In this case, the halfedge_ vector is not yet a set
* of triangles as required by this data structure, but is instead a set of
@@ -98,30 +185,45 @@ using AddTriangle = std::function<void(int, ivec3, vec3, TriRef)>;
* faceNormal_ values are retained, repeated as necessary.
*/
void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
- const Vec<TriRef>& halfedgeRef,
- bool allowConvex) {
+ const VecView<const Halfedge>& faceHalfedge,
+ const Vec<TriRef>& halfedgeRef, bool allowConvex,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
- Vec<ivec3> triVerts;
+ if (IsCancelled(ctx)) return;
Vec<vec3> triNormal;
- Vec<ivec3> triProp;
Vec<TriRef>& triRef = meshRelation_.triRef;
triRef.clear();
- auto processFace = [&](GeneralTriangulation general, AddTriangle addTri,
- int face) {
+ Vec<int> contour2Tri(faceHalfedge.size(), -1);
+
+ auto generalTriangulation = [&](int face) {
+ const vec3 normal = faceNormal_[face];
+ const mat2x3 projection = GetAxisAlignedProjection(normal);
+ const PolygonsIdx polys = ProjectPolygons(
+ AssembleHalfedges(faceHalfedge.cbegin() + faceEdge[face],
+ faceHalfedge.cbegin() + faceEdge[face + 1],
+ faceEdge[face]),
+ faceHalfedge, vertPos_, projection);
+ return TriangulateIdxHalfedges(polys, epsilon_, allowConvex);
+ };
+
+ auto outputFace = [&](int face, size_t firstTri,
+ const HalfedgeTriangulation* general) {
const int firstEdge = faceEdge[face];
const int lastEdge = faceEdge[face + 1];
const int numEdge = lastEdge - firstEdge;
if (numEdge == 0) return;
DEBUG_ASSERT(numEdge >= 3, topologyErr, "face has less than three edges.");
const vec3 normal = faceNormal_[face];
+ size_t numTri = numEdge - 2;
if (numEdge == 3) { // Single triangle
ivec3 triEdge(firstEdge, firstEdge + 1, firstEdge + 2);
- ivec3 tri(halfedge_[firstEdge].startVert,
- halfedge_[firstEdge + 1].startVert,
- halfedge_[firstEdge + 2].startVert);
- ivec3 ends(halfedge_[firstEdge].endVert, halfedge_[firstEdge + 1].endVert,
- halfedge_[firstEdge + 2].endVert);
+ ivec3 tri(faceHalfedge[firstEdge].startVert,
+ faceHalfedge[firstEdge + 1].startVert,
+ faceHalfedge[firstEdge + 2].startVert);
+ ivec3 ends(faceHalfedge[firstEdge].endVert,
+ faceHalfedge[firstEdge + 1].endVert,
+ faceHalfedge[firstEdge + 2].endVert);
if (ends[0] == tri[2]) {
std::swap(triEdge[1], triEdge[2]);
std::swap(tri[1], tri[2]);
@@ -130,19 +232,20 @@ void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
DEBUG_ASSERT(ends[0] == tri[1] && ends[1] == tri[2] && ends[2] == tri[0],
topologyErr, "These 3 edges do not form a triangle!");
- addTri(face, triEdge, normal, halfedgeRef[firstEdge]);
+ WriteLocalTriangles(halfedge_, contour2Tri, faceHalfedge, firstTri,
+ &triEdge, 1);
} else if (numEdge == 4) { // Pair of triangles
const mat2x3 projection = GetAxisAlignedProjection(normal);
- auto triCCW = [&projection, this](const ivec3 tri) {
- return CCW(projection * this->vertPos_[halfedge_[tri[0]].startVert],
- projection * this->vertPos_[halfedge_[tri[1]].startVert],
- projection * this->vertPos_[halfedge_[tri[2]].startVert],
+ auto triCCW = [&projection, &faceHalfedge, this](const ivec3 tri) {
+ return CCW(projection * this->vertPos_[faceHalfedge[tri[0]].startVert],
+ projection * this->vertPos_[faceHalfedge[tri[1]].startVert],
+ projection * this->vertPos_[faceHalfedge[tri[2]].startVert],
epsilon_) >= 0;
};
std::vector<int> quad = AssembleHalfedges(
- halfedge_.cbegin() + faceEdge[face],
- halfedge_.cbegin() + faceEdge[face + 1], faceEdge[face])[0];
+ faceHalfedge.cbegin() + faceEdge[face],
+ faceHalfedge.cbegin() + faceEdge[face + 1], faceEdge[face])[0];
const la::mat<int, 3, 2> tris[2] = {
{{quad[0], quad[1], quad[2]}, {quad[0], quad[2], quad[3]}},
@@ -153,103 +256,115 @@ void Manifold::Impl::Face2Tri(const Vec<int>& faceEdge,
if (!(triCCW(tris[0][0]) && triCCW(tris[0][1]))) {
choice = 1;
} else if (triCCW(tris[1][0]) && triCCW(tris[1][1])) {
- vec3 diag0 = vertPos_[halfedge_[quad[0]].startVert] -
- vertPos_[halfedge_[quad[2]].startVert];
- vec3 diag1 = vertPos_[halfedge_[quad[1]].startVert] -
- vertPos_[halfedge_[quad[3]].startVert];
+ vec3 diag0 = vertPos_[faceHalfedge[quad[0]].startVert] -
+ vertPos_[faceHalfedge[quad[2]].startVert];
+ vec3 diag1 = vertPos_[faceHalfedge[quad[1]].startVert] -
+ vertPos_[faceHalfedge[quad[3]].startVert];
if (la::length2(diag0) > la::length2(diag1)) {
choice = 1;
}
}
- for (const auto& tri : tris[choice]) {
- addTri(face, tri, normal, halfedgeRef[firstEdge]);
- }
+ WriteLocalTriangles(halfedge_, contour2Tri, faceHalfedge, firstTri,
+ &tris[choice][0], 2);
} else { // General triangulation
- for (const auto& tri : general(face)) {
- addTri(face, tri, normal, halfedgeRef[firstEdge]);
- }
+ DEBUG_ASSERT(general != nullptr, logicErr,
+ "general face missing triangulation result");
+ numTri = general->NumTri();
+ WriteGeneralTriangulation(halfedge_, contour2Tri, faceHalfedge, firstTri,
+ *general, ctx);
}
+
+ WriteTriRefs(triNormal, triRef, firstTri, numTri, normal,
+ halfedgeRef[firstEdge], ctx);
};
- auto generalTriangulation = [&](int face) {
- const vec3 normal = faceNormal_[face];
- const mat2x3 projection = GetAxisAlignedProjection(normal);
- const PolygonsIdx polys = ProjectPolygons(
- AssembleHalfedges(halfedge_.cbegin() + faceEdge[face],
- halfedge_.cbegin() + faceEdge[face + 1],
- faceEdge[face]),
- halfedge_, vertPos_, projection);
- return TriangulateIdx(polys, epsilon_, allowConvex);
- };
+
+ Vec<size_t> triOffset(faceEdge.size());
+ triOffset.back() = 0;
#if (MANIFOLD_PAR == 1) && __has_include(<tbb/tbb.h>)
tbb::task_group group;
- // map from face to triangle
- tbb::concurrent_unordered_map<int, std::vector<ivec3>> results;
- Vec<size_t> triCount(faceEdge.size());
- triCount.back() = 0;
+ tbb::concurrent_unordered_map<int, HalfedgeTriangulation> results;
// precompute number of triangles per face, and launch async tasks to
// triangulate complex faces
for_each(autoPolicy(faceEdge.size(), 1e5), countAt(0_uz),
- countAt(faceEdge.size() - 1), [&](size_t face) {
- triCount[face] = faceEdge[face + 1] - faceEdge[face] - 2;
- DEBUG_ASSERT(triCount[face] >= 1, topologyErr,
+ countAt(faceEdge.size() - 1), ctx, [&](size_t face) {
+ const int numEdge = faceEdge[face + 1] - faceEdge[face];
+ if (numEdge == 0) {
+ triOffset[face] = 0;
+ return;
+ }
+ DEBUG_ASSERT(numEdge >= 3, topologyErr,
"face has less than three edges.");
- if (triCount[face] > 2)
+ triOffset[face] = numEdge - 2;
+ if (numEdge > 4)
group.run([&, face] {
- std::vector<ivec3> newTris = generalTriangulation(face);
- triCount[face] = newTris.size();
- results[face] = std::move(newTris);
+ if (IsCancelled(ctx)) return;
+ HalfedgeTriangulation triangulation =
+ generalTriangulation(face);
+ triOffset[face] = triangulation.NumTri();
+ results[face] = std::move(triangulation);
});
});
group.wait();
- // prefix sum computation (assign unique index to each face) and preallocation
- exclusive_scan(triCount.begin(), triCount.end(), triCount.begin(), 0_uz);
- triVerts.resize(triCount.back());
- triProp.resize(triCount.back());
- triNormal.resize(triCount.back());
- triRef.resize(triCount.back());
-
- auto processFace2 = std::bind(
- processFace, [&](size_t face) { return std::move(results[face]); },
- [&](size_t face, ivec3 tri, vec3 normal, TriRef r) {
- for (const int i : {0, 1, 2}) {
- triVerts[triCount[face]][i] = halfedge_[tri[i]].startVert;
- triProp[triCount[face]][i] = halfedge_[tri[i]].propVert;
- }
- triNormal[triCount[face]] = normal;
- triRef[triCount[face]] = r;
- triCount[face]++;
- },
- std::placeholders::_1);
+ if (IsCancelled(ctx)) return;
+#else
+ std::unordered_map<int, HalfedgeTriangulation> results;
+ for (int face = 0; face < static_cast<int>(faceEdge.size()) - 1; ++face) {
+ if (IsCancelled(ctx)) return;
+ const int numEdge = faceEdge[face + 1] - faceEdge[face];
+ if (numEdge == 0) {
+ triOffset[face] = 0;
+ continue;
+ }
+ DEBUG_ASSERT(numEdge >= 3, topologyErr, "face has less than three edges.");
+ triOffset[face] = numEdge - 2;
+ if (numEdge > 4) {
+ HalfedgeTriangulation triangulation = generalTriangulation(face);
+ triOffset[face] = triangulation.NumTri();
+ results.emplace(face, std::move(triangulation));
+ }
+ }
+#endif
+
+ exclusive_scan(triOffset.begin(), triOffset.end(), triOffset.begin(), 0_uz);
+ halfedge_.resize_nofill(3 * triOffset.back());
+ triNormal.resize(triOffset.back());
+ triRef.resize(triOffset.back());
+
+#if (MANIFOLD_PAR == 1) && __has_include(<tbb/tbb.h>)
+ auto processFace2 = [&](size_t face) {
+ const HalfedgeTriangulation* resultPtr = nullptr;
+ auto result = results.find(face);
+ if (result != results.end()) resultPtr = &result->second;
+ outputFace(face, triOffset[face], resultPtr);
+ };
// set triangles in parallel
for_each(autoPolicy(faceEdge.size(), 1e4), countAt(0_uz),
- countAt(faceEdge.size() - 1), processFace2);
+ countAt(faceEdge.size() - 1), ctx, processFace2);
#else
- triVerts.reserve(faceEdge.size());
- triNormal.reserve(faceEdge.size());
- triRef.reserve(faceEdge.size());
- auto processFace2 = std::bind(
- processFace, generalTriangulation,
- [&](size_t, ivec3 tri, vec3 normal, TriRef r) {
- ivec3 verts;
- ivec3 props;
- for (const int i : {0, 1, 2}) {
- verts[i] = halfedge_[tri[i]].startVert;
- props[i] = halfedge_[tri[i]].propVert;
- }
- triVerts.push_back(verts);
- triProp.push_back(props);
- triNormal.push_back(normal);
- triRef.push_back(r);
- },
- std::placeholders::_1);
for (size_t face = 0; face < faceEdge.size() - 1; ++face) {
- processFace2(face);
+ if (IsCancelled(ctx)) return;
+ const HalfedgeTriangulation* resultPtr = nullptr;
+ auto result = results.find(face);
+ if (result != results.end()) resultPtr = &result->second;
+ outputFace(face, triOffset[face], resultPtr);
}
#endif
+ if (IsCancelled(ctx)) return;
+ for_each(autoPolicy(faceHalfedge.size(), 1e5), countAt(0_uz),
+ countAt(faceHalfedge.size()), ctx, [&](size_t edge) {
+ const int triEdge = contour2Tri[edge];
+ if (triEdge < 0) return;
+ const int pair = faceHalfedge[edge].pairedHalfedge;
+ if (pair < 0) return;
+ const int pairTri = contour2Tri[pair];
+ DEBUG_ASSERT(pairTri >= 0, topologyErr,
+ "boundary edge did not triangulate with its pair");
+ halfedge_.SetPair(triEdge, pairTri);
+ });
+ if (IsCancelled(ctx)) return;
faceNormal_ = std::move(triNormal);
- CreateHalfedges(triProp, triVerts);
}
Polygons Manifold::Impl::Slice(double height) const {
@@ -263,7 +378,7 @@ Polygons Manifold::Impl::Slice(double height) const {
double min = std::numeric_limits<double>::infinity();
double max = -std::numeric_limits<double>::infinity();
for (const int j : {0, 1, 2}) {
- const double z = vertPos_[halfedge_[3 * tri + j].startVert].z;
+ const double z = vertPos_[halfedge_.Start(3 * tri + j)].z;
min = std::min(min, z);
max = std::max(max, z);
}
@@ -274,7 +389,7 @@ Polygons Manifold::Impl::Slice(double height) const {
};
auto recorder = MakeSimpleRecorder(recordCollision);
- collider_.Collisions<false>(query.cview(), recorder, false);
+ collider_.Collisions<false>(recorder, query.cview(), false);
Polygons polys;
while (!tris.empty()) {
@@ -283,8 +398,8 @@ Polygons Manifold::Impl::Slice(double height) const {
int k = 0;
for (const int j : {0, 1, 2}) {
- if (vertPos_[halfedge_[3 * startTri + j].startVert].z > height &&
- vertPos_[halfedge_[3 * startTri + Next3(j)].startVert].z <= height) {
+ if (vertPos_[halfedge_.Start(3 * startTri + j)].z > height &&
+ vertPos_[halfedge_.Start(3 * startTri + Next3(j))].z <= height) {
k = Next3(j);
break;
}
@@ -293,17 +408,18 @@ Polygons Manifold::Impl::Slice(double height) const {
int tri = startTri;
do {
tris.erase(tris.find(tri));
- if (vertPos_[halfedge_[3 * tri + k].endVert].z <= height) {
+ const int edge = 3 * tri + k;
+ if (vertPos_[halfedge_.End(edge)].z <= height) {
k = Next3(k);
}
- Halfedge up = halfedge_[3 * tri + k];
- const vec3 below = vertPos_[up.startVert];
- const vec3 above = vertPos_[up.endVert];
+ const int up = 3 * tri + k;
+ const vec3 below = vertPos_[halfedge_.Start(up)];
+ const vec3 above = vertPos_[halfedge_.End(up)];
const double a = (height - below.z) / (above.z - below.z);
poly.push_back(vec2(la::lerp(below, above, a)));
- const int pair = up.pairedHalfedge;
+ const int pair = halfedge_.Pair(up);
tri = pair / 3;
k = Next3(pair % 3);
} while (tri != startTri);
@@ -317,16 +433,15 @@ Polygons Manifold::Impl::Slice(double height) const {
Polygons Manifold::Impl::Project() const {
const mat2x3 projection = GetAxisAlignedProjection({0, 0, 1});
Vec<Halfedge> cusps(NumEdge());
- cusps.resize(
- copy_if(
- halfedge_.cbegin(), halfedge_.cend(), cusps.begin(),
- [&](Halfedge edge) {
- return faceNormal_[halfedge_[edge.pairedHalfedge].pairedHalfedge /
- 3]
- .z >= 0 &&
- faceNormal_[edge.pairedHalfedge / 3].z < 0;
- }) -
- cusps.begin());
+ size_t numCusps = 0;
+ for (size_t i = 0; i < halfedge_.size(); ++i) {
+ const int pair = halfedge_.Pair(i);
+ if (faceNormal_[halfedge_.Pair(pair) / 3].z >= 0 &&
+ faceNormal_[pair / 3].z < 0) {
+ cusps[numCusps++] = halfedge_.Get(i);
+ }
+ }
+ cusps.resize(numCusps);
PolygonsIdx polysIndexed =
ProjectPolygons(AssembleHalfedges(cusps.cbegin(), cusps.cend(), 0), cusps,
diff --git a/thirdparty/manifold/src/hashtable.h b/thirdparty/manifold/src/hashtable.h
index 96107c357f2..05dc9da0e2c 100644
--- a/thirdparty/manifold/src/hashtable.h
+++ b/thirdparty/manifold/src/hashtable.h
@@ -16,6 +16,10 @@
#include <atomic>
+#ifdef _MSC_VER
+#include <intrin.h>
+#endif
+
#include "utils.h"
#include "vec.h"
@@ -23,6 +27,39 @@ namespace {
using hash_fun_t = uint64_t(uint64_t);
inline constexpr uint64_t kOpen = std::numeric_limits<uint64_t>::max();
+inline uint32_t ClzSizeT(size_t value) {
+#ifdef _MSC_VER
+#if defined(_WIN64)
+ unsigned long index = 0;
+ if (_BitScanReverse64(&index, static_cast<uint64_t>(value))) {
+ return 63u - index;
+ }
+ return 64u;
+#else
+ unsigned long index = 0;
+ if (_BitScanReverse(&index, static_cast<unsigned long>(value))) {
+ return 31u - index;
+ }
+ return 32u;
+#endif
+#else
+ if (value == 0) return 8u * static_cast<uint32_t>(sizeof(size_t));
+#if SIZE_MAX == UINT64_MAX
+ return static_cast<uint32_t>(
+ __builtin_clzll(static_cast<unsigned long long>(value)));
+#else
+ return static_cast<uint32_t>(__builtin_clz(static_cast<unsigned int>(value)));
+#endif
+#endif
+}
+
+inline uint32_t CeilLog2(size_t value) {
+ if (value <= 1) return 0;
+ const size_t x = value - 1;
+ const uint32_t width = 8u * static_cast<uint32_t>(sizeof(size_t));
+ return width - ClzSizeT(x);
+}
+
template <typename T>
T AtomicCAS(T& target, T compare, T val) {
std::atomic<T>& tar = reinterpret_cast<std::atomic<T>&>(target);
@@ -115,8 +152,8 @@ template <typename V, hash_fun_t H = hash64bit>
class HashTable {
public:
HashTable(size_t size, uint32_t step = 1)
- : keys_{size == 0 ? 0 : 1_uz << (int)ceil(log2(size)), kOpen},
- values_{size == 0 ? 0 : 1_uz << (int)ceil(log2(size)), {}},
+ : keys_{size == 0 ? 0 : 1_uz << static_cast<int>(CeilLog2(size)), kOpen},
+ values_{size == 0 ? 0 : 1_uz << static_cast<int>(CeilLog2(size)), {}},
step_(step) {}
HashTable(const HashTable& other)
diff --git a/thirdparty/manifold/src/impl.cpp b/thirdparty/manifold/src/impl.cpp
index d4b3a0c3e25..0267a339a97 100644
--- a/thirdparty/manifold/src/impl.cpp
+++ b/thirdparty/manifold/src/impl.cpp
@@ -15,14 +15,25 @@
#include "impl.h"
#include <algorithm>
+#include <array>
#include <atomic>
+#include <cstdio>
+#include <cstdlib>
#include <cstring>
+#ifndef MANIFOLD_NO_IOSTREAM
+#include <iomanip>
+#endif
#include <map>
#include <optional>
+#include <regex>
+#ifndef MANIFOLD_NO_IOSTREAM
+#include <sstream>
+#endif
#include "csg_tree.h"
#include "disjoint_sets.h"
#include "hashtable.h"
+#include "manifold/manifold.h"
#include "manifold/optional_assert.h"
#include "mesh_fixes.h"
#include "parallel.h"
@@ -32,96 +43,6 @@
namespace {
using namespace manifold;
-/**
- * Returns arc cosine of 𝑥.
- *
- * @return value in range [0,M_PI]
- * @return NAN if 𝑥 ∈ {NAN,+INFINITY,-INFINITY}
- * @return NAN if 𝑥 ∉ [-1,1]
- */
-double sun_acos(double x) {
- /*
- * Origin of acos function: FreeBSD /usr/src/lib/msun/src/e_acos.c
- * Changed the use of union to memcpy to avoid undefined behavior.
- * ====================================================
- * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
- *
- * Developed at SunSoft, a Sun Microsystems, Inc. business.
- * Permission to use, copy, modify, and distribute this
- * software is freely granted, provided that this notice
- * is preserved.
- * ====================================================
- */
- constexpr double pio2_hi =
- 1.57079632679489655800e+00; /* 0x3FF921FB, 0x54442D18 */
- constexpr double pio2_lo =
- 6.12323399573676603587e-17; /* 0x3C91A626, 0x33145C07 */
- constexpr double pS0 =
- 1.66666666666666657415e-01; /* 0x3FC55555, 0x55555555 */
- constexpr double pS1 =
- -3.25565818622400915405e-01; /* 0xBFD4D612, 0x03EB6F7D */
- constexpr double pS2 =
- 2.01212532134862925881e-01; /* 0x3FC9C155, 0x0E884455 */
- constexpr double pS3 =
- -4.00555345006794114027e-02; /* 0xBFA48228, 0xB5688F3B */
- constexpr double pS4 =
- 7.91534994289814532176e-04; /* 0x3F49EFE0, 0x7501B288 */
- constexpr double pS5 =
- 3.47933107596021167570e-05; /* 0x3F023DE1, 0x0DFDF709 */
- constexpr double qS1 =
- -2.40339491173441421878e+00; /* 0xC0033A27, 0x1C8A2D4B */
- constexpr double qS2 =
- 2.02094576023350569471e+00; /* 0x40002AE5, 0x9C598AC8 */
- constexpr double qS3 =
- -6.88283971605453293030e-01; /* 0xBFE6066C, 0x1B8D0159 */
- constexpr double qS4 =
- 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */
- auto R = [=](double z) {
- double p, q;
- p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))));
- q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)));
- return p / q;
- };
- double z, w, s, c, df;
- uint64_t xx;
- uint32_t hx, lx, ix;
- memcpy(&xx, &x, sizeof(xx));
- hx = xx >> 32;
- ix = hx & 0x7fffffff;
- /* |x| >= 1 or nan */
- if (ix >= 0x3ff00000) {
- lx = xx;
- if (((ix - 0x3ff00000) | lx) == 0) {
- /* acos(1)=0, acos(-1)=pi */
- if (hx >> 31) return 2 * pio2_hi + 0x1p-120f;
- return 0;
- }
- return 0 / (x - x);
- }
- /* |x| < 0.5 */
- if (ix < 0x3fe00000) {
- if (ix <= 0x3c600000) /* |x| < 2**-57 */
- return pio2_hi + 0x1p-120f;
- return pio2_hi - (x - (pio2_lo - x * R(x * x)));
- }
- /* x < -0.5 */
- if (hx >> 31) {
- z = (1.0 + x) * 0.5;
- s = sqrt(z);
- w = R(z) * s - pio2_lo;
- return 2 * (pio2_hi - (s + w));
- }
- /* x > 0.5 */
- z = (1.0 - x) * 0.5;
- s = sqrt(z);
- memcpy(&xx, &s, sizeof(xx));
- xx &= 0xffffffff00000000;
- memcpy(&df, &xx, sizeof(xx));
- c = (z - df * df) / (s + df);
- w = R(z) * s + c;
- return 2 * (df + w);
-}
-
struct Transform4x3 {
const mat3x4 transform;
@@ -144,18 +65,21 @@ int GetLabels(std::vector<int>& components,
return uf.connectedComponents(components);
}
+
+#ifndef MANIFOLD_NO_IOSTREAM
+template <typename T>
+double FromChars(T buffer) {
+ double tmp;
+ std::istringstream iss(buffer);
+ iss >> std::setprecision(19);
+ iss >> tmp;
+ return tmp;
+}
+#endif
} // namespace
namespace manifold {
-#if (MANIFOLD_PAR == 1)
-#if (TBB_VERSION_MAJOR < 2021)
-tbb::task_arena gc_arena(1, 1);
-#else
-tbb::task_arena gc_arena(1, 1, tbb::task_arena::priority::low);
-#endif
-#endif
-
std::atomic<uint32_t> Manifold::Impl::meshIDCounter_(1);
uint32_t Manifold::Impl::ReserveIDs(uint32_t n) {
@@ -206,12 +130,14 @@ Manifold::Impl::Impl(Shape shape, const mat3x4 m) {
{3, 0, 4}, {2, 5, 1}};
break;
}
- vertPos_ = vertPos;
+ vertPos_ = Vec(vertPos);
for (auto& v : vertPos_) v = m * vec4(v, 1.0);
CreateHalfedges(triVerts);
- Finish();
InitializeOriginal();
- MarkCoplanar();
+ CalculateBBox();
+ SetEpsilon();
+ SortGeometry();
+ SetNormalsAndCoplanar();
}
void Manifold::Impl::RemoveUnreferencedVerts() {
@@ -219,9 +145,10 @@ void Manifold::Impl::RemoveUnreferencedVerts() {
const int numVert = NumVert();
Vec<int> keep(numVert, 0);
auto policy = autoPolicy(numVert, 1e5);
- for_each(policy, halfedge_.cbegin(), halfedge_.cend(), [&keep](Halfedge h) {
- if (h.startVert >= 0) {
- reinterpret_cast<std::atomic<int>*>(&keep[h.startVert])
+ for_each_n(policy, countAt(0), halfedge_.size(), [&keep, this](int edge) {
+ const int startVert = halfedge_.Start(edge);
+ if (startVert >= 0) {
+ reinterpret_cast<std::atomic<int>*>(&keep[startVert])
->store(1, std::memory_order_relaxed);
}
});
@@ -233,23 +160,61 @@ void Manifold::Impl::RemoveUnreferencedVerts() {
});
}
-void Manifold::Impl::InitializeOriginal(bool keepFaceID) {
+void Manifold::Impl::EagerTransformPropNormals(
+ const Halfedges& halfedge, const MeshRelationD& meshRelation,
+ const mat3& normalTransform, Vec<double>& properties, int numPropVert,
+ int stride, int offset) {
+ // Short-circuit when no meshID carries normals. OR semantics (any has
+ // it), unlike AllHaveNormals() - mixed inputs still need the per-meshID
+ // iteration below to rotate the with-normals subset.
+ bool anyHasNormals = false;
+ for (const auto& m : meshRelation.meshIDtransform) {
+ if (m.second.hasNormals) {
+ anyHasNormals = true;
+ break;
+ }
+ }
+ if (!anyHasNormals) return;
+ Vec<bool> propVisited(numPropVert, false);
+ for (size_t e = 0; e < halfedge.size(); ++e) {
+ if (!TriHasNormals(meshRelation, e / 3)) continue;
+ const int prop = halfedge.Prop(e);
+ if (prop < 0 || propVisited[prop]) continue;
+ propVisited[prop] = true;
+ vec3 n;
+ for (const int i : {0, 1, 2})
+ n[i] = properties[(offset + prop) * stride + i];
+ // Re-normalize as we transform: non-orthogonal transforms (scale) and
+ // barycentric interpolation upstream both leave non-unit values that
+ // would otherwise compound and break downstream lighting / smoothing.
+ n = SafeNormalize(normalTransform * n);
+ for (const int i : {0, 1, 2})
+ properties[(offset + prop) * stride + i] = n[i];
+ }
+}
+
+void Manifold::Impl::InitializeOriginal() {
const int meshID = ReserveIDs(1);
meshRelation_.originalID = meshID;
auto& triRef = meshRelation_.triRef;
triRef.resize_nofill(NumTri());
for_each_n(autoPolicy(NumTri(), 1e5), countAt(0), NumTri(),
- [meshID, keepFaceID, &triRef](const int tri) {
- triRef[tri] = {meshID, meshID, -1,
- keepFaceID ? triRef[tri].coplanarID : tri};
+ [meshID, &triRef](const int tri) {
+ triRef[tri] = {meshID, meshID, -1, triRef[tri].coplanarID};
});
+ // Preserve the AND-across-old-Relations state so AsOriginal keeps the
+ // recording when it builds a fresh Relation. Primitives start with an
+ // empty map, which AllHaveNormals() returns false for.
+ const bool hadNormals = AllHaveNormals();
meshRelation_.meshIDtransform.clear();
- meshRelation_.meshIDtransform[meshID] = {meshID};
+ meshRelation_.meshIDtransform[meshID] = {meshID, la::identity, false,
+ hadNormals};
}
-void Manifold::Impl::MarkCoplanar() {
+void Manifold::Impl::SetNormalsAndCoplanar() {
ZoneScoped;
const int numTri = NumTri();
+ faceNormal_.resize(numTri);
struct TriPriority {
double area2;
int tri;
@@ -258,15 +223,17 @@ void Manifold::Impl::MarkCoplanar() {
for_each_n(autoPolicy(numTri), countAt(0), numTri,
[&triPriority, this](int tri) {
meshRelation_.triRef[tri].coplanarID = -1;
- if (halfedge_[3 * tri].startVert < 0) {
+ if (halfedge_.Start(3 * tri) < 0) {
triPriority[tri] = {0, tri};
return;
}
- const vec3 v = vertPos_[halfedge_[3 * tri].startVert];
- triPriority[tri] = {
- length2(cross(vertPos_[halfedge_[3 * tri].endVert] - v,
- vertPos_[halfedge_[3 * tri + 1].endVert] - v)),
- tri};
+ const vec3 v = vertPos_[halfedge_.Start(3 * tri)];
+ const vec3 n = cross(vertPos_[halfedge_.End(3 * tri)] - v,
+ vertPos_[halfedge_.End(3 * tri + 1)] - v);
+ faceNormal_[tri] = normalize(n);
+ if (std::isnan(faceNormal_[tri].x))
+ faceNormal_[tri] = vec3(0, 0, 1);
+ triPriority[tri] = {length2(n), tri};
});
stable_sort(triPriority.begin(), triPriority.end(),
@@ -277,25 +244,26 @@ void Manifold::Impl::MarkCoplanar() {
if (meshRelation_.triRef[tp.tri].coplanarID >= 0) continue;
meshRelation_.triRef[tp.tri].coplanarID = tp.tri;
- if (halfedge_[3 * tp.tri].startVert < 0) continue;
- const vec3 base = vertPos_[halfedge_[3 * tp.tri].startVert];
+ if (halfedge_.Start(3 * tp.tri) < 0) continue;
+ const vec3 base = vertPos_[halfedge_.Start(3 * tp.tri)];
const vec3 normal = faceNormal_[tp.tri];
interiorHalfedges.resize(3);
interiorHalfedges[0] = 3 * tp.tri;
interiorHalfedges[1] = 3 * tp.tri + 1;
interiorHalfedges[2] = 3 * tp.tri + 2;
while (!interiorHalfedges.empty()) {
- const int h =
- NextHalfedge(halfedge_[interiorHalfedges.back()].pairedHalfedge);
+ const int h = NextHalfedge(halfedge_.Pair(interiorHalfedges.back()));
interiorHalfedges.pop_back();
if (meshRelation_.triRef[h / 3].coplanarID >= 0) continue;
- const vec3 v = vertPos_[halfedge_[h].endVert];
+ const vec3 v = vertPos_[halfedge_.End(h)];
if (std::abs(dot(v - base, normal)) < tolerance_) {
- meshRelation_.triRef[h / 3].coplanarID = tp.tri;
+ const size_t tri = h / 3;
+ meshRelation_.triRef[tri].coplanarID = tp.tri;
+ faceNormal_[tri] = normal;
if (interiorHalfedges.empty() ||
- h != halfedge_[interiorHalfedges.back()].pairedHalfedge) {
+ h != halfedge_.Pair(interiorHalfedges.back())) {
interiorHalfedges.push_back(h);
} else {
interiorHalfedges.pop_back();
@@ -305,6 +273,7 @@ void Manifold::Impl::MarkCoplanar() {
}
}
}
+ CalculateVertNormals();
}
/**
@@ -316,21 +285,21 @@ void Manifold::Impl::DedupePropVerts() {
const size_t numProp = NumProp();
if (numProp == 0) return;
+ halfedge_.MakeUnique();
Vec<std::pair<int, int>> vert2vert(halfedge_.size(), {-1, -1});
for_each_n(autoPolicy(halfedge_.size(), 1e4), countAt(0), halfedge_.size(),
[&vert2vert, numProp, this](const int edgeIdx) {
- const Halfedge edge = halfedge_[edgeIdx];
- if (edge.pairedHalfedge < 0) return;
+ const int pair = halfedge_.Pair(edgeIdx);
+ if (pair < 0) return;
const int edgeFace = edgeIdx / 3;
- const int pairFace = edge.pairedHalfedge / 3;
+ const int pairFace = pair / 3;
if (meshRelation_.triRef[edgeFace].meshID !=
meshRelation_.triRef[pairFace].meshID)
return;
- const int prop0 = halfedge_[edgeIdx].propVert;
- const int prop1 =
- halfedge_[NextHalfedge(edge.pairedHalfedge)].propVert;
+ const int prop0 = halfedge_.Prop(edgeIdx);
+ const int prop1 = halfedge_.Prop(NextHalfedge(pair));
bool propEqual = true;
for (size_t p = 0; p < numProp; ++p) {
if (properties_[numProp * prop0 + p] !=
@@ -350,11 +319,16 @@ void Manifold::Impl::DedupePropVerts() {
std::vector<int> label2vert(numLabels);
for (size_t v = 0; v < numPropVert; ++v) label2vert[vertLabels[v]] = v;
- for (Halfedge& edge : halfedge_)
- edge.propVert = label2vert[vertLabels[edge.propVert]];
+ for (size_t edge = 0; edge < halfedge_.size(); ++edge) {
+ halfedge_.SetProp(edge, label2vert[vertLabels[halfedge_.Prop(edge)]]);
+ }
}
-constexpr int kRemovedHalfedge = -2;
+struct CreateHalfedge {
+ int startVert;
+ int endVert;
+ int propVert;
+};
struct HalfedgePairData {
int largeVert;
@@ -369,7 +343,7 @@ struct HalfedgePairData {
template <bool useProp, typename F>
struct PrepHalfedges {
- VecView<Halfedge> halfedges;
+ VecView<CreateHalfedge> halfedges;
const VecView<ivec3> triProp;
const VecView<ivec3> triVert;
F& f;
@@ -383,7 +357,7 @@ struct PrepHalfedges {
const int v0 = useProp ? props[i] : triVert[tri][i];
const int v1 = useProp ? props[j] : triVert[tri][j];
DEBUG_ASSERT(v0 != v1, logicErr, "topological degeneracy");
- halfedges[e] = {v0, v1, -1, props[i]};
+ halfedges[e] = {v0, v1, props[i]};
f(e, v0, v1);
}
}
@@ -401,9 +375,7 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
ZoneScoped;
const size_t numTri = triProp.size();
const int numHalfedge = 3 * numTri;
- // drop the old value first to avoid copy
- halfedge_.clear(true);
- halfedge_.resize_nofill(numHalfedge);
+ Vec<CreateHalfedge> halfedge(numHalfedge);
auto policy = autoPolicy(numTri, 1e5);
int vertCount = static_cast<int>(vertPos_.size());
@@ -420,11 +392,11 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
};
if (triVert.empty()) {
for_each_n(policy, countAt(0), numTri,
- PrepHalfedges<true, decltype(setEdge)>{halfedge_, triProp,
+ PrepHalfedges<true, decltype(setEdge)>{halfedge, triProp,
triVert, setEdge});
} else {
for_each_n(policy, countAt(0), numTri,
- PrepHalfedges<false, decltype(setEdge)>{halfedge_, triProp,
+ PrepHalfedges<false, decltype(setEdge)>{halfedge, triProp,
triVert, setEdge});
}
sequence(ids.begin(), ids.end());
@@ -446,19 +418,19 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
if (triVert.empty()) {
for_each_n(policy, countAt(0), numTri,
PrepHalfedges<true, decltype(setOffset)>{
- halfedge_, triProp, triVert, setOffset});
+ halfedge, triProp, triVert, setOffset});
} else {
for_each_n(policy, countAt(0), numTri,
PrepHalfedges<false, decltype(setOffset)>{
- halfedge_, triProp, triVert, setOffset});
+ halfedge, triProp, triVert, setOffset});
}
exclusive_scan(offsets.begin(), offsets.end(), offsets.begin());
for_each_n(policy, countAt(0), numTri,
- [this, &offsets, &entries, vertCount](const int tri) {
+ [&halfedge, &offsets, &entries, vertCount](const int tri) {
for (const int i : {0, 1, 2}) {
const int e = 3 * tri + i;
- const int v0 = halfedge_[e].startVert;
- const int v1 = halfedge_[e].endVert;
+ const int v0 = halfedge[e].startVert;
+ const int v1 = halfedge[e].endVert;
const int offset = v0 > v1 ? 0 : vertCount;
const int start = std::min(v0, v1);
const int index = AtomicAdd(offsets[start + offset], 1);
@@ -479,28 +451,51 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
// Mark opposed triangles for removal - this may strand unreferenced verts
// which are removed later by RemoveUnreferencedVerts() and Finish().
const int numEdge = numHalfedge / 2;
+ Vec<unsigned char> removed(numHalfedge, false);
const auto body = [&](int i, int consecutiveStart, int segmentEnd) {
const int pair0 = ids[i];
- Halfedge& h0 = halfedge_[pair0];
+ const CreateHalfedge h0 = halfedge[pair0];
int k = consecutiveStart + numEdge;
while (1) {
const int pair1 = ids[k];
- Halfedge& h1 = halfedge_[pair1];
+ const CreateHalfedge h1 = halfedge[pair1];
if (h0.startVert != h1.endVert || h0.endVert != h1.startVert) break;
- if (h1.pairedHalfedge != kRemovedHalfedge &&
- halfedge_[NextHalfedge(pair0)].endVert ==
- halfedge_[NextHalfedge(pair1)].endVert) {
- h0.pairedHalfedge = h1.pairedHalfedge = kRemovedHalfedge;
- // Reorder so that remaining edges pair up
- if (k != i + numEdge) std::swap(ids[i + numEdge], ids[k]);
+ if (!removed[pair1] && halfedge[NextHalfedge(pair0)].endVert ==
+ halfedge[NextHalfedge(pair1)].endVert) {
+ removed[pair0] = true;
+ removed[pair1] = true;
+ if (i + numEdge != k) {
+ // Reorder so that remaining edges pair up, while preserving relative
+ // order between the edges (triangle id order)
+ // cannot directly use move and move_backward because we need to keep
+ // removed halfedges in-place
+ int dir = i + numEdge < k ? 1 : -1;
+ int a = k;
+ int b = k + dir;
+ auto isRemoved = [&removed, &ids](int x) { return removed[ids[x]]; };
+ auto inRange = [&a, dir, i, numEdge]() {
+ return (dir > 0 ? a >= i + numEdge : a <= i + numEdge);
+ };
+ while (1) {
+ do {
+ a -= dir;
+ } while (inRange() && isRemoved(a));
+ if (!inRange()) break;
+ do {
+ b -= dir;
+ } while (isRemoved(b) && b != k);
+ ids[b] = ids[a];
+ }
+ ids[i + numEdge] = pair1;
+ }
break;
}
++k;
if (k >= segmentEnd + numEdge) break;
}
if (i + 1 == segmentEnd) return consecutiveStart;
- Halfedge& h1 = halfedge_[ids[i + 1]];
+ const CreateHalfedge h1 = halfedge[ids[i + 1]];
if (h1.startVert == h0.startVert && h1.endVert == h0.endVert)
return consecutiveStart;
return i + 1;
@@ -512,8 +507,8 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
std::max(numEdge / tbb::this_task_arena::max_concurrency() / 2, 1024),
numEdge);
const auto duplicated = [&](int a, int b) {
- const Halfedge& h0 = halfedge_[ids[a]];
- const Halfedge& h1 = halfedge_[ids[b]];
+ const CreateHalfedge h0 = halfedge[ids[a]];
+ const CreateHalfedge h1 = halfedge[ids[b]];
return h0.startVert == h1.startVert && h0.endVert == h1.endVert;
};
int end = 0;
@@ -536,38 +531,51 @@ void Manifold::Impl::CreateHalfedges(const Vec<ivec3>& triProp,
for (int i = 0; i < numEdge; ++i)
consecutiveStart = body(i, consecutiveStart, numEdge);
#endif
- for_each_n(policy, countAt(0), numEdge, [this, &ids, numEdge](int i) {
- const int pair0 = ids[i];
- const int pair1 = ids[i + numEdge];
- if (halfedge_[pair0].pairedHalfedge != kRemovedHalfedge) {
- halfedge_[pair0].pairedHalfedge = pair1;
- halfedge_[pair1].pairedHalfedge = pair0;
- } else {
- halfedge_[pair0] = halfedge_[pair1] = {-1, -1, -1};
- }
- });
-}
-/**
- * Does a full recalculation of the face bounding boxes, including updating
- * the collider, but does not resort the faces.
- */
-void Manifold::Impl::Update() {
- CalculateBBox();
- Vec<Box> faceBox;
- Vec<uint32_t> faceMorton;
- GetFaceBoxMorton(faceBox, faceMorton);
- collider_.UpdateBoxes(faceBox);
+ halfedge_.clear(true);
+ halfedge_.resize_nofill(numHalfedge);
+ for_each_n(policy, countAt(0), numEdge,
+ [this, &halfedge, &ids, &removed, numEdge](int i) {
+ const int pair0 = ids[i];
+ const int pair1 = ids[i + numEdge];
+ if (!removed[pair0]) {
+ halfedge_.SetStart(pair0, halfedge[pair0].startVert);
+ halfedge_.SetProp(pair0, halfedge[pair0].propVert);
+ halfedge_.SetPair(pair0, pair1);
+ halfedge_.SetStart(pair1, halfedge[pair1].startVert);
+ halfedge_.SetProp(pair1, halfedge[pair1].propVert);
+ halfedge_.SetPair(pair1, pair0);
+ } else {
+ halfedge_.SetStart(pair0, -1);
+ halfedge_.SetProp(pair0, 0);
+ halfedge_.SetPair(pair0, -1);
+ halfedge_.SetStart(pair1, -1);
+ halfedge_.SetProp(pair1, 0);
+ halfedge_.SetPair(pair1, -1);
+ }
+ });
+#ifdef MANIFOLD_DEBUG
+ for (int edge = 0; edge < numHalfedge; ++edge) {
+ const int next = NextHalfedge(edge);
+ if (!removed[edge] && !removed[next]) {
+ DEBUG_ASSERT(halfedge[edge].endVert == halfedge[next].startVert,
+ topologyErr,
+ "CreateHalfedges requires triangle-ordered edges!");
+ }
+ }
+#endif
}
void Manifold::Impl::MakeEmpty(Error status) {
bBox_ = Box();
vertPos_.clear();
+ halfedge_.MakeUnique();
halfedge_.clear();
vertNormal_.clear();
faceNormal_.clear();
halfedgeTangent_.clear();
meshRelation_ = MeshRelationD();
+ collider_ = {};
status_ = status;
}
@@ -584,11 +592,9 @@ void Manifold::Impl::WarpBatch(std::function<void(VecView<vec3>)> warpFunc) {
MakeEmpty(Error::NonFiniteVertex);
return;
}
- Update();
- faceNormal_.clear(); // force recalculation of triNormal
SetEpsilon();
- Finish();
- MarkCoplanar();
+ SortGeometry();
+ SetNormalsAndCoplanar();
meshRelation_.originalID = -1;
}
@@ -605,7 +611,6 @@ Manifold::Impl Manifold::Impl::Transform(const mat3x4& transform_) const {
result.MakeEmpty(Error::NonFiniteVertex);
return result;
}
- result.collider_ = collider_;
result.meshRelation_ = meshRelation_;
result.epsilon_ = epsilon_;
result.tolerance_ = tolerance_;
@@ -632,6 +637,11 @@ Manifold::Impl Manifold::Impl::Transform(const mat3x4& transform_) const {
transform(vertNormal_.begin(), vertNormal_.end(), result.vertNormal_.begin(),
TransformNormals({normalTransform}));
+ if (numProp_ >= 3) {
+ EagerTransformPropNormals(halfedge_, meshRelation_, normalTransform,
+ result.properties_, NumPropVert(), numProp_);
+ }
+
const bool invert = la::determinant(mat3(transform_)) < 0;
if (halfedgeTangent_.size() > 0) {
@@ -641,19 +651,29 @@ Manifold::Impl Manifold::Impl::Transform(const mat3x4& transform_) const {
}
if (invert) {
+ result.halfedge_.MakeUnique();
for_each_n(policy, countAt(0), result.NumTri(),
FlipTris({result.halfedge_}));
}
- // This optimization does a cheap collider update if the transform is
- // axis-aligned.
- if (!result.collider_.Transform(transform_)) result.Update();
-
result.CalculateBBox();
// Scale epsilon by the norm of the 3x3 portion of the transform.
result.epsilon_ *= SpectralNorm(mat3(transform_));
// Maximum of inherited epsilon loss and translational epsilon loss.
result.SetEpsilon(result.epsilon_);
+
+ if (!result.IsEmpty()) {
+ if (Collider::IsAxisAligned(transform_)) {
+ result.collider_ = collider_;
+ result.collider_.Transform(transform_);
+ } else if (!result.IsEmpty()) {
+ result.collider_ = collider_;
+ Vec<Box> faceBox;
+ Vec<uint32_t> faceMorton;
+ result.GetFaceBoxMorton(faceBox, faceMorton);
+ result.collider_.UpdateBoxes(faceBox);
+ }
+ }
return result;
}
@@ -671,18 +691,13 @@ void Manifold::Impl::SetEpsilon(double minEpsilon, bool useSingle) {
}
/**
- * If face normals are already present, this function uses them to compute
- * vertex normals (angle-weighted pseudo-normals); otherwise it also computes
- * the face normals. Face normals are only calculated when needed because
- * nearly degenerate faces will accrue rounding error, while the Boolean can
- * retain their original normal, which is more accurate and can help with
- * merging coplanar faces.
- *
- * If the face normals have been invalidated by an operation like Warp(),
- * ensure you do faceNormal_.resize(0) before calling this function to force
- * recalculation.
+ * This function uses the face normals to compute
+ * vertex normals (angle-weighted pseudo-normals). Face normals should only be
+ * calculated when needed because nearly degenerate faces will accrue rounding
+ * error, while the Boolean can retain their original normal, which is more
+ * accurate and can help with merging coplanar faces.
*/
-void Manifold::Impl::CalculateNormals() {
+void Manifold::Impl::CalculateVertNormals() {
ZoneScoped;
vertNormal_.resize(NumVert());
auto policy = autoPolicy(NumTri());
@@ -698,34 +713,9 @@ void Manifold::Impl::CalculateNormals() {
while (!vertHalfedgeMap[vert].compare_exchange_strong(old, value))
if (old < value) break;
};
- if (faceNormal_.size() != NumTri()) {
- faceNormal_.resize(NumTri());
- for_each_n(policy, countAt(0), NumTri(), [&](const int face) {
- vec3& triNormal = faceNormal_[face];
- if (halfedge_[3 * face].startVert < 0) {
- triNormal = vec3(0, 0, 1);
- return;
- }
-
- ivec3 triVerts;
- for (int i : {0, 1, 2}) {
- int v = halfedge_[3 * face + i].startVert;
- triVerts[i] = v;
- atomicMin(3 * face + i, v);
- }
- vec3 edge[3];
- for (int i : {0, 1, 2}) {
- const int j = (i + 1) % 3;
- edge[i] = la::normalize(vertPos_[triVerts[j]] - vertPos_[triVerts[i]]);
- }
- triNormal = la::normalize(la::cross(edge[0], edge[1]));
- if (std::isnan(triNormal.x)) triNormal = vec3(0, 0, 1);
- });
- } else {
- for_each_n(policy, countAt(0), halfedge_.size(),
- [&](const int i) { atomicMin(i, halfedge_[i].startVert); });
- }
+ for_each_n(policy, countAt(0), halfedge_.size(),
+ [&](const int i) { atomicMin(i, halfedge_.Start(i)); });
for_each_n(policy, countAt(0), NumVert(), [&](const size_t vert) {
int firstEdge = vertHalfedgeMap[vert].load();
@@ -736,8 +726,8 @@ void Manifold::Impl::CalculateNormals() {
}
vec3 normal = vec3(0.0);
ForVert(firstEdge, [&](int edge) {
- ivec3 triVerts = {halfedge_[edge].startVert, halfedge_[edge].endVert,
- halfedge_[NextHalfedge(edge)].endVert};
+ ivec3 triVerts = {halfedge_.Start(edge), halfedge_.End(edge),
+ halfedge_.End(NextHalfedge(edge))};
vec3 currEdge =
la::normalize(vertPos_[triVerts[1]] - vertPos_[triVerts[0]]);
vec3 prevEdge =
@@ -747,7 +737,7 @@ void Manifold::Impl::CalculateNormals() {
// should just exclude it from the normal calculation...
if (!la::isfinite(currEdge[0]) || !la::isfinite(prevEdge[0])) return;
double dot = -la::dot(prevEdge, currEdge);
- double phi = dot >= 1 ? 0 : (dot <= -1 ? kPi : sun_acos(dot));
+ double phi = dot >= 1 ? 0 : (dot <= -1 ? kPi : math::acos(dot));
normal += phi * faceNormal_[edge / 3];
});
vertNormal_[vert] = SafeNormalize(normal);
@@ -759,6 +749,7 @@ void Manifold::Impl::CalculateNormals() {
* instances of these meshes.
*/
void Manifold::Impl::IncrementMeshIDs() {
+ ZoneScoped;
HashTable<uint32_t> meshIDold2new(meshRelation_.meshIDtransform.size() * 2);
// Update keys of the transform map
std::map<int, Relation> oldTransforms;
@@ -775,107 +766,161 @@ void Manifold::Impl::IncrementMeshIDs() {
UpdateMeshID({meshIDold2new.D()}));
}
-#ifdef MANIFOLD_DEBUG
-/**
- * Debugging output using high precision OBJ files with specialized comments
- */
-std::ostream& operator<<(std::ostream& stream, const Manifold::Impl& impl) {
+#ifndef MANIFOLD_NO_IOSTREAM
+static std::ostream& WriteOBJWithEpsilon(std::ostream& stream,
+ const MeshGL64& mesh,
+ std::optional<double> epsilon) {
+ auto useHexFloat = []() {
+ const char* v = std::getenv("MANIFOLD_OBJ_HEX_FLOAT");
+ if (v == nullptr) return false;
+ return std::strcmp(v, "1") == 0 || std::strcmp(v, "true") == 0 ||
+ std::strcmp(v, "TRUE") == 0 || std::strcmp(v, "on") == 0 ||
+ std::strcmp(v, "ON") == 0;
+ };
+ const bool hexFloat = useHexFloat();
+ auto writeValue = [&](double value) {
+ if (hexFloat) {
+ // Use explicit C-format hex to keep text stable across standard library
+ // implementations.
+ char buf[128];
+ std::snprintf(buf, sizeof(buf), "%.13a", value);
+ stream << buf;
+ } else {
+ stream << value;
+ }
+ };
+
stream << std::setprecision(19); // for double precision
- stream << std::fixed; // for uniformity in output numbers
+ if (!hexFloat) {
+ stream << std::fixed; // for uniformity in output numbers
+ }
stream << "# ======= begin mesh ======" << std::endl;
- stream << "# tolerance = " << impl.tolerance_ << std::endl;
- stream << "# epsilon = " << impl.epsilon_ << std::endl;
- // TODO: Mesh relation, vertex normal and face normal
- for (const vec3& v : impl.vertPos_)
- stream << "v " << v.x << " " << v.y << " " << v.z << std::endl;
- std::vector<ivec3> triangles;
- triangles.reserve(impl.halfedge_.size() / 3);
- for (size_t i = 0; i < impl.halfedge_.size(); i += 3)
- triangles.emplace_back(impl.halfedge_[i].startVert + 1,
- impl.halfedge_[i + 1].startVert + 1,
- impl.halfedge_[i + 2].startVert + 1);
+ stream << "# float_format = " << (hexFloat ? "hexfloat" : "fixed")
+ << std::endl;
+ stream << "# tolerance = ";
+ writeValue(mesh.tolerance);
+ stream << std::endl;
+ if (epsilon.has_value()) {
+ stream << "# epsilon = ";
+ writeValue(epsilon.value());
+ stream << std::endl;
+ }
+ for (size_t i = 0; i < mesh.NumVert(); i++) {
+ stream << "v";
+ size_t offset = i * mesh.numProp;
+ for (size_t j : {0, 1, 2}) {
+ stream << " ";
+ writeValue(mesh.vertProperties[offset + j]);
+ }
+ stream << std::endl;
+ }
+ std::vector<std::array<uint64_t, 3>> triangles;
+ triangles.reserve(mesh.NumTri());
+ for (size_t i = 0; i < mesh.NumTri(); i++)
+ triangles.push_back({mesh.triVerts[3 * i] + 1, mesh.triVerts[3 * i + 1] + 1,
+ mesh.triVerts[3 * i + 2] + 1});
sort(triangles.begin(), triangles.end());
for (const auto& tri : triangles)
- stream << "f " << tri.x << " " << tri.y << " " << tri.z << std::endl;
+ stream << "f " << tri[0] << " " << tri[1] << " " << tri[2] << std::endl;
stream << "# ======== end mesh =======" << std::endl;
return stream;
}
-/**
- * Import a mesh from a Wavefront OBJ file that was exported with Write. This
- * function is the counterpart to Write and should be used with it. This
- * function is not guaranteed to be able to import OBJ files not written by the
- * Write function.
- */
-Manifold Manifold::ReadOBJ(std::istream& stream) {
- if (!stream.good()) return Invalid();
+static std::pair<MeshGL64, std::optional<double>> ReadOBJWithEpsilon(
+ std::istream& stream) {
+ static const std::string FLOAT_PATTERN =
+ "(-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)";
+ static const std::string FACE_ELEMENT = "(\\d+)(?:\\S+)?";
+ static const std::string TRAILING_SPACES = "(?:\\s*)";
+ static const std::string SEPARATOR = "\\s+";
+ static const std::regex TOLERANCE_COMMENT_PATTERN(
+ "^# tolerance = " + FLOAT_PATTERN + TRAILING_SPACES);
+ static const std::regex EPSILON_COMMENT_PATTERN(
+ "^# epsilon = " + FLOAT_PATTERN + TRAILING_SPACES);
+ static const std::regex VERTEX_PATTERN("^v" + SEPARATOR + FLOAT_PATTERN +
+ SEPARATOR + FLOAT_PATTERN + SEPARATOR +
+ FLOAT_PATTERN + TRAILING_SPACES);
+ static const std::regex FACE_PATTERN("^f" + SEPARATOR + FACE_ELEMENT +
+ SEPARATOR + FACE_ELEMENT + SEPARATOR +
+ FACE_ELEMENT + TRAILING_SPACES);
MeshGL64 mesh;
std::optional<double> epsilon;
- stream >> std::setprecision(19);
- while (true) {
- char c = stream.get();
- if (stream.eof()) break;
- switch (c) {
- case '#': {
- char c = stream.get();
- if (c == ' ') {
- constexpr int SIZE = 10;
- std::array<char, SIZE> tmp;
- stream.get(tmp.data(), SIZE, '\n');
- if (strncmp(tmp.data(), "tolerance", SIZE) == 0) {
- // skip 3 letters
- for (int _ : {0, 1, 2}) stream.get();
- stream >> mesh.tolerance;
- } else if (strncmp(tmp.data(), "epsilon =", SIZE) == 0) {
- double tmp;
- stream >> tmp;
- epsilon = {tmp};
- } else {
- // add it back because it is not what we want
- int end = 0;
- while (end < SIZE && tmp[end] != 0) end++;
- while (--end > -1) stream.putback(tmp[end]);
- }
- c = stream.get();
- }
- // just skip the remaining comment
- while (c != '\n' && !stream.eof()) {
- c = stream.get();
- }
- break;
- }
- case 'v':
- for (int _ : {0, 1, 2}) {
- double x;
- stream >> x;
- mesh.vertProperties.push_back(x);
- }
- break;
- case 'f':
- for (int _ : {0, 1, 2}) {
- uint64_t x;
- stream >> x;
- mesh.triVerts.push_back(x - 1);
- }
- break;
- case '\r':
- case '\n':
- break;
- default:
- DEBUG_ASSERT(false, userErr, "unexpected character in Manifold import");
+ if (!stream.good()) return std::make_pair(mesh, epsilon);
+
+ constexpr size_t BUFFER_SIZE = 1000;
+ std::array<char, BUFFER_SIZE> buffer;
+ std::cmatch m;
+
+ while (!stream.eof()) {
+ // extract line, and skip the line if it is longer than BUFFER_SIZE
+ // because the lines we care about should not be that long
+ // not using std::basic_istream<...>::getline because getline throws when
+ // the size exceeds the limit, but we don't want exception related code
+ size_t i = 0;
+ char c;
+ while (!stream.eof() && (c = stream.get()) != '\n' && c != '\r')
+ if (i < BUFFER_SIZE) buffer[i++] = c;
+ if (i == BUFFER_SIZE) continue;
+ buffer[i] = '\0';
+ // check pattern...
+ if (std::regex_match(buffer.data(), m, TOLERANCE_COMMENT_PATTERN)) {
+ mesh.tolerance = FromChars(m[1]);
+ } else if (std::regex_match(buffer.data(), m, EPSILON_COMMENT_PATTERN)) {
+ epsilon = {FromChars(m[1])};
+ } else if (std::regex_match(buffer.data(), m, VERTEX_PATTERN)) {
+ for (int j : {0, 1, 2})
+ mesh.vertProperties.push_back(FromChars(m[j + 1]));
+ } else if (std::regex_match(buffer.data(), m, FACE_PATTERN)) {
+ for (int j : {0, 1, 2})
+ mesh.triVerts.push_back(std::stoi(m[j + 1].str()) - 1);
}
}
- auto m = std::make_shared<Manifold::Impl>(mesh);
- if (epsilon) m->SetEpsilon(*epsilon);
- return Manifold(m);
+
+ return std::make_pair(mesh, epsilon);
+}
+
+/**
+ * Import a mesh from a Wavefront OBJ file.
+ */
+MeshGL64 ReadOBJ(std::istream& stream) {
+ return ReadOBJWithEpsilon(stream).first;
+}
+
+/**
+ * Import a mesh from a Wavefront OBJ file.
+ * This supports reading tolerance and epsilon values from WriteOBJ.
+ */
+Manifold Manifold::ReadOBJ(std::istream& stream) {
+ if (!stream.good()) return Invalid();
+ auto [mesh, epsilon] = ReadOBJWithEpsilon(stream);
+ auto impl = std::make_shared<Impl>(mesh);
+ if (epsilon) impl->SetEpsilon(epsilon.value());
+ return Manifold(impl);
+}
+
+/**
+ * Export the mesh to a Wavefront OBJ file in a way that preserves the full
+ * 64-bit precision of the vertex positions.
+ */
+bool WriteOBJ(std::ostream& stream, const MeshGL64& mesh) {
+ if (!stream.good()) return false;
+ WriteOBJWithEpsilon(stream, mesh, {});
+ return true;
+}
+
+/**
+ * Debugging output using high precision OBJ files with specialized comments
+ */
+std::ostream& operator<<(std::ostream& stream, const Manifold::Impl& impl) {
+ MeshGL64 mesh = GetMeshGLImpl<double, uint64_t>(impl, -1);
+ return WriteOBJWithEpsilon(stream, mesh, {impl.epsilon_});
}
/**
* Export the mesh to a Wavefront OBJ file in a way that preserves the full
* 64-bit precision of the vertex positions, as well as storing metadata such as
- * the tolerance and epsilon. Useful for debugging and testing. Files written
- * by WriteOBJ should be read back in with ReadOBJ.
+ * the tolerance and epsilon.
*/
bool Manifold::WriteOBJ(std::ostream& stream) const {
if (!stream.good()) return false;
@@ -883,5 +928,4 @@ bool Manifold::WriteOBJ(std::ostream& stream) const {
return true;
}
#endif
-
} // namespace manifold
diff --git a/thirdparty/manifold/src/impl.h b/thirdparty/manifold/src/impl.h
index 62e368012df..00f9c6bbace 100644
--- a/thirdparty/manifold/src/impl.h
+++ b/thirdparty/manifold/src/impl.h
@@ -16,6 +16,7 @@
#include <map>
#include "collider.h"
+#include "execution_impl.h"
#include "manifold/common.h"
#include "manifold/manifold.h"
#include "shared.h"
@@ -29,6 +30,18 @@ struct Manifold::Impl {
int originalID = -1;
mat3x4 transform = la::identity;
bool backSide = false;
+ // True when this meshID's contribution to properties_ slots 0..2 holds
+ // world-frame vertex normals (set by CalculateNormals at slot 0). Carries
+ // through Transforms and Booleans. Exported as runFlags bit 1.
+ bool hasNormals = false;
+
+ mat3 GetNormalTransform() const {
+ return NormalTransform(transform) * (backSide ? -1.0 : 1.0);
+ }
+
+ mat3 GetInverseNormalTransform() const {
+ return InverseNormalTransform(transform) * (backSide ? -1.0 : 1.0);
+ }
};
struct MeshRelationD {
/// The originalID of this Manifold if it is an original; -1 otherwise.
@@ -45,11 +58,30 @@ struct Manifold::Impl {
double tolerance_ = -1;
int numProp_ = 0;
Error status_ = Error::NoError;
+
+ // True only when every meshID carries normals at slot 0..2 - the
+ // condition under which GetMeshGL(-1) can safely auto-substitute that
+ // slot. A mixed Boolean output (some meshIDs with normals, some
+ // without) returns false; the output MeshGL's per-run bit 1 still
+ // marks the with-normals runs individually.
+ bool AllHaveNormals() const {
+ if (meshRelation_.meshIDtransform.empty()) return false;
+ for (const auto& m : meshRelation_.meshIDtransform) {
+ if (!m.second.hasNormals) return false;
+ }
+ return true;
+ }
+
+ // True iff the meshID owning `tri` has hasNormals set. Returns false when
+ // the meshID isn't in meshRelation_.meshIDtransform (treat as no-normals).
+ static bool TriHasNormals(const MeshRelationD& meshRelation, int tri) {
+ const int meshID = meshRelation.triRef[tri].meshID;
+ auto it = meshRelation.meshIDtransform.find(meshID);
+ return it != meshRelation.meshIDtransform.end() && it->second.hasNormals;
+ }
Vec<vec3> vertPos_;
- Vec<Halfedge> halfedge_;
+ Halfedges halfedge_;
Vec<double> properties_;
- // Note that vertNormal_ is not precise due to the use of an approximated acos
- // function
Vec<vec3> vertNormal_;
Vec<vec3> faceNormal_;
Vec<vec4> halfedgeTangent_;
@@ -59,248 +91,51 @@ struct Manifold::Impl {
static std::atomic<uint32_t> meshIDCounter_;
static uint32_t ReserveIDs(uint32_t);
- Impl() {}
+ Impl() {};
enum class Shape { Tetrahedron, Cube, Octahedron };
Impl(Shape, const mat3x4 = la::identity);
template <typename Precision, typename I>
- Impl(const MeshGLP<Precision, I>& meshGL) {
- const uint32_t numVert = meshGL.NumVert();
- const uint32_t numTri = meshGL.NumTri();
-
- if (numVert == 0 && numTri == 0) {
- MakeEmpty(Error::NoError);
- return;
- }
-
- if (numVert < 4 || numTri < 4) {
- MakeEmpty(Error::NotManifold);
- return;
- }
-
- if (meshGL.numProp < 3) {
- MakeEmpty(Error::MissingPositionProperties);
- return;
- }
-
- if (meshGL.mergeFromVert.size() != meshGL.mergeToVert.size()) {
- MakeEmpty(Error::MergeVectorsDifferentLengths);
- return;
- }
-
- if (!meshGL.runTransform.empty() &&
- 12 * meshGL.runOriginalID.size() != meshGL.runTransform.size()) {
- MakeEmpty(Error::TransformWrongLength);
- return;
- }
-
- if (!meshGL.runOriginalID.empty() && !meshGL.runIndex.empty() &&
- meshGL.runOriginalID.size() + 1 != meshGL.runIndex.size() &&
- meshGL.runOriginalID.size() != meshGL.runIndex.size()) {
- MakeEmpty(Error::RunIndexWrongLength);
- return;
- }
-
- if (!meshGL.faceID.empty() && meshGL.faceID.size() != meshGL.NumTri()) {
- MakeEmpty(Error::FaceIDWrongLength);
- return;
- }
-
- if (!manifold::all_of(meshGL.vertProperties.begin(),
- meshGL.vertProperties.end(),
- [](Precision x) { return std::isfinite(x); })) {
- MakeEmpty(Error::NonFiniteVertex);
- return;
- }
-
- if (!manifold::all_of(meshGL.runTransform.begin(),
- meshGL.runTransform.end(),
- [](Precision x) { return std::isfinite(x); })) {
- MakeEmpty(Error::InvalidConstruction);
- return;
- }
-
- if (!manifold::all_of(meshGL.halfedgeTangent.begin(),
- meshGL.halfedgeTangent.end(),
- [](Precision x) { return std::isfinite(x); })) {
- MakeEmpty(Error::InvalidConstruction);
- return;
- }
-
- std::vector<int> prop2vert;
- if (!meshGL.mergeFromVert.empty()) {
- prop2vert.resize(numVert);
- std::iota(prop2vert.begin(), prop2vert.end(), 0);
- for (size_t i = 0; i < meshGL.mergeFromVert.size(); ++i) {
- const uint32_t from = meshGL.mergeFromVert[i];
- const uint32_t to = meshGL.mergeToVert[i];
- if (from >= numVert || to >= numVert) {
- MakeEmpty(Error::MergeIndexOutOfBounds);
- return;
- }
- prop2vert[from] = to;
- }
- }
-
- const auto numProp = meshGL.numProp - 3;
- numProp_ = numProp;
- properties_.resize_nofill(meshGL.NumVert() * numProp);
- tolerance_ = meshGL.tolerance;
- // This will have unreferenced duplicate positions that will be removed by
- // Impl::RemoveUnreferencedVerts().
- vertPos_.resize_nofill(meshGL.NumVert());
-
- for (size_t i = 0; i < meshGL.NumVert(); ++i) {
- for (const int j : {0, 1, 2})
- vertPos_[i][j] = meshGL.vertProperties[meshGL.numProp * i + j];
- for (size_t j = 0; j < numProp; ++j)
- properties_[i * numProp + j] =
- meshGL.vertProperties[meshGL.numProp * i + 3 + j];
- }
+ Impl(const MeshGLP<Precision, I>& meshGL,
+ ExecutionContext::Impl* ctx = nullptr);
- halfedgeTangent_.resize_nofill(meshGL.halfedgeTangent.size() / 4);
- for (size_t i = 0; i < halfedgeTangent_.size(); ++i) {
- for (const int j : {0, 1, 2, 3})
- halfedgeTangent_[i][j] = meshGL.halfedgeTangent[4 * i + j];
- }
-
- Vec<TriRef> triRef;
- triRef.resize_nofill(meshGL.NumTri());
-
- auto runIndex = meshGL.runIndex;
- const auto runEnd = meshGL.triVerts.size();
- if (runIndex.empty()) {
- runIndex = {0, static_cast<I>(runEnd)};
- } else if (runIndex.size() == meshGL.runOriginalID.size()) {
- runIndex.push_back(runEnd);
- } else if (runIndex.size() == 1) {
- runIndex.push_back(runEnd);
- }
-
- const auto startID =
- Impl::ReserveIDs(std::max(1_uz, meshGL.runOriginalID.size()));
- auto runOriginalID = meshGL.runOriginalID;
- if (runOriginalID.empty()) {
- runOriginalID.push_back(startID);
- }
- for (size_t i = 0; i < runOriginalID.size(); ++i) {
- const int meshID = startID + i;
- const int originalID = runOriginalID[i];
- for (size_t tri = runIndex[i] / 3; tri < runIndex[i + 1] / 3; ++tri) {
- TriRef& ref = triRef[tri];
- ref.meshID = meshID;
- ref.originalID = originalID;
- ref.faceID = meshGL.faceID.empty() ? -1 : meshGL.faceID[tri];
- ref.coplanarID = tri;
- }
-
- if (meshGL.runTransform.empty()) {
- meshRelation_.meshIDtransform[meshID] = {originalID};
- } else {
- const Precision* m = meshGL.runTransform.data() + 12 * i;
- meshRelation_.meshIDtransform[meshID] = {originalID,
- {{m[0], m[1], m[2]},
- {m[3], m[4], m[5]},
- {m[6], m[7], m[8]},
- {m[9], m[10], m[11]}}};
- }
- }
-
- Vec<ivec3> triProp;
- triProp.reserve(numTri);
- Vec<ivec3> triVert;
- const bool needsPropMap = numProp > 0 && !prop2vert.empty();
- if (needsPropMap) triVert.reserve(numTri);
- if (triRef.size() > 0) meshRelation_.triRef.reserve(numTri);
- for (size_t i = 0; i < numTri; ++i) {
- ivec3 triP, triV;
- for (const size_t j : {0, 1, 2}) {
- uint32_t vert = (uint32_t)meshGL.triVerts[3 * i + j];
- if (vert >= numVert) {
- MakeEmpty(Error::VertexOutOfBounds);
- return;
- }
- triP[j] = vert;
- triV[j] = prop2vert.empty() ? vert : prop2vert[vert];
- }
- if (triV[0] != triV[1] && triV[1] != triV[2] && triV[2] != triV[0]) {
- if (needsPropMap) {
- triProp.push_back(triP);
- triVert.push_back(triV);
- } else {
- triProp.push_back(triV);
- }
- if (triRef.size() > 0) {
- meshRelation_.triRef.push_back(triRef[i]);
- }
- }
- }
-
- CreateHalfedges(triProp, triVert);
- if (!IsManifold()) {
- MakeEmpty(Error::NotManifold);
- return;
- }
-
- CalculateBBox();
- SetEpsilon(-1, std::is_same<Precision, float>::value);
-
- // we need to split pinched verts before calculating vertex normals, because
- // the algorithm doesn't work with pinched verts
- CleanupTopology();
- CalculateNormals();
-
- DedupePropVerts();
- MarkCoplanar();
-
- RemoveDegenerates();
- RemoveUnreferencedVerts();
- Finish();
-
- if (!IsFinite()) {
- MakeEmpty(Error::NonFiniteVertex);
- return;
- }
-
- // A Manifold created from an input mesh is never an original - the input is
- // the original.
- meshRelation_.originalID = -1;
- }
+ // sdf.cpp. Populates an empty Impl with the level set of `sdf`. `ctx`
+ // (when non-null) checks cancel and credits Progress() between the five
+ // phases counted by kPhasesPerLevelSet.
+ void CreateLevelSet(std::function<double(vec3)> sdf, Box bounds,
+ double edgeLength, double level, double tolerance,
+ bool canParallel, ExecutionContext::Impl* ctx = nullptr);
template <typename F>
- inline void ForVert(int halfedge, F func) {
- int current = halfedge;
- do {
- current = NextHalfedge(halfedge_[current].pairedHalfedge);
- func(current);
- } while (current != halfedge);
- }
+ inline void ForVert(int halfedge, F func);
template <typename T>
void ForVert(
int halfedge, std::function<T(int halfedge)> transform,
- std::function<void(int halfedge, const T& here, T& next)> binaryOp) {
- T here = transform(halfedge);
- int current = halfedge;
- do {
- const int nextHalfedge = NextHalfedge(halfedge_[current].pairedHalfedge);
- T next = transform(nextHalfedge);
- binaryOp(current, here, next);
- here = next;
- current = nextHalfedge;
- } while (current != halfedge);
- }
+ std::function<void(int halfedge, const T& here, T& next)> binaryOp);
- void MarkCoplanar();
+ void SetNormalsAndCoplanar();
void DedupePropVerts();
void RemoveUnreferencedVerts();
- void InitializeOriginal(bool keepFaceID = false);
+ void InitializeOriginal();
void CreateHalfedges(const Vec<ivec3>& triProp,
const Vec<ivec3>& triVert = {});
- void CalculateNormals();
+ void CalculateVertNormals();
void IncrementMeshIDs();
- void Update();
+ // Eager-transform slot 0..2 of properties_ for propVerts whose meshID
+ // carries hasNormals. Used by both Impl::Transform and Compose. The buffer
+ // is laid out as `properties[(offset + propVert) * stride + i]` so the
+ // helper can target either an in-place properties_ vector (offset=0) or
+ // a per-node slice of a combined properties array (offset=propVertIndices,
+ // stride=numPropOut).
+ static void EagerTransformPropNormals(const Halfedges& halfedge,
+ const MeshRelationD& meshRelation,
+ const mat3& normalTransform,
+ Vec<double>& properties,
+ int numPropVert, int stride,
+ int offset = 0);
+
void MakeEmpty(Error status);
void Warp(std::function<void(vec3&)> warpFunc);
void WarpBatch(std::function<void(VecView<vec3>)> warpFunc);
@@ -328,21 +163,32 @@ struct Manifold::Impl {
bool IsSelfIntersecting() const;
bool MatchesTriNormals() const;
int NumDegenerateTris() const;
+ bool IsConvex() const;
double MinGap(const Impl& other, double searchLength) const;
+ // boolean3.cpp
+ std::vector<RayHit> RayCast(vec3 origin, vec3 endpoint) const;
+
// sort.cpp
- void Finish();
- void SortVerts();
- void ReindexVerts(const Vec<int>& vertNew2Old, size_t numOldVert);
- void CompactProps();
- void GetFaceBoxMorton(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) const;
- void SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton);
- void GatherFaces(const Vec<int>& faceNew2Old);
- void GatherFaces(const Impl& old, const Vec<int>& faceNew2Old);
+ void SortGeometry(ExecutionContext::Impl* ctx = nullptr);
+ void SortVerts(ExecutionContext::Impl* ctx = nullptr);
+ void ReindexVerts(const Vec<int>& vertNew2Old, size_t numOldVert,
+ ExecutionContext::Impl* ctx = nullptr);
+ void CompactProps(ExecutionContext::Impl* ctx = nullptr);
+ void GetFaceBoxMorton(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton,
+ ExecutionContext::Impl* ctx = nullptr) const;
+ void SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton,
+ ExecutionContext::Impl* ctx = nullptr);
+ void GatherFaces(const Vec<int>& faceNew2Old,
+ ExecutionContext::Impl* ctx = nullptr);
+ void GatherFaces(const Impl& old, const Vec<int>& faceNew2Old,
+ ExecutionContext::Impl* ctx = nullptr);
+ void ReorderHalfedges(ExecutionContext::Impl* ctx = nullptr);
// face_op.cpp
- void Face2Tri(const Vec<int>& faceEdge, const Vec<TriRef>& halfedgeRef,
- bool allowConvex = false);
+ void Face2Tri(const Vec<int>& faceEdge, const VecView<const Halfedge>&,
+ const Vec<TriRef>& halfedgeRef, bool allowConvex = false,
+ ExecutionContext::Impl* ctx = nullptr);
Polygons Slice(double height) const;
Polygons Project() const;
@@ -354,10 +200,10 @@ struct Manifold::Impl {
void CollapseColinearEdges(int firstNewVert = 0);
void SwapDegenerates(int firstNewVert = 0);
void DedupeEdge(int edge);
- bool CollapseEdge(int edge, std::vector<int>& edges);
- void RecursiveEdgeSwap(int edge, int& tag, std::vector<int>& visited,
- std::vector<int>& edgeSwapStack,
- std::vector<int>& edges);
+ bool CollapseEdge(int edge, Vec<int>& edges, double tol = -1,
+ int firstNewVert = 0);
+ void RecursiveEdgeSwap(int edge, int& tag, Vec<int>& visited,
+ Vec<int>& edgeSwapStack, Vec<int>& edges);
void RemoveIfFolded(int edge);
void PairUp(int edge0, int edge1);
void UpdateVert(int vert, int startEdge, int endEdge);
@@ -379,6 +225,7 @@ struct Manifold::Impl {
bool IsMarkedInsideQuad(int halfedge) const;
vec3 GetNormal(int halfedge, int normalIdx) const;
vec4 TangentFromNormal(const vec3& normal, int halfedge) const;
+ bool ValidTangents() const;
std::vector<Smoothness> UpdateSharpenedEdges(
const std::vector<Smoothness>&) const;
Vec<bool> FlatFaces() const;
@@ -391,13 +238,490 @@ struct Manifold::Impl {
void LinearizeFlatTangents();
void DistributeTangents(const Vec<bool>& fixedHalfedges);
void CreateTangents(int normalIdx);
- void CreateTangents(std::vector<Smoothness>);
- void Refine(std::function<int(vec3, vec4, vec4)>, bool = false);
+ void CreateTangents(std::vector<Smoothness>,
+ ExecutionContext::Impl* ctx = nullptr);
+ void Refine(std::function<int(vec3, vec4, vec4)>, bool = false,
+ ExecutionContext::Impl* ctx = nullptr);
// quickhull.cpp
- void Hull(VecView<vec3> vertPos);
+ void Hull(VecView<const vec3> vertPos, ExecutionContext::Impl* ctx = nullptr);
+
+ // minkowski.cpp
+ Manifold Minkowski(const Impl& other, bool inset,
+ ExecutionContext::Impl* ctx = nullptr) const;
};
extern std::mutex dump_lock;
std::ostream& operator<<(std::ostream& stream, const Manifold::Impl& impl);
+
+// ------------------------------------------------------------------------------
+// Template implementations follow:
+
+template <typename F>
+inline void Manifold::Impl::ForVert(int halfedge, F func) {
+ int current = halfedge;
+ do {
+ current = NextHalfedge(halfedge_.Pair(current));
+ func(current);
+ } while (current != halfedge);
+}
+
+template <typename T>
+void Manifold::Impl::ForVert(
+ int halfedge, std::function<T(int halfedge)> transform,
+ std::function<void(int halfedge, const T& here, T& next)> binaryOp) {
+ T here = transform(halfedge);
+ int current = halfedge;
+ do {
+ const int nextHalfedge = NextHalfedge(halfedge_.Pair(current));
+ T next = transform(nextHalfedge);
+ binaryOp(current, here, next);
+ here = next;
+ current = nextHalfedge;
+ } while (current != halfedge);
+}
+
+template <typename Precision, typename I>
+Manifold::Impl::Impl(const MeshGLP<Precision, I>& meshGL,
+ ExecutionContext::Impl* ctx) {
+ // Entry-time cancel wins over empty/malformed input; past this gate,
+ // validation errors win over races.
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
+
+ const uint32_t numVert = meshGL.NumVert();
+ const uint32_t numTri = meshGL.NumTri();
+
+ if (numVert == 0 && numTri == 0) {
+ MakeEmpty(Error::NoError);
+ return;
+ }
+
+ if (numVert < 4 || numTri < 4) {
+ MakeEmpty(Error::NotManifold);
+ return;
+ }
+
+ if (meshGL.numProp < 3) {
+ MakeEmpty(Error::MissingPositionProperties);
+ return;
+ }
+
+ if (meshGL.mergeFromVert.size() != meshGL.mergeToVert.size()) {
+ MakeEmpty(Error::MergeVectorsDifferentLengths);
+ return;
+ }
+
+ if (!meshGL.runTransform.empty() &&
+ 12 * meshGL.runOriginalID.size() != meshGL.runTransform.size()) {
+ MakeEmpty(Error::TransformWrongLength);
+ return;
+ }
+
+ if (!meshGL.runOriginalID.empty() && !meshGL.runIndex.empty() &&
+ meshGL.runOriginalID.size() + 1 != meshGL.runIndex.size() &&
+ meshGL.runOriginalID.size() != meshGL.runIndex.size()) {
+ MakeEmpty(Error::RunIndexWrongLength);
+ return;
+ }
+
+ if (!meshGL.faceID.empty() && meshGL.faceID.size() != meshGL.NumTri()) {
+ MakeEmpty(Error::FaceIDWrongLength);
+ return;
+ }
+
+ if (!manifold::all_of(meshGL.vertProperties.begin(),
+ meshGL.vertProperties.end(),
+ [](Precision x) { return std::isfinite(x); })) {
+ MakeEmpty(Error::NonFiniteVertex);
+ return;
+ }
+
+ if (!manifold::all_of(meshGL.runTransform.begin(), meshGL.runTransform.end(),
+ [](Precision x) { return std::isfinite(x); })) {
+ MakeEmpty(Error::InvalidConstruction);
+ return;
+ }
+
+ if (!manifold::all_of(meshGL.halfedgeTangent.begin(),
+ meshGL.halfedgeTangent.end(),
+ [](Precision x) { return std::isfinite(x); })) {
+ MakeEmpty(Error::InvalidConstruction);
+ return;
+ }
+
+ std::vector<int> prop2vert;
+ if (!meshGL.mergeFromVert.empty()) {
+ prop2vert.resize(numVert);
+ std::iota(prop2vert.begin(), prop2vert.end(), 0);
+ for (size_t i = 0; i < meshGL.mergeFromVert.size(); ++i) {
+ const uint32_t from = meshGL.mergeFromVert[i];
+ const uint32_t to = meshGL.mergeToVert[i];
+ if (from >= numVert || to >= numVert) {
+ MakeEmpty(Error::MergeIndexOutOfBounds);
+ return;
+ }
+ prop2vert[from] = to;
+ }
+ }
+
+ const auto numProp = meshGL.numProp - 3;
+ numProp_ = numProp;
+ properties_.resize_nofill(meshGL.NumVert() * numProp);
+ tolerance_ = meshGL.tolerance;
+ // This will have unreferenced duplicate positions that will be removed by
+ // Impl::RemoveUnreferencedVerts().
+ vertPos_.resize_nofill(meshGL.NumVert());
+
+ for (size_t i = 0; i < meshGL.NumVert(); ++i) {
+ for (const int j : {0, 1, 2})
+ vertPos_[i][j] = meshGL.vertProperties[meshGL.numProp * i + j];
+ for (size_t j = 0; j < numProp; ++j)
+ properties_[i * numProp + j] =
+ meshGL.vertProperties[meshGL.numProp * i + 3 + j];
+ }
+
+ halfedgeTangent_.resize_nofill(meshGL.halfedgeTangent.size() / 4);
+ for (size_t i = 0; i < halfedgeTangent_.size(); ++i) {
+ for (const int j : {0, 1, 2, 3})
+ halfedgeTangent_[i][j] = meshGL.halfedgeTangent[4 * i + j];
+ }
+
+ Vec<TriRef> triRef;
+ triRef.resize_nofill(meshGL.NumTri());
+
+ auto runIndex = meshGL.runIndex;
+ const auto runEnd = meshGL.triVerts.size();
+ if (runIndex.empty()) {
+ runIndex = {0, static_cast<I>(runEnd)};
+ } else if (runIndex.size() == meshGL.runOriginalID.size()) {
+ runIndex.push_back(runEnd);
+ } else if (runIndex.size() == 1) {
+ runIndex.push_back(runEnd);
+ }
+
+ const auto startID =
+ Impl::ReserveIDs(std::max(1_uz, meshGL.runOriginalID.size()));
+ auto runOriginalID = meshGL.runOriginalID;
+ if (runOriginalID.empty()) {
+ runOriginalID.push_back(startID);
+ }
+ for (size_t i = 0; i < runOriginalID.size(); ++i) {
+ const int meshID = startID + i;
+ const int originalID = runOriginalID[i];
+ const bool backside = meshGL.Backside(i);
+ // Per-run hasNormals (runFlags bit 1). Defensively require numProp >= 3
+ // so a caller setting the bit on a too-small MeshGL doesn't make us read
+ // past the property bounds.
+ const bool runHasN = meshGL.HasNormals(i) && numProp >= 3;
+ for (size_t tri = runIndex[i] / 3; tri < runIndex[i + 1] / 3; ++tri) {
+ TriRef& ref = triRef[tri];
+ ref.meshID = meshID;
+ ref.originalID = originalID;
+ ref.faceID = meshGL.faceID.empty() ? -1 : meshGL.faceID[tri];
+ ref.coplanarID = tri;
+ }
+
+ if (meshGL.runTransform.empty()) {
+ meshRelation_.meshIDtransform[meshID] = {originalID, la::identity, false,
+ runHasN};
+ } else {
+ const Precision* m = meshGL.runTransform.data() + 12 * i;
+ meshRelation_.meshIDtransform[meshID] = {originalID,
+ {{m[0], m[1], m[2]},
+ {m[3], m[4], m[5]},
+ {m[6], m[7], m[8]},
+ {m[9], m[10], m[11]}},
+ backside,
+ runHasN};
+ }
+ }
+
+ Vec<ivec3> triProp;
+ triProp.reserve(numTri);
+ Vec<ivec3> triVert;
+ const bool needsPropMap = numProp > 0 && !prop2vert.empty();
+ if (needsPropMap) triVert.reserve(numTri);
+ if (triRef.size() > 0) meshRelation_.triRef.reserve(numTri);
+ for (size_t i = 0; i < numTri; ++i) {
+ ivec3 triP, triV;
+ for (const size_t j : {0, 1, 2}) {
+ uint32_t vert = (uint32_t)meshGL.triVerts[3 * i + j];
+ if (vert >= numVert) {
+ MakeEmpty(Error::VertexOutOfBounds);
+ return;
+ }
+ triP[j] = vert;
+ triV[j] = prop2vert.empty() ? vert : prop2vert[vert];
+ }
+ if (triV[0] != triV[1] && triV[1] != triV[2] && triV[2] != triV[0]) {
+ if (needsPropMap) {
+ triProp.push_back(triP);
+ triVert.push_back(triV);
+ } else {
+ triProp.push_back(triV);
+ }
+ if (triRef.size() > 0) {
+ meshRelation_.triRef.push_back(triRef[i]);
+ }
+ }
+ }
+
+ // Phase boundaries; count of ADVANCE_PHASE_OR_RETURN calls below must
+ // equal kPhasesPerFromMesh.
+ CreateHalfedges(triProp, triVert);
+ if (!IsManifold()) {
+ MakeEmpty(Error::NotManifold);
+ return;
+ }
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ CalculateBBox();
+ SetEpsilon(-1, std::is_same<Precision, float>::value);
+
+ // we need to split pinched verts before calculating vertex normals, because
+ // the algorithm doesn't work with pinched verts
+ CleanupTopology();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ DedupePropVerts();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ SetNormalsAndCoplanar();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ RemoveDegenerates();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ RemoveUnreferencedVerts();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ SortGeometry(ctx);
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ if (!IsFinite()) {
+ MakeEmpty(Error::NonFiniteVertex);
+ return;
+ }
+
+ // A Manifold created from an input mesh is never an original - the input is
+ // the original.
+ meshRelation_.originalID = -1;
+}
+
+template <typename Precision, typename I>
+inline MeshGLP<Precision, I> GetMeshGLImpl(const manifold::Manifold::Impl& impl,
+ int normalIdx) {
+ ZoneScoped;
+ const int numProp = impl.NumProp();
+ const int numVert = impl.NumPropVert();
+ const int numTri = impl.NumTri();
+
+ const bool isOriginal = impl.meshRelation_.originalID >= 0;
+ const bool updateNormals = !isOriginal && normalIdx >= 0;
+
+ MeshGLP<Precision, I> out;
+ out.numProp = 3 + numProp;
+ out.tolerance = impl.tolerance_;
+ if (std::is_same<Precision, float>::value)
+ out.tolerance =
+ std::max(out.tolerance,
+ static_cast<Precision>(std::numeric_limits<float>::epsilon() *
+ impl.bBox_.Scale()));
+ out.triVerts.resize(3 * numTri);
+
+ const int numHalfedge = impl.halfedgeTangent_.size();
+ out.halfedgeTangent.resize(4 * numHalfedge);
+ for (int i = 0; i < numHalfedge; ++i) {
+ const vec4 t = impl.halfedgeTangent_[i];
+ out.halfedgeTangent[4 * i] = t.x;
+ out.halfedgeTangent[4 * i + 1] = t.y;
+ out.halfedgeTangent[4 * i + 2] = t.z;
+ out.halfedgeTangent[4 * i + 3] = t.w;
+ }
+ // Sort the triangles into runs
+ out.faceID.resize(numTri);
+ std::vector<int> triNew2Old(numTri);
+ std::iota(triNew2Old.begin(), triNew2Old.end(), 0);
+ VecView<const TriRef> triRef = impl.meshRelation_.triRef;
+ // Don't sort originals - keep them in order
+ if (!isOriginal) {
+ std::stable_sort(triNew2Old.begin(), triNew2Old.end(),
+ [triRef](int a, int b) {
+ return triRef[a].originalID == triRef[b].originalID
+ ? triRef[a].meshID < triRef[b].meshID
+ : triRef[a].originalID < triRef[b].originalID;
+ });
+ }
+
+ // runFlags layout: bit 0 = backSide, bit 1 = hasNormals (slot 0..2 of the
+ // extra properties is world-frame vertex normals; consumers should skip
+ // re-applying runTransform to those channels).
+ auto addRun = [isOriginal](MeshGLP<Precision, I>& out, int tri,
+ const manifold::Manifold::Impl::Relation& rel) {
+ out.runIndex.push_back(3 * tri);
+ out.runOriginalID.push_back(rel.originalID);
+ // runFlags carries hasNormals (bit 1) which we want on originals too;
+ // runTransform is just metadata so skip it for originals where it would
+ // always be identity.
+ const uint8_t flags = (rel.backSide ? 1u : 0u) | (rel.hasNormals ? 2u : 0u);
+ out.runFlags.push_back(flags);
+ if (!isOriginal) {
+ for (const int col : {0, 1, 2, 3}) {
+ for (const int row : {0, 1, 2}) {
+ out.runTransform.push_back(rel.transform[col][row]);
+ }
+ }
+ }
+ };
+
+ auto meshIDtransform = impl.meshRelation_.meshIDtransform;
+ int lastID = -1;
+ for (int tri = 0; tri < numTri; ++tri) {
+ const int oldTri = triNew2Old[tri];
+ const auto ref = triRef[oldTri];
+ const int meshID = ref.meshID;
+
+ out.faceID[tri] = ref.faceID >= 0 ? ref.faceID : ref.coplanarID;
+ for (const int i : {0, 1, 2})
+ out.triVerts[3 * tri + i] = impl.halfedge_.Start(3 * oldTri + i);
+
+ if (meshID != lastID) {
+ manifold::Manifold::Impl::Relation rel;
+ auto it = meshIDtransform.find(meshID);
+ if (it != meshIDtransform.end()) rel = it->second;
+ addRun(out, tri, rel);
+ meshIDtransform.erase(meshID);
+ lastID = meshID;
+ }
+ }
+ // Add runs for originals that did not contribute any faces to the output
+ for (const auto& pair : meshIDtransform) {
+ addRun(out, numTri, pair.second);
+ }
+ out.runIndex.push_back(3 * numTri);
+
+ // Early return for no props
+ if (numProp == 0) {
+ out.vertProperties.resize(3 * numVert);
+ for (int i = 0; i < numVert; ++i) {
+ const vec3 v = impl.vertPos_[i];
+ out.vertProperties[3 * i] = v.x;
+ out.vertProperties[3 * i + 1] = v.y;
+ out.vertProperties[3 * i + 2] = v.z;
+ }
+ return out;
+ }
+ // Duplicate verts with different props
+ std::vector<int> vert2idx(impl.NumVert(), -1);
+ std::vector<std::vector<ivec2>> vertPropPair(impl.NumVert());
+ out.vertProperties.reserve(numVert * static_cast<size_t>(out.numProp));
+
+ for (size_t run = 0; run < out.runOriginalID.size(); ++run) {
+ for (size_t tri = out.runIndex[run] / 3; tri < out.runIndex[run + 1] / 3;
+ ++tri) {
+ for (const int i : {0, 1, 2}) {
+ const int prop = impl.halfedge_.Prop(3 * triNew2Old[tri] + i);
+ const int vert = out.triVerts[3 * tri + i];
+
+ auto& bin = vertPropPair[vert];
+ bool bFound = false;
+ for (const auto& b : bin) {
+ if (b.x == prop) {
+ bFound = true;
+ out.triVerts[3 * tri + i] = b.y;
+ break;
+ }
+ }
+ if (bFound) continue;
+ const int idx = out.vertProperties.size() / out.numProp;
+ out.triVerts[3 * tri + i] = idx;
+ bin.push_back({prop, idx});
+
+ for (int p : {0, 1, 2}) {
+ out.vertProperties.push_back(impl.vertPos_[vert][p]);
+ }
+ for (int p = 0; p < numProp; ++p) {
+ out.vertProperties.push_back(impl.properties_[prop * numProp + p]);
+ }
+
+ // Normalize the requested normal slot. For runs that already carry
+ // world-frame normals (hasNormals bit), just normalize; for legacy
+ // callers asking to interpret a slot as normals on a run without
+ // hasNormals, apply the per-run inverse-frame transform first.
+ // TODO: collapse the !runHasN branch into a no-op once the explicit-
+ // normalIdx parameter on GetMeshGL is removed and `updateNormals`
+ // becomes implied by the hasNormals bit.
+ if (updateNormals) {
+ vec3 normal;
+ const int start = out.vertProperties.size() - out.numProp;
+ for (int i : {0, 1, 2}) {
+ normal[i] = out.vertProperties[start + 3 + normalIdx + i];
+ }
+ const bool runHasN = !isOriginal && (out.runFlags[run] & 2) != 0;
+ if (!isOriginal && !runHasN) {
+ const Precision* m = out.runTransform.data() + 12 * run;
+ const mat3x4 t({m[0], m[1], m[2]}, {m[3], m[4], m[5]},
+ {m[6], m[7], m[8]}, {m[9], m[10], m[11]});
+ normal = NormalTransform(t) *
+ ((out.runFlags[run] & 1) ? -1.0 : 1.0) * normal;
+ }
+ normal = SafeNormalize(normal);
+ for (int i : {0, 1, 2}) {
+ out.vertProperties[start + 3 + normalIdx + i] = normal[i];
+ }
+ }
+
+ if (vert2idx[vert] == -1) {
+ vert2idx[vert] = idx;
+ } else {
+ out.mergeFromVert.push_back(idx);
+ out.mergeToVert.push_back(vert2idx[vert]);
+ }
+ }
+ }
+ }
+ return out;
+}
+
+// Entry-time cancel wins over empty/malformed input; past this gate,
+// validation errors win over races.
+template <typename P, typename I>
+std::shared_ptr<Manifold::Impl> MakeSmoothImpl(
+ const MeshGLP<P, I>& meshGL, const std::vector<Smoothness>& sharpenedEdges,
+ ExecutionContext::Impl* ctx = nullptr) {
+ if (IsCancelled(ctx)) {
+ auto impl = std::make_shared<Manifold::Impl>();
+ impl->MakeEmpty(Manifold::Error::Cancelled);
+ return impl;
+ }
+
+ DEBUG_ASSERT(meshGL.halfedgeTangent.empty(), std::runtime_error,
+ "when supplying tangents, the normal constructor should be used "
+ "rather than Smooth().");
+
+ MeshGLP<P, I> meshTmp = meshGL;
+ meshTmp.faceID.resize(meshGL.NumTri());
+ std::iota(meshTmp.faceID.begin(), meshTmp.faceID.end(), 0);
+
+ std::shared_ptr<Manifold::Impl> impl =
+ std::make_shared<Manifold::Impl>(meshTmp, ctx);
+ // Skip tangent creation if ingest failed; phase counters must not
+ // credit smoothing phases that never ran.
+ if (impl->status_ != Manifold::Error::NoError) return impl;
+ impl->CreateTangents(impl->UpdateSharpenedEdges(sharpenedEdges), ctx);
+ // NumTri() is 0 after MakeEmpty, so this loop is a no-op on cancel.
+ const size_t numTri = impl->NumTri();
+ for (size_t i = 0; i < numTri; ++i) {
+ if (meshGL.faceID.size() == numTri) {
+ impl->meshRelation_.triRef[i].faceID =
+ meshGL.faceID[impl->meshRelation_.triRef[i].faceID];
+ } else {
+ impl->meshRelation_.triRef[i].faceID = -1;
+ }
+ }
+ return impl;
+}
} // namespace manifold
diff --git a/thirdparty/manifold/src/iters.h b/thirdparty/manifold/src/iters.h
index 65a1000ffca..5b3ebbc9488 100644
--- a/thirdparty/manifold/src/iters.h
+++ b/thirdparty/manifold/src/iters.h
@@ -13,12 +13,21 @@
// limitations under the License.
#pragma once
+#include <cstddef>
#include <iterator>
#include <optional>
#include <type_traits>
namespace manifold {
+/**
+ * Stand-in for C++23's operator""uz (P0330R8)[https://wg21.link/P0330R8].
+ */
+[[nodiscard]] constexpr std::size_t operator""_uz(
+ unsigned long long n) noexcept {
+ return n;
+}
+
template <typename F, typename Iter>
struct TransformIterator {
private:
@@ -208,7 +217,8 @@ struct CountingIterator {
}
};
-constexpr CountingIterator<size_t> countAt(size_t i) {
+template <typename T, std::enable_if_t<std::is_integral_v<T>, bool> = true>
+constexpr CountingIterator<T> countAt(T i) {
return CountingIterator(i);
}
diff --git a/thirdparty/manifold/src/manifold.cpp b/thirdparty/manifold/src/manifold.cpp
index 05082def869..4d28483cf27 100644
--- a/thirdparty/manifold/src/manifold.cpp
+++ b/thirdparty/manifold/src/manifold.cpp
@@ -13,11 +13,10 @@
// limitations under the License.
#include <algorithm>
-#include <map>
-#include <numeric>
#include "boolean3.h"
#include "csg_tree.h"
+#include "execution_impl.h"
#include "impl.h"
#include "parallel.h"
#include "shared.h"
@@ -33,169 +32,10 @@ Manifold Halfspace(Box bBox, vec3 normal, double originOffset) {
double size = la::length(bBox.Center() - normal * originOffset) +
0.5 * la::length(bBox.Size());
cutter = cutter.Scale(vec3(size)).Translate({originOffset, 0.0, 0.0});
- double yDeg = degrees(-std::asin(normal.z));
- double zDeg = degrees(std::atan2(normal.y, normal.x));
+ double yDeg = degrees(-math::asin(normal.z));
+ double zDeg = degrees(math::atan2(normal.y, normal.x));
return cutter.Rotate(0.0, yDeg, zDeg);
}
-
-template <typename Precision, typename I>
-MeshGLP<Precision, I> GetMeshGLImpl(const manifold::Manifold::Impl& impl,
- int normalIdx) {
- ZoneScoped;
- const int numProp = impl.NumProp();
- const int numVert = impl.NumPropVert();
- const int numTri = impl.NumTri();
-
- const bool isOriginal = impl.meshRelation_.originalID >= 0;
- const bool updateNormals = !isOriginal && normalIdx >= 0;
-
- MeshGLP<Precision, I> out;
- out.numProp = 3 + numProp;
- out.tolerance = impl.tolerance_;
- if (std::is_same<Precision, float>::value)
- out.tolerance =
- std::max(out.tolerance,
- static_cast<Precision>(std::numeric_limits<float>::epsilon() *
- impl.bBox_.Scale()));
- out.triVerts.resize(3 * numTri);
-
- const int numHalfedge = impl.halfedgeTangent_.size();
- out.halfedgeTangent.resize(4 * numHalfedge);
- for (int i = 0; i < numHalfedge; ++i) {
- const vec4 t = impl.halfedgeTangent_[i];
- out.halfedgeTangent[4 * i] = t.x;
- out.halfedgeTangent[4 * i + 1] = t.y;
- out.halfedgeTangent[4 * i + 2] = t.z;
- out.halfedgeTangent[4 * i + 3] = t.w;
- }
- // Sort the triangles into runs
- out.faceID.resize(numTri);
- std::vector<int> triNew2Old(numTri);
- std::iota(triNew2Old.begin(), triNew2Old.end(), 0);
- VecView<const TriRef> triRef = impl.meshRelation_.triRef;
- // Don't sort originals - keep them in order
- if (!isOriginal) {
- std::stable_sort(triNew2Old.begin(), triNew2Old.end(),
- [triRef](int a, int b) {
- return triRef[a].originalID == triRef[b].originalID
- ? triRef[a].meshID < triRef[b].meshID
- : triRef[a].originalID < triRef[b].originalID;
- });
- }
-
- std::vector<mat3> runNormalTransform;
- auto addRun = [updateNormals, isOriginal](
- MeshGLP<Precision, I>& out,
- std::vector<mat3>& runNormalTransform, int tri,
- const manifold::Manifold::Impl::Relation& rel) {
- out.runIndex.push_back(3 * tri);
- out.runOriginalID.push_back(rel.originalID);
- if (updateNormals) {
- runNormalTransform.push_back(NormalTransform(rel.transform) *
- (rel.backSide ? -1.0 : 1.0));
- }
- if (!isOriginal) {
- for (const int col : {0, 1, 2, 3}) {
- for (const int row : {0, 1, 2}) {
- out.runTransform.push_back(rel.transform[col][row]);
- }
- }
- }
- };
-
- auto meshIDtransform = impl.meshRelation_.meshIDtransform;
- int lastID = -1;
- for (int tri = 0; tri < numTri; ++tri) {
- const int oldTri = triNew2Old[tri];
- const auto ref = triRef[oldTri];
- const int meshID = ref.meshID;
-
- out.faceID[tri] = ref.faceID >= 0 ? ref.faceID : ref.coplanarID;
- for (const int i : {0, 1, 2})
- out.triVerts[3 * tri + i] = impl.halfedge_[3 * oldTri + i].startVert;
-
- if (meshID != lastID) {
- manifold::Manifold::Impl::Relation rel;
- auto it = meshIDtransform.find(meshID);
- if (it != meshIDtransform.end()) rel = it->second;
- addRun(out, runNormalTransform, tri, rel);
- meshIDtransform.erase(meshID);
- lastID = meshID;
- }
- }
- // Add runs for originals that did not contribute any faces to the output
- for (const auto& pair : meshIDtransform) {
- addRun(out, runNormalTransform, numTri, pair.second);
- }
- out.runIndex.push_back(3 * numTri);
-
- // Early return for no props
- if (numProp == 0) {
- out.vertProperties.resize(3 * numVert);
- for (int i = 0; i < numVert; ++i) {
- const vec3 v = impl.vertPos_[i];
- out.vertProperties[3 * i] = v.x;
- out.vertProperties[3 * i + 1] = v.y;
- out.vertProperties[3 * i + 2] = v.z;
- }
- return out;
- }
- // Duplicate verts with different props
- std::vector<int> vert2idx(impl.NumVert(), -1);
- std::vector<std::vector<ivec2>> vertPropPair(impl.NumVert());
- out.vertProperties.reserve(numVert * static_cast<size_t>(out.numProp));
-
- for (size_t run = 0; run < out.runOriginalID.size(); ++run) {
- for (size_t tri = out.runIndex[run] / 3; tri < out.runIndex[run + 1] / 3;
- ++tri) {
- for (const int i : {0, 1, 2}) {
- const int prop = impl.halfedge_[3 * triNew2Old[tri] + i].propVert;
- const int vert = out.triVerts[3 * tri + i];
-
- auto& bin = vertPropPair[vert];
- bool bFound = false;
- for (const auto& b : bin) {
- if (b.x == prop) {
- bFound = true;
- out.triVerts[3 * tri + i] = b.y;
- break;
- }
- }
- if (bFound) continue;
- const int idx = out.vertProperties.size() / out.numProp;
- out.triVerts[3 * tri + i] = idx;
- bin.push_back({prop, idx});
-
- for (int p : {0, 1, 2}) {
- out.vertProperties.push_back(impl.vertPos_[vert][p]);
- }
- for (int p = 0; p < numProp; ++p) {
- out.vertProperties.push_back(impl.properties_[prop * numProp + p]);
- }
-
- if (updateNormals) {
- vec3 normal;
- const int start = out.vertProperties.size() - out.numProp;
- for (int i : {0, 1, 2}) {
- normal[i] = out.vertProperties[start + 3 + normalIdx + i];
- }
- normal = la::normalize(runNormalTransform[run] * normal);
- for (int i : {0, 1, 2}) {
- out.vertProperties[start + 3 + normalIdx + i] = normal[i];
- }
- }
-
- if (vert2idx[vert] == -1) {
- vert2idx[vert] = idx;
- } else {
- out.mergeFromVert.push_back(idx);
- out.mergeToVert.push_back(vert2idx[vert]);
- }
- }
- }
- }
- return out;
-}
} // namespace
namespace manifold {
@@ -257,7 +97,7 @@ void Quality::SetCircularSegments(int number) {
int Quality::GetCircularSegments(double radius) {
if (circularSegments_ > 0) return circularSegments_;
int nSegA = 360.0 / circularAngle_;
- int nSegL = 2.0 * radius * kPi / circularEdgeLength_;
+ int nSegL = 2.0 * std::abs(radius) * kPi / circularEdgeLength_;
int nSeg = fmin(nSegA, nSegL) + 3;
nSeg -= nSeg % 4;
return std::max(nSeg, 4);
@@ -283,7 +123,11 @@ Manifold::~Manifold() = default;
Manifold::Manifold(Manifold&&) noexcept = default;
Manifold& Manifold::operator=(Manifold&&) noexcept = default;
-Manifold::Manifold(const Manifold& other) : pNode_(other.pNode_) {}
+Manifold::Manifold(const Manifold& other) {
+ std::lock_guard<std::mutex> lock(*other.pNodeMutex_);
+ pNode_ = other.pNode_;
+ std::atomic_store(&ctx_, std::atomic_load(&other.ctx_));
+}
Manifold::Manifold(std::shared_ptr<CsgNode> pNode) : pNode_(pNode) {}
@@ -296,16 +140,65 @@ Manifold Manifold::Invalid() {
return Manifold(pImpl_);
}
+Manifold Manifold::PropagateStatus(Error status) {
+ auto pImpl = std::make_shared<Impl>();
+ pImpl->status_ = status;
+ return Manifold(pImpl);
+}
+
+Manifold Manifold::FromImpl(std::shared_ptr<Impl> pImpl) {
+ return Manifold(std::move(pImpl));
+}
+
Manifold& Manifold::operator=(const Manifold& other) {
if (this != &other) {
+ std::scoped_lock lock(*pNodeMutex_, *other.pNodeMutex_);
pNode_ = other.pNode_;
+ std::atomic_store(&ctx_, std::atomic_load(&other.ctx_));
}
return *this;
}
-CsgLeafNode& Manifold::GetCsgLeafNode() const {
+/**
+ * Returns a copy of this Manifold with the given ExecutionContext attached.
+ * The attachment is consumed by the next eager op on the result (Status,
+ * Refine family). Deferred ops produce a result with no attached ctx; raw
+ * copy preserves the attachment. See ExecutionContext in common.h for the
+ * full model.
+ */
+Manifold Manifold::WithContext(const ExecutionContext& ctx) const {
+ Manifold result = *this;
+ std::atomic_store(&result.ctx_, ctx.impl_);
+ return result;
+}
+
+std::shared_ptr<CsgNode> Manifold::LoadPNode() const {
+ std::lock_guard<std::mutex> lock(*pNodeMutex_);
+ return pNode_;
+}
+
+CsgLeafNode& Manifold::GetCsgLeafNode(ExecutionContext::Impl* ctx) const {
+ std::lock_guard<std::mutex> lock(*pNodeMutex_);
+ if (ctx != nullptr) {
+ // Reset counters to reflect this evaluation. For pre-evaluated leaf
+ // Manifolds, NumLeaves() returns 1 so totalBooleans is 0 — no work.
+ // This also prevents stale counters from a previous use of the same
+ // ctx. The cancel flag is intentionally NOT reset — sticky cancel is
+ // part of the documented API contract (see ExecutionContext in
+ // common.h).
+ const size_t leaves = pNode_->NumLeaves();
+ const int booleans = leaves > 0 ? static_cast<int>(leaves - 1) : 0;
+ // Reset numerators before denominators so a concurrent `Progress()`
+ // observer cannot see (old donePhases / new totalPhases), which could
+ // yield Progress > 1.0 transiently when a ctx is reused across evals.
+ ctx->doneBooleans.store(0, std::memory_order_relaxed);
+ ctx->donePhases.store(0, std::memory_order_relaxed);
+ ctx->totalBooleans.store(booleans, std::memory_order_relaxed);
+ ctx->totalPhases.store(booleans * kPhasesPerBoolean,
+ std::memory_order_relaxed);
+ }
if (pNode_->GetNodeType() != CsgNodeType::Leaf) {
- pNode_ = pNode_->ToLeafNode();
+ pNode_ = pNode_->ToLeafNode(ctx);
}
return *std::static_pointer_cast<CsgLeafNode>(pNode_);
}
@@ -343,40 +236,54 @@ Manifold::Manifold(const MeshGL64& meshGL64)
: pNode_(std::make_shared<CsgLeafNode>(std::make_shared<Impl>(meshGL64))) {}
/**
- * The most complete output of this library, returning a MeshGL that is designed
+ * Returns a MeshGL that is designed
* to easily push into a renderer, including all interleaved vertex properties
* that may have been input. It also includes relations to all the input meshes
* that form a part of this result and the transforms applied to each.
*
- * @param normalIdx If the original MeshGL inputs that formed this manifold had
- * properties corresponding to normal vectors, you can specify the first of the
- * three consecutive property channels forming the (x, y, z) normals, which will
- * cause this output MeshGL to automatically update these normals according to
- * the applied transforms and front/back side. normalIdx + 3 must be <=
- * numProp, and all original MeshGLs must use the same channels for their
- * normals.
+ * @param normalIdx If this manifold has properties corresponding to normal
+ * vectors, you can specify the first of the three consecutive property channels
+ * forming the (x, y, z) normals, which will cause this output MeshGL to
+ * automatically update these normals according to the applied transforms and
+ * front/back side. normalIdx + 3 must be <= numProp, and all original meshes
+ * must use the same channels for their normals. Default is -1: if
+ * `CalculateNormals()` recorded normals at the standard slot, that slot is
+ * used automatically; otherwise no normals are applied. If normals are
+ * selected, the runTransform matrices will be removed from the output, to
+ * avoid them being double-applied when round-tripped.
+ * Passing a non-negative `normalIdx` is the legacy interface from before
+ * `CalculateNormals` recorded the slot on the Manifold itself; prefer the
+ * no-arg form after `CalculateNormals(0)`. The explicit-idx path will be
+ * removed in a future release.
*/
MeshGL Manifold::GetMeshGL(int normalIdx) const {
const Impl& impl = *GetCsgLeafNode().GetImpl();
+ if (normalIdx < 0 && impl.AllHaveNormals()) normalIdx = 0;
return GetMeshGLImpl<float, uint32_t>(impl, normalIdx);
}
/**
- * The most complete output of this library, returning a MeshGL that is designed
+ * Returns a MeshGL64 that is designed
* to easily push into a renderer, including all interleaved vertex properties
* that may have been input. It also includes relations to all the input meshes
* that form a part of this result and the transforms applied to each.
*
- * @param normalIdx If the original MeshGL inputs that formed this manifold had
- * properties corresponding to normal vectors, you can specify the first of the
- * three consecutive property channels forming the (x, y, z) normals, which will
- * cause this output MeshGL to automatically update these normals according to
- * the applied transforms and front/back side. normalIdx + 3 must be <=
- * numProp, and all original MeshGLs must use the same channels for their
- * normals.
+ * @param normalIdx If this manifold has properties corresponding to normal
+ * vectors, you can specify the first of the three consecutive property channels
+ * forming the (x, y, z) normals, which will cause this output MeshGL to
+ * automatically update these normals according to the applied transforms and
+ * front/back side. normalIdx + 3 must be <= numProp, and all original meshes
+ * must use the same channels for their normals. Default is -1: if
+ * `CalculateNormals()` recorded normals at the standard slot, that slot is
+ * used automatically; otherwise no normals are applied. If normals are
+ * selected, the runTransform matrices will be removed from the output, to
+ * avoid them being double-applied when round-tripped.
+ * Same deprecation note as `GetMeshGL`: prefer the no-arg form after
+ * `CalculateNormals(0)`.
*/
MeshGL64 Manifold::GetMeshGL64(int normalIdx) const {
const Impl& impl = *GetCsgLeafNode().GetImpl();
+ if (normalIdx < 0 && impl.AllHaveNormals()) normalIdx = 0;
return GetMeshGLImpl<double, uint64_t>(impl, normalIdx);
}
@@ -391,7 +298,12 @@ bool Manifold::IsEmpty() const { return GetCsgLeafNode().GetImpl()->IsEmpty(); }
* NoError, for instance the intersection of non-overlapping meshes.
*/
Manifold::Error Manifold::Status() const {
- return GetCsgLeafNode().GetImpl()->status_;
+ // Routes through any attached ExecutionContext (see WithContext). The
+ // atomic_load temporary pins the Impl's lifetime for the duration of the full
+ // expression -- through the lazy eval inside GetCsgLeafNode -- so a
+ // concurrent op= reseating ctx_ on this Manifold can't free the Impl out
+ // from under us.
+ return GetCsgLeafNode(std::atomic_load(&ctx_).get()).GetImpl()->status_;
}
/**
* The number of vertices in the Manifold.
@@ -453,12 +365,15 @@ double Manifold::GetTolerance() const {
* This performs mesh simplification when the tolerance value is increased.
*/
Manifold Manifold::SetTolerance(double tolerance) const {
- auto impl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto impl = std::make_shared<Impl>(*leafImpl);
if (tolerance > impl->tolerance_) {
impl->tolerance_ = tolerance;
- impl->MarkCoplanar();
+ impl->SetNormalsAndCoplanar();
impl->SimplifyTopology();
- impl->Finish();
+ impl->SortGeometry();
} else {
// for reducing tolerance, we need to make sure it is still at least
// equal to epsilon.
@@ -475,15 +390,18 @@ Manifold Manifold::SetTolerance(double tolerance) const {
* have moved by less than tolerance.
*/
Manifold Manifold::Simplify(double tolerance) const {
- auto impl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto impl = std::make_shared<Impl>(*leafImpl);
const double oldTolerance = impl->tolerance_;
if (tolerance == 0) tolerance = oldTolerance;
if (tolerance > oldTolerance) {
impl->tolerance_ = tolerance;
- impl->MarkCoplanar();
+ impl->SetNormalsAndCoplanar();
}
impl->SimplifyTopology();
- impl->Finish();
+ impl->SortGeometry();
impl->tolerance_ = oldTolerance;
return Manifold(impl);
}
@@ -530,15 +448,11 @@ int Manifold::OriginalID() const {
*/
Manifold Manifold::AsOriginal() const {
auto oldImpl = GetCsgLeafNode().GetImpl();
- if (oldImpl->status_ != Error::NoError) {
- auto newImpl = std::make_shared<Impl>();
- newImpl->status_ = oldImpl->status_;
- return Manifold(std::make_shared<CsgLeafNode>(newImpl));
- }
+ if (oldImpl->status_ != Error::NoError)
+ return PropagateStatus(oldImpl->status_);
auto newImpl = std::make_shared<Impl>(*oldImpl);
newImpl->InitializeOriginal();
- newImpl->MarkCoplanar();
- newImpl->InitializeOriginal(true);
+ newImpl->SetNormalsAndCoplanar();
return Manifold(std::make_shared<CsgLeafNode>(newImpl));
}
@@ -576,7 +490,7 @@ size_t Manifold::NumDegenerateTris() const {
* @param v The vector to add to every vertex.
*/
Manifold Manifold::Translate(vec3 v) const {
- return Manifold(pNode_->Translate(v));
+ return Manifold(LoadPNode()->Translate(v));
}
/**
@@ -585,23 +499,32 @@ Manifold Manifold::Translate(vec3 v) const {
*
* @param v The vector to multiply every vertex by per component.
*/
-Manifold Manifold::Scale(vec3 v) const { return Manifold(pNode_->Scale(v)); }
+Manifold Manifold::Scale(vec3 v) const {
+ return Manifold(LoadPNode()->Scale(v));
+}
/**
- * Applies an Euler angle rotation to the manifold, first about the X axis, then
- * Y, then Z, in degrees. We use degrees so that we can minimize rounding error,
- * and eliminate it completely for any multiples of 90 degrees. Additionally,
- * more efficient code paths are used to update the manifold when the transforms
- * only rotate by multiples of 90 degrees. This operation can be chained.
- * Transforms are combined and applied lazily.
+ * Applies an Euler angle rotation to the manifold, This operation can be
+ * chained. Transforms are combined and applied lazily.
+ *
+ * We use degrees so that we can minimize rounding error, and eliminate it
+ * completely for any multiples of 90 degrees. Additionally, more efficient code
+ * paths are used to update the manifold when the transforms only rotate by
+ * multiples of 90 degrees.
+ *
+ * From the reference frame of the model being rotated, rotations are applied in
+ * *z-y'-x"* order. That is yaw first, then pitch and finally roll.
+ *
+ * From the global reference frame, a model will be rotated in *x-y-z* order.
+ * That is about the global X axis, then global Y axis, and finally global Z.
*
- * @param xDegrees First rotation, degrees about the X-axis.
- * @param yDegrees Second rotation, degrees about the Y-axis.
- * @param zDegrees Third rotation, degrees about the Z-axis.
+ * @param xDegrees First rotation, degrees about the global X-axis.
+ * @param yDegrees Second rotation, degrees about the global Y-axis.
+ * @param zDegrees Third rotation, degrees about the global Z-axis.
*/
Manifold Manifold::Rotate(double xDegrees, double yDegrees,
double zDegrees) const {
- return Manifold(pNode_->Rotate(xDegrees, yDegrees, zDegrees));
+ return Manifold(LoadPNode()->Rotate(xDegrees, yDegrees, zDegrees));
}
/**
@@ -612,7 +535,7 @@ Manifold Manifold::Rotate(double xDegrees, double yDegrees,
* @param m The affine transform matrix to apply to all the vertices.
*/
Manifold Manifold::Transform(const mat3x4& m) const {
- return Manifold(pNode_->Transform(m));
+ return Manifold(LoadPNode()->Transform(m));
}
/**
@@ -624,12 +547,15 @@ Manifold Manifold::Transform(const mat3x4& m) const {
* @param normal The normal vector of the plane to be mirrored over
*/
Manifold Manifold::Mirror(vec3 normal) const {
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
if (la::length(normal) == 0.) {
return Manifold();
}
auto n = la::normalize(normal);
auto m = mat3x4(mat3(la::identity) - 2.0 * la::outerprod(n, n), vec3());
- return Manifold(pNode_->Transform(m));
+ return Manifold(LoadPNode()->Transform(m));
}
/**
@@ -639,35 +565,37 @@ Manifold Manifold::Mirror(vec3 normal) const {
* that is not checked here, so it is up to the user to choose their function
* with discretion.
*
+ * Any normals recording set by `CalculateNormals()` is preserved across the
+ * Warp, but the stored values reflect the pre-warp surface and may no longer
+ * match the new geometry. Re-call `CalculateNormals()` if accurate normals
+ * matter after a non-rigid warp.
+ *
* @param warpFunc A function that modifies a given vertex position.
*/
Manifold Manifold::Warp(std::function<void(vec3&)> warpFunc) const {
auto oldImpl = GetCsgLeafNode().GetImpl();
- if (oldImpl->status_ != Error::NoError) {
- auto pImpl = std::make_shared<Impl>();
- pImpl->status_ = oldImpl->status_;
- return Manifold(std::make_shared<CsgLeafNode>(pImpl));
- }
+ if (oldImpl->status_ != Error::NoError)
+ return PropagateStatus(oldImpl->status_);
auto pImpl = std::make_shared<Impl>(*oldImpl);
pImpl->Warp(warpFunc);
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
/**
- * Same as Manifold::Warp but calls warpFunc with with
+ * Same as Manifold::Warp but calls warpFunc with
* a VecView which is roughly equivalent to std::span
- * pointing to all vec3 elements to be modified in-place
+ * pointing to all vec3 elements to be modified in-place. Like Warp, this
+ * preserves any normals recording without updating the stored values;
+ * re-call `CalculateNormals()` if accurate normals matter after a non-rigid
+ * warp.
*
* @param warpFunc A function that modifies multiple vertex positions.
*/
Manifold Manifold::WarpBatch(
std::function<void(VecView<vec3>)> warpFunc) const {
auto oldImpl = GetCsgLeafNode().GetImpl();
- if (oldImpl->status_ != Error::NoError) {
- auto pImpl = std::make_shared<Impl>();
- pImpl->status_ = oldImpl->status_;
- return Manifold(std::make_shared<CsgLeafNode>(pImpl));
- }
+ if (oldImpl->status_ != Error::NoError)
+ return PropagateStatus(oldImpl->status_);
auto pImpl = std::make_shared<Impl>(*oldImpl);
pImpl->WarpBatch(warpFunc);
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
@@ -682,6 +610,11 @@ Manifold Manifold::WarpBatch(
*
* If propFunc is a nullptr, this function will just set the channel to zeroes.
*
+ * Any normals recording set by `CalculateNormals()` is preserved. If the new
+ * properties overwrite slot 0..2 with non-normal data, the recording becomes
+ * stale; re-call `CalculateNormals()` (or use a numProp < 3 call followed by
+ * CalculateNormals) to reset.
+ *
* @param numProp The new number of properties per vertex.
* @param propFunc A function that modifies the properties of a given vertex.
*/
@@ -689,7 +622,10 @@ Manifold Manifold::SetProperties(
int numProp,
std::function<void(double* newProp, vec3 position, const double* oldProp)>
propFunc) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
const int oldNumProp = NumProp();
const Vec<double> oldProperties = pImpl->properties_;
@@ -701,9 +637,9 @@ Manifold Manifold::SetProperties(
propFunc == nullptr ? ExecutionPolicy::Par : ExecutionPolicy::Seq,
countAt(0), NumTri(), [&](int tri) {
for (int i : {0, 1, 2}) {
- const Halfedge& edge = pImpl->halfedge_[3 * tri + i];
- const int vert = edge.startVert;
- const int propVert = edge.propVert;
+ const int edge = 3 * tri + i;
+ const int vert = pImpl->halfedge_.Start(edge);
+ const int propVert = pImpl->halfedge_.Prop(edge);
if (propFunc == nullptr) {
for (int p = 0; p < numProp; ++p) {
pImpl->properties_[numProp * propVert + p] = 0;
@@ -738,19 +674,26 @@ Manifold Manifold::SetProperties(
* will be automatically expanded to include the channel index specified.
*/
Manifold Manifold::CalculateCurvature(int gaussianIdx, int meanIdx) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
pImpl->CalculateCurvature(gaussianIdx, meanIdx);
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
/**
* Fills in vertex properties for normal vectors, calculated from the mesh
- * geometry. Flat faces composed of three or more triangles will remain flat.
+ * geometry.
*
- * @param normalIdx The property channel in which to store the X
- * values of the normals. The X, Y, and Z channels will be sequential. The
- * property set will be automatically expanded such that NumProp will be at
- * least normalIdx + 3.
+ * @param normalIdx The property channel in which to store the X values of the
+ * normals. The X, Y, and Z channels will be sequential. The property set will
+ * be automatically expanded such that NumProp will be at least normalIdx + 3.
+ * Default is 0, the standard slot (MeshGL channels 3, 4, 5); the Manifold
+ * records the recording per-meshID in that case so subsequent `GetMeshGL()` /
+ * `GetMeshGL64()` without an explicit normalIdx will return world-frame
+ * normals and mark each output run via runFlags bit 1. Non-zero values are
+ * retained for compatibility and will not be supported in a future release.
*
* @param minSharpAngle Any edges with angles greater than this value will
* remain sharp, getting different normal vector properties on each side of the
@@ -759,24 +702,41 @@ Manifold Manifold::CalculateCurvature(int gaussianIdx, int meanIdx) const {
* but in this case it would be better not to calculate normals at all.
*/
Manifold Manifold::CalculateNormals(int normalIdx, double minSharpAngle) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
pImpl->SetNormals(normalIdx, minSharpAngle);
+ // Mark per-meshID hasNormals so GetMeshGL(-1) can auto-substitute slot 0 on
+ // export. Restricted to the standard slot since a non-zero slot would be
+ // ambiguous when round-tripping through MeshGL.
+ if (normalIdx == 0) {
+ for (auto& m : pImpl->meshRelation_.meshIDtransform) {
+ m.second.hasNormals = true;
+ }
+ }
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
/**
* Smooths out the Manifold by filling in the halfedgeTangent vectors. The
- * geometry will remain unchanged until Refine or RefineToLength is called to
- * interpolate the surface. This version uses the supplied vertex normal
- * properties to define the tangent vectors. Faces of two coplanar triangles
- * will be marked as quads, while faces with three or more will be flat.
+ * geometry will remain unchanged until Refine, RefineToLength, or
+ * RefineToTolerance is called to interpolate the surface. This version uses the
+ * supplied vertex normal properties to define the tangent vectors. Zero-length
+ * normals are considered missing and will defer to their neighboring normals
+ * instead. If all normals are missing, the vertex pseudonormal will be used.
*
* @param normalIdx The first property channel of the normals. NumProp must be
* at least normalIdx + 3. Any vertex where multiple normals exist and don't
- * agree will result in a sharp edge.
+ * agree will result in a sharp edge. Default is 0, the standard slot.
+ * Non-zero values are retained for compatibility and will not be supported in
+ * a future release.
*/
Manifold Manifold::SmoothByNormals(int normalIdx) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
if (!IsEmpty()) {
pImpl->CreateTangents(normalIdx);
}
@@ -785,16 +745,16 @@ Manifold Manifold::SmoothByNormals(int normalIdx) const {
/**
* Smooths out the Manifold by filling in the halfedgeTangent vectors. The
- * geometry will remain unchanged until Refine or RefineToLength is called to
- * interpolate the surface. This version uses the geometry of the triangles and
- * pseudo-normals to define the tangent vectors. Faces of two coplanar triangles
- * will be marked as quads.
+ * geometry will remain unchanged until Refine, RefineToLength, or
+ * RefineToTolerance is called to interpolate the surface. This version uses the
+ * geometry of the triangles and pseudo-normals to define the tangent vectors.
+ * Faces of two coplanar triangles will be marked as quads, while faces with
+ * three or more will be flat.
*
- * @param minSharpAngle degrees, default 60. Any edges with angles greater than
- * this value will remain sharp. The rest will be smoothed to G1 continuity,
- * with the caveat that flat faces of three or more triangles will always remain
- * flat. With a value of zero, the model is faceted, but in this case there is
- * no point in smoothing.
+ * @param minSharpAngle degrees, default 52.5. Any edges with angles greater
+ * than this value will remain sharp. The rest will be smoothed to G1
+ * continuity. With a value of zero, the model is faceted, but in this case
+ * there is no point in smoothing.
*
* @param minSmoothness range: 0 - 1, default 0. The smoothness applied to sharp
* angles. The default gives a hard edge, while values > 0 will give a small
@@ -802,21 +762,12 @@ Manifold Manifold::SmoothByNormals(int normalIdx) const {
* 180 - all edges will be smooth.
*/
Manifold Manifold::SmoothOut(double minSharpAngle, double minSmoothness) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
if (!IsEmpty()) {
- if (minSmoothness == 0) {
- const int numProp = pImpl->numProp_;
- Vec<double> properties = pImpl->properties_;
- Vec<Halfedge> halfedge = pImpl->halfedge_;
- pImpl->SetNormals(0, minSharpAngle);
- pImpl->CreateTangents(0);
- // Reset the properties to the original values, removing temporary normals
- pImpl->numProp_ = numProp;
- pImpl->properties_.swap(properties);
- pImpl->halfedge_.swap(halfedge);
- } else {
- pImpl->CreateTangents(pImpl->SharpenEdges(minSharpAngle, minSmoothness));
- }
+ pImpl->CreateTangents(pImpl->SharpenEdges(minSharpAngle, minSmoothness));
}
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
@@ -828,14 +779,20 @@ Manifold Manifold::SmoothOut(double minSharpAngle, double minSmoothness) const {
* will not be immediately collapsed) unless the Mesh/Manifold has
* halfedgeTangents specified (e.g. from the Smooth() constructor), in which
* case the new vertices will be moved to the interpolated surface according to
- * their barycentric coordinates.
+ * their barycentric coordinates. Any normals recording set by
+ * `CalculateNormals()` is preserved; the new verts get linearly-interpolated
+ * normals, which are less precise than recomputed ones but still meaningful.
*
* @param n The number of pieces to split every edge into. Must be > 1.
*/
Manifold Manifold::Refine(int n) const {
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto ctx = std::atomic_load(&ctx_);
+ auto leafImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
if (n > 1) {
- pImpl->Refine([n](vec3, vec4, vec4) { return n - 1; });
+ pImpl->Refine([n](vec3, vec4, vec4) { return n - 1; }, false, ctx.get());
}
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
@@ -846,16 +803,24 @@ Manifold Manifold::Refine(int n) const {
* triangulation edges also of roughly the same length. If halfedgeTangents are
* present (e.g. from the Smooth() constructor), the new vertices will be moved
* to the interpolated surface according to their barycentric coordinates. Quads
- * will ignore their interior triangle bisector.
+ * will ignore their interior triangle bisector. Any normals recording set by
+ * `CalculateNormals()` is preserved; the new verts get linearly-interpolated
+ * normals, which are less precise than recomputed ones but still meaningful.
*
* @param length The length that edges will be broken down to.
*/
Manifold Manifold::RefineToLength(double length) const {
length = std::abs(length);
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
- pImpl->Refine([length](vec3 edge, vec4, vec4) {
- return static_cast<int>(la::length(edge) / length);
- });
+ auto ctx = std::atomic_load(&ctx_);
+ auto leafImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
+ pImpl->Refine(
+ [length](vec3 edge, vec4, vec4) {
+ return static_cast<int>(la::length(edge) / length);
+ },
+ false, ctx.get());
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
@@ -865,7 +830,9 @@ Manifold Manifold::RefineToLength(double length) const {
* smoothly curved surface defined by the tangent vectors. This means tightly
* curving regions will be divided more finely than smoother regions. If
* halfedgeTangents are not present, the result will simply be a copy of the
- * original. Quads will ignore their interior triangle bisector.
+ * original. Quads will ignore their interior triangle bisector. Any normals
+ * recording set by `CalculateNormals()` is preserved; the new verts get
+ * linearly-interpolated normals.
*
* @param tolerance The desired maximum distance between the faceted mesh
* produced and the exact smoothly curving surface. All vertices are exactly on
@@ -873,7 +840,11 @@ Manifold Manifold::RefineToLength(double length) const {
*/
Manifold Manifold::RefineToTolerance(double tolerance) const {
tolerance = std::abs(tolerance);
- auto pImpl = std::make_shared<Impl>(*GetCsgLeafNode().GetImpl());
+ auto ctx = std::atomic_load(&ctx_);
+ auto leafImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (leafImpl->status_ != Error::NoError)
+ return PropagateStatus(leafImpl->status_);
+ auto pImpl = std::make_shared<Impl>(*leafImpl);
if (!pImpl->halfedgeTangent_.empty()) {
pImpl->Refine(
[tolerance](vec3 edge, vec4 tangentStart, vec4 tangentEnd) {
@@ -889,7 +860,7 @@ Manifold Manifold::RefineToTolerance(double tolerance) const {
la::length(start - end);
return static_cast<int>(std::sqrt(3 * d / (4 * tolerance)));
},
- true);
+ true, ctx.get());
}
return Manifold(std::make_shared<CsgLeafNode>(pImpl));
}
@@ -909,12 +880,15 @@ Manifold Manifold::RefineToTolerance(double tolerance) const {
* @param op The type of operation to perform.
*/
Manifold Manifold::Boolean(const Manifold& second, OpType op) const {
- return Manifold(pNode_->Boolean(second.pNode_, op));
+ return Manifold(LoadPNode()->Boolean(second.LoadPNode(), op));
}
/**
* Perform the given boolean operation on a list of Manifolds. In case of
- * Subtract, all Manifolds in the tail are differenced from the head.
+ * Subtract, all Manifolds in the tail are differenced from the head. The
+ * empty-input case returns a default-constructed Manifold; the
+ * single-input case returns the input unchanged (a no-op identity, including
+ * any attached ExecutionContext on that single input).
*/
Manifold Manifold::BatchBoolean(const std::vector<Manifold>& manifolds,
OpType op) {
@@ -924,7 +898,7 @@ Manifold Manifold::BatchBoolean(const std::vector<Manifold>& manifolds,
return manifolds[0];
std::vector<std::shared_ptr<CsgNode>> children;
children.reserve(manifolds.size());
- for (const auto& m : manifolds) children.push_back(m.pNode_);
+ for (const auto& m : manifolds) children.push_back(m.LoadPNode());
return Manifold(std::make_shared<CsgOpNode>(children, op));
}
@@ -1003,6 +977,12 @@ std::pair<Manifold, Manifold> Manifold::Split(const Manifold& cutter) const {
*/
std::pair<Manifold, Manifold> Manifold::SplitByPlane(
vec3 normal, double originOffset) const {
+ auto leafImpl = GetCsgLeafNode().GetImpl();
+ if (leafImpl->status_ != Error::NoError) {
+ Manifold err = PropagateStatus(leafImpl->status_);
+ return {err, err};
+ }
+ if (IsEmpty()) return {Manifold(), Manifold()};
return Split(Halfspace(BoundingBox(), normal, originOffset));
}
@@ -1019,6 +999,42 @@ Manifold Manifold::TrimByPlane(vec3 normal, double originOffset) const {
return *this ^ Halfspace(BoundingBox(), normal, originOffset);
}
+/**
+ * Compute the minkowski sum of this manifold with another.
+ * This corresponds to the morphological dilation of the manifold.
+ *
+ * @note Performance is best when using convex objects. For non-convex inputs,
+ * performance scales with the product of face counts, so keep face counts low.
+ *
+ * @param other The other manifold to minkowski sum to this one.
+ */
+Manifold Manifold::MinkowskiSum(const Manifold& other) const {
+ auto ctx = std::atomic_load(&ctx_);
+ auto aImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (aImpl->status_ != Error::NoError) return PropagateStatus(aImpl->status_);
+ auto bImpl = other.GetCsgLeafNode(ctx.get()).GetImpl();
+ if (bImpl->status_ != Error::NoError) return PropagateStatus(bImpl->status_);
+ return aImpl->Minkowski(*bImpl, false, ctx.get());
+}
+
+/**
+ * Subtract the sweep of the other manifold across this manifold's surface.
+ * This corresponds to the morphological erosion of the manifold.
+ *
+ * @note Performance is best when using convex objects. For non-convex inputs,
+ * performance scales with the product of face counts, so keep face counts low.
+ *
+ * @param other The other manifold to minkowski subtract from this one.
+ */
+Manifold Manifold::MinkowskiDifference(const Manifold& other) const {
+ auto ctx = std::atomic_load(&ctx_);
+ auto aImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (aImpl->status_ != Error::NoError) return PropagateStatus(aImpl->status_);
+ auto bImpl = other.GetCsgLeafNode(ctx.get()).GetImpl();
+ if (bImpl->status_ != Error::NoError) return PropagateStatus(bImpl->status_);
+ return aImpl->Minkowski(*bImpl, true, ctx.get());
+}
+
/**
* Returns the cross section of this object parallel to the X-Y plane at the
* specified Z height, defaulting to zero. Using a height equal to the bottom of
@@ -1058,18 +1074,40 @@ Manifold Manifold::Hull(const std::vector<vec3>& pts) {
* Compute the convex hull of this manifold.
*/
Manifold Manifold::Hull() const {
+ auto ctx = std::atomic_load(&ctx_);
+ auto srcImpl = GetCsgLeafNode(ctx.get()).GetImpl();
+ if (srcImpl->status_ != Error::NoError)
+ return PropagateStatus(srcImpl->status_);
std::shared_ptr<Impl> impl = std::make_shared<Impl>();
- impl->Hull(GetCsgLeafNode().GetImpl()->vertPos_);
+ impl->Hull(srcImpl->vertPos_, ctx.get());
return Manifold(std::make_shared<CsgLeafNode>(impl));
}
/**
- * Compute the convex hull enveloping a set of manifolds.
+ * Compute the convex hull enveloping a set of manifolds. If the input list
+ * is empty (or all input manifolds are empty), returns a default-constructed
+ * Manifold with no attached ExecutionContext (no source operand to inherit
+ * from).
*
* @param manifolds A vector of manifolds over which to compute a convex hull.
*/
Manifold Manifold::Hull(const std::vector<Manifold>& manifolds) {
- return Compose(manifolds).Hull();
+ for (const auto& man : manifolds) {
+ auto status = man.Status();
+ if (status != Error::NoError) return PropagateStatus(status);
+ }
+ std::vector<vec3> vertPos;
+ size_t size = 0;
+ for (const auto& man : manifolds) size += man.NumVert();
+ if (size == 0) return Manifold();
+ vertPos.reserve(size);
+ for (const auto& man : manifolds) {
+ const auto& impl = man.GetCsgLeafNode().GetImpl();
+ vertPos.insert(vertPos.end(), impl->vertPos_.begin(), impl->vertPos_.end());
+ }
+ std::shared_ptr<Impl> impl = std::make_shared<Impl>();
+ impl->Hull(VecView<const vec3>(vertPos));
+ return Manifold(std::make_shared<CsgLeafNode>(impl));
}
/**
@@ -1086,4 +1124,16 @@ double Manifold::MinGap(const Manifold& other, double searchLength) const {
return GetCsgLeafNode().GetImpl()->MinGap(*other.GetCsgLeafNode().GetImpl(),
searchLength);
}
+
+/**
+ * Cast a ray segment against this manifold, returning all hits sorted by
+ * distance from origin.
+ *
+ * @param origin The start point of the ray segment.
+ * @param endpoint The end point of the ray segment.
+ * @return A vector of RayHit sorted by distance, empty on miss.
+ */
+std::vector<RayHit> Manifold::RayCast(vec3 origin, vec3 endpoint) const {
+ return GetCsgLeafNode().GetImpl()->RayCast(origin, endpoint);
+}
} // namespace manifold
diff --git a/thirdparty/manifold/src/mesh_fixes.h b/thirdparty/manifold/src/mesh_fixes.h
index fc11486a6b5..46df8972cc5 100644
--- a/thirdparty/manifold/src/mesh_fixes.h
+++ b/thirdparty/manifold/src/mesh_fixes.h
@@ -39,26 +39,30 @@ struct TransformTangents {
const mat3 transform;
const bool invert;
VecView<const vec4> oldTangents;
- VecView<const Halfedge> halfedge;
+ const Halfedges& halfedge;
void operator()(const int edgeOut) {
- const int edgeIn =
- invert ? halfedge[FlipHalfedge(edgeOut)].pairedHalfedge : edgeOut;
+ const int edgeIn = invert ? halfedge.Pair(FlipHalfedge(edgeOut)) : edgeOut;
tangent[edgeOut + edgeOffset] =
vec4(transform * vec3(oldTangents[edgeIn]), oldTangents[edgeIn].w);
}
};
struct FlipTris {
- VecView<Halfedge> halfedge;
+ Halfedges& halfedge;
void operator()(const int tri) {
- std::swap(halfedge[3 * tri], halfedge[3 * tri + 2]);
-
+ std::array<Halfedge, 3> face = {halfedge.Get(3 * tri + 2),
+ halfedge.Get(3 * tri + 1),
+ halfedge.Get(3 * tri)};
+ for (const int i : {0, 1, 2}) {
+ std::swap(face[i].startVert, face[i].endVert);
+ face[i].pairedHalfedge = FlipHalfedge(face[i].pairedHalfedge);
+ }
for (const int i : {0, 1, 2}) {
- std::swap(halfedge[3 * tri + i].startVert, halfedge[3 * tri + i].endVert);
- halfedge[3 * tri + i].pairedHalfedge =
- FlipHalfedge(halfedge[3 * tri + i].pairedHalfedge);
+ halfedge.SetStart(3 * tri + i, face[i].startVert);
+ halfedge.SetPair(3 * tri + i, face[i].pairedHalfedge);
+ halfedge.SetProp(3 * tri + i, face[i].propVert);
}
}
};
diff --git a/thirdparty/manifold/src/minkowski.cpp b/thirdparty/manifold/src/minkowski.cpp
new file mode 100644
index 00000000000..570a1fc7462
--- /dev/null
+++ b/thirdparty/manifold/src/minkowski.cpp
@@ -0,0 +1,200 @@
+// Copyright 2024 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "execution_impl.h"
+#include "impl.h"
+#include "parallel.h"
+
+namespace manifold {
+
+/**
+ * Compute the minkowski sum of two manifolds.
+ *
+ * @param other The other Impl to minkowski sum/diff with this one.
+ * @param inset Whether it should subtract (erode) rather than add (dilate).
+ */
+Manifold Manifold::Impl::Minkowski(const Impl& other, bool inset,
+ ExecutionContext::Impl* ctx) const {
+ // Helper to short-circuit on cancel. Cancellation is observed both at
+ // the boundaries between hull/Boolean phases and inside each
+ // BatchBoolean (via the same ctx threaded into GetCsgLeafNode, which
+ // routes into Boolean3's existing cancel checks). The per-hull work
+ // itself is currently not interrupted -- granularity inside a batch
+ // is "one Manifold::Hull(simpleHull) call."
+ auto cancelled = [] {
+ auto impl = std::make_shared<Impl>();
+ impl->status_ = Error::Cancelled;
+ return Manifold(impl);
+ };
+ // Build a BatchBoolean and force ctx-observed evaluation so an
+ // attached cancel fires inside Boolean3 rather than after the whole
+ // batch completes.
+ auto evalBatch = [ctx](std::vector<Manifold>&& items, OpType op) {
+ Manifold tree = Manifold::BatchBoolean(items, op);
+ // Trigger lazy eval with ctx. The returned leaf may have
+ // status_=Cancelled if cancel fired mid-Boolean; the caller still
+ // pushes it into composedHulls and the outer cancel check catches
+ // it.
+ tree.GetCsgLeafNode(ctx);
+ return tree;
+ };
+ if (IsCancelled(ctx)) return cancelled();
+
+ const Impl* aImpl = this;
+ const Impl* bImpl = &other;
+
+ bool aConvex = aImpl->IsConvex();
+ bool bConvex = bImpl->IsConvex();
+
+ constexpr size_t BATCH_SIZE = 1000;
+
+ // If the convex manifold was supplied first, swap them!
+ if (aConvex && !bConvex) {
+ std::swap(aImpl, bImpl);
+ std::swap(aConvex, bConvex);
+ }
+
+ // Early-exit if either input is empty
+ if (bImpl->IsEmpty()) {
+ std::shared_ptr<Impl> result = std::make_shared<Impl>(*aImpl);
+ return Manifold(result);
+ }
+ if (aImpl->IsEmpty()) {
+ std::shared_ptr<Impl> result = std::make_shared<Impl>(*bImpl);
+ return Manifold(result);
+ }
+
+ std::shared_ptr<Impl> aImplCopy = std::make_shared<Impl>(*aImpl);
+ Manifold a(aImplCopy);
+ std::vector<Manifold> composedHulls;
+ // Reserve space: 1 for base + batches for non-convex cases
+ size_t numBatches = (aImpl->NumTri() + BATCH_SIZE - 1) / BATCH_SIZE;
+ composedHulls.reserve(1 + numBatches);
+ composedHulls.push_back(a);
+
+ // Convex-Convex Minkowski: Very Fast
+ if (!inset && aConvex && bConvex) {
+ const VecView<vec3> verts = bImpl->vertPos_;
+ std::vector<vec3> simpleHull;
+ simpleHull.reserve(verts.size() * aImpl->vertPos_.size());
+ for (const vec3& vertex : aImpl->vertPos_) {
+ auto t = [vertex](vec3 v) { return v + vertex; };
+ simpleHull.insert(simpleHull.end(), TransformIterator(verts.begin(), t),
+ TransformIterator(verts.end(), t));
+ }
+ composedHulls.push_back(Manifold::Hull(simpleHull));
+ // Convex - Non-Convex Minkowski: Slower
+ } else if ((inset || !aConvex) && bConvex) {
+ const size_t numTri = aImpl->NumTri();
+ const VecView<vec3> verts = bImpl->vertPos_;
+
+ // do it in batches of 1000 meshes
+ for (size_t offset = 0; offset < numTri; offset += BATCH_SIZE) {
+ if (IsCancelled(ctx)) return cancelled();
+ size_t numIter = std::min(numTri - offset, BATCH_SIZE);
+ std::vector<Manifold> newHulls(numIter);
+ for_each_n(autoPolicy(numIter, 100), countAt(0), numIter,
+ [&newHulls, &aImpl, &verts, offset](const int iter) {
+ std::vector<vec3> simpleHull;
+ for (int i : {0, 1, 2}) {
+ const int edge = ((offset + iter) * 3) + i;
+ const auto vertex =
+ aImpl->vertPos_[aImpl->halfedge_.Start(edge)];
+ auto t = [vertex](vec3 v) { return v + vertex; };
+ simpleHull.insert(simpleHull.end(),
+ TransformIterator(verts.begin(), t),
+ TransformIterator(verts.end(), t));
+ }
+ newHulls[iter] = Manifold::Hull(simpleHull);
+ });
+ composedHulls.push_back(evalBatch(std::move(newHulls), OpType::Add));
+ }
+ // Non-Convex - Non-Convex Minkowski: Very Slow
+ // Process A faces sequentially with periodic batch reduction to balance
+ // memory usage and performance.
+ } else if (!aConvex && !bConvex) {
+ const size_t numTriA = aImpl->NumTri();
+ const size_t numTriB = bImpl->NumTri();
+
+ // Reduce accumulated results after this many A faces to limit memory
+ constexpr size_t REDUCE_THRESHOLD = 200;
+
+ // Accumulated per-A-face results (periodically reduced)
+ std::vector<Manifold> accumulated;
+ accumulated.reserve(std::min(numTriA, REDUCE_THRESHOLD));
+
+ // Process each A face sequentially
+ for (size_t aFace = 0; aFace < numTriA; ++aFace) {
+ if (IsCancelled(ctx)) return cancelled();
+ vec3 a1 = aImpl->vertPos_[aImpl->halfedge_.Start((aFace * 3) + 0)];
+ vec3 a2 = aImpl->vertPos_[aImpl->halfedge_.Start((aFace * 3) + 1)];
+ vec3 a3 = aImpl->vertPos_[aImpl->halfedge_.Start((aFace * 3) + 2)];
+ vec3 nA = aImpl->faceNormal_[aFace];
+
+ // Create hulls for all B faces paired with this A face (parallel)
+ std::vector<Manifold> faceHulls(numTriB);
+
+ for_each_n(
+ autoPolicy(numTriB, 100), countAt(0), numTriB, [&](const int bFace) {
+ // Tolerance for detecting coplanar faces (skip degenerate hull
+ // cases)
+ constexpr double kCoplanarTol = 1e-12;
+ vec3 nB = bImpl->faceNormal_[bFace];
+ double dotSame = linalg::dot(nA, nB);
+ double dotOpp = linalg::dot(nA, -nB);
+ const bool coplanar = (std::abs(dotSame - 1.0) < kCoplanarTol) ||
+ (std::abs(dotOpp - 1.0) < kCoplanarTol);
+ if (coplanar) return;
+
+ vec3 b1 = bImpl->vertPos_[bImpl->halfedge_.Start((bFace * 3) + 0)];
+ vec3 b2 = bImpl->vertPos_[bImpl->halfedge_.Start((bFace * 3) + 1)];
+ vec3 b3 = bImpl->vertPos_[bImpl->halfedge_.Start((bFace * 3) + 2)];
+ faceHulls[bFace] =
+ Manifold::Hull({a1 + b1, a1 + b2, a1 + b3, a2 + b1, a2 + b2,
+ a2 + b3, a3 + b1, a3 + b2, a3 + b3});
+ });
+
+ // Collect non-empty hulls for this A face
+ std::vector<Manifold> validFaceHulls;
+ for (auto& hull : faceHulls) {
+ if (!hull.IsEmpty()) {
+ validFaceHulls.push_back(std::move(hull));
+ }
+ }
+
+ if (!validFaceHulls.empty()) {
+ accumulated.push_back(
+ evalBatch(std::move(validFaceHulls), OpType::Add));
+ }
+
+ // Periodically reduce to limit memory usage
+ if (accumulated.size() >= REDUCE_THRESHOLD) {
+ Manifold reduced = evalBatch(std::move(accumulated), OpType::Add);
+ accumulated.clear();
+ accumulated.push_back(std::move(reduced));
+ }
+ }
+
+ // Final merge of remaining accumulated results
+ if (!accumulated.empty()) {
+ composedHulls.push_back(evalBatch(std::move(accumulated), OpType::Add));
+ }
+ }
+ if (IsCancelled(ctx)) return cancelled();
+ return evalBatch(std::move(composedHulls),
+ inset ? manifold::OpType::Subtract : manifold::OpType::Add)
+ .AsOriginal();
+}
+
+} // namespace manifold
diff --git a/thirdparty/manifold/src/parallel.h b/thirdparty/manifold/src/parallel.h
index 05d75be9594..3d0a0aabbbe 100644
--- a/thirdparty/manifold/src/parallel.h
+++ b/thirdparty/manifold/src/parallel.h
@@ -17,6 +17,7 @@
#pragma once
+#include "execution_impl.h"
#include "iters.h"
#if (MANIFOLD_PAR == 1)
#include <tbb/combinable.h>
@@ -70,28 +71,46 @@ using manifold::kSeqThreshold;
// https://duvanenko.tech.blog/2018/01/14/parallel-merge/
// https://github.com/DragonSpit/ParallelAlgorithms
// note that the ranges are now [p, r) to fit our convention.
+// also the implementation in the reference is not stable,
+// and we now changed it to stable.
template <typename SrcIter, typename DestIter, typename Comp>
void mergeRec(SrcIter src, DestIter dest, size_t p1, size_t r1, size_t p2,
size_t r2, size_t p3, Comp comp) {
size_t length1 = r1 - p1;
size_t length2 = r2 - p2;
- if (length1 < length2) {
- std::swap(p1, p2);
- std::swap(r1, r2);
- std::swap(length1, length2);
+ if (length1 == 0) {
+ manifold::copy(src + p2, src + r2, dest + p3);
+ return;
+ }
+ if (length2 == 0) {
+ manifold::copy(src + p1, src + r1, dest + p3);
+ return;
}
- if (length1 == 0) return;
if (length1 + length2 <= kSeqThreshold) {
std::merge(src + p1, src + r1, src + p2, src + r2, dest + p3, comp);
} else {
- size_t q1 = p1 + length1 / 2;
- size_t q2 =
- std::distance(src, std::lower_bound(src + p2, src + r2, src[q1], comp));
+ size_t q1, q2;
+ // For stability: equal-keyed elements from the left half must precede
+ // those from the right in the output. Pivot from the larger half and
+ // use the bound that puts equal-to-pivot from the OPPOSITE half on the
+ // pivot's stable side.
+ if (length1 > length2) {
+ // Left pivot: right-side equals belong after pivot. lower_bound on
+ // right places them at q2+ (second sub-merge with pivot).
+ q1 = p1 + length1 / 2;
+ auto end = std::lower_bound(src + p2, src + r2, src[q1], comp);
+ q2 = std::distance(src, end);
+ } else {
+ // Right pivot: left-side equals belong before pivot. upper_bound on
+ // left places them strictly before q1 (first sub-merge).
+ q2 = p2 + length2 / 2;
+ auto end = std::upper_bound(src + p1, src + r1, src[q2], comp);
+ q1 = std::distance(src, end);
+ }
size_t q3 = p3 + (q1 - p1) + (q2 - p2);
- dest[q3] = src[q1];
tbb::parallel_invoke(
[=] { mergeRec(src, dest, p1, q1, p2, q2, p3, comp); },
- [=] { mergeRec(src, dest, q1 + 1, r1, q2, r2, q3 + 1, comp); });
+ [=] { mergeRec(src, dest, q1, r1, q2, r2, q3, comp); });
}
}
@@ -369,9 +388,18 @@ struct SortFunctor<
#endif
-// Applies the function `f` to each element in the range `[first, last)`
+// Applies the function `f` to each element in the range `[first, last)`,
+// optionally checking `ctx` for cancellation periodically. `ctx` may be
+// nullptr — the cancel branch is null-short-circuited and folds out at
+// the call site, so non-cancellable callers pay nothing.
+//
+// Cancel granularity: once per parallel chunk, and once per kSeqCancelChunk
+// elements on the sequential branch. Only safe when "skip the rest of the
+// range" produces a result the caller will discard via a post-loop
+// `IsCancelled` check.
template <typename Iter, typename F>
-void for_each(ExecutionPolicy policy, Iter first, Iter last, F f) {
+void for_each(ExecutionPolicy policy, Iter first, Iter last,
+ ExecutionContext::Impl* ctx, F f) {
static_assert(std::is_convertible_v<
typename std::iterator_traits<Iter>::iterator_category,
std::random_access_iterator_tag>,
@@ -381,7 +409,8 @@ void for_each(ExecutionPolicy policy, Iter first, Iter last, F f) {
if (policy == ExecutionPolicy::Par) {
tbb::this_task_arena::isolate([&]() {
tbb::parallel_for(tbb::blocked_range<Iter>(first, last),
- [&f](const tbb::blocked_range<Iter>& range) {
+ [&f, ctx](const tbb::blocked_range<Iter>& range) {
+ if (IsCancelled(ctx)) return;
for (Iter i = range.begin(); i != range.end(); i++)
f(*i);
});
@@ -389,17 +418,47 @@ void for_each(ExecutionPolicy policy, Iter first, Iter last, F f) {
return;
}
#endif
- std::for_each(first, last, f);
+ // Sequential branch: check once at start, then every kSeqCancelChunk
+ // elements. Bounded latency for MANIFOLD_PAR=OFF builds and for the
+ // small-input branch under PAR=ON.
+ constexpr size_t kSeqCancelChunk = 1024;
+ if (IsCancelled(ctx)) return;
+ if (ctx == nullptr) {
+ std::for_each(first, last, f);
+ return;
+ }
+ size_t since_check = 0;
+ for (Iter i = first; i != last; ++i) {
+ if (++since_check == kSeqCancelChunk) {
+ if (IsCancelled(ctx)) return;
+ since_check = 0;
+ }
+ f(*i);
+ }
}
-// Applies the function `f` to each element in the range `[first, last)`
+// Non-cancellable shim. Threads `nullptr` through the ctx-aware impl.
template <typename Iter, typename F>
-void for_each_n(ExecutionPolicy policy, Iter first, size_t n, F f) {
+void for_each(ExecutionPolicy policy, Iter first, Iter last, F f) {
+ for_each(policy, first, last, nullptr, f);
+}
+
+// for_each over [first, first + n).
+template <typename Iter, typename F>
+void for_each_n(ExecutionPolicy policy, Iter first, size_t n,
+ ExecutionContext::Impl* ctx, F f) {
static_assert(std::is_convertible_v<
typename std::iterator_traits<Iter>::iterator_category,
std::random_access_iterator_tag>,
"You can only parallelize RandomAccessIterator.");
- for_each(policy, first, first + n, f);
+ using Difference = typename std::iterator_traits<Iter>::difference_type;
+ for_each(policy, first, first + static_cast<Difference>(n), ctx, f);
+}
+
+// Non-cancellable shim.
+template <typename Iter, typename F>
+void for_each_n(ExecutionPolicy policy, Iter first, size_t n, F f) {
+ for_each_n(policy, first, n, nullptr, f);
}
// Reduce the range `[first, last)` using a binary operation `f` with an initial
@@ -753,7 +812,8 @@ size_t count_if(ExecutionPolicy policy, InputIter first, InputIter last,
#if (MANIFOLD_PAR == 1)
if (policy == ExecutionPolicy::Par) {
return reduce(policy, TransformIterator(first, pred),
- TransformIterator(last, pred), 0, std::plus<size_t>());
+ TransformIterator(last, pred), size_t{0},
+ std::plus<size_t>());
}
#endif
return std::count_if(first, last, pred);
@@ -1091,7 +1151,7 @@ template <typename InputIterator1, typename InputIterator2,
typename OutputIterator>
void scatter(ExecutionPolicy policy, InputIterator1 first, InputIterator1 last,
InputIterator2 mapFirst, OutputIterator outputFirst) {
- for_each(policy, countAt(0),
+ for_each(policy, countAt(0_uz),
countAt(static_cast<size_t>(std::distance(first, last))),
[first, mapFirst, outputFirst](size_t i) {
outputFirst[mapFirst[i]] = first[i];
@@ -1123,7 +1183,7 @@ template <typename InputIterator, typename RandomAccessIterator,
void gather(ExecutionPolicy policy, InputIterator mapFirst,
InputIterator mapLast, RandomAccessIterator inputFirst,
OutputIterator outputFirst) {
- for_each(policy, countAt(0),
+ for_each(policy, countAt(0_uz),
countAt(static_cast<size_t>(std::distance(mapFirst, mapLast))),
[mapFirst, inputFirst, outputFirst](size_t i) {
outputFirst[i] = inputFirst[mapFirst[i]];
@@ -1147,7 +1207,7 @@ void gather(InputIterator mapFirst, InputIterator mapLast,
// Write `[0, last - first)` to the range `[first, last)`.
template <typename Iterator>
void sequence(ExecutionPolicy policy, Iterator first, Iterator last) {
- for_each(policy, countAt(0),
+ for_each(policy, countAt(0_uz),
countAt(static_cast<size_t>(std::distance(first, last))),
[first](size_t i) { first[i] = i; });
}
diff --git a/thirdparty/manifold/src/polygon.cpp b/thirdparty/manifold/src/polygon.cpp
index 2beec64cc52..5f65e7aac8d 100644
--- a/thirdparty/manifold/src/polygon.cpp
+++ b/thirdparty/manifold/src/polygon.cpp
@@ -14,13 +14,13 @@
#include "manifold/polygon.h"
-#include <functional>
#include <map>
#include <set>
#include "manifold/manifold.h"
#include "manifold/optional_assert.h"
#include "parallel.h"
+#include "polygon_internal.h"
#include "tree2d.h"
#include "utils.h"
@@ -31,7 +31,7 @@
namespace {
using namespace manifold;
-constexpr int TRIANGULATOR_VERBOSE_LEVEL = 2;
+constexpr int TRIANGULATOR_VERBOSE_LEVEL = 3;
constexpr double kBest = -std::numeric_limits<double>::infinity();
@@ -45,24 +45,11 @@ struct PolyEdge {
int startVert, endVert;
};
-std::vector<PolyEdge> Polygons2Edges(const PolygonsIdx& polys) {
+std::vector<PolyEdge> Halfedges2Edges(const HalfedgeTriangulation& result) {
std::vector<PolyEdge> halfedges;
- for (const auto& poly : polys) {
- for (size_t i = 1; i < poly.size(); ++i) {
- halfedges.push_back({poly[i - 1].idx, poly[i].idx});
- }
- halfedges.push_back({poly.back().idx, poly[0].idx});
- }
- return halfedges;
-}
-
-std::vector<PolyEdge> Triangles2Edges(const std::vector<ivec3>& triangles) {
- std::vector<PolyEdge> halfedges;
- halfedges.reserve(triangles.size() * 3);
- for (const ivec3& tri : triangles) {
- halfedges.push_back({tri[0], tri[1]});
- halfedges.push_back({tri[1], tri[2]});
- halfedges.push_back({tri[2], tri[0]});
+ halfedges.reserve(result.halfedges.size());
+ for (const Halfedge& edge : result.halfedges) {
+ halfedges.push_back({edge.startVert, edge.endVert});
}
return halfedges;
}
@@ -102,14 +89,8 @@ void CheckTopology(const std::vector<PolyEdge>& halfedges) {
}
}
-void CheckTopology(const std::vector<ivec3>& triangles,
- const PolygonsIdx& polys) {
- std::vector<PolyEdge> halfedges = Triangles2Edges(triangles);
- std::vector<PolyEdge> openEdges = Polygons2Edges(polys);
- for (PolyEdge e : openEdges) {
- halfedges.push_back({e.endVert, e.startVert});
- }
- CheckTopology(halfedges);
+void CheckTopology(const HalfedgeTriangulation& result) {
+ CheckTopology(Halfedges2Edges(result));
}
void CheckGeometry(const std::vector<ivec3>& triangles,
@@ -128,6 +109,11 @@ void CheckGeometry(const std::vector<ivec3>& triangles,
geometryErr, "triangulation is not entirely CCW!");
}
+void CheckGeometry(const HalfedgeTriangulation& result,
+ const PolygonsIdx& polys, double epsilon) {
+ CheckGeometry(result.Triangles(), polys, epsilon);
+}
+
void Dump(const PolygonsIdx& polys, double epsilon) {
std::cout << std::setprecision(19);
std::cout << "Polygon 0 " << epsilon << " " << polys.size() << std::endl;
@@ -206,20 +192,21 @@ bool IsConvex(const PolygonsIdx& polys, double epsilon) {
* Triangulates a set of convex polygons by alternating instead of a fan, to
* avoid creating high-degree vertices.
*/
-std::vector<ivec3> TriangulateConvex(const PolygonsIdx& polys) {
+HalfedgeTriangulation TriangulateConvex(const PolygonsIdx& polys) {
const size_t numTri = manifold::transform_reduce(
polys.begin(), polys.end(), 0_uz,
[](size_t a, size_t b) { return a + b; },
[](const SimplePolygonIdx& poly) { return poly.size() - 2; });
- std::vector<ivec3> triangles;
- triangles.reserve(numTri);
+ HalfedgeTriangulation result;
+ result.AddContours(polys);
+ result.ReserveTriangles(numTri);
for (const SimplePolygonIdx& poly : polys) {
size_t i = 0;
size_t k = poly.size() - 1;
bool right = true;
while (i + 1 < k) {
const size_t j = right ? i + 1 : k - 1;
- triangles.push_back({poly[i].idx, poly[j].idx, poly[k].idx});
+ result.AddTriangle(poly[i].idx, poly[j].idx, poly[k].idx);
if (right) {
i = j;
} else {
@@ -228,7 +215,7 @@ std::vector<ivec3> TriangulateConvex(const PolygonsIdx& polys) {
right = !right;
}
}
- return triangles;
+ return result;
}
/**
@@ -265,7 +252,7 @@ class EarClip {
}
}
- std::vector<ivec3> Triangulate() {
+ HalfedgeTriangulation Triangulate() {
ZoneScoped;
for (const VertItr start : holes_) {
@@ -276,7 +263,7 @@ class EarClip {
TriangulatePoly(start);
}
- return triangles_;
+ return result_;
}
double GetPrecision() const { return epsilon_; }
@@ -309,8 +296,8 @@ class EarClip {
std::map<VertItr, Rect> hole2BBox_;
// A priority queue of valid ears - the multiset allows them to be updated.
std::multiset<VertItr, MinCost> earsQueue_;
- // The output triangulation.
- std::vector<ivec3> triangles_;
+ // The output triangulation, represented directly as halfedges.
+ HalfedgeTriangulation result_;
// Bounding box of the entire set of polygons
Rect bBox_;
// Working epsilon: max of float error and input value.
@@ -588,8 +575,8 @@ class EarClip {
ear->right->mesh_idx != ear->left->mesh_idx) {
// Filter out topological degenerates, which can form in bad
// triangulations of polygons with holes, due to vert duplication.
- triangles_.push_back(
- {ear->left->mesh_idx, ear->mesh_idx, ear->right->mesh_idx});
+ result_.AddTriangle(ear->left->mesh_idx, ear->mesh_idx,
+ ear->right->mesh_idx);
} else {
PRINT("Topological degenerate!");
}
@@ -655,13 +642,16 @@ class EarClip {
if (epsilon_ < 0) epsilon_ = bBox_.Scale() * kPrecision;
+ result_.AddContours(polys);
// Slightly more than enough, since each hole can cause two extra triangles.
- triangles_.reserve(polygon_.size() + 2 * starts.size());
+ result_.ReserveTriangles(polygon_.size() + 2 * starts.size());
return starts;
}
// Find the actual rightmost starts after degenerate removal. Also calculate
- // the polygon bounding boxes.
+ // the polygon bounding boxes. Only holes need rightmost starts, and the CCW
+ // check is to handle degenerate cases for them - the other contour starts are
+ // arbitrary.
void FindStart(VertItr first) {
const vec2 origin = first->pos;
@@ -680,7 +670,7 @@ class EarClip {
areaCompensation += (area - t1) + area1;
area = t1;
- if (v->pos.x > maxX) {
+ if (v->pos.x > maxX && v->IsReflex(epsilon_)) {
maxX = v->pos.x;
start = v;
}
@@ -935,40 +925,55 @@ namespace manifold {
* triangulation if the input is convex, falling back to ear-clipping if not.
* The triangle quality may be lower, so set to false to disable this
* optimization.
- * @return std::vector<ivec3> The triangles, referencing the original
- * vertex indicies.
+ * @return HalfedgeTriangulation The contour and triangle halfedges,
+ * referencing the original vertex indicies.
*/
-std::vector<ivec3> TriangulateIdx(const PolygonsIdx& polys, double epsilon,
- bool allowConvex) {
- std::vector<ivec3> triangles;
+HalfedgeTriangulation TriangulateIdxHalfedges(const PolygonsIdx& polys,
+ double epsilon,
+ bool allowConvex) {
+ HalfedgeTriangulation result;
double updatedEpsilon = epsilon;
#ifdef MANIFOLD_DEBUG
try {
#endif
if (allowConvex && IsConvex(polys, epsilon)) { // fast path
- triangles = TriangulateConvex(polys);
+ result = TriangulateConvex(polys);
} else {
EarClip triangulator(polys, epsilon);
- triangles = triangulator.Triangulate();
+ result = triangulator.Triangulate();
updatedEpsilon = triangulator.GetPrecision();
}
+ result.epsilon = updatedEpsilon;
#ifdef MANIFOLD_DEBUG
if (ManifoldParams().intermediateChecks) {
- CheckTopology(triangles, polys);
+ CheckTopology(result);
if (!ManifoldParams().processOverlaps) {
- CheckGeometry(triangles, polys, 2 * updatedEpsilon);
+ CheckGeometry(result, polys, 2 * updatedEpsilon);
}
}
+#endif
+ result.Finalize();
+#ifdef MANIFOLD_DEBUG
} catch (const geometryErr& e) {
if (!ManifoldParams().suppressErrors) {
+ std::vector<ivec3> triangles = result.Triangles();
PrintFailure(e, polys, triangles, updatedEpsilon);
}
throw;
} catch (const std::exception& e) {
+ std::vector<ivec3> triangles = result.Triangles();
PrintFailure(e, polys, triangles, updatedEpsilon);
throw;
}
#endif
+ return result;
+}
+
+std::vector<ivec3> TriangulateIdx(const PolygonsIdx& polys, double epsilon,
+ bool allowConvex) {
+ HalfedgeTriangulation result =
+ TriangulateIdxHalfedges(polys, epsilon, allowConvex);
+ std::vector<ivec3> triangles = result.Triangles();
return triangles;
}
diff --git a/thirdparty/manifold/src/polygon_internal.h b/thirdparty/manifold/src/polygon_internal.h
new file mode 100644
index 00000000000..b29d7f85ca4
--- /dev/null
+++ b/thirdparty/manifold/src/polygon_internal.h
@@ -0,0 +1,118 @@
+// Copyright 2026 The Manifold Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+
+#include <cstdint>
+#include <unordered_map>
+#include <vector>
+
+#include "manifold/polygon.h"
+#include "shared.h"
+
+namespace manifold {
+
+struct HalfedgeTriangulation {
+ std::vector<Halfedge> halfedges;
+ size_t contourEnd = 0;
+ double epsilon = -1;
+
+ void AddContours(const PolygonsIdx& polys) {
+ size_t numContourEdges = 0;
+ for (const SimplePolygonIdx& poly : polys) numContourEdges += poly.size();
+ halfedges.reserve(halfedges.size() + numContourEdges);
+ edge2halfedge.reserve(edge2halfedge.size() + numContourEdges);
+ for (const SimplePolygonIdx& poly : polys) {
+ for (size_t i = 0; i < poly.size(); ++i) {
+ const int start = poly[i].idx;
+ const int end = poly[i + 1 < poly.size() ? i + 1 : 0].idx;
+ // Store the exterior contour halfedge, opposite the filled contour.
+ AddHalfedge(end, start);
+ }
+ }
+ contourEnd = halfedges.size();
+ }
+
+ void ReserveTriangles(size_t numTri) {
+ halfedges.reserve(contourEnd + 3 * numTri);
+ edge2halfedge.reserve(edge2halfedge.size() + numTri);
+ }
+
+ void AddTriangle(int first, int second, int third) {
+ AddHalfedge(first, second);
+ AddHalfedge(second, third);
+ AddHalfedge(third, first);
+ }
+
+ size_t NumTri() const { return (halfedges.size() - contourEnd) / 3; }
+
+ std::vector<ivec3> Triangles() const {
+ std::vector<ivec3> triangles;
+ triangles.reserve(NumTri());
+ for (size_t edge = contourEnd; edge < halfedges.size(); edge += 3) {
+ triangles.push_back({halfedges[edge].startVert,
+ halfedges[edge + 1].startVert,
+ halfedges[edge + 2].startVert});
+ }
+ return triangles;
+ }
+
+ void Finalize() {
+#ifdef MANIFOLD_DEBUG
+ DEBUG_ASSERT(edge2halfedge.empty(), topologyErr,
+ "triangulation has unpaired halfedges");
+ for (size_t i = 0; i < halfedges.size(); ++i) {
+ const int pair = halfedges[i].pairedHalfedge;
+ DEBUG_ASSERT(pair >= 0 && pair < static_cast<int>(halfedges.size()),
+ topologyErr, "invalid paired halfedge");
+ DEBUG_ASSERT(halfedges[pair].pairedHalfedge == static_cast<int>(i),
+ topologyErr, "halfedge pair is not reciprocal");
+ DEBUG_ASSERT(halfedges[i].startVert == halfedges[pair].endVert &&
+ halfedges[i].endVert == halfedges[pair].startVert,
+ topologyErr, "halfedge pair endpoints do not match");
+ }
+#endif
+ edge2halfedge.clear();
+ edge2halfedge.rehash(0);
+ }
+
+ private:
+ std::unordered_map<uint64_t, std::vector<int>> edge2halfedge;
+
+ static uint64_t EdgeKey(int start, int end) {
+ return (uint64_t{static_cast<uint32_t>(start)} << 32) |
+ static_cast<uint32_t>(end);
+ }
+
+ void AddHalfedge(int start, int end) {
+ const int halfedge = halfedges.size();
+ Halfedge data = {start, end, -1, -1};
+ auto reverse = edge2halfedge.find(EdgeKey(end, start));
+ if (reverse != edge2halfedge.end() && !reverse->second.empty()) {
+ data.pairedHalfedge = reverse->second.back();
+ halfedges[data.pairedHalfedge].pairedHalfedge = halfedge;
+ reverse->second.pop_back();
+ if (reverse->second.empty()) edge2halfedge.erase(reverse);
+ } else {
+ edge2halfedge[EdgeKey(start, end)].push_back(halfedge);
+ }
+ halfedges.push_back(data);
+ }
+};
+
+HalfedgeTriangulation TriangulateIdxHalfedges(const PolygonsIdx& polys,
+ double epsilon = -1,
+ bool allowConvex = true);
+
+} // namespace manifold
diff --git a/thirdparty/manifold/src/properties.cpp b/thirdparty/manifold/src/properties.cpp
index b80d5af1a37..289a119d7ae 100644
--- a/thirdparty/manifold/src/properties.cpp
+++ b/thirdparty/manifold/src/properties.cpp
@@ -30,7 +30,7 @@ struct CurvatureAngles {
VecView<double> gaussianCurvature;
VecView<double> area;
VecView<double> degree;
- VecView<const Halfedge> halfedge;
+ const Halfedges& halfedge;
VecView<const vec3> vertPos;
VecView<const vec3> triNormal;
@@ -38,30 +38,31 @@ struct CurvatureAngles {
vec3 edge[3];
vec3 edgeLength(0.0);
for (int i : {0, 1, 2}) {
- const int startVert = halfedge[3 * tri + i].startVert;
- const int endVert = halfedge[3 * tri + i].endVert;
+ const int edgeIdx = 3 * tri + i;
+ const int startVert = halfedge.Start(edgeIdx);
+ const int endVert = halfedge.End(edgeIdx);
edge[i] = vertPos[endVert] - vertPos[startVert];
edgeLength[i] = la::length(edge[i]);
edge[i] /= edgeLength[i];
- const int neighborTri = halfedge[3 * tri + i].pairedHalfedge / 3;
+ const int neighborTri = halfedge.Pair(edgeIdx) / 3;
const double dihedral =
0.25 * edgeLength[i] *
- std::asin(la::dot(la::cross(triNormal[tri], triNormal[neighborTri]),
- edge[i]));
+ math::asin(la::dot(la::cross(triNormal[tri], triNormal[neighborTri]),
+ edge[i]));
AtomicAdd(meanCurvature[startVert], dihedral);
AtomicAdd(meanCurvature[endVert], dihedral);
AtomicAdd(degree[startVert], 1.0);
}
vec3 phi;
- phi[0] = std::acos(-la::dot(edge[2], edge[0]));
- phi[1] = std::acos(-la::dot(edge[0], edge[1]));
+ phi[0] = math::acos(-la::dot(edge[2], edge[0]));
+ phi[1] = math::acos(-la::dot(edge[0], edge[1]));
phi[2] = kPi - phi[0] - phi[1];
const double area3 = edgeLength[0] * edgeLength[1] *
la::length(la::cross(edge[0], edge[1])) / 6;
for (int i : {0, 1, 2}) {
- const int vert = halfedge[3 * tri + i].startVert;
+ const int vert = halfedge.Start(3 * tri + i);
AtomicAdd(gaussianCurvature[vert], -phi[i]);
AtomicAdd(area[vert], area3);
}
@@ -69,47 +70,27 @@ struct CurvatureAngles {
};
struct CheckHalfedges {
- VecView<const Halfedge> halfedges;
+ const Halfedges& halfedges;
bool operator()(size_t edge) const {
- const Halfedge halfedge = halfedges[edge];
- if (halfedge.startVert == -1 && halfedge.endVert == -1 &&
- halfedge.pairedHalfedge == -1)
- return true;
- if (halfedges[NextHalfedge(edge)].startVert == -1 ||
- halfedges[NextHalfedge(NextHalfedge(edge))].startVert == -1) {
+ const int start = halfedges.Start(edge);
+ const int end = halfedges.End(edge);
+ const int pair = halfedges.Pair(edge);
+ if (start == -1 && end == -1 && pair == -1) return true;
+ if (halfedges.Start(NextHalfedge(edge)) == -1 ||
+ halfedges.Start(NextHalfedge(NextHalfedge(edge))) == -1) {
return false;
}
- if (halfedge.pairedHalfedge == -1) return false;
+ if (pair == -1) return false;
- const Halfedge paired = halfedges[halfedge.pairedHalfedge];
bool good = true;
- good &= paired.pairedHalfedge == static_cast<int>(edge);
- good &= halfedge.startVert != halfedge.endVert;
- good &= halfedge.startVert == paired.endVert;
- good &= halfedge.endVert == paired.startVert;
+ good &= halfedges.Pair(pair) == static_cast<int>(edge);
+ good &= start != end;
+ good &= start == halfedges.End(pair);
+ good &= end == halfedges.Start(pair);
return good;
}
};
-
-struct CheckCCW {
- VecView<const Halfedge> halfedges;
- VecView<const vec3> vertPos;
- VecView<const vec3> triNormal;
- const double tol;
-
- bool operator()(size_t face) const {
- if (halfedges[3 * face].pairedHalfedge < 0) return true;
-
- const mat2x3 projection = GetAxisAlignedProjection(triNormal[face]);
- vec2 v[3];
- for (int i : {0, 1, 2})
- v[i] = projection * vertPos[halfedges[3 * face + i].startVert];
-
- const int ccw = CCW(v[0], v[1], v[2], std::abs(tol));
- return tol > 0 ? ccw >= 0 : ccw == 0;
- }
-};
} // namespace
namespace manifold {
@@ -122,7 +103,7 @@ bool Manifold::Impl::IsManifold() const {
if (halfedge_.size() == 0) return true;
if (halfedge_.size() % 3 != 0) return false;
return all_of(countAt(0_uz), countAt(halfedge_.size()),
- CheckHalfedges({halfedge_}));
+ CheckHalfedges{halfedge_});
}
/**
@@ -133,7 +114,7 @@ bool Manifold::Impl::Is2Manifold() const {
if (halfedge_.size() == 0) return true;
if (!IsManifold()) return false;
- Vec<Halfedge> halfedge(halfedge_);
+ Vec<Halfedge> halfedge = halfedge_.ToData();
stable_sort(halfedge.begin(), halfedge.end());
return all_of(
@@ -166,8 +147,8 @@ bool Manifold::Impl::IsSelfIntersecting() const {
auto f = [&](int tri0, int tri1) {
std::array<vec3, 3> triVerts0, triVerts1;
for (int i : {0, 1, 2}) {
- triVerts0[i] = vertPos_[halfedge_[3 * tri0 + i].startVert];
- triVerts1[i] = vertPos_[halfedge_[3 * tri1 + i].startVert];
+ triVerts0[i] = vertPos_[halfedge_.Start(3 * tri0 + i)];
+ triVerts1[i] = vertPos_[halfedge_.Start(3 * tri1 + i)];
}
// if triangles tri0 and tri1 share a vertex, return true to skip the
// check. we relax the sharing criteria a bit to allow for at most
@@ -204,7 +185,7 @@ bool Manifold::Impl::IsSelfIntersecting() const {
};
auto recorder = MakeSimpleRecorder(f);
- collider_.Collisions<true>(faceBox.cview(), recorder);
+ collider_.Collisions<true>(recorder, faceBox.cview());
return intersecting.load();
}
@@ -214,18 +195,71 @@ bool Manifold::Impl::IsSelfIntersecting() const {
*/
bool Manifold::Impl::MatchesTriNormals() const {
if (halfedge_.size() == 0 || faceNormal_.size() != NumTri()) return true;
- return all_of(countAt(0_uz), countAt(NumTri()),
- CheckCCW({halfedge_, vertPos_, faceNormal_, 2 * epsilon_}));
+ return all_of(countAt(0_uz), countAt(NumTri()), [this](size_t face) {
+ if (halfedge_.Pair(3 * face) < 0) return true;
+
+ const mat2x3 projection = GetAxisAlignedProjection(faceNormal_[face]);
+ vec2 v[3];
+ double max = -std::numeric_limits<double>::infinity();
+ double min = std::numeric_limits<double>::infinity();
+ for (int i : {0, 1, 2}) {
+ const vec3 p = vertPos_[halfedge_.Start(3 * face + i)];
+ v[i] = projection * p;
+ const double d = la::dot(p, faceNormal_[face]);
+ if (!std::isfinite(d)) return true;
+ max = std::max(max, d);
+ min = std::min(min, d);
+ }
+ if (max - min > 2 * tolerance_) return false;
+
+ const int ccw = CCW(v[0], v[1], v[2], epsilon_ * 2);
+ return ccw >= 0;
+ });
}
/**
- * Returns the number of triangles that are colinear within epsilon_.
+ * Returns the number of triangles that are colinear within tolerance_.
*/
int Manifold::Impl::NumDegenerateTris() const {
if (halfedge_.size() == 0 || faceNormal_.size() != NumTri()) return true;
- return count_if(
- countAt(0_uz), countAt(NumTri()),
- CheckCCW({halfedge_, vertPos_, faceNormal_, -1 * epsilon_ / 2}));
+ return count_if(countAt(0_uz), countAt(NumTri()), [this](size_t face) {
+ if (halfedge_.Pair(3 * face) < 0) return true;
+
+ const mat2x3 projection = GetAxisAlignedProjection(faceNormal_[face]);
+ vec2 v[3];
+ for (int i : {0, 1, 2})
+ v[i] = projection * vertPos_[halfedge_.Start(3 * face + i)];
+
+ const int ccw = CCW(v[0], v[1], v[2], tolerance_ / 2);
+ return ccw == 0;
+ });
+}
+
+/**
+ * Returns true if the Manifold is genus 0 and contains no concave edges.
+ */
+bool Manifold::Impl::IsConvex() const {
+ // Convex shape must have genus of 0
+ int chi = NumVert() - NumEdge() + NumTri();
+ int genus = 1 - chi / 2;
+ if (genus != 0) return false;
+
+ // Iterate across all edges; return false if any edges are concave
+ const size_t nbEdges = halfedge_.size();
+ return all_of(countAt(0_uz), countAt(nbEdges), [this](size_t idx) {
+ if (!halfedge_.IsForward(idx)) return true;
+
+ const vec3 normal0 = faceNormal_[idx / 3];
+ const vec3 normal1 = faceNormal_[halfedge_.Pair(idx) / 3];
+
+ if (linalg::all(linalg::equal(normal0, normal1))) return true;
+
+ const vec3 edgeVec =
+ vertPos_[halfedge_.End(idx)] - vertPos_[halfedge_.Start(idx)];
+ const bool convex =
+ linalg::dot(edgeVec, linalg::cross(normal0, normal1)) > 0;
+ return convex;
+ });
}
double Manifold::Impl::GetProperty(Property prop) const {
@@ -233,17 +267,16 @@ double Manifold::Impl::GetProperty(Property prop) const {
if (IsEmpty()) return 0;
auto Volume = [this](size_t tri) {
- const vec3 v = vertPos_[halfedge_[3 * tri].startVert];
- vec3 crossP = la::cross(vertPos_[halfedge_[3 * tri + 1].startVert] - v,
- vertPos_[halfedge_[3 * tri + 2].startVert] - v);
+ const vec3 v = vertPos_[halfedge_.Start(3 * tri)];
+ vec3 crossP = la::cross(vertPos_[halfedge_.Start(3 * tri + 1)] - v,
+ vertPos_[halfedge_.Start(3 * tri + 2)] - v);
return la::dot(crossP, v) / 6.0;
};
auto Area = [this](size_t tri) {
- const vec3 v = vertPos_[halfedge_[3 * tri].startVert];
- return la::length(
- la::cross(vertPos_[halfedge_[3 * tri + 1].startVert] - v,
- vertPos_[halfedge_[3 * tri + 2].startVert] - v)) /
+ const vec3 v = vertPos_[halfedge_.Start(3 * tri)];
+ return la::length(la::cross(vertPos_[halfedge_.Start(3 * tri + 1)] - v,
+ vertPos_[halfedge_.Start(3 * tri + 2)] - v)) /
2.0;
};
@@ -270,8 +303,8 @@ void Manifold::Impl::CalculateCurvature(int gaussianIdx, int meanIdx) {
Vec<double> degree(NumVert(), 0);
auto policy = autoPolicy(NumTri(), 1e4);
for_each(policy, countAt(0_uz), countAt(NumTri()),
- CurvatureAngles({vertMeanCurvature, vertGaussianCurvature, vertArea,
- degree, halfedge_, vertPos_, faceNormal_}));
+ CurvatureAngles{vertMeanCurvature, vertGaussianCurvature, vertArea,
+ degree, halfedge_, vertPos_, faceNormal_});
for_each_n(policy, countAt(0), NumVert(),
[&vertMeanCurvature, &vertGaussianCurvature, &vertArea,
&degree](const int vert) {
@@ -289,9 +322,9 @@ void Manifold::Impl::CalculateCurvature(int gaussianIdx, int meanIdx) {
Vec<uint8_t> counters(NumPropVert(), 0);
for_each_n(policy, countAt(0_uz), NumTri(), [&](const size_t tri) {
for (const int i : {0, 1, 2}) {
- const Halfedge& edge = halfedge_[3 * tri + i];
- const int vert = edge.startVert;
- const int propVert = edge.propVert;
+ const int edge = 3 * tri + i;
+ const int vert = halfedge_.Start(edge);
+ const int propVert = halfedge_.Prop(edge);
auto old = std::atomic_exchange(
reinterpret_cast<std::atomic<uint8_t>*>(&counters[propVert]),
@@ -333,6 +366,11 @@ void Manifold::Impl::CalculateBBox() {
if (std::isnan(b.x)) return a;
return la::max(a, b);
});
+
+ if (!bBox_.IsFinite()) {
+ // Decimated out of existence - early out.
+ MakeEmpty(Error::NoError);
+ }
}
/**
@@ -390,8 +428,8 @@ struct MinDistanceRecorder {
std::array<vec3, 3> q;
for (const int j : {0, 1, 2}) {
- p[j] = self.vertPos_[self.halfedge_[3 * tri + j].startVert];
- q[j] = other.vertPos_[other.halfedge_[3 * triOther + j].startVert];
+ p[j] = self.vertPos_[self.halfedge_.Start(3 * tri + j)];
+ q[j] = other.vertPos_[other.halfedge_.Start(3 * triOther + j)];
}
minDistance = std::min(minDistance, DistanceTriangleTriangleSquared(p, q));
}
@@ -416,8 +454,7 @@ double Manifold::Impl::MinGap(const Manifold::Impl& other,
});
MinDistanceRecorder recorder{*this, other};
- collider_.Collisions<false, Box, MinDistanceRecorder>(faceBoxOther.cview(),
- recorder, false);
+ collider_.Collisions<false>(recorder, faceBoxOther.cview(), false);
double minDistanceSquared =
std::min(recorder.get(), searchLength * searchLength);
return sqrt(minDistanceSquared);
diff --git a/thirdparty/manifold/src/quickhull.cpp b/thirdparty/manifold/src/quickhull.cpp
index 5860f4a0440..d62d1dcc085 100644
--- a/thirdparty/manifold/src/quickhull.cpp
+++ b/thirdparty/manifold/src/quickhull.cpp
@@ -22,6 +22,7 @@
#include <limits>
#include <unordered_map>
+#include "execution_impl.h"
#include "impl.h"
namespace manifold {
@@ -223,9 +224,9 @@ HalfEdgeMesh::HalfEdgeMesh(const MeshBuilder& builderObject,
/*
* Implementation of the algorithm
*/
-std::pair<Vec<Halfedge>, Vec<vec3>> QuickHull::buildMesh(double epsilon) {
+std::pair<SharedVec<Halfedge>, Vec<vec3>> QuickHull::buildMesh(double epsilon) {
if (originalVertexData.size() == 0) {
- return {Vec<Halfedge>(), Vec<vec3>()};
+ return {SharedVec<Halfedge>(), Vec<vec3>()};
}
// Very first: find extreme values and use them to compute the scale of the
@@ -241,18 +242,16 @@ std::pair<Vec<Halfedge>, Vec<vec3>> QuickHull::buildMesh(double epsilon) {
// dimensional subspace of R^3.
planar = false;
createConvexHalfedgeMesh();
+
if (planar) {
+ // the extra point index was set to make the mesh has volume, we now set its
+ // coordinate back to make the coordinates correct
const int extraPointIndex = planarPointCloudTemp.size() - 1;
- for (auto& he : mesh.halfedges) {
- if (he.endVert == extraPointIndex) {
- he.endVert = 0;
- }
- }
- planarPointCloudTemp.clear();
+ planarPointCloudTemp.back() = planarPointCloudTemp.front();
}
// reorder halfedges
- Vec<Halfedge> halfedges(mesh.halfedges.size());
+ SharedVec<Halfedge> halfedges(mesh.halfedges.size());
Vec<int> halfedgeToFace(mesh.halfedges.size());
Vec<int> counts(mesh.halfedges.size(), 0);
Vec<int> mapping(mesh.halfedges.size());
@@ -651,9 +650,13 @@ void QuickHull::setupInitialTetrahedron() {
// If we have at most 4 points, just return a degenerate tetrahedron:
if (vertexCount <= 4) {
- size_t v[4] = {0, std::min((size_t)1, vertexCount - 1),
- std::min((size_t)2, vertexCount - 1),
- std::min((size_t)3, vertexCount - 1)};
+ if (vertexCount < 4) {
+ planarPointCloudTemp = Vec<vec3>(originalVertexData);
+ while (planarPointCloudTemp.size() < 4)
+ planarPointCloudTemp.push_back(planarPointCloudTemp.back());
+ originalVertexData = planarPointCloudTemp;
+ }
+ size_t v[4] = {0, 1, 2, 3};
const vec3 N =
getTriangleNormal(originalVertexData[v[0]], originalVertexData[v[1]],
originalVertexData[v[2]]);
@@ -681,9 +684,7 @@ void QuickHull::setupInitialTetrahedron() {
}
if (maxD == epsilonSquared) {
// A degenerate case: the point cloud seems to consists of a single point
- return mesh.setup(0, std::min((size_t)1, vertexCount - 1),
- std::min((size_t)2, vertexCount - 1),
- std::min((size_t)3, vertexCount - 1));
+ return mesh.setup(0, 1, 2, 3);
}
DEBUG_ASSERT(selectedPoints.first != selectedPoints.second, logicErr,
"degenerate selectedPoints");
@@ -706,32 +707,16 @@ void QuickHull::setupInitialTetrahedron() {
}
if (maxD == epsilonSquared) {
// It appears that the point cloud belongs to a 1 dimensional subspace of
- // R^3: convex hull has no volume => return a thin triangle Pick any point
- // other than selectedPoints.first and selectedPoints.second as the third
- // point of the triangle
- auto it =
- std::find_if(originalVertexData.begin(), originalVertexData.end(),
- [&](const vec3& ve) {
- return ve != originalVertexData[selectedPoints.first] &&
- ve != originalVertexData[selectedPoints.second];
- });
- const size_t thirdPoint =
- (it == originalVertexData.end())
- ? selectedPoints.first
- : std::distance(originalVertexData.begin(), it);
- it =
- std::find_if(originalVertexData.begin(), originalVertexData.end(),
- [&](const vec3& ve) {
- return ve != originalVertexData[selectedPoints.first] &&
- ve != originalVertexData[selectedPoints.second] &&
- ve != originalVertexData[thirdPoint];
- });
- const size_t fourthPoint =
- (it == originalVertexData.end())
- ? selectedPoints.first
- : std::distance(originalVertexData.begin(), it);
- return mesh.setup(selectedPoints.first, selectedPoints.second, thirdPoint,
- fourthPoint);
+ // R^3: convex hull has no volume => return a degenerate tetrahedron
+ // Pick two points other than selectedPoints.first and selectedPoints.second
+ size_t firstPoint = selectedPoints.first;
+ size_t secondPoint = selectedPoints.second;
+ size_t thirdPoint = 0;
+ while (thirdPoint == firstPoint || thirdPoint == secondPoint) thirdPoint++;
+ size_t fourthPoint = thirdPoint + 1;
+ while (fourthPoint == firstPoint || fourthPoint == secondPoint)
+ fourthPoint++;
+ return mesh.setup(firstPoint, secondPoint, thirdPoint, fourthPoint);
}
// These three points form the base triangle for our tetrahedron.
@@ -841,21 +826,40 @@ bool QuickHull::addPointToFace(typename MeshBuilder::Face& f,
}
// Wrapper to call the QuickHull algorithm with the given vertex data to build
-// the Impl
-void Manifold::Impl::Hull(VecView<vec3> vertPos) {
+// the Impl. Cancellation is observed between QuickHull's hot kernel and the
+// SortGeometry post-pass, plus during SortGeometry itself (which is
+// ctx-aware). QuickHull's own loop is cancel-blind for now -- the
+// granularity is "after buildMesh returns", matching how Refine handles
+// Subdivide.
+void Manifold::Impl::Hull(VecView<const vec3> vertPos,
+ ExecutionContext::Impl* ctx) {
size_t numVert = vertPos.size();
- if (numVert < 4) {
- status_ = Error::InvalidConstruction;
+ // empty hull
+ if (vertPos.empty()) return;
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
return;
}
-
QuickHull qh(vertPos);
- std::tie(halfedge_, vertPos_) = qh.buildMesh();
+ Vec<Halfedge> Halfedge;
+ std::tie(Halfedge, vertPos_) = qh.buildMesh();
+ halfedge_ = Halfedges(std::move(Halfedge));
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
CalculateBBox();
SetEpsilon();
InitializeOriginal();
- Finish();
- MarkCoplanar();
+ SortGeometry(ctx);
+ // SortGeometry returns silently on cancel, leaving the Impl in a
+ // partial state; catch that here so SetNormalsAndCoplanar doesn't
+ // run on broken geometry and the caller sees a Cancelled result.
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
+ SetNormalsAndCoplanar();
}
} // namespace manifold
diff --git a/thirdparty/manifold/src/quickhull.h b/thirdparty/manifold/src/quickhull.h
index 1167143c6aa..f1b9c29365d 100644
--- a/thirdparty/manifold/src/quickhull.h
+++ b/thirdparty/manifold/src/quickhull.h
@@ -150,7 +150,7 @@ class MeshBuilder {
// Mesh data
std::vector<Face> faces;
- Vec<Halfedge> halfedges;
+ SharedVec<Halfedge> halfedges;
Vec<int> halfedgeToFace;
Vec<int> halfedgeNext;
@@ -202,7 +202,7 @@ class HalfEdgeMesh {
Vec<vec3> vertices;
// Index of one of the half edges of the faces
std::vector<size_t> halfEdgeIndexFaces;
- Vec<Halfedge> halfedges;
+ SharedVec<Halfedge> halfedges;
Vec<int> halfedgeToFace;
Vec<int> halfedgeNext;
@@ -223,7 +223,7 @@ class QuickHull {
double m_epsilon, epsilonSquared, scale;
bool planar;
Vec<vec3> planarPointCloudTemp;
- VecView<vec3> originalVertexData;
+ VecView<const vec3> originalVertexData;
MeshBuilder mesh;
std::array<size_t, 6> extremeValues;
size_t failedHorizonEdges = 0;
@@ -275,14 +275,15 @@ class QuickHull {
public:
// This function assumes that the pointCloudVec data resides in memory in the
// following format: x_0,y_0,z_0,x_1,y_1,z_1,...
- QuickHull(VecView<vec3> pointCloudVec)
+ QuickHull(VecView<const vec3> pointCloudVec)
: originalVertexData(VecView(pointCloudVec)) {}
// Computes convex hull for a given point cloud. Params: eps: minimum distance
// to a plane to consider a point being on positive side of it (for a point
// cloud with scale 1) Returns: Convex hull of the point cloud as halfEdge
// vector and vertex vector
- std::pair<Vec<Halfedge>, Vec<vec3>> buildMesh(double eps = defaultEps());
+ std::pair<SharedVec<Halfedge>, Vec<vec3>> buildMesh(
+ double eps = defaultEps());
};
} // namespace manifold
diff --git a/thirdparty/manifold/src/sdf.cpp b/thirdparty/manifold/src/sdf.cpp
index 00bd40f81c7..7ef0ca810b0 100644
--- a/thirdparty/manifold/src/sdf.cpp
+++ b/thirdparty/manifold/src/sdf.cpp
@@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+#include <cmath>
+
+#include "execution_impl.h"
#include "hashtable.h"
#include "impl.h"
#include "manifold/manifold.h"
@@ -102,6 +105,16 @@ uint64_t EncodeIndex(ivec4 gridPos, ivec3 gridPow) {
static_cast<uint64_t>(gridPos.x) << (1 + gridPow.z + gridPow.y);
}
+ivec3 ComputeGridPow(ivec3 gridSize) {
+ // Equivalent to floor(log2(gridSize + 2)) + 1 for positive inputs, using
+ // integer-only and deterministic across platforms.
+ auto axisPow = [](int n) {
+ const size_t value = static_cast<size_t>(static_cast<uint32_t>(n + 2));
+ return static_cast<int>(CeilLog2(value + 1_uz));
+ };
+ return {axisPow(gridSize.x), axisPow(gridSize.y), axisPow(gridSize.z)};
+}
+
ivec4 DecodeIndex(uint64_t idx, ivec3 gridPow) {
ivec4 gridPos;
gridPos.w = idx & 1;
@@ -456,18 +469,37 @@ namespace manifold {
Manifold Manifold::LevelSet(std::function<double(vec3)> sdf, Box bounds,
double edgeLength, double level, double tolerance,
bool canParallel) {
+ auto pImpl = std::make_shared<Impl>();
+ pImpl->CreateLevelSet(sdf, bounds, edgeLength, level, tolerance, canParallel);
+ return Manifold(pImpl);
+}
+
+// Shared body of Manifold::LevelSet and ExecutionContext::LevelSet. Populates
+// this (empty) Impl. When ctx is non-null, the grid loops check cancel per
+// chunk and the ADVANCE_PHASE_OR_RETURN sites credit Progress(); their count
+// must equal kPhasesPerLevelSet (whose docstring enumerates the phases).
+void Manifold::Impl::CreateLevelSet(std::function<double(vec3)> sdf, Box bounds,
+ double edgeLength, double level,
+ double tolerance, bool canParallel,
+ ExecutionContext::Impl* ctx) {
+ // Pre-cancel wins over the (potentially large) voxel allocation and the
+ // sampling pass below.
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
+
if (tolerance <= 0) {
tolerance = std::numeric_limits<double>::infinity();
}
- auto pImpl_ = std::make_shared<Impl>();
- auto& vertPos = pImpl_->vertPos_;
+ auto& vertPos = vertPos_;
const vec3 dim = bounds.Size();
const ivec3 gridSize(dim / edgeLength + 1.0);
const vec3 spacing = dim / (vec3(gridSize - 1));
- const ivec3 gridPow(la::log2(gridSize + 2) + 1);
+ const ivec3 gridPow = ComputeGridPow(gridSize);
const uint64_t maxIndex = EncodeIndex(ivec4(gridSize + 2, 1), gridPow);
// Parallel policies violate will crash language runtimes with runtime locks
@@ -478,25 +510,44 @@ Manifold Manifold::LevelSet(std::function<double(vec3)> sdf, Box bounds,
const vec3 origin = bounds.min;
Vec<double> voxels(maxIndex);
+ // Per-chunk cancel only: a cancel cannot interrupt a single in-flight user
+ // sdf evaluation, same granularity as the other eager ops.
for_each_n(
- pol, countAt(0_uz), maxIndex,
+ pol, countAt(0_uz), maxIndex, ctx,
[&voxels, sdf, level, origin, spacing, gridSize, gridPow](uint64_t idx) {
voxels[idx] = BoundedSDF(DecodeIndex(idx, gridPow) - kVoxelOffset,
origin, spacing, gridSize, level, sdf);
});
-
- size_t tableSize = std::min(
- 2 * maxIndex, static_cast<uint64_t>(10 * la::pow(maxIndex, 0.667)));
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
+ const uint64_t tableSizeCap =
+ static_cast<uint64_t>(std::numeric_limits<size_t>::max());
+ const uint64_t denseTableSize64 =
+ maxIndex > tableSizeCap / 2 ? tableSizeCap : 2 * maxIndex;
+ // Level sets are sparse in the volume; cap dense sizing for large grids.
+ const uint64_t sparseTableSize64 = std::min(
+ tableSizeCap,
+ static_cast<uint64_t>(10 * std::sqrt(static_cast<double>(maxIndex))));
+ uint64_t tableSize64 = std::min(denseTableSize64, sparseTableSize64);
+ tableSize64 = std::max<uint64_t>(1, tableSize64);
+ size_t tableSize = static_cast<size_t>(tableSize64);
HashTable<GridVert> gridVerts(tableSize);
vertPos.resize_nofill(gridVerts.Size() * 7);
while (1) {
Vec<int> index(1, 0);
for_each_n(pol, countAt(0_uz), EncodeIndex(ivec4(gridSize, 1), gridPow),
+ ctx,
NearSurface({vertPos, index, gridVerts.D(), voxels, sdf, origin,
gridSize, gridPow, spacing, level, tolerance}));
if (gridVerts.Full()) { // Resize HashTable
+ // Skip the reallocation and the NearSurface re-run if cancel landed
+ // during this pass, before reading partial NearSurface output below.
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
const vec3 lastVert = vertPos[index[0] - 1];
const uint64_t lastIndex =
EncodeIndex(ivec4(ivec3((lastVert - origin) / spacing), 1), gridPow);
@@ -509,10 +560,13 @@ Manifold Manifold::LevelSet(std::function<double(vec3)> sdf, Box bounds,
gridVerts = HashTable<GridVert>(tableSize);
vertPos = Vec<vec3>(gridVerts.Size() * 7);
} else { // Success
+ // NearSurface counts as one phase regardless of resize iterations.
+ ADVANCE_PHASE_OR_RETURN(ctx);
for_each_n(
- pol, countAt(0), gridVerts.Size(),
+ pol, countAt(0), gridVerts.Size(), ctx,
ComputeVerts({vertPos, index, gridVerts.D(), voxels, sdf, origin,
gridSize, gridPow, spacing, level, tolerance}));
+ ADVANCE_PHASE_OR_RETURN(ctx);
vertPos.resize(index[0]);
break;
}
@@ -521,16 +575,28 @@ Manifold Manifold::LevelSet(std::function<double(vec3)> sdf, Box bounds,
Vec<ivec3> triVerts(gridVerts.Entries() * 12); // worst case
Vec<int> index(1, 0);
- for_each_n(pol, countAt(0), gridVerts.Size(),
+ for_each_n(pol, countAt(0), gridVerts.Size(), ctx,
BuildTris({triVerts, index, gridVerts.D(), gridPow}));
+ ADVANCE_PHASE_OR_RETURN(ctx);
triVerts.resize(index[0]);
- pImpl_->CreateHalfedges(triVerts);
- pImpl_->CleanupTopology();
- pImpl_->RemoveUnreferencedVerts();
- pImpl_->Finish();
- pImpl_->InitializeOriginal();
- pImpl_->MarkCoplanar();
- return Manifold(pImpl_);
+ // Finalize, lumped as one phase. (This sequence differs from the
+ // Manifold(MeshGL) ingest pipeline; do not route through that.) SortGeometry
+ // is the heavy step, so it takes ctx for cancel responsiveness like the
+ // sibling ops; its contract then requires a cancel check before its
+ // partial-on-cancel output feeds an unconditional consumer.
+ CreateHalfedges(triVerts);
+ CleanupTopology();
+ RemoveUnreferencedVerts();
+ InitializeOriginal();
+ CalculateBBox();
+ SetEpsilon();
+ SortGeometry(ctx);
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
+ SetNormalsAndCoplanar();
+ ADVANCE_PHASE_OR_RETURN(ctx);
}
} // namespace manifold
diff --git a/thirdparty/manifold/src/shared.h b/thirdparty/manifold/src/shared.h
index 7a28c414215..900b15a30ca 100644
--- a/thirdparty/manifold/src/shared.h
+++ b/thirdparty/manifold/src/shared.h
@@ -31,15 +31,70 @@ inline double MaxEpsilon(double minEpsilon, const Box& bBox) {
}
inline int NextHalfedge(int current) {
- ++current;
- if (current % 3 == 0) current -= 3;
+ current += current % 3 == 2 ? -2 : 1;
return current;
}
+inline int PrevHalfedge(int current) {
+ current += current % 3 == 0 ? 2 : -1;
+ return current;
+}
+
+/**
+When a transform is applied to the verts of an object, and different transform
+is needed for the normals. Note that applying this transform will stretch their
+length, so they should be renormalized after.
+*/
inline mat3 NormalTransform(const mat3x4& transform) {
return la::inverse(la::transpose(mat3(transform)));
}
+/**
+This is the corresponding normal transform for the inverse of the input
+transform.
+*/
+inline mat3 InverseNormalTransform(const mat3x4& transform) {
+ return la::inverse(la::transpose(la::inverse(mat3(transform))));
+}
+
+/**
+ * Symbolic perturbation primitives shared by Boolean3 and Boolean2.
+ * Carefully designed to minimize FP rounding error and eliminate it at edge
+ * cases.
+ */
+
+inline double withSign(bool pos, double v) { return pos ? v : -v; }
+
+/**
+ * Interpolate the (y, z) of segment aL-aR at the given x. The choice of
+ * (x - aL) vs (x - aR) is the smaller in magnitude, which keeps FP error
+ * low near either endpoint. Domain check via DEBUG_ASSERT.
+ */
+inline vec2 Interpolate(vec3 aL, vec3 aR, double x) {
+ const double dxL = x - aL.x;
+ const double dxR = x - aR.x;
+ DEBUG_ASSERT(dxL * dxR <= 0, logicErr,
+ "Boolean manifold error: not in domain");
+ const bool useL = fabs(dxL) < fabs(dxR);
+ const vec3 dLR = aR - aL;
+ const double lambda = (useL ? dxL : dxR) / dLR.x;
+ if (!std::isfinite(lambda) || !std::isfinite(dLR.y) || !std::isfinite(dLR.z))
+ return vec2(aL.y, aL.z);
+ vec2 yz;
+ yz[0] = lambda * dLR.y + (useL ? aL.y : aR.y);
+ yz[1] = lambda * dLR.z + (useL ? aL.z : aR.z);
+ return yz;
+}
+
+/**
+ * `p < q` with symbolic perturbation: when `p == q` exactly, `dir < 0`
+ * acts as the tiebreaker. Used to give consistent strict-ordering answers
+ * regardless of which side of an FP equality we land on.
+ */
+inline bool Shadows(double p, double q, double dir) {
+ return p == q ? dir < 0 : p < q;
+}
+
/**
* By using the closest axis-aligned projection to the normal instead of a
* projection along the normal, we avoid introducing any rounding error.
@@ -113,8 +168,8 @@ inline vec3 GetBarycentric(const vec3& v, const mat3& triPos,
}
/**
- * The fundamental component of the halfedge data structure used for storing and
- * operating on the Manifold.
+ * Temporary or value-style halfedge record. Persistent Manifold storage uses
+ * Halfedges below, which derives endVert from the next halfedge in each face.
*/
struct Halfedge {
int startVert, endVert;
@@ -127,6 +182,101 @@ struct Halfedge {
}
};
+class Halfedges {
+ public:
+ Halfedges() = default;
+ explicit Halfedges(size_t size) { resize_nofill(size); }
+ explicit Halfedges(const VecView<const Halfedge>& edges) { FromData(edges); }
+
+ size_t size() const { return start_.size(); }
+ bool empty() const { return start_.empty(); }
+
+ int Start(int idx) const { return start_[idx]; }
+ int End(int idx) const { return start_[NextHalfedge(idx)]; }
+ int Pair(int idx) const { return paired_[idx]; }
+ int Prop(int idx) const { return propVert_[idx]; }
+
+ void SetStart(int idx, int vert) { start_[idx] = vert; }
+ void SetEnd(int idx, int vert) { start_[NextHalfedge(idx)] = vert; }
+ void SetPair(int idx, int pair) { paired_[idx] = pair; }
+ void SetProp(int idx, int prop) { propVert_[idx] = prop; }
+
+ bool IsForward(int idx) const { return Start(idx) < End(idx); }
+
+ Halfedge Get(int idx) const {
+ return {Start(idx), End(idx), Pair(idx), Prop(idx)};
+ }
+
+ void Set(int idx, int startVert, int pairedHalfedge, int propVert) {
+ SetStart(idx, startVert);
+ SetPair(idx, pairedHalfedge);
+ SetProp(idx, propVert);
+ }
+
+ void push_back(int startVert, int pairedHalfedge, int propVert) {
+ start_.push_back(startVert);
+ paired_.push_back(pairedHalfedge);
+ propVert_.push_back(propVert);
+ }
+
+ void resize(size_t newSize) {
+ start_.resize(newSize, -1);
+ paired_.resize(newSize, -1);
+ propVert_.resize(newSize, -1);
+ }
+
+ void resize_nofill(size_t newSize) {
+ start_.resize_nofill(newSize);
+ paired_.resize_nofill(newSize);
+ propVert_.resize_nofill(newSize);
+ }
+
+ void clear(bool shrink = true) {
+ start_.clear(shrink);
+ paired_.clear(shrink);
+ propVert_.clear(shrink);
+ }
+
+ void MakeUnique() {
+ start_.MakeUnique();
+ paired_.MakeUnique();
+ propVert_.MakeUnique();
+ }
+
+ Vec<Halfedge> ToData() const {
+ Vec<Halfedge> data(size());
+ for_each_n(autoPolicy(size()), countAt(0), size(),
+ [this, &data](int idx) { data[idx] = Get(idx); });
+ return data;
+ }
+
+ void FromData(const VecView<const Halfedge>& data) {
+ clear(true);
+ resize_nofill(data.size());
+ for_each_n(autoPolicy(data.size()), countAt(0), data.size(),
+ [this, &data](int idx) {
+ start_[idx] = data[idx].startVert;
+ paired_[idx] = data[idx].pairedHalfedge;
+ propVert_[idx] = data[idx].propVert;
+ });
+#ifdef MANIFOLD_DEBUG
+ DEBUG_ASSERT(data.size() % 3 == 0, topologyErr,
+ "Halfedges::FromData requires triangle faces!");
+ for (size_t idx = 0; idx < data.size(); ++idx) {
+ const int next = NextHalfedge(static_cast<int>(idx));
+ if (data[idx].endVert >= 0 && data[next].startVert >= 0) {
+ DEBUG_ASSERT(data[idx].endVert == data[next].startVert, topologyErr,
+ "Halfedges::FromData requires triangle-ordered edges!");
+ }
+ }
+#endif
+ }
+
+ SharedVec<int> start_;
+ SharedVec<int> paired_;
+ SharedVec<int> propVert_;
+};
+
struct Barycentric {
int tri;
vec4 uvw;
@@ -140,10 +290,13 @@ struct TriRef {
/// The OriginalID of the mesh this triangle came from. This ID is ideal for
/// reapplying properties like UV coordinates to the output mesh.
int originalID;
- /// Probably the triangle index of the original triangle this was part of:
- /// Mesh.triVerts[tri], but it's an input, so just pass it along unchanged.
+ /// If set as an input of MeshGL, it is passed along unchanged. This is how
+ /// the user can tell us not to collapse certain edges: those that divide
+ /// difference faceIDs. If not set, this is always -1.
int faceID;
- /// Triangles with the same coplanar ID are coplanar.
+ /// Triangles with the same coplanar ID are coplanar. Starts as a canonical
+ /// triangle index, but after boolean operations it may refer to a triangle
+ /// that is no longer present in this mesh.
int coplanarID;
bool SameFace(const TriRef& other) const {
@@ -171,13 +324,12 @@ struct TmpEdge {
}
};
-Vec<TmpEdge> inline CreateTmpEdges(const Vec<Halfedge>& halfedge) {
+Vec<TmpEdge> inline CreateTmpEdges(const Halfedges& halfedge) {
Vec<TmpEdge> edges(halfedge.size());
for_each_n(autoPolicy(edges.size()), countAt(0), edges.size(),
[&edges, &halfedge](const int idx) {
- const Halfedge& half = halfedge[idx];
- edges[idx] = TmpEdge(half.startVert, half.endVert,
- half.IsForward() ? idx : -1);
+ edges[idx] = TmpEdge(halfedge.Start(idx), halfedge.End(idx),
+ halfedge.IsForward(idx) ? idx : -1);
});
size_t numEdge =
diff --git a/thirdparty/manifold/src/smoothing.cpp b/thirdparty/manifold/src/smoothing.cpp
index 3d275eba1b9..2295c2ea17b 100644
--- a/thirdparty/manifold/src/smoothing.cpp
+++ b/thirdparty/manifold/src/smoothing.cpp
@@ -14,6 +14,7 @@
#include <unordered_map>
+#include "execution_impl.h"
#include "impl.h"
#include "parallel.h"
@@ -37,10 +38,19 @@ double Wrap(double radians) {
: radians;
}
+// Minimum sharp angle in degrees, below which edges are considered coplanar.
+// Floating point noise in the dihedral angle computation can reach ~1e-6
+// degrees for nearly-parallel face normals; this threshold must exceed that.
+constexpr double kMinSharpAngle = 1e-4;
+
// Get the angle between two unit-vectors.
double AngleBetween(vec3 a, vec3 b) {
const double dot = la::dot(a, b);
- return dot >= 1 ? 0 : (dot <= -1 ? kPi : la::acos(dot));
+ return dot >= 1 ? 0 : (dot <= -1 ? kPi : math::acos(dot));
+}
+
+bool EqualNormals(vec3 a, vec3 b) {
+ return la::dot(SafeNormalize(a), SafeNormalize(b)) > 0.9999;
}
// Calculate a tangent vector in the form of a weighted cubic Bezier taking as
@@ -115,12 +125,12 @@ struct InterpTri {
cosTheta = -cosTheta;
}
- if (cosTheta > 1.0 - std::numeric_limits<double>::epsilon()) {
+ if (std::abs(cosTheta) > 1.0 - std::numeric_limits<double>::epsilon()) {
return la::lerp(x, z, a); // for numerical stability
} else {
- double angle = std::acos(cosTheta);
- return (std::sin((1.0 - a) * angle) * x + std::sin(a * angle) * z) /
- std::sin(angle);
+ double angle = math::acos(cosTheta);
+ return (math::sin((1.0 - a) * angle) * x + math::sin(a * angle) * z) /
+ math::sin(angle);
}
}
@@ -179,12 +189,11 @@ struct InterpTri {
const ivec4 halfedges = impl->GetHalfedges(tri);
const mat3x4 corners = {
- impl->vertPos_[impl->halfedge_[halfedges[0]].startVert],
- impl->vertPos_[impl->halfedge_[halfedges[1]].startVert],
- impl->vertPos_[impl->halfedge_[halfedges[2]].startVert],
- halfedges[3] < 0
- ? vec3(0.0)
- : impl->vertPos_[impl->halfedge_[halfedges[3]].startVert]};
+ impl->vertPos_[impl->halfedge_.Start(halfedges[0])],
+ impl->vertPos_[impl->halfedge_.Start(halfedges[1])],
+ impl->vertPos_[impl->halfedge_.Start(halfedges[2])],
+ halfedges[3] < 0 ? vec3(0.0)
+ : impl->vertPos_[impl->halfedge_.Start(halfedges[3])]};
for (const int i : {0, 1, 2, 3}) {
if (uvw[i] == 1) {
@@ -200,9 +209,9 @@ struct InterpTri {
impl->halfedgeTangent_[halfedges[1]],
impl->halfedgeTangent_[halfedges[2]]};
const mat4x3 tangentL = {
- impl->halfedgeTangent_[impl->halfedge_[halfedges[2]].pairedHalfedge],
- impl->halfedgeTangent_[impl->halfedge_[halfedges[0]].pairedHalfedge],
- impl->halfedgeTangent_[impl->halfedge_[halfedges[1]].pairedHalfedge]};
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[2])],
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[0])],
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[1])]};
const vec3 centroid = mat3(corners) * vec3(1.0 / 3);
for (const int i : {0, 1, 2}) {
@@ -224,13 +233,13 @@ struct InterpTri {
} else { // quad
const mat4 tangentsX = {
impl->halfedgeTangent_[halfedges[0]],
- impl->halfedgeTangent_[impl->halfedge_[halfedges[0]].pairedHalfedge],
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[0])],
impl->halfedgeTangent_[halfedges[2]],
- impl->halfedgeTangent_[impl->halfedge_[halfedges[2]].pairedHalfedge]};
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[2])]};
const mat4 tangentsY = {
- impl->halfedgeTangent_[impl->halfedge_[halfedges[3]].pairedHalfedge],
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[3])],
impl->halfedgeTangent_[halfedges[1]],
- impl->halfedgeTangent_[impl->halfedge_[halfedges[1]].pairedHalfedge],
+ impl->halfedgeTangent_[impl->halfedge_.Pair(halfedges[1])],
impl->halfedgeTangent_[halfedges[3]]};
const vec3 centroid = corners * vec4(0.25);
const double x = uvw[1] + uvw[2];
@@ -245,6 +254,9 @@ struct InterpTri {
posH += Homogeneous(vec4(pY, y * (1 - y)));
}
pos = HNormalize(posH);
+ if (la::any(!la::isfinite(pos))) {
+ pos = corners[0];
+ }
}
};
} // namespace
@@ -256,25 +268,37 @@ namespace manifold {
* normalIdx shows the beginning of where normals are stored in the properties.
*/
vec3 Manifold::Impl::GetNormal(int halfedge, int normalIdx) const {
- const int prop = halfedge_[halfedge].propVert;
+ const int prop = halfedge_.Prop(halfedge);
vec3 normal;
for (const int i : {0, 1, 2}) {
normal[i] = properties_[prop * numProp_ + normalIdx + i];
}
+ // hasNormals=true means CalculateNormals (or a flagged round-trip) wrote
+ // world-frame values, kept world-frame through Transform/Compose. Without
+ // the flag, treat the slot as per-mesh frame and re-rotate to world like
+ // pre-#1718 callers expected.
+ const int meshID = meshRelation_.triRef[halfedge / 3].meshID;
+ auto it = meshRelation_.meshIDtransform.find(meshID);
+ if (it != meshRelation_.meshIDtransform.end() && !it->second.hasNormals) {
+ normal = it->second.GetNormalTransform() * normal;
+ }
return normal;
}
/**
* Returns a circular tangent for the requested halfedge, orthogonal to the
- * given normal vector, and avoiding folding.
+ * given normal vector, and avoiding folding when the tangent needs to be more
+ * than 90 degrees from the edge vector.
*/
vec4 Manifold::Impl::TangentFromNormal(const vec3& normal, int halfedge) const {
- const Halfedge edge = halfedge_[halfedge];
- const vec3 edgeVec = vertPos_[edge.endVert] - vertPos_[edge.startVert];
+ const vec3 edgeVec =
+ vertPos_[halfedge_.End(halfedge)] - vertPos_[halfedge_.Start(halfedge)];
const vec3 edgeNormal =
- faceNormal_[halfedge / 3] + faceNormal_[edge.pairedHalfedge / 3];
- vec3 dir = la::cross(la::cross(edgeNormal, edgeVec), normal);
- return CircularTangent(dir, edgeVec);
+ faceNormal_[halfedge / 3] + faceNormal_[halfedge_.Pair(halfedge) / 3];
+ const vec3 biTangent = la::dot(normal, edgeNormal) < 0
+ ? la::cross(edgeNormal, edgeVec)
+ : la::cross(normal, edgeVec);
+ return CircularTangent(la::cross(biTangent, normal), edgeVec);
}
/**
@@ -288,14 +312,13 @@ bool Manifold::Impl::IsInsideQuad(int halfedge) const {
}
const int tri = halfedge / 3;
const TriRef ref = meshRelation_.triRef[tri];
- const int pair = halfedge_[halfedge].pairedHalfedge;
+ const int pair = halfedge_.Pair(halfedge);
const int pairTri = pair / 3;
const TriRef pairRef = meshRelation_.triRef[pairTri];
if (!ref.SameFace(pairRef)) return false;
auto SameFace = [this](int halfedge, const TriRef& ref) {
- return ref.SameFace(
- meshRelation_.triRef[halfedge_[halfedge].pairedHalfedge / 3]);
+ return ref.SameFace(meshRelation_.triRef[halfedge_.Pair(halfedge) / 3]);
};
int neighbor = NextHalfedge(halfedge);
@@ -345,8 +368,7 @@ Vec<bool> Manifold::Impl::FlatFaces() const {
int faceNeighbors = 0;
ivec3 faceTris = {-1, -1, -1};
for (const int j : {0, 1, 2}) {
- const int neighborTri =
- halfedge_[3 * tri + j].pairedHalfedge / 3;
+ const int neighborTri = halfedge_.Pair(3 * tri + j) / 3;
const TriRef& jRef = meshRelation_.triRef[neighborTri];
if (jRef.SameFace(ref)) {
++faceNeighbors;
@@ -374,7 +396,7 @@ Vec<int> Manifold::Impl::VertFlatFace(const Vec<bool>& flatFaces) const {
for (size_t tri = 0; tri < NumTri(); ++tri) {
if (flatFaces[tri]) {
for (const int j : {0, 1, 2}) {
- const int vert = halfedge_[3 * tri + j].startVert;
+ const int vert = halfedge_.Start(3 * tri + j);
if (vertRef[vert].SameFace(meshRelation_.triRef[tri])) continue;
vertRef[vert] = meshRelation_.triRef[tri];
vertFlatFace[vert] = vertFlatFace[vert] == -1 ? tri : -2;
@@ -389,13 +411,13 @@ Vec<int> Manifold::Impl::VertHalfedge() const {
Vec<uint8_t> counters(NumVert(), 0);
for_each_n(autoPolicy(halfedge_.size(), 1e5), countAt(0), halfedge_.size(),
[&vertHalfedge, &counters, this](const int idx) {
+ const int start = halfedge_.Start(idx);
auto old = std::atomic_exchange(
- reinterpret_cast<std::atomic<uint8_t>*>(
- &counters[halfedge_[idx].startVert]),
+ reinterpret_cast<std::atomic<uint8_t>*>(&counters[start]),
static_cast<uint8_t>(1));
if (old == 1) return;
// arbitrary, last one wins.
- vertHalfedge[halfedge_[idx].startVert] = idx;
+ vertHalfedge[start] = idx;
});
return vertHalfedge;
}
@@ -403,12 +425,13 @@ Vec<int> Manifold::Impl::VertHalfedge() const {
std::vector<Smoothness> Manifold::Impl::SharpenEdges(
double minSharpAngle, double minSmoothness) const {
std::vector<Smoothness> sharpenedEdges;
+ minSharpAngle = std::max(minSharpAngle, kMinSharpAngle);
const double minRadians = radians(minSharpAngle);
for (size_t e = 0; e < halfedge_.size(); ++e) {
- if (!halfedge_[e].IsForward()) continue;
- const size_t pair = halfedge_[e].pairedHalfedge;
+ if (!halfedge_.IsForward(e)) continue;
+ const size_t pair = halfedge_.Pair(e);
const double dihedral =
- std::acos(la::dot(faceNormal_[e / 3], faceNormal_[pair / 3]));
+ AngleBetween(faceNormal_[e / 3], faceNormal_[pair / 3]);
if (dihedral > minRadians) {
sharpenedEdges.push_back({e, minSmoothness});
sharpenedEdges.push_back({pair, minSmoothness});
@@ -436,33 +459,24 @@ void Manifold::Impl::SharpenTangent(int halfedge, double smoothness) {
void Manifold::Impl::SetNormals(int normalIdx, double minSharpAngle) {
if (IsEmpty()) return;
if (normalIdx < 0) return;
+ // Ensure minSharpAngle is large enough to avoid treating nearly-coplanar
+ // faces as sharp due to floating point noise in the dihedral computation.
+ minSharpAngle = std::max(minSharpAngle, kMinSharpAngle);
+ halfedge_.MakeUnique();
const int oldNumProp = NumProp();
- Vec<bool> triIsFlatFace = FlatFaces();
- Vec<int> vertFlatFace = VertFlatFace(triIsFlatFace);
Vec<int> vertNumSharp(NumVert(), 0);
for (size_t e = 0; e < halfedge_.size(); ++e) {
- if (!halfedge_[e].IsForward()) continue;
- const int pair = halfedge_[e].pairedHalfedge;
+ if (!halfedge_.IsForward(e)) continue;
+ const int pair = halfedge_.Pair(e);
const int tri1 = e / 3;
const int tri2 = pair / 3;
const double dihedral =
- degrees(std::acos(la::dot(faceNormal_[tri1], faceNormal_[tri2])));
+ degrees(AngleBetween(faceNormal_[tri1], faceNormal_[tri2]));
if (dihedral > minSharpAngle) {
- ++vertNumSharp[halfedge_[e].startVert];
- ++vertNumSharp[halfedge_[e].endVert];
- } else {
- const bool faceSplit =
- triIsFlatFace[tri1] != triIsFlatFace[tri2] ||
- (triIsFlatFace[tri1] && triIsFlatFace[tri2] &&
- !meshRelation_.triRef[tri1].SameFace(meshRelation_.triRef[tri2]));
- if (vertFlatFace[halfedge_[e].startVert] == -2 && faceSplit) {
- ++vertNumSharp[halfedge_[e].startVert];
- }
- if (vertFlatFace[halfedge_[e].endVert] == -2 && faceSplit) {
- ++vertNumSharp[halfedge_[e].endVert];
- }
+ ++vertNumSharp[halfedge_.Start(e)];
+ ++vertNumSharp[halfedge_.End(e)];
}
}
@@ -474,23 +488,49 @@ void Manifold::Impl::SetNormals(int normalIdx, double minSharpAngle) {
Vec<int> oldHalfedgeProp(halfedge_.size());
for_each_n(autoPolicy(halfedge_.size(), 1e5), countAt(0), halfedge_.size(),
[this, &oldHalfedgeProp](int i) {
- oldHalfedgeProp[i] = halfedge_[i].propVert;
- halfedge_[i].propVert = -1;
+ oldHalfedgeProp[i] = halfedge_.Prop(i);
+ halfedge_.SetProp(i, -1);
});
+ // Cached per-meshID inverse-normal-transform for the legacy non-zero
+ // normalIdx path. Lazily populated on first lookup; reused across all
+ // verts in the loop below.
+ // TODO: drop this and its only caller below when the non-zero normalIdx
+ // parameter on CalculateNormals is removed.
+ std::map<int, mat3> meshIDtoNormalTransform;
+ auto getTransform = [&](int meshID) {
+ if (meshIDtoNormalTransform.find(meshID) == meshIDtoNormalTransform.end()) {
+ meshIDtoNormalTransform[meshID] =
+ meshRelation_.meshIDtransform[meshID].GetInverseNormalTransform();
+ }
+ return meshIDtoNormalTransform[meshID];
+ };
+
const int numEdge = halfedge_.size();
for (int startEdge = 0; startEdge < numEdge; ++startEdge) {
- if (halfedge_[startEdge].propVert >= 0) continue;
- const int vert = halfedge_[startEdge].startVert;
+ if (halfedge_.Prop(startEdge) >= 0) continue;
+ const int vert = halfedge_.Start(startEdge);
if (vertNumSharp[vert] < 2) { // vertex has single normal
- const vec3 normal = vertFlatFace[vert] >= 0
- ? faceNormal_[vertFlatFace[vert]]
- : vertNormal_[vert];
+ const vec3 worldNormal = vertNormal_[vert];
+ // Non-zero normalIdx is the legacy deferred-transform path: store in
+ // per-mesh frame so GetMeshGL's runTransform application on export
+ // recovers world frame even after later transforms. Standard slot 0
+ // uses the eager-transform contract: store world-frame directly.
+ // Caveat: for legacy idx!=0, if a single propVert is shared between
+ // triangles of different meshIDs, we pick startEdge's meshID for the
+ // per-mesh-frame mapping. Other meshIDs reading the same propVert
+ // through a different runTransform on export will get a wrong
+ // rotation. Same shape as master; out of scope here.
+ const vec3 normal =
+ normalIdx == 0
+ ? worldNormal
+ : getTransform(meshRelation_.triRef[startEdge / 3].meshID) *
+ worldNormal;
int lastProp = -1;
ForVert(startEdge, [&](int current) {
const int prop = oldHalfedgeProp[current];
- halfedge_[current].propVert = prop;
+ halfedge_.SetProp(current, prop);
if (prop == lastProp) return;
lastProp = prop;
// update property vertex
@@ -500,122 +540,105 @@ void Manifold::Impl::SetNormals(int normalIdx, double minSharpAngle) {
for (const int i : {0, 1, 2})
properties_[prop * numProp + normalIdx + i] = normal[i];
});
- } else { // vertex has multiple normals
- const vec3 centerPos = vertPos_[vert];
- // Length degree
- std::vector<int> group;
- // Length number of normals
- std::vector<vec3> normals;
- int current = startEdge;
- int prevFace = current / 3;
-
- do { // find a sharp edge to start on
- int next = NextHalfedge(halfedge_[current].pairedHalfedge);
- const int face = next / 3;
-
- const double dihedral = degrees(
- std::acos(la::dot(faceNormal_[face], faceNormal_[prevFace])));
- if (dihedral > minSharpAngle ||
- triIsFlatFace[face] != triIsFlatFace[prevFace] ||
- (triIsFlatFace[face] && triIsFlatFace[prevFace] &&
- !meshRelation_.triRef[face].SameFace(
- meshRelation_.triRef[prevFace]))) {
- break;
- }
- current = next;
- prevFace = face;
- } while (current != startEdge);
-
- const int endEdge = current;
-
- struct FaceEdge {
- int face;
- vec3 edgeVec;
- };
-
- // calculate pseudo-normals between each sharp edge
- ForVert<FaceEdge>(
- endEdge,
- [this, centerPos, &vertNumSharp, &vertFlatFace](int current) {
- if (IsInsideQuad(current)) {
- return FaceEdge({current / 3, vec3(NAN)});
- }
- const int vert = halfedge_[current].endVert;
- vec3 pos = vertPos_[vert];
- if (vertNumSharp[vert] < 2) {
- // opposite vert has fixed normal
- const vec3 normal = vertFlatFace[vert] >= 0
- ? faceNormal_[vertFlatFace[vert]]
- : vertNormal_[vert];
- // Flair out the normal we're calculating to give the edge a
- // more constant curvature to meet the opposite normal. Achieve
- // this by pointing the tangent toward the opposite bezier
- // control point instead of the vert itself.
- pos += vec3(
- TangentFromNormal(normal, halfedge_[current].pairedHalfedge));
- }
- return FaceEdge({current / 3, SafeNormalize(pos - centerPos)});
- },
- [this, &triIsFlatFace, &normals, &group, minSharpAngle](
- int, const FaceEdge& here, FaceEdge& next) {
- const double dihedral = degrees(std::acos(
- la::dot(faceNormal_[here.face], faceNormal_[next.face])));
- if (dihedral > minSharpAngle ||
- triIsFlatFace[here.face] != triIsFlatFace[next.face] ||
- (triIsFlatFace[here.face] && triIsFlatFace[next.face] &&
- !meshRelation_.triRef[here.face].SameFace(
- meshRelation_.triRef[next.face]))) {
- normals.push_back(vec3(0.0));
- }
- group.push_back(normals.size() - 1);
- if (std::isfinite(next.edgeVec.x)) {
- normals.back() +=
- SafeNormalize(la::cross(next.edgeVec, here.edgeVec)) *
- AngleBetween(here.edgeVec, next.edgeVec);
- } else {
- next.edgeVec = here.edgeVec;
- }
- });
+ continue;
+ }
- for (auto& normal : normals) {
- normal = SafeNormalize(normal);
+ // vertex has multiple normals
+ const vec3 centerPos = vertPos_[vert];
+ // Length degree
+ std::vector<int> groups;
+ // Length number of normals
+ std::vector<vec3> normals;
+ std::vector<int> meshIds;
+ int current = startEdge;
+ int prevFace = current / 3;
+
+ do { // find a sharp edge to start on
+ int next = NextHalfedge(halfedge_.Pair(current));
+ const int face = next / 3;
+
+ const double dihedral =
+ degrees(AngleBetween(faceNormal_[face], faceNormal_[prevFace]));
+ if (dihedral > minSharpAngle) {
+ break;
}
+ current = next;
+ prevFace = face;
+ } while (current != startEdge);
+
+ const int endEdge = current;
+
+ struct FaceEdge {
+ int face;
+ vec3 normalizedEdge;
+ };
+
+ // calculate pseudo-normals between each sharp edge
+ ForVert<FaceEdge>(
+ endEdge,
+ [&](int current) {
+ const int vert = halfedge_.End(current);
+ return FaceEdge(
+ {current / 3, SafeNormalize(vertPos_[vert] - centerPos)});
+ },
+ [&](int, const FaceEdge& here, FaceEdge& next) {
+ const double dihedral = degrees(
+ AngleBetween(faceNormal_[here.face], faceNormal_[next.face]));
+ if (dihedral > minSharpAngle) {
+ normals.push_back(vec3(0.0));
+ meshIds.push_back(meshRelation_.triRef[next.face].meshID);
+ }
+ groups.push_back(normals.size() - 1);
+ if (std::isfinite(next.normalizedEdge.x)) {
+ vec3 dir = SafeNormalize(
+ la::cross(next.normalizedEdge, here.normalizedEdge));
+ normals.back() +=
+ dir * AngleBetween(here.normalizedEdge, next.normalizedEdge);
+ } else {
+ next.normalizedEdge = here.normalizedEdge;
+ }
+ });
- int lastGroup = 0;
- int lastProp = -1;
- int newProp = -1;
- int idx = 0;
- ForVert(endEdge, [&](int current1) {
- const int prop = oldHalfedgeProp[current1];
- auto start = oldProperties.begin() + prop * oldNumProp;
+ for (int i = 0; i < normals.size(); ++i) {
+ vec3 n = normals[i];
+ // Same frame-storage rule as the single-normal path above.
+ if (normalIdx != 0) n = getTransform(meshIds[i]) * n;
+ normals[i] = SafeNormalize(n);
+ }
- if (group[idx] != lastGroup && group[idx] != 0 && prop == lastProp) {
- // split property vertex, duplicating but with an updated normal
- lastGroup = group[idx];
- newProp = NumPropVert();
- properties_.resize(properties_.size() + numProp);
- std::copy(start, start + oldNumProp,
- properties_.begin() + newProp * numProp);
- for (const int i : {0, 1, 2}) {
- properties_[newProp * numProp + normalIdx + i] =
- normals[group[idx]][i];
- }
- } else if (prop != lastProp) {
- // update property vertex
- lastProp = prop;
- newProp = prop;
- std::copy(start, start + oldNumProp,
- properties_.begin() + prop * numProp);
- for (const int i : {0, 1, 2})
- properties_[prop * numProp + normalIdx + i] =
- normals[group[idx]][i];
+ int lastGroup = 0;
+ int lastProp = -1;
+ int newProp = -1;
+ int idx = 0;
+ ForVert(endEdge, [&](int current1) {
+ const int prop = oldHalfedgeProp[current1];
+ auto start = oldProperties.begin() + prop * oldNumProp;
+
+ if (groups[idx] != lastGroup && groups[idx] != 0 && prop == lastProp) {
+ // split property vertex, duplicating but with an updated normal
+ lastGroup = groups[idx];
+ newProp = NumPropVert();
+ properties_.resize(properties_.size() + numProp);
+ std::copy(start, start + oldNumProp,
+ properties_.begin() + newProp * numProp);
+ for (const int i : {0, 1, 2}) {
+ properties_[newProp * numProp + normalIdx + i] =
+ normals[groups[idx]][i];
}
+ } else if (prop != lastProp) {
+ // update property vertex
+ lastProp = prop;
+ newProp = prop;
+ std::copy(start, start + oldNumProp,
+ properties_.begin() + prop * numProp);
+ for (const int i : {0, 1, 2})
+ properties_[prop * numProp + normalIdx + i] = normals[groups[idx]][i];
+ }
- // point to updated property vertex
- halfedge_[current1].propVert = newProp;
- ++idx;
- });
- }
+ // point to updated property vertex
+ halfedge_.SetProp(current1, newProp);
+ ++idx;
+ });
}
}
@@ -633,15 +656,16 @@ void Manifold::Impl::LinearizeFlatTangents() {
const int n = halfedgeTangent_.size();
for_each_n(autoPolicy(n, 1e4), countAt(0), n, [this](const int halfedge) {
vec4& tangent = halfedgeTangent_[halfedge];
- vec4& otherTangent = halfedgeTangent_[halfedge_[halfedge].pairedHalfedge];
+ const int pair = halfedge_.Pair(halfedge);
+ vec4& otherTangent = halfedgeTangent_[pair];
const bool flat[2] = {tangent.w == 0, otherTangent.w == 0};
- if (!halfedge_[halfedge].IsForward() || (!flat[0] && !flat[1])) {
+ if (!halfedge_.IsForward(halfedge) || (!flat[0] && !flat[1])) {
return;
}
- const vec3 edgeVec = vertPos_[halfedge_[halfedge].endVert] -
- vertPos_[halfedge_[halfedge].startVert];
+ const vec3 edgeVec =
+ vertPos_[halfedge_.End(halfedge)] - vertPos_[halfedge_.Start(halfedge)];
if (flat[0] && flat[1]) {
tangent = vec4(edgeVec / 3.0, 1);
@@ -667,29 +691,25 @@ void Manifold::Impl::DistributeTangents(const Vec<bool>& fixedHalfedges) {
for_each_n(
autoPolicy(numHalfedge, 1e4), countAt(0), numHalfedge,
[this, &fixedHalfedges](int halfedge) {
- if (!fixedHalfedges[halfedge]) return;
-
- if (IsMarkedInsideQuad(halfedge)) {
- halfedge = NextHalfedge(halfedge_[halfedge].pairedHalfedge);
- }
+ if (!fixedHalfedges[halfedge] || IsMarkedInsideQuad(halfedge)) return;
vec3 normal(0.0);
Vec<double> currentAngle;
Vec<double> desiredAngle;
- const vec3 approxNormal = vertNormal_[halfedge_[halfedge].startVert];
- const vec3 center = vertPos_[halfedge_[halfedge].startVert];
+ const vec3 approxNormal = vertNormal_[halfedge_.Start(halfedge)];
+ const vec3 center = vertPos_[halfedge_.Start(halfedge)];
vec3 lastEdgeVec =
- SafeNormalize(vertPos_[halfedge_[halfedge].endVert] - center);
+ SafeNormalize(vertPos_[halfedge_.End(halfedge)] - center);
const vec3 firstTangent =
SafeNormalize(vec3(halfedgeTangent_[halfedge]));
vec3 lastTangent = firstTangent;
int current = halfedge;
do {
- current = NextHalfedge(halfedge_[current].pairedHalfedge);
+ current = NextHalfedge(halfedge_.Pair(current));
if (IsMarkedInsideQuad(current)) continue;
const vec3 thisEdgeVec =
- SafeNormalize(vertPos_[halfedge_[current].endVert] - center);
+ SafeNormalize(vertPos_[halfedge_.End(current)] - center);
const vec3 thisTangent =
SafeNormalize(vec3(halfedgeTangent_[current]));
normal += la::cross(thisTangent, lastTangent);
@@ -724,7 +744,8 @@ void Manifold::Impl::DistributeTangents(const Vec<bool>& fixedHalfedges) {
current = halfedge;
size_t i = 0;
do {
- current = NextHalfedge(halfedge_[current].pairedHalfedge);
+ current = NextHalfedge(halfedge_.Pair(current));
+ if (current != halfedge && fixedHalfedges[current]) break;
if (IsMarkedInsideQuad(current)) continue;
desiredAngle[i] *= scale;
const double lastAngle = i > 0 ? desiredAngle[i - 1] : 0;
@@ -738,8 +759,10 @@ void Manifold::Impl::DistributeTangents(const Vec<bool>& fixedHalfedges) {
const double angle = currentAngle[i] - desiredAngle[i] - offset;
vec3 tangent(halfedgeTangent_[current]);
const quat q = la::rotation_quat(la::normalize(normal), angle);
- halfedgeTangent_[current] =
- vec4(la::qrot(q, tangent), halfedgeTangent_[current].w);
+ const vec3 newTangent = la::qrot(q, tangent);
+ for (const int j : {0, 1, 2}) {
+ halfedgeTangent_[current][j] = newTangent[j];
+ }
++i;
} while (!fixedHalfedges[current]);
});
@@ -749,9 +772,11 @@ void Manifold::Impl::DistributeTangents(const Vec<bool>& fixedHalfedges) {
* Calculates halfedgeTangent_, allowing the manifold to be refined and
* smoothed. The tangents form weighted cubic Beziers along each edge. This
* function creates circular arcs where possible (minimizing maximum curvature),
- * constrained to the indicated property normals. Across edges that form
- * discontinuities in the normals, the tangent vectors are zero-length, allowing
- * the shape to form a sharp corner with minimal oscillation.
+ * constrained to the indicated property normals. Where a vert has multiple
+ * normals, the tangents will form a crease. Where the only normal is that of a
+ * flat face, the tangents at its ends will be made colinear. Zero-length
+ * normals are considered missing and will defer to their neighboring normals
+ * instead. If all normals are missing, the vertex pseudonormal will be used.
*/
void Manifold::Impl::CreateTangents(int normalIdx) {
ZoneScoped;
@@ -761,37 +786,37 @@ void Manifold::Impl::CreateTangents(int normalIdx) {
Vec<vec4> tangent(numHalfedge);
Vec<bool> fixedHalfedge(numHalfedge, false);
+ // special flags for tangent.w
+ constexpr double kInsideQuad = -1;
+ constexpr double kMissingNormal = -3;
+
Vec<int> vertHalfedge = VertHalfedge();
for_each_n(
- autoPolicy(numVert, 1e4), vertHalfedge.begin(), numVert,
- [this, &tangent, &fixedHalfedge, normalIdx](int e) {
+ autoPolicy(numVert, 1e4), vertHalfedge.begin(), numVert, [&](int e) {
struct FlatNormal {
bool isFlatFace;
vec3 normal;
};
ivec2 faceEdges(-1, -1);
+ int startHalfedge = -1;
+ vec3 lastNormal(0.0);
ForVert<FlatNormal>(
e,
[normalIdx, this](int halfedge) {
const vec3 normal = GetNormal(halfedge, normalIdx);
- const vec3 diff = faceNormal_[halfedge / 3] - normal;
return FlatNormal(
- {la::dot(diff, diff) < kPrecision * kPrecision, normal});
+ {EqualNormals(normal, faceNormal_[halfedge / 3]), normal});
},
- [&faceEdges, &tangent, &fixedHalfedge, this](
- int halfedge, const FlatNormal& here, const FlatNormal& next) {
- if (IsInsideQuad(halfedge)) {
- tangent[halfedge] = {0, 0, 0, -1};
- return;
- }
- // mark special edges
- const vec3 diff = next.normal - here.normal;
- const bool differentNormals =
- la::dot(diff, diff) > kPrecision * kPrecision;
- if (differentNormals || here.isFlatFace != next.isFlatFace) {
- fixedHalfedge[halfedge] = true;
+ [&](int halfedge, const FlatNormal& here, const FlatNormal& next) {
+ // Tangents not known at first are used as temporary storage for
+ // normals and w is set to a negative flag value. This starts with
+ // the flag clear.
+ tangent[halfedge].w = 1;
+
+ if (here.isFlatFace != next.isFlatFace) {
+ // Record the two halfedges that border a single flat face.
if (faceEdges[0] == -1) {
faceEdges[0] = halfedge;
} else if (faceEdges[1] == -1) {
@@ -800,32 +825,102 @@ void Manifold::Impl::CreateTangents(int normalIdx) {
faceEdges[0] = -2;
}
}
+
+ if (next.normal == vec3(0.) || here.normal == vec3(0.)) {
+ if (here.normal != vec3(0.)) { // next missing
+ lastNormal = here.normal;
+ } else if (next.normal != vec3(0.)) { // here missing
+ if (startHalfedge < 0) startHalfedge = halfedge;
+ } else { // both missing
+ if (startHalfedge < 0) startHalfedge = -2;
+ }
+ tangent[halfedge] = {lastNormal, kMissingNormal};
+ }
+
+ if (IsInsideQuad(halfedge))
+ tangent[halfedge] = {lastNormal, kInsideQuad};
+
+ if (tangent[halfedge].w < 0) return;
+
// calculate tangents
- if (differentNormals) {
- const vec3 edgeVec = vertPos_[halfedge_[halfedge].endVert] -
- vertPos_[halfedge_[halfedge].startVert];
+ if (EqualNormals(next.normal, here.normal)) {
+ tangent[halfedge] = TangentFromNormal(here.normal, halfedge);
+ } else {
+ // tangents at the intersection of two normals are fixed.
+ fixedHalfedge[halfedge] = true;
+ // Override the flat face logic if more than one normal.
+ faceEdges[0] = -2;
+
+ const vec3 edgeVec = vertPos_[halfedge_.End(halfedge)] -
+ vertPos_[halfedge_.Start(halfedge)];
const vec3 dir = la::cross(here.normal, next.normal);
tangent[halfedge] = CircularTangent(
(la::dot(dir, edgeVec) < 0 ? -1.0 : 1.0) * dir, edgeVec);
- } else {
- tangent[halfedge] = TangentFromNormal(here.normal, halfedge);
}
});
+ if (startHalfedge != -1 && lastNormal == vec3(0.)) {
+ // Use vert pseudo normal if no normals are present at all.
+ const vec3 normal = vertNormal_[halfedge_.Start(e)];
+ ForVert(e, [&](int halfedge) {
+ if (tangent[halfedge].w != kInsideQuad)
+ tangent[halfedge] = TangentFromNormal(normal, halfedge);
+ });
+ return;
+ }
+
+ if (startHalfedge >= 0) {
+ // Orbit the vertex backwards, pulling the next normal from the
+ // tangent where it is stored temporarily.
+ int current = startHalfedge;
+ vec3 prevNormal =
+ GetNormal(NextHalfedge(halfedge_.Pair(current)), normalIdx);
+ do {
+ DEBUG_ASSERT(prevNormal != vec3(0.), logicErr,
+ "missing prevNormal");
+ if (tangent[current].w == kMissingNormal) {
+ vec3 nextNormal = tangent[current].xyz();
+ if (nextNormal == vec3(0.)) {
+ nextNormal = lastNormal;
+ }
+
+ if (EqualNormals(prevNormal, nextNormal)) {
+ tangent[current] = TangentFromNormal(prevNormal, current);
+ } else {
+ const vec3 dir = la::cross(prevNormal, nextNormal);
+ const vec3 edgeVec = vertPos_[halfedge_.End(current)] -
+ vertPos_[halfedge_.Start(current)];
+ tangent[current] = CircularTangent(
+ (la::dot(dir, edgeVec) < 0 ? -1.0 : 1.0) * dir, edgeVec);
+ }
+ }
+ vec3 currentNormal = GetNormal(current, normalIdx);
+ if (currentNormal != vec3(0.)) {
+ prevNormal = currentNormal;
+ }
+ current = halfedge_.Pair(PrevHalfedge(current));
+
+ } while (current != startHalfedge);
+ }
+
if (faceEdges[0] >= 0 && faceEdges[1] >= 0) {
- const vec3 edge0 = vertPos_[halfedge_[faceEdges[0]].endVert] -
- vertPos_[halfedge_[faceEdges[0]].startVert];
- const vec3 edge1 = vertPos_[halfedge_[faceEdges[1]].endVert] -
- vertPos_[halfedge_[faceEdges[1]].startVert];
+ // When only a single flat face is present with a single shared normal
+ // for the entire vert, the tangents on either side of it should be
+ // aligned to give a continuous curve.
+ const vec3 edge0 = vertPos_[halfedge_.End(faceEdges[0])] -
+ vertPos_[halfedge_.Start(faceEdges[0])];
+ const vec3 edge1 = vertPos_[halfedge_.End(faceEdges[1])] -
+ vertPos_[halfedge_.Start(faceEdges[1])];
const vec3 newTangent = la::normalize(edge0) - la::normalize(edge1);
tangent[faceEdges[0]] = CircularTangent(newTangent, edge0);
tangent[faceEdges[1]] = CircularTangent(-newTangent, edge1);
- } else if (faceEdges[0] == -1 && faceEdges[0] == -1) {
- fixedHalfedge[e] = true;
+ // Fix these tangents to keep them even to the edges.
+ fixedHalfedge[faceEdges[0]] = true;
+ fixedHalfedge[faceEdges[1]] = true;
}
});
- halfedgeTangent_.swap(tangent);
+ halfedgeTangent_ = std::move(tangent);
DistributeTangents(fixedHalfedge);
}
@@ -838,7 +933,8 @@ void Manifold::Impl::CreateTangents(int normalIdx) {
* curvature there, while the tangents of the sharp edges themselves are aligned
* for continuity.
*/
-void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
+void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
const int numHalfedge = halfedge_.size();
halfedgeTangent_.clear();
@@ -854,37 +950,40 @@ void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
vertNormal[v] = faceNormal_[vertFlatFace[v]];
}
}
+ ADVANCE_PHASE_OR_RETURN(ctx);
- for_each_n(autoPolicy(numHalfedge, 1e4), countAt(0), numHalfedge,
+ for_each_n(autoPolicy(numHalfedge, 1e4), countAt(0), numHalfedge, ctx,
[&tangent, &vertNormal, this](const int edgeIdx) {
tangent[edgeIdx] =
IsInsideQuad(edgeIdx)
? vec4(0, 0, 0, -1)
- : TangentFromNormal(
- vertNormal[halfedge_[edgeIdx].startVert], edgeIdx);
+ : TangentFromNormal(vertNormal[halfedge_.Start(edgeIdx)],
+ edgeIdx);
});
- halfedgeTangent_.swap(tangent);
+ halfedgeTangent_ = std::move(tangent);
+ ADVANCE_PHASE_OR_RETURN(ctx);
// Add sharpened edges around faces, just on the face side.
for (size_t tri = 0; tri < NumTri(); ++tri) {
if (!triIsFlatFace[tri]) continue;
for (const int j : {0, 1, 2}) {
- const int tri2 = halfedge_[3 * tri + j].pairedHalfedge / 3;
+ const int tri2 = halfedge_.Pair(3 * tri + j) / 3;
if (!triIsFlatFace[tri2] ||
!meshRelation_.triRef[tri].SameFace(meshRelation_.triRef[tri2])) {
sharpenedEdges.push_back({3 * tri + j, 0});
}
}
}
+ ADVANCE_PHASE_OR_RETURN(ctx);
using Pair = std::pair<Smoothness, Smoothness>;
// Fill in missing pairs with default smoothness = 1.
std::map<int, Pair> edges;
for (Smoothness edge : sharpenedEdges) {
if (edge.smoothness >= 1) continue;
- const bool forward = halfedge_[edge.halfedge].IsForward();
- const int pair = halfedge_[edge.halfedge].pairedHalfedge;
+ const bool forward = halfedge_.IsForward(edge.halfedge);
+ const int pair = halfedge_.Pair(edge.halfedge);
const int idx = forward ? edge.halfedge : pair;
if (edges.find(idx) == edges.end()) {
edges[idx] = {edge, {static_cast<size_t>(pair), 1}};
@@ -898,14 +997,15 @@ void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
std::map<int, std::vector<Pair>> vertTangents;
for (const auto& value : edges) {
const Pair edge = value.second;
- vertTangents[halfedge_[edge.first.halfedge].startVert].push_back(edge);
- vertTangents[halfedge_[edge.second.halfedge].startVert].push_back(
+ vertTangents[halfedge_.Start(edge.first.halfedge)].push_back(edge);
+ vertTangents[halfedge_.Start(edge.second.halfedge)].push_back(
{edge.second, edge.first});
}
+ ADVANCE_PHASE_OR_RETURN(ctx);
const int numVert = NumVert();
for_each_n(
- autoPolicy(numVert, 1e4), countAt(0), numVert,
+ autoPolicy(numVert, 1e4), countAt(0), numVert, ctx,
[this, &vertTangents, &fixedHalfedge, &vertHalfedge,
&triIsFlatFace](int v) {
auto it = vertTangents.find(v);
@@ -924,11 +1024,11 @@ void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
const vec3 newTangent = la::normalize(vec3(halfedgeTangent_[first]) -
vec3(halfedgeTangent_[second]));
- const vec3 pos = vertPos_[halfedge_[first].startVert];
- halfedgeTangent_[first] = CircularTangent(
- newTangent, vertPos_[halfedge_[first].endVert] - pos);
+ const vec3 pos = vertPos_[halfedge_.Start(first)];
+ halfedgeTangent_[first] =
+ CircularTangent(newTangent, vertPos_[halfedge_.End(first)] - pos);
halfedgeTangent_[second] = CircularTangent(
- -newTangent, vertPos_[halfedge_[second].endVert] - pos);
+ -newTangent, vertPos_[halfedge_.End(second)] - pos);
double smoothness =
(vert[0].second.smoothness + vert[1].first.smoothness) / 2;
@@ -955,7 +1055,7 @@ void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
ForVert(vert[0].first.halfedge,
[this, &triIsFlatFace, smoothness](int current) {
if (!IsMarkedInsideQuad(current)) {
- const int pair = halfedge_[current].pairedHalfedge;
+ const int pair = halfedge_.Pair(current);
SharpenTangent(current, triIsFlatFace[current / 3] ||
triIsFlatFace[pair / 3]
? 0
@@ -964,16 +1064,52 @@ void Manifold::Impl::CreateTangents(std::vector<Smoothness> sharpenedEdges) {
});
}
});
+ ADVANCE_PHASE_OR_RETURN(ctx);
LinearizeFlatTangents();
+ ADVANCE_PHASE_OR_RETURN(ctx);
+
DistributeTangents(fixedHalfedge);
+ ADVANCE_PHASE_OR_RETURN(ctx);
+}
+
+bool Manifold::Impl::ValidTangents() const {
+ const int numHalfedge = halfedge_.size();
+ return all_of(autoPolicy(numHalfedge, 1e4), countAt(0), countAt(numHalfedge),
+ [&](const size_t edgeIdx) {
+ const bool inQuad = IsMarkedInsideQuad(edgeIdx);
+ const size_t pair = halfedge_.Pair(edgeIdx);
+ if (inQuad != IsMarkedInsideQuad(pair)) return false;
+ if (!inQuad) return true;
+ // missing tangents cannot be adjacent
+ if (IsMarkedInsideQuad(NextHalfedge(edgeIdx)) ||
+ IsMarkedInsideQuad(PrevHalfedge(edgeIdx)) ||
+ IsMarkedInsideQuad(NextHalfedge(pair)) ||
+ IsMarkedInsideQuad(PrevHalfedge(pair)))
+ return false;
+ return true;
+ });
}
void Manifold::Impl::Refine(std::function<int(vec3, vec4, vec4)> edgeDivisions,
- bool keepInterior) {
+ bool keepInterior, ExecutionContext::Impl* ctx) {
if (IsEmpty()) return;
+
+ if (!ValidTangents()) {
+ MakeEmpty(Error::InvalidTangents);
+ return;
+ }
+
Manifold::Impl old = *this;
+ halfedge_.MakeUnique();
Vec<Barycentric> vertBary = Subdivide(edgeDivisions, keepInterior);
+ // Cancel observed AFTER Subdivide (which is currently cancel-blind) but
+ // BEFORE the no-op early-return: the user requested cancel, so honour it
+ // even when Subdivide produced nothing to interpolate.
+ if (IsCancelled(ctx)) {
+ MakeEmpty(Error::Cancelled);
+ return;
+ }
if (vertBary.size() == 0) return;
if (old.halfedgeTangent_.size() == old.halfedge_.size()) {
@@ -982,10 +1118,13 @@ void Manifold::Impl::Refine(std::function<int(vec3, vec4, vec4)> edgeDivisions,
}
halfedgeTangent_.clear();
- Finish();
if (old.halfedgeTangent_.size() == old.halfedge_.size()) {
- MarkCoplanar();
+ SetNormalsAndCoplanar();
+ CalculateBBox();
+ } else {
+ CalculateVertNormals();
}
+ SortGeometry(ctx);
meshRelation_.originalID = -1;
}
diff --git a/thirdparty/manifold/src/sort.cpp b/thirdparty/manifold/src/sort.cpp
index 7ac362bd308..93a4167767e 100644
--- a/thirdparty/manifold/src/sort.cpp
+++ b/thirdparty/manifold/src/sort.cpp
@@ -34,9 +34,9 @@ uint32_t MortonCode(vec3 position, Box bBox) {
}
struct ReindexFace {
- VecView<Halfedge> halfedge;
+ Halfedges& halfedge;
VecView<vec4> halfedgeTangent;
- VecView<const Halfedge> oldHalfedge;
+ const Halfedges& oldHalfedge;
VecView<const vec4> oldHalfedgeTangent;
VecView<const int> faceNew2Old;
VecView<const int> faceOld2New;
@@ -45,12 +45,12 @@ struct ReindexFace {
const int oldFace = faceNew2Old[newFace];
for (const int i : {0, 1, 2}) {
const int oldEdge = 3 * oldFace + i;
- Halfedge edge = oldHalfedge[oldEdge];
+ Halfedge edge = oldHalfedge.Get(oldEdge);
const int pairedFace = edge.pairedHalfedge / 3;
const int offset = edge.pairedHalfedge - 3 * pairedFace;
edge.pairedHalfedge = 3 * faceOld2New[pairedFace] + offset;
const int newEdge = 3 * newFace + i;
- halfedge[newEdge] = edge;
+ halfedge.Set(newEdge, edge.startVert, edge.pairedHalfedge, edge.propVert);
if (!oldHalfedgeTangent.empty()) {
halfedgeTangent[newEdge] = oldHalfedgeTangent[oldEdge];
}
@@ -159,7 +159,7 @@ bool MergeMeshGLP(MeshGLP<Precision, I>& mesh) {
return uf.unite(openVerts[a], openVerts[b]);
};
auto recorder = MakeSimpleRecorder(f);
- collider.Collisions<true>(vertBox.cview(), recorder, false);
+ collider.Collisions<true>(recorder, vertBox.cview(), false);
for (size_t i = 0; i < mesh.mergeFromVert.size(); ++i) {
uf.unite(static_cast<int>(mesh.mergeFromVert[i]),
@@ -178,6 +178,7 @@ bool MergeMeshGLP(MeshGLP<Precision, I>& mesh) {
return true;
}
+
} // namespace
namespace manifold {
@@ -187,24 +188,32 @@ namespace manifold {
* rest of the internal data structures. This function also removes the verts
* and halfedges flagged for removal (NaN verts and -1 halfedges).
*/
-void Manifold::Impl::Finish() {
- if (halfedge_.size() == 0) return;
-
- CalculateBBox();
- SetEpsilon(epsilon_);
- if (!bBox_.IsFinite()) {
- // Decimated out of existence - early out.
- MakeEmpty(Error::NoError);
+void Manifold::Impl::SortGeometry(ExecutionContext::Impl* ctx) {
+ if (halfedge_.size() == 0) {
+ collider_ = {};
return;
}
- SortVerts();
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
+
+ halfedge_.MakeUnique();
+ SortVerts(ctx);
+ if (IsCancelled(ctx)) return;
Vec<Box> faceBox;
Vec<uint32_t> faceMorton;
- GetFaceBoxMorton(faceBox, faceMorton);
- SortFaces(faceBox, faceMorton);
- if (halfedge_.size() == 0) return;
- CompactProps();
+ GetFaceBoxMorton(faceBox, faceMorton, ctx);
+ if (IsCancelled(ctx)) return;
+ SortFaces(faceBox, faceMorton, ctx);
+ if (IsCancelled(ctx)) return;
+ if (halfedge_.size() == 0) {
+ collider_ = {};
+ return;
+ }
+ collider_ = Collider(faceBox, faceMorton);
+ bBox_ = collider_.GetBoundingBox();
+ CompactProps(ctx);
+ if (IsCancelled(ctx)) return;
DEBUG_ASSERT(halfedge_.size() % 6 == 0, topologyErr,
"Not an even number of faces after sorting faces!");
@@ -217,12 +226,14 @@ void Manifold::Impl::Finish() {
int face = 0;
Halfedge extrema = {0, 0, 0};
for (size_t i = 0; i < halfedge_.size(); i++) {
- Halfedge e = halfedge_[i];
- if (!e.IsForward()) std::swap(e.startVert, e.endVert);
- extrema.startVert = std::min(extrema.startVert, e.startVert);
- extrema.endVert = std::min(extrema.endVert, e.endVert);
+ const int start =
+ halfedge_.IsForward(i) ? halfedge_.Start(i) : halfedge_.End(i);
+ const int end =
+ halfedge_.IsForward(i) ? halfedge_.End(i) : halfedge_.Start(i);
+ extrema.startVert = std::min(extrema.startVert, start);
+ extrema.endVert = std::min(extrema.endVert, end);
extrema.pairedHalfedge =
- MaxOrMinus(extrema.pairedHalfedge, e.pairedHalfedge);
+ MaxOrMinus(extrema.pairedHalfedge, halfedge_.Pair(i));
face = MaxOrMinus(face, i / 3);
}
DEBUG_ASSERT(extrema.startVert >= 0, topologyErr,
@@ -242,12 +253,6 @@ void Manifold::Impl::Finish() {
DEBUG_ASSERT(meshRelation_.triRef.size() == NumTri() ||
meshRelation_.triRef.size() == 0,
logicErr, "Mesh Relation doesn't fit!");
- DEBUG_ASSERT(faceNormal_.size() == NumTri() || faceNormal_.size() == 0,
- logicErr,
- "faceNormal size = " + std::to_string(faceNormal_.size()) +
- ", NumTri = " + std::to_string(NumTri()));
- CalculateNormals();
- collider_ = Collider(faceBox, faceMorton);
DEBUG_ASSERT(Is2Manifold(), logicErr, "mesh is not 2-manifold!");
}
@@ -255,14 +260,18 @@ void Manifold::Impl::Finish() {
/**
* Sorts the vertices according to their Morton code.
*/
-void Manifold::Impl::SortVerts() {
+void Manifold::Impl::SortVerts(ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const auto numVert = NumVert();
Vec<uint32_t> vertMorton(numVert);
auto policy = autoPolicy(numVert, 1e5);
- for_each_n(policy, countAt(0), numVert, [this, &vertMorton](const int vert) {
- vertMorton[vert] = MortonCode(vertPos_[vert], bBox_);
- });
+ for_each_n(policy, countAt(0), numVert, ctx,
+ [this, &vertMorton](const int vert) {
+ vertMorton[vert] = MortonCode(vertPos_[vert], bBox_);
+ });
+ if (IsCancelled(ctx)) return;
Vec<int> vertNew2Old(numVert);
sequence(vertNew2Old.begin(), vertNew2Old.end());
@@ -272,7 +281,8 @@ void Manifold::Impl::SortVerts() {
return vertMorton[a] < vertMorton[b];
});
- ReindexVerts(vertNew2Old, numVert);
+ ReindexVerts(vertNew2Old, numVert, ctx);
+ if (IsCancelled(ctx)) return;
// Verts were flagged for removal with NaNs and assigned kNoCode to sort
// them to the end, which allows them to be removed.
@@ -297,39 +307,47 @@ void Manifold::Impl::SortVerts() {
* also given.
*/
void Manifold::Impl::ReindexVerts(const Vec<int>& vertNew2Old,
- size_t oldNumVert) {
+ size_t oldNumVert,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
Vec<int> vertOld2New(oldNumVert);
scatter(countAt(0), countAt(static_cast<int>(NumVert())), vertNew2Old.begin(),
vertOld2New.begin());
const bool hasProp = NumProp() > 0;
- for_each(autoPolicy(oldNumVert, 1e5), halfedge_.begin(), halfedge_.end(),
- [&vertOld2New, hasProp](Halfedge& edge) {
- if (edge.startVert < 0) return;
- edge.startVert = vertOld2New[edge.startVert];
- edge.endVert = vertOld2New[edge.endVert];
- if (!hasProp) {
- edge.propVert = edge.startVert;
- }
- });
+ for_each_n(autoPolicy(oldNumVert, 1e5), countAt(0), halfedge_.size(), ctx,
+ [this, &vertOld2New, hasProp](int idx) {
+ const int startVert = halfedge_.Start(idx);
+ if (startVert < 0) return;
+ const int newStart = vertOld2New[startVert];
+ halfedge_.SetStart(idx, newStart);
+ if (!hasProp) {
+ halfedge_.SetProp(idx, newStart);
+ }
+ });
+ if (IsCancelled(ctx)) return;
}
/**
* Removes unreferenced property verts and reindexes propVerts.
*/
-void Manifold::Impl::CompactProps() {
+void Manifold::Impl::CompactProps(ExecutionContext::Impl* ctx) {
ZoneScoped;
if (numProp_ == 0) return;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const int numProp = NumProp();
const auto numVerts = properties_.size() / numProp;
Vec<int> keep(numVerts, 0);
auto policy = autoPolicy(numVerts, 1e5);
- for_each(policy, halfedge_.cbegin(), halfedge_.cend(), [&keep](Halfedge h) {
- reinterpret_cast<std::atomic<int>*>(&keep[h.propVert])
+ for_each_n(policy, countAt(0), halfedge_.size(), ctx, [this, &keep](int idx) {
+ reinterpret_cast<std::atomic<int>*>(&keep[halfedge_.Prop(idx)])
->store(1, std::memory_order_relaxed);
});
+ if (IsCancelled(ctx)) return;
Vec<int> propOld2New(numVerts + 1, 0);
inclusive_scan(keep.begin(), keep.end(), propOld2New.begin() + 1);
@@ -338,7 +356,7 @@ void Manifold::Impl::CompactProps() {
auto& properties = properties_;
properties.resize_nofill(numProp * numVertsNew);
for_each_n(
- policy, countAt(0), numVerts,
+ policy, countAt(0), numVerts, ctx,
[&properties, &oldProp, &propOld2New, &keep, &numProp](const int oldIdx) {
if (keep[oldIdx] == 0) return;
for (int p = 0; p < numProp; ++p) {
@@ -346,10 +364,12 @@ void Manifold::Impl::CompactProps() {
oldProp[oldIdx * numProp + p];
}
});
- for_each(policy, halfedge_.begin(), halfedge_.end(),
- [&propOld2New](Halfedge& edge) {
- edge.propVert = propOld2New[edge.propVert];
- });
+ if (IsCancelled(ctx)) return;
+ for_each_n(policy, countAt(0), halfedge_.size(), ctx,
+ [this, &propOld2New](int idx) {
+ halfedge_.SetProp(idx, propOld2New[halfedge_.Prop(idx)]);
+ });
+ if (IsCancelled(ctx)) return;
}
/**
@@ -358,17 +378,20 @@ void Manifold::Impl::CompactProps() {
* the bounding box.
*/
void Manifold::Impl::GetFaceBoxMorton(Vec<Box>& faceBox,
- Vec<uint32_t>& faceMorton) const {
+ Vec<uint32_t>& faceMorton,
+ ExecutionContext::Impl* ctx) const {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
// faceBox should be initialized
faceBox.resize(NumTri(), Box());
faceMorton.resize_nofill(NumTri());
- for_each_n(autoPolicy(NumTri(), 1e5), countAt(0), NumTri(),
+ for_each_n(autoPolicy(NumTri(), 1e5), countAt(0), NumTri(), ctx,
[this, &faceBox, &faceMorton](const int face) {
// Removed tris are marked by all halfedges having pairedHalfedge
// = -1, and this will sort them to the end (the Morton code only
// uses the first 30 of 32 bits).
- if (halfedge_[3 * face].pairedHalfedge < 0) {
+ if (halfedge_.Pair(3 * face) < 0) {
faceMorton[face] = kNoCode;
return;
}
@@ -376,7 +399,7 @@ void Manifold::Impl::GetFaceBoxMorton(Vec<Box>& faceBox,
vec3 center(0.0);
for (const int i : {0, 1, 2}) {
- const vec3 pos = vertPos_[halfedge_[3 * face + i].startVert];
+ const vec3 pos = vertPos_[halfedge_.Start(3 * face + i)];
center += pos;
faceBox[face].Union(pos);
}
@@ -384,14 +407,18 @@ void Manifold::Impl::GetFaceBoxMorton(Vec<Box>& faceBox,
faceMorton[face] = MortonCode(center, bBox_);
});
+ if (IsCancelled(ctx)) return;
}
/**
* Sorts the faces of this manifold according to their input Morton code. The
* bounding box and Morton code arrays are also sorted accordingly.
*/
-void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) {
+void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
Vec<int> faceNew2Old(NumTri());
sequence(faceNew2Old.begin(), faceNew2Old.end());
@@ -412,7 +439,8 @@ void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) {
Permute(faceMorton, faceNew2Old);
Permute(faceBox, faceNew2Old);
- GatherFaces(faceNew2Old);
+ GatherFaces(faceNew2Old, ctx);
+ if (IsCancelled(ctx)) return;
}
/**
@@ -420,14 +448,18 @@ void Manifold::Impl::SortFaces(Vec<Box>& faceBox, Vec<uint32_t>& faceMorton) {
* another manifold, given by oldHalfedge. Input faceNew2Old defines the old
* faces to gather into this.
*/
-void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old) {
+void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const auto numTri = faceNew2Old.size();
if (meshRelation_.triRef.size() == NumTri())
Permute(meshRelation_.triRef, faceNew2Old);
if (faceNormal_.size() == NumTri()) Permute(faceNormal_, faceNew2Old);
- Vec<Halfedge> oldHalfedge(std::move(halfedge_));
+ Halfedges oldHalfedge(std::move(halfedge_));
+ halfedge_ = Halfedges();
Vec<vec4> oldHalfedgeTangent(std::move(halfedgeTangent_));
Vec<int> faceOld2New(oldHalfedge.size() / 3);
auto policy = autoPolicy(numTri, 1e5);
@@ -437,13 +469,17 @@ void Manifold::Impl::GatherFaces(const Vec<int>& faceNew2Old) {
halfedge_.resize_nofill(3 * numTri);
if (oldHalfedgeTangent.size() != 0)
halfedgeTangent_.resize_nofill(3 * numTri);
- for_each_n(policy, countAt(0), numTri,
- ReindexFace({halfedge_, halfedgeTangent_, oldHalfedge,
- oldHalfedgeTangent, faceNew2Old, faceOld2New}));
+ for_each_n(policy, countAt(0), numTri, ctx,
+ ReindexFace{halfedge_, halfedgeTangent_, oldHalfedge,
+ oldHalfedgeTangent, faceNew2Old, faceOld2New});
+ if (IsCancelled(ctx)) return;
}
-void Manifold::Impl::GatherFaces(const Impl& old, const Vec<int>& faceNew2Old) {
+void Manifold::Impl::GatherFaces(const Impl& old, const Vec<int>& faceNew2Old,
+ ExecutionContext::Impl* ctx) {
ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
const auto numTri = faceNew2Old.size();
meshRelation_.triRef.resize_nofill(numTri);
@@ -472,9 +508,53 @@ void Manifold::Impl::GatherFaces(const Impl& old, const Vec<int>& faceNew2Old) {
halfedge_.resize_nofill(3 * numTri);
if (old.halfedgeTangent_.size() != 0)
halfedgeTangent_.resize_nofill(3 * numTri);
- for_each_n(autoPolicy(numTri, 1e5), countAt(0), numTri,
- ReindexFace({halfedge_, halfedgeTangent_, old.halfedge_,
- old.halfedgeTangent_, faceNew2Old, faceOld2New}));
+ for_each_n(autoPolicy(numTri, 1e5), countAt(0), numTri, ctx,
+ ReindexFace{halfedge_, halfedgeTangent_, old.halfedge_,
+ old.halfedgeTangent_, faceNew2Old, faceOld2New});
+ if (IsCancelled(ctx)) return;
+}
+
+void Manifold::Impl::ReorderHalfedges(ExecutionContext::Impl* ctx) {
+ ZoneScoped;
+ // Invariant: every ctx-passing parallel op is followed by IsCancelled to
+ // keep partial output from feeding unconditional downstream consumers.
+ // halfedges in the same face are added in non-deterministic order, so we have
+ // to reorder them for determinism
+
+ // step 1: reorder within the same face, such that the halfedge with the
+ // smallest starting vertex is placed first
+ for_each(autoPolicy(halfedge_.size() / 3), countAt(0_uz),
+ countAt(halfedge_.size() / 3), ctx, [this](size_t tri) {
+ std::array<Halfedge, 3> face = {halfedge_.Get(tri * 3),
+ halfedge_.Get(tri * 3 + 1),
+ halfedge_.Get(tri * 3 + 2)};
+ if (face[0].startVert < 0) return;
+ int index = 0;
+ for (int i : {1, 2})
+ if (face[i].startVert < face[index].startVert) index = i;
+ for (int i : {0, 1, 2}) {
+ const auto& f = face[(index + i) % 3];
+ halfedge_.Set(tri * 3 + i, f.startVert, f.pairedHalfedge,
+ f.propVert);
+ }
+ });
+ if (IsCancelled(ctx)) return;
+ // step 2: fix paired halfedge
+ for_each(autoPolicy(halfedge_.size() / 3), countAt(0_uz),
+ countAt(halfedge_.size() / 3), ctx, [this](size_t tri) {
+ for (int i : {0, 1, 2}) {
+ const int currIdx = tri * 3 + i;
+ const int startVert = halfedge_.Start(currIdx);
+ if (startVert < 0) return;
+ int oppositeFace = halfedge_.Pair(currIdx) / 3;
+ int index = -1;
+ for (int j : {0, 1, 2})
+ if (startVert == halfedge_.End(oppositeFace * 3 + j))
+ index = j;
+ halfedge_.SetPair(currIdx, oppositeFace * 3 + index);
+ }
+ });
+ if (IsCancelled(ctx)) return;
}
/**
@@ -500,4 +580,5 @@ template <>
bool MeshGL64::Merge() {
return MergeMeshGLP(*this);
}
+
} // namespace manifold
diff --git a/thirdparty/manifold/src/subdivision.cpp b/thirdparty/manifold/src/subdivision.cpp
index 6aa855f6fdd..c1ac24b3534 100644
--- a/thirdparty/manifold/src/subdivision.cpp
+++ b/thirdparty/manifold/src/subdivision.cpp
@@ -116,7 +116,7 @@ class Partition {
const int offset = interiorOffset - newVerts.size();
size_t old = newVerts.size();
newVerts.resize_nofill(vertBary.size());
- std::iota(newVerts.begin() + old, newVerts.end(), old + offset);
+ std::iota(newVerts.begin() + old, newVerts.end(), interiorOffset);
const int numTri = triVert.size();
Vec<ivec3> newTriVert(numTri);
@@ -409,7 +409,7 @@ ivec4 Manifold::Impl::GetHalfedges(int tri) const {
}
const int neighbor = GetNeighbor(tri);
if (neighbor >= 0) { // quad
- const int pair = halfedge_[3 * tri + neighbor].pairedHalfedge;
+ const int pair = halfedge_.Pair(3 * tri + neighbor);
if (pair / 3 < tri) {
return ivec4(-1); // only process lower tri index
}
@@ -440,7 +440,7 @@ Manifold::Impl::BaryIndices Manifold::Impl::GetIndices(int halfedge) const {
if (neighbor < 0) { // tri
return {tri, idx, Next3(idx)};
} else { // quad
- const int pair = halfedge_[3 * tri + neighbor].pairedHalfedge;
+ const int pair = halfedge_.Pair(3 * tri + neighbor);
if (pair / 3 < tri) {
tri = pair / 3;
idx = Next3(neighbor) == idx ? 0 : 1;
@@ -465,7 +465,7 @@ void Manifold::Impl::FillRetainedVerts(Vec<Barycentric>& vertBary) const {
if (indices.start4 < 0) continue; // skip quad interiors
vec4 uvw(0.0);
uvw[indices.start4] = 1;
- vertBary[halfedge_[3 * tri + i].startVert] = {indices.tri, uvw};
+ vertBary[halfedge_.Start(3 * tri + i)] = {indices.tri, uvw};
}
}
}
@@ -479,6 +479,7 @@ void Manifold::Impl::FillRetainedVerts(Vec<Barycentric>& vertBary) const {
*/
Vec<Barycentric> Manifold::Impl::Subdivide(
std::function<int(vec3, vec4, vec4)> edgeDivisions, bool keepInterior) {
+ halfedge_.MakeUnique();
Vec<TmpEdge> edges = CreateTmpEdges(halfedge_);
const int numVert = NumVert();
const int numEdge = edges.size();
@@ -489,7 +490,7 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
[&half2Edge, &edges, this](const int edge) {
const int idx = edges[edge].halfedgeIdx;
half2Edge[idx] = edge;
- half2Edge[halfedge_[idx].pairedHalfedge] = edge;
+ half2Edge[halfedge_.Pair(idx)] = edge;
});
Vec<ivec4> faceHalfedges(numTri);
@@ -498,24 +499,23 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
});
Vec<int> edgeAdded(numEdge);
- for_each_n(policy, countAt(0), numEdge,
- [&edgeAdded, &edges, edgeDivisions, this](const int i) {
- const TmpEdge edge = edges[i];
- const int hIdx = edge.halfedgeIdx;
- if (IsMarkedInsideQuad(hIdx)) {
- edgeAdded[i] = 0;
- return;
- }
- const vec3 vec = vertPos_[edge.first] - vertPos_[edge.second];
- const vec4 tangent0 = halfedgeTangent_.empty()
- ? vec4(0.0)
- : halfedgeTangent_[hIdx];
- const vec4 tangent1 =
- halfedgeTangent_.empty()
- ? vec4(0.0)
- : halfedgeTangent_[halfedge_[hIdx].pairedHalfedge];
- edgeAdded[i] = edgeDivisions(vec, tangent0, tangent1);
- });
+ for_each_n(
+ policy, countAt(0), numEdge,
+ [&edgeAdded, &edges, edgeDivisions, this](const int i) {
+ const TmpEdge edge = edges[i];
+ const int hIdx = edge.halfedgeIdx;
+ if (IsMarkedInsideQuad(hIdx)) {
+ edgeAdded[i] = 0;
+ return;
+ }
+ const vec3 vec = vertPos_[edge.first] - vertPos_[edge.second];
+ const vec4 tangent0 =
+ halfedgeTangent_.empty() ? vec4(0.0) : halfedgeTangent_[hIdx];
+ const vec4 tangent1 = halfedgeTangent_.empty()
+ ? vec4(0.0)
+ : halfedgeTangent_[halfedge_.Pair(hIdx)];
+ edgeAdded[i] = edgeDivisions(vec, tangent0, tangent1);
+ });
if (keepInterior) {
// Triangles where the greatest number of divisions exceeds the sum of the
@@ -551,12 +551,13 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
}
const int minExtra = longest * 0.2 + 1;
const int extra = 2 * longest + minExtra - total;
+ if (longest == 0) return 0;
return extra > 0 ? (extra * (longest - thisAdded)) / longest : 0;
};
- tmp[i] += la::max(Added(hIdx), Added(halfedge_[hIdx].pairedHalfedge));
+ tmp[i] += la::max(Added(hIdx), Added(halfedge_.Pair(hIdx)));
});
- edgeAdded.swap(tmp);
+ edgeAdded = std::move(tmp);
}
Vec<int> edgeOffset(numEdge);
@@ -619,10 +620,11 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
Vec<ivec3> triVerts(triOffset.back() + subTris.back().triVert.size());
vertBary.resize(interiorOffset.back() + subTris.back().NumInterior());
Vec<TriRef> triRef(triVerts.size());
+ Vec<vec3> faceNormal(triVerts.size());
for_each_n(
policy, countAt(0), numTri,
[this, &triVerts, &triRef, &vertBary, &subTris, &edgeOffset, &half2Edge,
- &triOffset, &interiorOffset, &faceHalfedges](int tri) {
+ &triOffset, &interiorOffset, &faceHalfedges, &faceNormal](int tri) {
const ivec4 halfedges = faceHalfedges[tri];
if (halfedges[0] < 0) return;
ivec4 tri3;
@@ -633,17 +635,18 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
tri3[i] = -1;
continue;
}
- const Halfedge& halfedge = halfedge_[halfedges[i]];
- tri3[i] = halfedge.startVert;
+ tri3[i] = halfedge_.Start(halfedges[i]);
edgeOffsets[i] = edgeOffset[half2Edge[halfedges[i]]];
- edgeFwd[i] = halfedge.IsForward();
+ edgeFwd[i] = halfedge_.IsForward(halfedges[i]);
}
Vec<ivec3> newTris = subTris[tri].Reindex(tri3, edgeOffsets, edgeFwd,
interiorOffset[tri]);
copy(newTris.begin(), newTris.end(), triVerts.begin() + triOffset[tri]);
- auto start = triRef.begin() + triOffset[tri];
- fill(start, start + newTris.size(), meshRelation_.triRef[tri]);
+ auto startRef = triRef.begin() + triOffset[tri];
+ fill(startRef, startRef + newTris.size(), meshRelation_.triRef[tri]);
+ auto startN = faceNormal.begin() + triOffset[tri];
+ fill(startN, startN + newTris.size(), faceNormal_[tri]);
const ivec4 idx = subTris[tri].idx;
const ivec4 vIdx = halfedges[3] >= 0 || idx[1] == Next3(idx[0])
@@ -663,7 +666,8 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
bary[rIdx[2]], bary[rIdx[3]]}});
});
});
- meshRelation_.triRef = triRef;
+ meshRelation_.triRef = std::move(triRef);
+ faceNormal_ = std::move(faceNormal);
Vec<vec3> newVertPos(vertBary.size());
for_each_n(policy, countAt(0), vertBary.size(),
@@ -673,21 +677,19 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
if (halfedges[3] < 0) {
mat3 triPos;
for (const int i : {0, 1, 2}) {
- triPos[i] = vertPos_[halfedge_[halfedges[i]].startVert];
+ triPos[i] = vertPos_[halfedge_.Start(halfedges[i])];
}
newVertPos[vert] = triPos * vec3(bary.uvw);
} else {
mat3x4 quadPos;
for (const int i : {0, 1, 2, 3}) {
- quadPos[i] = vertPos_[halfedge_[halfedges[i]].startVert];
+ quadPos[i] = vertPos_[halfedge_.Start(halfedges[i])];
}
newVertPos[vert] = quadPos * bary.uvw;
}
});
vertPos_ = newVertPos;
- faceNormal_.clear();
-
if (numProp_ > 0) {
const int numPropVert = NumPropVert();
const int addedVerts = NumVert() - numVert;
@@ -715,15 +717,14 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
vec3 triProp;
for (const int i : {0, 1, 2}) {
triProp[i] =
- properties_[halfedge_[3 * bary.tri + i].propVert * numProp +
- p];
+ properties_[halfedge_.Prop(3 * bary.tri + i) * numProp + p];
}
prop[vert * numProp + p] = la::dot(triProp, vec3(bary.uvw));
} else {
vec4 quadProp;
for (const int i : {0, 1, 2, 3}) {
quadProp[i] =
- properties_[halfedge_[halfedges[i]].propVert * numProp + p];
+ properties_[halfedge_.Prop(halfedges[i]) * numProp + p];
}
prop[vert * numProp + p] = la::dot(quadProp, bary.uvw);
}
@@ -740,11 +741,9 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
const int numProp = NumProp();
const double frac = 1.0 / (n + 1);
- const int halfedgeIdx =
- halfedge_[edges[i].halfedgeIdx].pairedHalfedge;
- const int prop0 = halfedge_[halfedgeIdx].propVert;
- const int prop1 =
- halfedge_[NextHalfedge(halfedgeIdx)].propVert;
+ const int halfedgeIdx = halfedge_.Pair(edges[i].halfedgeIdx);
+ const int prop0 = halfedge_.Prop(halfedgeIdx);
+ const int prop1 = halfedge_.Prop(NextHalfedge(halfedgeIdx));
for (int i = 0; i < n; ++i) {
for (int p = 0; p < numProp; ++p) {
prop[(offset + i) * numProp + p] = la::lerp(
@@ -755,45 +754,44 @@ Vec<Barycentric> Manifold::Impl::Subdivide(
});
Vec<ivec3> triProp(triVerts.size());
- for_each_n(
- policy, countAt(0), numTri,
- [this, &triProp, &subTris, &edgeOffset, &half2Edge, &triOffset,
- &interiorOffset, &faceHalfedges, propOffset,
- addedVerts](const int tri) {
- const ivec4 halfedges = faceHalfedges[tri];
- if (halfedges[0] < 0) return;
-
- ivec4 tri3;
- ivec4 edgeOffsets;
- bvec4 edgeFwd(true);
- for (const int i : {0, 1, 2, 3}) {
- if (halfedges[i] < 0) {
- tri3[i] = -1;
- continue;
- }
- const Halfedge& halfedge = halfedge_[halfedges[i]];
- tri3[i] = halfedge.propVert;
- edgeOffsets[i] = edgeOffset[half2Edge[halfedges[i]]];
- if (!halfedge.IsForward()) {
- if (halfedge_[halfedge.pairedHalfedge].propVert !=
- halfedge_[NextHalfedge(halfedges[i])].propVert ||
- halfedge_[NextHalfedge(halfedge.pairedHalfedge)].propVert !=
- halfedge.propVert) {
- // if the edge doesn't match, point to the backward edge
- // propverts.
- edgeOffsets[i] += addedVerts;
- } else {
- edgeFwd[i] = false;
- }
- }
- }
+ for_each_n(policy, countAt(0), numTri,
+ [this, &triProp, &subTris, &edgeOffset, &half2Edge, &triOffset,
+ &interiorOffset, &faceHalfedges, propOffset,
+ addedVerts](const int tri) {
+ const ivec4 halfedges = faceHalfedges[tri];
+ if (halfedges[0] < 0) return;
+
+ ivec4 tri3;
+ ivec4 edgeOffsets;
+ bvec4 edgeFwd(true);
+ for (const int i : {0, 1, 2, 3}) {
+ if (halfedges[i] < 0) {
+ tri3[i] = -1;
+ continue;
+ }
+ tri3[i] = halfedge_.Prop(halfedges[i]);
+ edgeOffsets[i] = edgeOffset[half2Edge[halfedges[i]]];
+ if (!halfedge_.IsForward(halfedges[i])) {
+ const int pair = halfedge_.Pair(halfedges[i]);
+ if (halfedge_.Prop(pair) !=
+ halfedge_.Prop(NextHalfedge(halfedges[i])) ||
+ halfedge_.Prop(NextHalfedge(pair)) !=
+ halfedge_.Prop(halfedges[i])) {
+ // if the edge doesn't match, point to the backward edge
+ // propverts.
+ edgeOffsets[i] += addedVerts;
+ } else {
+ edgeFwd[i] = false;
+ }
+ }
+ }
- Vec<ivec3> newTris =
- subTris[tri].Reindex(tri3, edgeOffsets + propOffset, edgeFwd,
- interiorOffset[tri] + propOffset);
- copy(newTris.begin(), newTris.end(),
- triProp.begin() + triOffset[tri]);
- });
+ Vec<ivec3> newTris = subTris[tri].Reindex(
+ tri3, edgeOffsets + propOffset, edgeFwd,
+ interiorOffset[tri] + propOffset);
+ copy(newTris.begin(), newTris.end(),
+ triProp.begin() + triOffset[tri]);
+ });
properties_ = prop;
CreateHalfedges(triProp, triVerts);
diff --git a/thirdparty/manifold/src/svd.h b/thirdparty/manifold/src/svd.h
index 3978a174153..cad9b4fbc19 100644
--- a/thirdparty/manifold/src/svd.h
+++ b/thirdparty/manifold/src/svd.h
@@ -92,7 +92,7 @@ inline double Dist2(vec3 v) { return manifold::la::dot(v, v); }
inline Givens ApproximateGivensQuaternion(Symmetric3x3& A) {
Givens g{2.0 * (A.m_00 - A.m_11), A.m_10};
bool b = _gamma * g.sh * g.sh < g.ch * g.ch;
- double w = 1.0 / hypot(g.ch, g.sh);
+ double w = 1.0 / std::sqrt(g.ch * g.ch + g.sh * g.sh);
if (!std::isfinite(w)) b = 0;
return Givens{b ? w * g.ch : _cStar, b ? w * g.sh : _sStar};
}
@@ -190,11 +190,11 @@ inline Givens QRGivensQuaternion(double a1, double a2) {
// a1 = pivot point on diagonal
// a2 = lower triangular entry we want to annihilate
double epsilon = _SVD_EPSILON;
- double rho = hypot(a1, a2);
+ double rho = std::sqrt(a1 * a1 + a2 * a2);
Givens g{fabs(a1) + fmax(rho, epsilon), rho > epsilon ? a2 : 0};
bool b = a1 < 0.0;
CondSwap(b, g.sh, g.ch);
- double w = 1.0 / hypot(g.ch, g.sh);
+ double w = 1.0 / std::sqrt(g.ch * g.ch + g.sh * g.sh);
g.ch *= w;
g.sh *= w;
return g;
diff --git a/thirdparty/manifold/src/utils.h b/thirdparty/manifold/src/utils.h
index 07fde0ce1fe..724e11dd0cc 100644
--- a/thirdparty/manifold/src/utils.h
+++ b/thirdparty/manifold/src/utils.h
@@ -34,28 +34,8 @@
#include "parallel.h"
-#if __has_include(<tracy/Tracy.hpp>)
-#include <tracy/Tracy.hpp>
-#else
-#define FrameMarkStart(x)
-#define FrameMarkEnd(x)
-// putting ZoneScoped in a function will instrument the function execution when
-// TRACY_ENABLE is set, which allows the profiler to record more accurate
-// timing.
-#define ZoneScoped
-#define ZoneScopedN(name)
-#endif
-
namespace manifold {
-/**
- * Stand-in for C++23's operator""uz (P0330R8)[https://wg21.link/P0330R8].
- */
-[[nodiscard]] constexpr std::size_t operator""_uz(
- unsigned long long n) noexcept {
- return n;
-}
-
constexpr double kPrecision = 1e-12;
inline int Next3(int i) {
diff --git a/thirdparty/manifold/src/vec.h b/thirdparty/manifold/src/vec.h
index fcb1e4f93cc..a316a3bd8ae 100644
--- a/thirdparty/manifold/src/vec.h
+++ b/thirdparty/manifold/src/vec.h
@@ -19,6 +19,18 @@
#define TracyAllocS(ptr, size, n) (void)0
#define TracyFreeS(ptr, n) (void)0
#endif
+
+#if __has_include(<tracy/Tracy.hpp>)
+#include <tracy/Tracy.hpp>
+#else
+#define FrameMarkStart(x)
+#define FrameMarkEnd(x)
+// putting ZoneScoped in a function will instrument the function execution when
+// TRACY_ENABLE is set, which allows the profiler to record more accurate
+// timing.
+#define ZoneScoped
+#define ZoneScopedN(name)
+#endif
#include <vector>
#include "manifold/vec_view.h"
@@ -26,13 +38,20 @@
namespace manifold {
-#if (MANIFOLD_PAR == 1)
-extern tbb::task_arena gc_arena;
-#endif
+struct Empty {};
-template <typename T>
+template <typename T, bool shared = false>
class Vec;
+// Shareable vector that forbids structural update when shared.
+// Note that if you do `Vec<T>& vec = sharedVec`, this will perform a copy,
+// so please do `SharedVec<T>& vec = shareVec` instead.
+//
+// The copy constructor and copy assignment operator will share the
+// underlying vector.
+template <typename T>
+using SharedVec = Vec<T, true>;
+
/*
* Specialized vector implementation with multithreaded fill and uninitialized
* memory optimizations.
@@ -41,36 +60,61 @@ class Vec;
* implementation that did not consider things like non-trivial
* constructor/destructor, please keep T trivial.
*/
-template <typename T>
+template <typename T, bool shared>
class Vec : public VecView<T> {
public:
- Vec() {}
+ Vec() : VecView<T>() {
+ if constexpr (shared) count_ = new std::atomic<int>(1);
+ }
// Note that the vector constructed with this constructor will contain
// uninitialized memory. Please specify `val` if you need to make sure that
// the data is initialized.
- Vec(size_t size) : VecView<T>() {
+ inline Vec(size_t size) : VecView<T>() {
+ ZoneScopedN("Vec(size)");
+ if constexpr (shared) count_ = new std::atomic<int>(1);
reserve(size);
this->size_ = size;
}
- Vec(size_t size, T val) : VecView<T>() { resize(size, val); }
+ inline Vec(size_t size, T val) : VecView<T>() {
+ ZoneScopedN("Vec(size, val)");
+ if constexpr (shared) count_ = new std::atomic<int>(1);
+ resize(size, val);
+ }
- Vec(const Vec<T>& vec) : VecView<T>() { *this = Vec(vec.view()); }
+ // manually specialized because copy constructor and copy assignment operators
+ // cannot be template methods
+ inline Vec(const Vec<T, true>& vec) : VecView<T>() {
+ ZoneScopedN("Vec(const vec&)");
+ // initialized with operator=
+ if constexpr (shared) count_ = nullptr;
+ *this = Vec(vec.view());
+ }
- Vec(const VecView<const T>& vec) : VecView<T>() {
- this->size_ = vec.size();
- this->capacity_ = this->size_;
- auto policy = autoPolicy(this->size_);
- if (this->size_ != 0) {
- this->ptr_ = reinterpret_cast<T*>(malloc(this->size_ * sizeof(T)));
- ASSERT(this->ptr_ != nullptr, std::bad_alloc());
- TracyAllocS(this->ptr_, this->size_ * sizeof(T), 3);
- copy(policy, vec.begin(), vec.end(), this->ptr_);
+ inline Vec(const Vec<T, false>& vec) : VecView<T>() {
+ ZoneScopedN("Vec(const vec&)");
+ // initialized with operator=
+ if constexpr (shared) count_ = nullptr;
+ *this = Vec(vec.view());
+ }
+
+ inline Vec(Vec<T, true>&& other) : VecView<T>() {
+ if constexpr (shared) {
+ this->count_ = other.count_;
+ other.count_ = nullptr;
}
+ moveContent(other);
}
- Vec(const std::vector<T>& vec) : VecView<T>() {
+ inline Vec(Vec<T, false>&& other) : VecView<T>() {
+ if constexpr (shared) this->count_ = new std::atomic<int>(1);
+ moveContent(other);
+ }
+
+ inline Vec(const VecView<const T>& vec) : VecView<T>() {
+ ZoneScopedN("Vec(const VecView&)");
+ if constexpr (shared) this->count_ = new std::atomic<int>(1);
this->size_ = vec.size();
this->capacity_ = this->size_;
auto policy = autoPolicy(this->size_);
@@ -82,34 +126,28 @@ class Vec : public VecView<T> {
}
}
- Vec(Vec<T>&& vec) : VecView<T>() {
- this->ptr_ = vec.ptr_;
- this->size_ = vec.size_;
- capacity_ = vec.capacity_;
- vec.ptr_ = nullptr;
- vec.size_ = 0;
- vec.capacity_ = 0;
- }
+ inline Vec(const std::vector<T>& vec)
+ : Vec<T>(VecView<const T>(vec.data(), vec.size())) {}
- operator VecView<T>() { return {this->ptr_, this->size_}; }
- operator VecView<const T>() const { return {this->ptr_, this->size_}; }
+ inline operator VecView<T>() { return {this->ptr_, this->size_}; }
+ inline operator VecView<T>() const { return {this->ptr_, this->size_}; }
- ~Vec() {
- if (this->ptr_ != nullptr) {
- free_async(this->ptr_, capacity_);
- }
- this->ptr_ = nullptr;
- this->size_ = 0;
- capacity_ = 0;
- }
+ ~Vec() { dealloc(); }
- Vec<T>& operator=(const Vec<T>& other) {
+ Vec& operator=(const Vec& other) {
+ ZoneScopedN("Vec operator=(other)");
if (&other == this) return *this;
- if (this->ptr_ != nullptr) {
- free_async(this->ptr_, capacity_);
+ dealloc();
+ if constexpr (shared) {
+ other.count_->fetch_add(1);
+ this->count_ = other.count_;
+ this->ptr_ = other.ptr_;
+ this->size_ = other.size_;
+ this->capacity_ = other.capacity_;
+ return *this;
}
this->size_ = other.size_;
- capacity_ = other.size_;
+ this->capacity_ = other.size_;
if (this->size_ != 0) {
this->ptr_ = reinterpret_cast<T*>(malloc(this->size_ * sizeof(T)));
ASSERT(this->ptr_ != nullptr, std::bad_alloc());
@@ -119,29 +157,50 @@ class Vec : public VecView<T> {
return *this;
}
- Vec<T>& operator=(Vec<T>&& other) {
+ inline Vec<T, shared>& operator=(const Vec<T, !shared>& other) {
+ ZoneScopedN("Vec operator=(other)");
+ dealloc();
+ if constexpr (shared) this->count_ = new std::atomic<int>(1);
+ this->size_ = other.size_;
+ this->capacity_ = other.size_;
+ if (this->size_ != 0) {
+ this->ptr_ = reinterpret_cast<T*>(malloc(this->size_ * sizeof(T)));
+ ASSERT(this->ptr_ != nullptr, std::bad_alloc());
+ TracyAllocS(this->ptr_, this->size_ * sizeof(T), 3);
+ manifold::copy(other.begin(), other.end(), this->ptr_);
+ }
+ return *this;
+ }
+
+ inline Vec& operator=(Vec&& other) {
if (&other == this) return *this;
- if (this->ptr_ != nullptr) {
- free_async(this->ptr_, capacity_);
+ dealloc();
+ if constexpr (shared) {
+ this->count_ = other.count_;
+ other.count_ = nullptr;
}
- this->size_ = other.size_;
- capacity_ = other.capacity_;
- this->ptr_ = other.ptr_;
- other.ptr_ = nullptr;
- other.size_ = 0;
- other.capacity_ = 0;
+ moveContent(other);
return *this;
}
- operator VecView<T>() const { return {this->ptr_, this->size_}; }
+ inline Vec<T, shared>& operator=(Vec<T, !shared>&& other) {
+ dealloc();
+ if constexpr (shared) this->count_ = new std::atomic<int>(1);
+ moveContent(other);
+ return *this;
+ }
- void swap(Vec<T>& other) {
+ template <bool shared2>
+ void swap(Vec<T, shared2>& other) {
+ AssertUnique();
+ if constexpr (shared2) other.AssertUnique();
std::swap(this->ptr_, other.ptr_);
std::swap(this->size_, other.size_);
std::swap(capacity_, other.capacity_);
}
inline void push_back(const T& val) {
+ AssertUnique();
if (this->size_ >= capacity_) {
// avoid dangling pointer in case val is a reference of our array
T val_copy = val;
@@ -152,13 +211,15 @@ class Vec : public VecView<T> {
this->ptr_[this->size_++] = val;
}
- inline void extend(size_t n) {
+ void extend(size_t n) {
+ AssertUnique();
if (this->size_ + n >= capacity_)
reserve(capacity_ == 0 ? 128 : std::max(capacity_ * 2, this->size_ + n));
this->size_ += n;
}
void reserve(size_t n) {
+ AssertUnique();
if (n > capacity_) {
T* newBuffer = reinterpret_cast<T*>(malloc(n * sizeof(T)));
ASSERT(newBuffer != nullptr, std::bad_alloc());
@@ -167,7 +228,8 @@ class Vec : public VecView<T> {
manifold::copy(autoPolicy(this->size_), this->ptr_,
this->ptr_ + this->size_, newBuffer);
if (this->ptr_ != nullptr) {
- free_async(this->ptr_, capacity_);
+ TracyFreeS(this->ptr_, 3);
+ free(this->ptr_);
}
this->ptr_ = newBuffer;
capacity_ = n;
@@ -175,9 +237,10 @@ class Vec : public VecView<T> {
}
void resize(size_t newSize, T val = T()) {
+ AssertUnique();
bool shrink = this->size_ > 2 * newSize && this->size_ > 16;
- reserve(newSize);
if (this->size_ < newSize) {
+ reserve(newSize);
fill(autoPolicy(newSize - this->size_), this->ptr_ + this->size_,
this->ptr_ + newSize, val);
}
@@ -185,21 +248,27 @@ class Vec : public VecView<T> {
if (shrink) shrink_to_fit();
}
- void resize_nofill(size_t newSize) {
+ inline void resize_nofill(size_t newSize) {
+ AssertUnique();
bool shrink = this->size_ > 2 * newSize && this->size_ > 16;
reserve(newSize);
this->size_ = newSize;
if (shrink) shrink_to_fit();
}
- void pop_back() { resize_nofill(this->size_ - 1); }
+ inline void pop_back() {
+ AssertUnique();
+ resize_nofill(this->size_ - 1);
+ }
void clear(bool shrink = true) {
+ AssertUnique();
this->size_ = 0;
if (shrink) shrink_to_fit();
}
void shrink_to_fit() {
+ AssertUnique();
T* newBuffer = nullptr;
if (this->size_ > 0) {
newBuffer = reinterpret_cast<T*>(malloc(this->size_ * sizeof(T)));
@@ -208,36 +277,70 @@ class Vec : public VecView<T> {
manifold::copy(this->ptr_, this->ptr_ + this->size_, newBuffer);
}
if (this->ptr_ != nullptr) {
- free_async(this->ptr_, capacity_);
+ TracyFreeS(this->ptr_, 3);
+ free(this->ptr_);
}
this->ptr_ = newBuffer;
capacity_ = this->size_;
}
- size_t capacity() const { return capacity_; }
+ inline size_t capacity() const { return capacity_; }
+
+ // Makes the SharedVec unique, so mutation operations are allowed.
+ // Note that this does nothing if the vector is already unique.
+ void MakeUnique() {
+ if constexpr (shared) {
+ if (count_->load() > 1) {
+ *this = Vec<T, true>(this->view());
+ }
+ }
+ }
private:
size_t capacity_ = 0;
- static_assert(std::is_trivially_destructible<T>::value);
-
- static void free_async(T* ptr, size_t size) {
- // Only do async free if the size is large, because otherwise we may be able
- // to reuse the allocation, and the deallocation probably won't trigger
- // munmap.
- // Currently it is set to 64 pages (4kB page).
- constexpr size_t ASYNC_FREE_THRESHOLD = 1 << 18;
- TracyFreeS(ptr, 3);
-#if defined(__has_feature)
-#if !__has_feature(address_sanitizer)
-#if (MANIFOLD_PAR == 1)
- if (size * sizeof(T) > ASYNC_FREE_THRESHOLD)
- gc_arena.enqueue([ptr]() { free(ptr); });
- else
-#endif
+ // Normally empty structs have size 1 (1 byte) to ensure every field has a
+ // unique address, but in c++20 no_unique_address can avoid this and the field
+ // takes no space.
+#if __cplusplus >= 202002L
+ [[no_unique_address]]
#endif
-#endif
- free(ptr);
+ std::conditional_t<shared, std::atomic<int>*, Empty> count_;
+
+ inline void AssertUnique() const {
+ if constexpr (shared) {
+ ASSERT(count_->load() == 1, logicErr("can only mutate unique vector"));
+ }
+ }
+
+ inline void dealloc() {
+ if constexpr (shared) {
+ if (count_ == nullptr || count_->fetch_sub(1) > 1) return;
+ delete count_;
+ this->count_ = nullptr;
+ }
+ if (this->ptr_ != nullptr) {
+ TracyFreeS(this->ptr_, 3);
+ free(this->ptr_);
+ }
+ this->ptr_ = nullptr;
+ this->size_ = 0;
+ this->capacity_ = 0;
}
+
+ template <typename V>
+ inline void moveContent(V&& other) {
+ this->ptr_ = other.ptr_;
+ this->size_ = other.size_;
+ this->capacity_ = other.capacity_;
+ other.ptr_ = nullptr;
+ other.size_ = 0;
+ other.capacity_ = 0;
+ }
+
+ static_assert(std::is_trivially_destructible<T>::value);
+ // This is required so we can access private fields between shared and
+ // non-shared vectors.
+ friend Vec<T, !shared>;
};
} // namespace manifold