Files
ViewDesignEngine/src/mesh/halfedge_mesh.cpp
T
hm d2f0a40d10 fix(brep,mesh): entity diagnostics/ref validation + robust polygon triangulation (VDE-1342..1345, 1.0.176)
- VDE-1345 mesh: to_mcm ear-clips n>3 faces (Newell normal + 2D ear clipping,
  fallback to fan on degeneracy) and maps local triangle indices back to face
  vertices; empty HalfedgeMesh/PointCloud bounds return a finite zero box;
  faces_range()/vertex_one_ring() implemented (FaceRange iterator, adjacency
  from vertex outgoing half-edges).
- VDE-1342 FeatureNode: last_error()/last_evaluate_ok() diagnostics, stronger
  boolean success predicate, invalid primitive/edit parameters throw
  std::invalid_argument instead of being silently clamped.
- VDE-1343 edit_feature: face_ids range validation before the no-op early
  return, analytic hole location first, warnings on geometric fallback,
  15% radial consistency check between reference faces and matched hole.
- VDE-1344 rebind_entity: id hit now verified against the anchor distance
  (vertex/edge/face), falls back to nearest-anchor match, returns -1 when
  still mismatched; Body rebinds through anchor's nearest face.
- Tests: test_mesh_1177_fixes 11 cases, test_entity_1177_fixes 12 cases;
  registry 8,339 -> 8,362; full CTest 8,362/8,362 passed, 0 failed, 35 SKIP,
  635.55 s; release checks 14/14 PASS, report-check latest=224.
- Docs: report 224 (self-verification), verifier report 223 (1.0.175 PASS)
  included, RegressionExtreme count corrected to 10/10 (P3-1).
  Mesh VDE id renumbered 1341 -> 1345 to avoid collision with upstream
  docs/feedback/VDE-1341 (shell_multi).
2026-11-07 03:53:07 +08:00

738 lines
29 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file halfedge_mesh.cpp
* @brief 半边数据结构三角网格(Half-edge Mesh)实现
*/
#include "vde/mesh/halfedge_mesh.h"
#include "vde/mesh/marching_cubes.h"
#include <algorithm>
#include <cmath>
#include <utility>
#ifdef VDE_USE_OPENMP
#include <omp.h>
#endif
namespace vde::mesh {
namespace {
/// 顶点索引对打包为 64 位键:高 32 位 = min(v0,v1),低 32 位 = max(v0,v1)。
inline std::uint64_t edge_key(int a, int b) {
const std::uint32_t lo = static_cast<std::uint32_t>(a < b ? a : b);
const std::uint32_t hi = static_cast<std::uint32_t>(a < b ? b : a);
return (static_cast<std::uint64_t>(lo) << 32) | hi;
}
inline std::uint64_t mix64(std::uint64_t x) {
x ^= x >> 30;
x *= 0xBF58476D1CE4E5B9ull;
x ^= x >> 27;
x *= 0x94D049BB133111EBull;
x ^= x >> 31;
return x;
}
/// build_from_triangles 专用开放寻址无向边表。
///
/// 旧实现每条边在 std::unordered_map<pair<int,int>,int> 中分配一个节点,
/// 大网格(百万级三角形)建拓扑时 malloc 与指针追逐占主导(实测 2M 三角形
/// 约 4.1s)。此处改为内存连续的开放寻址表(负载 < 0.75),键为 64 位紧凑
/// 边键,构建结束后立即释放,并让持久成员 edge_map_ 惰性重建。
class TriangleEdgeTable {
public:
explicit TriangleEdgeTable(std::size_t triangle_count) {
std::size_t capacity = 256;
const std::size_t want = triangle_count * 3 / 2 + 16;
while (capacity < want * 2) capacity <<= 1; // 负载上限约 0.5
slots_.assign(capacity, Slot{});
mask_ = capacity - 1;
}
/// 查找边键;命中返回槽位下标,未命中返回空槽位下标(he < 0)。
std::size_t slot_of(std::uint64_t key) const {
std::size_t i = static_cast<std::size_t>(mix64(key)) & mask_;
while (slots_[i].he >= 0 && slots_[i].key != key) i = (i + 1) & mask_;
return i;
}
/// 记录边键对应的首条半边(仅首次插入生效)。
void insert(std::size_t slot, std::uint64_t key, int he0) {
slots_[slot].key = key;
slots_[slot].he = he0;
}
[[nodiscard]] int halfedge_at(std::size_t slot) const { return slots_[slot].he; }
private:
struct Slot {
std::uint64_t key = 0;
int he = -1;
};
std::vector<Slot> slots_;
std::size_t mask_ = 0;
};
/// 从面记录直接计算几何法向:取面首条半边链上的前三个顶点,
/// 返回 (v1-v0)×(v2-v0) 归一化结果。与 face_normal() 直接计算路径逐位一致。
/// 面首条半边链不足 3 个有效顶点时返回 +Z(与历史行为一致)。
Vector3D face_normal_from_face(const std::vector<Point3D>& vertices,
const std::vector<Halfedge>& halfedges,
const Face& f) {
if (f.valence < 3 || f.halfedge_index < 0) return Vector3D::UnitZ();
int v[3] = {-1, -1, -1};
int he = f.halfedge_index;
for (int k = 0; k < 3; ++k) {
if (he < 0 || static_cast<std::size_t>(he) >= halfedges.size()) break;
v[k] = halfedges[static_cast<std::size_t>(he)].vertex_index;
he = halfedges[static_cast<std::size_t>(he)].next_index;
}
if (v[0] < 0 || v[1] < 0 || v[2] < 0) return Vector3D::UnitZ();
const std::size_t nv = vertices.size();
if (static_cast<std::size_t>(v[0]) >= nv || static_cast<std::size_t>(v[1]) >= nv ||
static_cast<std::size_t>(v[2]) >= nv) {
return Vector3D::UnitZ();
}
const Vector3D v0 = vertices[static_cast<std::size_t>(v[1])] -
vertices[static_cast<std::size_t>(v[0])];
const Vector3D v1 = vertices[static_cast<std::size_t>(v[2])] -
vertices[static_cast<std::size_t>(v[0])];
return v0.cross(v1).normalized();
}
/// 多边形耳切三角化(VDE-1345)。
///
/// to_mcm() 旧实现对所有非三角面一律从 v0 扇形分割,凹多边形会生成越界三角形
/// (三角形落在多边形外/相互重叠)。此处在最佳拟合平面上做 2D 耳切:
/// - Newell 法向给出平面与朝向;
/// - 以首边为 u 轴、normal×u 为 v 轴投影;
/// - 按投影有向面积确定绕向,凹顶点(叉积 <= 0)不可作为耳;
/// - 耳三角形内不得含其它环顶点(含边界视为不可切),避免自交多边形误切。
/// 失败(共线/自交/退化)返回 false,由调用方回退扇形分割。
bool triangulate_polygon_face(const std::vector<Point3D>& pts,
std::vector<std::array<int, 3>>& out) {
const std::size_t n = pts.size();
if (n < 3) return false;
if (n == 3) {
out.push_back({0, 1, 2});
return true;
}
// Newell 法向
Vector3D normal{0.0, 0.0, 0.0};
for (std::size_t i = 0; i < n; ++i) {
const Point3D& p = pts[i];
const Point3D& q = pts[(i + 1) % n];
normal += Vector3D((p.y() - q.y()) * (p.z() + q.z()),
(p.z() - q.z()) * (p.x() + q.x()),
(p.x() - q.x()) * (p.y() + q.y()));
}
const double normal_len = normal.norm();
if (!(normal_len > 0.0) || !std::isfinite(normal_len)) return false;
normal /= normal_len;
Vector3D u = pts[1] - pts[0];
const double u_len = u.norm();
if (!(u_len > 0.0) || !std::isfinite(u_len)) return false;
u /= u_len;
Vector3D v = normal.cross(u);
const double v_len = v.norm();
if (!(v_len > 0.0)) return false;
v /= v_len;
double extent = 0.0;
for (const auto& p : pts) extent = std::max(extent, (p - pts[0]).norm());
const double area_tol = 1e-14 * extent * extent;
std::vector<double> px(n), py(n);
for (std::size_t i = 0; i < n; ++i) {
const Vector3D d = pts[i] - pts[0];
px[i] = d.dot(u);
py[i] = d.dot(v);
}
double area2 = 0.0;
for (std::size_t i = 0; i < n; ++i) {
const std::size_t j = (i + 1) % n;
area2 += px[i] * py[j] - px[j] * py[i];
}
if (std::abs(area2) <= area_tol) return false;
std::vector<int> ring;
ring.reserve(n);
const bool reversed = area2 < 0.0;
for (std::size_t i = 0; i < n; ++i)
ring.push_back(reversed ? static_cast<int>(n - 1 - i) : static_cast<int>(i));
auto cross = [&](int a, int b, int c) {
return (px[b] - px[a]) * (py[c] - py[a]) -
(py[b] - py[a]) * (px[c] - px[a]);
};
auto point_in_triangle = [&](int a, int b, int c, int p) {
const double d1 = cross(a, b, p);
const double d2 = cross(b, c, p);
const double d3 = cross(c, a, p);
const double eps = -1e-12 * extent * extent; // 允许边界/近共线
return d1 >= eps && d2 >= eps && d3 >= eps;
};
auto emit = [&](int a, int b, int c) {
if (reversed) out.push_back({a, c, b});
else out.push_back({a, b, c});
};
std::size_t guard = n * n + 8;
while (ring.size() > 3 && guard-- > 0) {
const std::size_t m = ring.size();
bool clipped = false;
for (std::size_t i = 0; i < m; ++i) {
const int ia = ring[(i + m - 1) % m];
const int ib = ring[i];
const int ic = ring[(i + 1) % m];
if (cross(ia, ib, ic) <= area_tol) continue; // 凹或退化顶点
bool blocked = false;
for (std::size_t k = 0; k < m; ++k) {
const int ip = ring[k];
if (ip == ia || ip == ib || ip == ic) continue;
if (point_in_triangle(ia, ib, ic, ip)) { blocked = true; break; }
}
if (blocked) continue;
emit(ia, ib, ic);
ring.erase(ring.begin() + static_cast<std::ptrdiff_t>(i));
clipped = true;
break;
}
if (!clipped) return false; // 自交/退化:交给调用方回退
}
if (ring.size() != 3) return false;
emit(ring[0], ring[1], ring[2]);
return true;
}
} // namespace
// EdgeKey / EdgeKeyHash 定义于头文件(持久边查找表成员使用)
void HalfedgeMesh::clear() {
vertices_.clear();
halfedges_.clear();
faces_.clear();
face_normals_.clear();
vertex_normals_.clear();
edge_map_.clear();
edge_map_stale_ = false;
normals_dirty_ = true;
vertex_halfedge_.clear();
halfedge_next_out_.clear();
}
int HalfedgeMesh::add_vertex(const Point3D& p) {
vertices_.push_back(p);
vertex_halfedge_.push_back(-1);
normals_dirty_ = true;
return static_cast<int>(vertices_.size()) - 1;
}
void HalfedgeMesh::link_outgoing_halfedge(int he) {
if (he < 0 || static_cast<std::size_t>(he) >= halfedges_.size()) return;
const int v = halfedges_[static_cast<std::size_t>(he)].vertex_index;
if (v < 0) return;
if (vertex_halfedge_.size() < static_cast<std::size_t>(v) + 1)
vertex_halfedge_.resize(static_cast<std::size_t>(v) + 1, -1);
if (halfedge_next_out_.size() != halfedges_.size())
halfedge_next_out_.resize(halfedges_.size(), -1);
halfedge_next_out_[static_cast<std::size_t>(he)] =
vertex_halfedge_[static_cast<std::size_t>(v)];
vertex_halfedge_[static_cast<std::size_t>(v)] = he;
}
int HalfedgeMesh::append_halfedge_pair(int vj, int vi) {
const int he0 = static_cast<int>(halfedges_.size());
halfedges_.push_back({vj, -1, -1, -1, he0 + 1}); // forward
halfedges_.push_back({vi, -1, -1, -1, he0}); // backward
halfedge_next_out_.push_back(-1);
halfedge_next_out_.push_back(-1);
link_outgoing_halfedge(he0);
link_outgoing_halfedge(he0 + 1);
return he0;
}
void HalfedgeMesh::rebuild_vertex_adjacency() {
vertex_halfedge_.assign(vertices_.size(), -1);
halfedge_next_out_.assign(halfedges_.size(), -1);
for (std::size_t he = 0; he < halfedges_.size(); ++he) {
const int v = halfedges_[he].vertex_index;
if (v < 0 || static_cast<std::size_t>(v) >= vertex_halfedge_.size()) continue;
halfedge_next_out_[he] = vertex_halfedge_[static_cast<std::size_t>(v)];
vertex_halfedge_[static_cast<std::size_t>(v)] = static_cast<int>(he);
}
}
int HalfedgeMesh::add_face(const std::vector<int>& vis) {
const int n = static_cast<int>(vis.size());
if (n < 3) return -1;
// 输入校验:索引必须落在顶点数组内,且面内不允许重复顶点(退化面)。
const std::size_t nv = vertices_.size();
for (int i = 0; i < n; ++i) {
const int vi = vis[i];
if (vi < 0 || static_cast<std::size_t>(vi) >= nv) return -1;
}
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (vis[i] == vis[j]) return -1;
}
}
if (edge_map_stale_) rebuild_edge_map();
// For each edge, find or create the halfedge belonging to this face
// 使用持久边查找表 edge_map_(O(1) 均摊),避免每次 O(E) 重建
std::vector<int> face_he(static_cast<std::size_t>(n));
for (int i = 0; i < n; ++i) {
int vi = vis[i];
int vj = vis[(i + 1) % n];
EdgeKey key(std::min(vi, vj), std::max(vi, vj));
auto it = edge_map_.find(key);
int he_used = -1;
if (it != edge_map_.end()) {
// 已有边对 {he0: 首次使用方(vertex=vj0), he1: 其对偶(vertex=vi0)}。
// 本面需要指向 vj 的半边:优先复用空闲的既有半边,否则(对偶方向已
// 被占用,即非流形/绕向冲突——显示级三角片常见)分配新半边对,保证
// 本面三个顶点记录完整、几何不塌缩。
int he0 = it->second;
int he1 = he0 + 1;
int cand = (halfedges_[he0].vertex_index == vj) ? he0 : he1;
if (halfedges_[cand].face_index < 0) he_used = cand;
}
if (he_used < 0) {
// Create new forward/backward pair
const int he0 = append_halfedge_pair(vj, vi);
if (it == edge_map_.end()) edge_map_[key] = he0;
he_used = he0;
}
face_he[static_cast<std::size_t>(i)] = he_used;
}
// Set up next/prev links for this face's halfedges
for (int i = 0; i < n; ++i) {
halfedges_[face_he[i]].next_index = face_he[(i + 1) % n];
halfedges_[face_he[i]].prev_index = face_he[(i - 1 + n) % n];
}
// Create face
int fi = static_cast<int>(faces_.size());
faces_.push_back({face_he[0], n});
// Set face_index for this face's halfedges
for (int i = 0; i < n; ++i) {
halfedges_[face_he[i]].face_index = fi;
}
normals_dirty_ = true;
return fi;
}
void HalfedgeMesh::rebuild_edge_map() {
edge_map_.clear();
edge_map_.reserve(faces_.size() * 2);
for (size_t fi = 0; fi < faces_.size(); ++fi) {
const Face& f = faces_[fi];
int he = f.halfedge_index;
for (int k = 0; k < f.valence; ++k) {
const int prev = halfedges_[he].prev_index;
const int a = halfedges_[prev].vertex_index;
const int b = halfedges_[he].vertex_index;
const EdgeKey key(std::min(a, b), std::max(a, b));
if (edge_map_.find(key) == edge_map_.end()) edge_map_[key] = he;
he = halfedges_[he].next_index;
}
}
edge_map_stale_ = false;
}
int HalfedgeMesh::add_triangle_fast(int v0, int v1, int v2) {
if (edge_map_stale_) rebuild_edge_map();
const int vis[3] = {v0, v1, v2};
int face_he[3];
for (int i = 0; i < 3; ++i) {
const int vi = vis[i];
const int vj = vis[(i + 1) % 3];
const EdgeKey key(std::min(vi, vj), std::max(vi, vj));
auto it = edge_map_.find(key);
int he_used = -1;
if (it != edge_map_.end()) {
const int he0 = it->second;
const int he1 = he0 + 1;
const int cand = (halfedges_[he0].vertex_index == vj) ? he0 : he1;
if (halfedges_[cand].face_index < 0) he_used = cand;
}
if (he_used < 0) {
const int he0 = append_halfedge_pair(vj, vi);
if (it == edge_map_.end()) edge_map_[key] = he0;
he_used = he0;
}
face_he[i] = he_used;
}
for (int i = 0; i < 3; ++i) {
halfedges_[face_he[i]].next_index = face_he[(i + 1) % 3];
halfedges_[face_he[i]].prev_index = face_he[(i + 2) % 3];
}
const int fi = static_cast<int>(faces_.size());
faces_.push_back({face_he[0], 3});
for (int i = 0; i < 3; ++i) halfedges_[face_he[i]].face_index = fi;
normals_dirty_ = true;
return fi;
}
bool HalfedgeMesh::build_from_triangles(
const std::vector<Point3D>& verts,
const std::vector<std::array<int, 3>>& tris) {
clear();
// 预留容量,避免逐元素扩容(Phase5-TessPerf)
vertices_ = verts;
vertex_halfedge_.assign(verts.size(), -1);
// 输入校验:越界索引 → 整批失败(网格清空);退化三角形 → 跳过并标记失败。
const int nv = static_cast<int>(verts.size());
std::vector<char> keep(tris.size(), 1);
for (std::size_t ti = 0; ti < tris.size(); ++ti) {
const auto& t = tris[ti];
for (int k = 0; k < 3; ++k) {
if (t[static_cast<std::size_t>(k)] < 0 || t[static_cast<std::size_t>(k)] >= nv) {
clear();
return false;
}
}
if (t[0] == t[1] || t[1] == t[2] || t[0] == t[2]) keep[ti] = 0;
}
faces_.reserve(tris.size());
halfedges_.reserve(tris.size() * 4);
normals_dirty_ = true;
// VDE-1277:大网格建拓扑用连续内存开放寻址边表,替代 unordered_map
// 逐边节点分配(实测 2M 三角形 4.1s -> 见 docs/reference/155 报告)。
TriangleEdgeTable edges(tris.size());
for (std::size_t ti = 0; ti < tris.size(); ++ti) {
if (!keep[ti]) continue;
const auto& t = tris[ti];
const int vis[3] = {t[0], t[1], t[2]};
int face_he[3] = {-1, -1, -1};
for (int i = 0; i < 3; ++i) {
const int vi = vis[i];
const int vj = vis[(i + 1) % 3];
const std::uint64_t key = edge_key(vi, vj);
const std::size_t slot = edges.slot_of(key);
const int existing = edges.halfedge_at(slot);
int he_used = -1;
if (existing >= 0) {
const int he0 = existing;
const int candidate = (halfedges_[he0].vertex_index == vj) ? he0 : he0 + 1;
if (halfedges_[candidate].face_index < 0) he_used = candidate;
}
if (he_used < 0) {
const int he0 = append_halfedge_pair(vj, vi);
if (existing < 0) edges.insert(slot, key, he0);
he_used = he0;
}
face_he[i] = he_used;
}
// next/prev 链接与面归属(语义同 add_triangle_fast)
for (int i = 0; i < 3; ++i) {
halfedges_[face_he[i]].next_index = face_he[(i + 1) % 3];
halfedges_[face_he[i]].prev_index = face_he[(i + 2) % 3];
}
const int fi = static_cast<int>(faces_.size());
faces_.push_back({face_he[0], 3});
for (int i = 0; i < 3; ++i) halfedges_[face_he[i]].face_index = fi;
}
// 持久边查找表惰性重建(与 build_from_triangles_parallel 合并后的约定一致):
// 避免百万级网格常驻 unordered_map,后续 add_face/add_triangle_fast 首次
// 调用时按需重建。
edge_map_.clear();
edge_map_stale_ = true;
for (std::size_t ti = 0; ti < tris.size(); ++ti) {
if (!keep[ti]) return false;
}
return true;
}
bool HalfedgeMesh::build_from_triangles_parallel(
const std::vector<Point3D>& verts,
const std::vector<std::array<int, 3>>& tris,
const std::vector<size_t>& group_tri_begin,
const std::vector<size_t>& group_vert_begin,
int num_threads) {
clear();
// 分组结构校验:必须存在至少一组,且两个前缀数组维度一致、从 0 开始、
// 单调不减、恰好覆盖全部顶点/三角形(否则合并会静默产生错误拓扑)。
if (group_tri_begin.size() < 2 || group_vert_begin.size() != group_tri_begin.size())
return false;
const size_t groups = group_tri_begin.size() - 1;
if (groups == 0) return false;
if (group_vert_begin.front() != 0 || group_vert_begin.back() != verts.size())
return false;
if (group_tri_begin.front() != 0 || group_tri_begin.back() != tris.size())
return false;
for (size_t g = 0; g < groups; ++g) {
if (group_vert_begin[g] > group_vert_begin[g + 1]) return false;
if (group_tri_begin[g] > group_tri_begin[g + 1]) return false;
}
// 每组三角形索引必须落在本组顶点区间内(组间顶点不相交);退化三角形跳过。
std::vector<char> keep(tris.size(), 1);
bool ok = true;
for (size_t g = 0; g < groups; ++g) {
const int vb = static_cast<int>(group_vert_begin[g]);
const int ve = static_cast<int>(group_vert_begin[g + 1]);
for (size_t ti = group_tri_begin[g]; ti < group_tri_begin[g + 1]; ++ti) {
const auto& t = tris[ti];
for (int k = 0; k < 3; ++k) {
const int idx = t[static_cast<std::size_t>(k)];
if (idx < vb || idx >= ve) {
clear();
return false;
}
}
if (t[0] == t[1] || t[1] == t[2] || t[0] == t[2]) {
keep[ti] = 0;
ok = false;
}
}
}
if (num_threads < 1) num_threads = 1;
if (groups == 1) {
// 单组语义等价于串行构建(其内部会再次校验并处理退化三角形)。
const bool serial_ok = build_from_triangles(verts, tris);
return serial_ok;
}
std::vector<HalfedgeMesh> parts(groups);
#ifdef VDE_USE_OPENMP
#pragma omp parallel for schedule(dynamic, 1) num_threads(num_threads)
#endif
for (int g = 0; g < static_cast<int>(groups); ++g) {
const size_t vb = group_vert_begin[static_cast<size_t>(g)];
const size_t ve = group_vert_begin[static_cast<size_t>(g) + 1];
const size_t tb = group_tri_begin[static_cast<size_t>(g)];
const size_t te = group_tri_begin[static_cast<size_t>(g) + 1];
HalfedgeMesh& part = parts[static_cast<size_t>(g)];
part.vertices_.reserve(ve - vb);
for (size_t vi = vb; vi < ve; ++vi) part.vertices_.push_back(verts[vi]);
part.vertex_halfedge_.assign(part.vertices_.size(), -1);
part.faces_.reserve(te - tb);
part.halfedges_.reserve((te - tb) * 4);
part.edge_map_.reserve((te - tb) * 2);
for (size_t ti = tb; ti < te; ++ti) {
if (!keep[ti]) continue;
const auto& t = tris[ti];
part.add_triangle_fast(static_cast<int>(t[0] - static_cast<int>(vb)),
static_cast<int>(t[1] - static_cast<int>(vb)),
static_cast<int>(t[2] - static_cast<int>(vb)));
}
part.rebuild_vertex_adjacency();
}
// 按组顺序确定性合并(组间顶点不相交,无需跨组合并边)
size_t tv = 0, th = 0, tf = 0;
for (const auto& p : parts) {
tv += p.vertices_.size();
th += p.halfedges_.size();
tf += p.faces_.size();
}
vertices_.reserve(tv);
halfedges_.reserve(th);
faces_.reserve(tf);
for (size_t g = 0; g < groups; ++g) {
const HalfedgeMesh& p = parts[g];
const int voff = static_cast<int>(vertices_.size());
const int hoff = static_cast<int>(halfedges_.size());
const int foff = static_cast<int>(faces_.size());
vertices_.insert(vertices_.end(), p.vertices_.begin(), p.vertices_.end());
for (const auto& he : p.halfedges_) {
Halfedge h = he;
h.vertex_index += voff;
if (h.opposite_index >= 0) h.opposite_index += hoff;
if (h.next_index >= 0) h.next_index += hoff;
if (h.prev_index >= 0) h.prev_index += hoff;
if (h.face_index >= 0) h.face_index += foff;
halfedges_.push_back(h);
}
for (const auto& f : p.faces_) {
Face nf = f;
if (nf.halfedge_index >= 0) nf.halfedge_index += hoff;
faces_.push_back(nf);
}
}
rebuild_vertex_adjacency();
edge_map_.clear();
edge_map_stale_ = true;
normals_dirty_ = true;
return ok;
}
std::vector<int> HalfedgeMesh::face_vertices(int fi) const {
const auto& f = faces_[fi];
std::vector<int> vis;
int he = f.halfedge_index;
for (int i = 0; i < f.valence; ++i) {
vis.push_back(halfedges_[he].vertex_index);
he = halfedges_[he].next_index;
}
return vis;
}
HalfedgeMesh::FaceRange HalfedgeMesh::faces_range() const {
return FaceRange(this);
}
HalfedgeMesh::VertexOneRing HalfedgeMesh::vertex_one_ring(int vi) const {
std::vector<int> neighbors;
if (vi < 0 || static_cast<std::size_t>(vi) >= vertices_.size()) {
return VertexOneRing(std::move(neighbors));
}
for (int he = vertex_halfedge_[static_cast<std::size_t>(vi)]; he >= 0;
he = halfedge_next_out_[static_cast<std::size_t>(he)]) {
const Halfedge& h = halfedges_[static_cast<std::size_t>(he)];
int nb = -1;
const int opp = h.opposite_index;
if (opp >= 0 && static_cast<std::size_t>(opp) < halfedges_.size()) {
nb = halfedges_[static_cast<std::size_t>(opp)].vertex_index;
} else if (h.next_index >= 0 &&
static_cast<std::size_t>(h.next_index) < halfedges_.size()) {
// 边界半边无对侧:沿面的下一条半边起点即本边终点。
nb = halfedges_[static_cast<std::size_t>(h.next_index)].vertex_index;
}
if (nb >= 0 && nb != vi) neighbors.push_back(nb);
}
std::sort(neighbors.begin(), neighbors.end());
neighbors.erase(std::unique(neighbors.begin(), neighbors.end()), neighbors.end());
return VertexOneRing(std::move(neighbors));
}
std::vector<int> HalfedgeMesh::vertex_faces(int vi) const {
std::vector<int> result;
if (vi < 0 || static_cast<std::size_t>(vi) >= vertices_.size()) return result;
for (int he = vertex_halfedge_[static_cast<std::size_t>(vi)]; he >= 0;
he = halfedge_next_out_[static_cast<std::size_t>(he)]) {
const int fi = halfedges_[static_cast<std::size_t>(he)].face_index;
if (fi >= 0) result.push_back(fi);
}
// 与历史实现一致:返回升序面索引(同一面至多一条从 vi 出发的边)。
std::sort(result.begin(), result.end());
result.erase(std::unique(result.begin(), result.end()), result.end());
return result;
}
bool HalfedgeMesh::is_boundary_vertex(int vi) const {
if (vi < 0 || static_cast<std::size_t>(vi) >= vertices_.size()) return false;
for (int he = vertex_halfedge_[static_cast<std::size_t>(vi)]; he >= 0;
he = halfedge_next_out_[static_cast<std::size_t>(he)]) {
const Halfedge& h = halfedges_[static_cast<std::size_t>(he)];
// 与历史实现一致:本侧无面,或对侧半边存在且无面 → 边界顶点。
if (h.face_index < 0) return true;
const int opp = h.opposite_index;
if (opp >= 0 && opp < static_cast<int>(halfedges_.size()) &&
halfedges_[static_cast<std::size_t>(opp)].face_index < 0)
return true;
}
return false;
}
Vector3D HalfedgeMesh::face_normal(int fi) const {
if (!normals_dirty_ && fi >= 0 && static_cast<std::size_t>(fi) < face_normals_.size())
return face_normals_[static_cast<std::size_t>(fi)];
if (fi < 0 || static_cast<std::size_t>(fi) >= faces_.size()) return Vector3D::UnitZ();
return face_normal_from_face(vertices_, halfedges_, faces_[static_cast<std::size_t>(fi)]);
}
Vector3D HalfedgeMesh::vertex_normal(int vi) const {
if (!normals_dirty_ && vi >= 0 && static_cast<std::size_t>(vi) < vertex_normals_.size())
return vertex_normals_[static_cast<std::size_t>(vi)];
const auto fis = vertex_faces(vi);
if (fis.empty()) return Vector3D::UnitZ();
Vector3D sum = Vector3D::Zero();
for (int fi : fis) sum += face_normal(fi);
return sum.normalized();
}
void HalfedgeMesh::update_normals() {
// 强制直接计算路径,避免在重算过程中命中旧缓存。
normals_dirty_ = true;
face_normals_.resize(faces_.size());
for (std::size_t i = 0; i < faces_.size(); ++i) {
face_normals_[i] = face_normal_from_face(vertices_, halfedges_, faces_[i]);
}
// 单遍面遍历:按面索引升序把面法向累加到其顶点(与逐顶点 vertex_normal
// 的累加顺序一致,保证结果逐位不变),随后统一归一化。
vertex_normals_.assign(vertices_.size(), Vector3D::UnitZ());
std::vector<char> touched(vertices_.size(), 0);
for (std::size_t fi = 0; fi < faces_.size(); ++fi) {
const Face& f = faces_[fi];
int he = f.halfedge_index;
for (int k = 0; k < f.valence; ++k) {
if (he < 0 || static_cast<std::size_t>(he) >= halfedges_.size()) break;
const int v = halfedges_[static_cast<std::size_t>(he)].vertex_index;
if (v >= 0 && static_cast<std::size_t>(v) < vertex_normals_.size()) {
if (!touched[static_cast<std::size_t>(v)]) {
vertex_normals_[static_cast<std::size_t>(v)] = Vector3D::Zero();
touched[static_cast<std::size_t>(v)] = 1;
}
vertex_normals_[static_cast<std::size_t>(v)] += face_normals_[fi];
}
he = halfedges_[static_cast<std::size_t>(he)].next_index;
}
}
for (std::size_t i = 0; i < vertex_normals_.size(); ++i) {
if (touched[i]) vertex_normals_[i] = vertex_normals_[i].normalized();
}
normals_dirty_ = false;
}
AABB3D HalfedgeMesh::bounds() const {
if (vertices_.empty()) {
// VDE-1345:空网格返回原点退化盒,而不是 min=+inf/max=-inf
// (旧实现的 extent() 为 -inf,参与尺寸/容差计算会静默传播)。
return AABB3D(Point3D::Zero(), Point3D::Zero());
}
AABB3D b;
for (const auto& v : vertices_) b.expand(v);
return b;
}
MCMesh HalfedgeMesh::to_mcm() const {
MCMesh result;
result.vertices = vertices_;
result.triangles.reserve(faces_.size());
std::vector<Point3D> polygon;
for (std::size_t fi = 0; fi < faces_.size(); ++fi) {
const std::vector<int> vis = face_vertices(static_cast<int>(fi));
if (vis.size() < 3) continue;
if (vis.size() == 3) {
result.triangles.push_back({vis[0], vis[1], vis[2]});
continue;
}
// VDE-1345:非三角面用耳切三角化(凹多边形正确),退化/自交回退扇形。
polygon.clear();
polygon.reserve(vis.size());
for (int vi : vis) polygon.push_back(vertices_[static_cast<std::size_t>(vi)]);
const std::size_t before = result.triangles.size();
if (triangulate_polygon_face(polygon, result.triangles)) {
// 耳切在局部多边形索引下工作,需映射回网格顶点索引
// (face_vertices 可能从环的任意顶点起始,二者顺序不同)。
for (std::size_t k = before; k < result.triangles.size(); ++k) {
auto& t = result.triangles[k];
t = {vis[static_cast<std::size_t>(t[0])],
vis[static_cast<std::size_t>(t[1])],
vis[static_cast<std::size_t>(t[2])]};
}
continue;
}
result.triangles.resize(before);
for (std::size_t i = 1; i + 1 < vis.size(); ++i) {
result.triangles.push_back({vis[0], vis[i], vis[i + 1]});
}
}
return result;
}
} // namespace vde::mesh