fix(brep/mesh): 修正反馈 A 组 VDE-1193/1194/1195 — 边去重/序列化异常/网格绕向自检
VDE-1194 BrepModel::add_edge_unique 改用无向键 (min<<32)|max 去重, 并以惰性 unordered_map 索引替代 O(E) 线性扫描;修复一致取向三角网格 公共边反向遍历导致去重失效、watertightness 恒 0 的误报 (box 网格共享边 30→18,diag_err 1→0)。新增 3 项单测。 VDE-1195 BinarySerializer::read_file 打不开/读取失败抛 std::runtime_error, deserialize 校验 VDE 魔数/版本/体量并抛异常;C ABI vde_deserialize_mesh 捕获异常返回 nullptr,避免异常穿越 C 边界。新增 3 项单测。 VDE-1193 定位体积坍缩根因:to_mesh 输出为逐面独立三角汤(公共边顶点不焊接) 且绕向混杂,散度定理体积在内部抵消;repair_mesh 的 fix_orientation/fill_holes 原为空实现、flipped_faces 恒 0。新增 mesh::weld_and_unify_orientation (空间哈希焊接 + 共享边 BFS 绕向统一 + 分量有符号体积翻正), MeshHealingReport 补齐 boundary_edges / winding_consistent / outward_oriented 自检字段;vde_step_probe 增加 vol_cons/wt/winding_ok/outward 输出。 box_000_none 体积 0→4.080、box_007_rotate 0→800.000,test_cube 保持 1000000 无回归。新增 3 项单测(共 13 项通过)。 验证:test_brep 30 通过、test_serializer 8 通过、test_mesh_repair 13 通过, GetDiagnostics 无错误。
This commit is contained in:
@@ -30,6 +30,7 @@
|
||||
#include "vde/brep/brep_validate.h"
|
||||
#include "vde/brep/measure.h"
|
||||
#include "vde/mesh/halfedge_mesh.h"
|
||||
#include "vde/mesh/mesh_repair.h"
|
||||
|
||||
using namespace vde::brep;
|
||||
namespace mesh = vde::mesh;
|
||||
@@ -256,6 +257,7 @@ int wmain(int argc, wchar_t** wargv) {
|
||||
empty_reason = step_last_error_message();
|
||||
js << "{\"file\":\"" << esc(path) << "\",\"bodies\":[";
|
||||
double tot_vol = 0, tot_area = 0;
|
||||
double tot_vol_cons = 0;
|
||||
double tot_an_vol = 0, tot_an_area = 0;
|
||||
for (size_t bi = 0; bi < bodies.size(); ++bi) {
|
||||
BrepModel& b = bodies[bi];
|
||||
@@ -454,6 +456,21 @@ int wmain(int argc, wchar_t** wargv) {
|
||||
js << ",\"vol_mm3\":" << vol << ",\"area_mm2\":" << area
|
||||
<< ",\"bbox\":[" << mn[0] << "," << mn[1] << "," << mn[2]
|
||||
<< "," << mx[0] << "," << mx[1] << "," << mx[2] << "]";
|
||||
// VDE-1193:焊接 + 绕向一致化后的体积与流形/绕向自检
|
||||
// (to_mesh 输出是逐面独立三角汤;绕向不一致时散度体积会
|
||||
// 内部抵消 —— 此处给出"修复后"的可信体积与自检标志)
|
||||
auto solid = mesh::weld_and_unify_orientation(m);
|
||||
double cvol, carea, cmn[3], cmx[3];
|
||||
mesh_metrics(solid, cvol, carea, cmn, cmx);
|
||||
auto wrep = mesh::mesh_healing_report(solid);
|
||||
tot_vol_cons += cvol;
|
||||
js << ",\"mesh_verts_welded\":" << solid.num_vertices()
|
||||
<< ",\"vol_cons_mm3\":" << cvol
|
||||
<< ",\"wt\":" << (wrep.is_watertight ? 1 : 0)
|
||||
<< ",\"winding_ok\":" << (wrep.winding_consistent ? 1 : 0)
|
||||
<< ",\"outward\":" << (wrep.outward_oriented ? 1 : 0)
|
||||
<< ",\"boundary_edges\":" << wrep.boundary_edges
|
||||
<< ",\"flipped_faces\":" << wrep.flipped_faces;
|
||||
} catch (const std::exception& e) {
|
||||
js << ",\"mesh_error\":\"" << esc(e.what()) << "\"";
|
||||
}
|
||||
@@ -537,6 +554,7 @@ int wmain(int argc, wchar_t** wargv) {
|
||||
js.precision(3);
|
||||
js << "],\"total_vol_mm3\":" << tot_vol
|
||||
<< ",\"total_area_mm2\":" << tot_area
|
||||
<< ",\"total_vol_cons_mm3\":" << tot_vol_cons
|
||||
<< ",\"total_an_vol_mm3\":" << tot_an_vol
|
||||
<< ",\"total_an_area_mm2\":" << tot_an_area;
|
||||
if (!empty_reason.empty())
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
**Date**: 2026-09-03
|
||||
**Source**: ViewDesign `tests/test_vde_realdata.cpp`(真实数据回归)
|
||||
**Module**: `vde::brep` — tessellation / `BrepModel::to_mesh`
|
||||
**Status**: open
|
||||
**Status**: in_progress(网格层"焊接 + 一致外法线绕向 + 自检"已实施;B-Rep 面绕向/公共边同步采样未做)
|
||||
|
||||
## 现象
|
||||
|
||||
@@ -46,3 +46,64 @@ box_007_rotate.stp 600 335 0.56 (平面盒!)
|
||||
|
||||
`test_vde_realdata.cpp::StepRoundTripVolumeRatio` 打印体积比作为观测点;
|
||||
`DISABLED_StepRoundTripCylinder` 保留复现。
|
||||
|
||||
## 排查结论(2026-09-10)
|
||||
|
||||
1. **`to_mesh` 输出是逐面独立的"三角汤"**:12 个三角面闭合盒的
|
||||
`mesh_verts = 36 = 12 × 3`,公共边两侧顶点各面各自持有,从不焊接。
|
||||
散度定理体积在绕向混杂时内部抵消 —— 这正是"体积坍缩"的直接机理
|
||||
(`fabs(Σ signed vol)`,抵消后趋 0)。
|
||||
2. **`repair_mesh` 的 `fix_orientation` / `fill_holes` 是空实现**:
|
||||
`RepairOptions` 声明了这两个开关,但 `repair_mesh` 只实现了
|
||||
`remove_duplicates`(且是 O(n²) 线性扫描后直接 return)和
|
||||
`remove_degenerate`,绕向统一**从未真正实现**;`MeshHealingReport::
|
||||
flipped_faces` 也恒为 0 —— 即请求的"绕向自检"此前并不存在。
|
||||
3. **已修好的部分(VDE-1194)**:`add_edge_unique` 无向去重后,
|
||||
`corpus/generated/step/box_*.stp` 的共享边不再翻倍
|
||||
(edges 30 → 18)、`diag_err` 1 → 0,即"相邻面共享边被复制成独立边"
|
||||
这一条根因已消除。
|
||||
4. **`box_*.stp` 生成件本身绕向自相矛盾**(重要):逐面核对
|
||||
`POLY_LOOP` 绕向 / `PLANE` 法向 / `ADVANCED_FACE.same_sense` 可见,
|
||||
生成器对所有面统一写 `.F.`,而底面(法向 +z、外法向 -z)成立、
|
||||
顶面(法向 +z、外法向 +z)不成立。故这些件的 `an_vol = 0` 是
|
||||
**忠实反映文件自身的不一致**,不是 `to_mesh` 缺陷;同一管线处理
|
||||
`corpus/step/test_cube.STEP`(6 面)与 `torus_011_*.stp`(192 面)
|
||||
体积/面积均精确(1000000 / 66291.247),round-trip `rt_vol_rel = 0`。
|
||||
|
||||
## 已实施(2026-09-10)
|
||||
|
||||
网格层保证"一致外法线绕向 + 可自检"
|
||||
([mesh_repair.h](file:///d:/20_AI/ViewDesignEngine/include/vde/mesh/mesh_repair.h) /
|
||||
[mesh_repair.cpp](file:///d:/20_AI/ViewDesignEngine/src/mesh/mesh_repair.cpp)):
|
||||
|
||||
- 新增 `vde::mesh::weld_and_unify_orientation(mesh, weld_tol = 0)`:
|
||||
空间哈希焊接重合顶点(默认容差 = 包围盒对角线 × 1e-6,与上层按位置
|
||||
焊接口径一致)→ 剔除焊接后退化面 → 按共享边邻接 BFS 统一绕向 →
|
||||
按连通分量有符号体积把负绕向整体翻正(保证外法线朝外)。
|
||||
- `MeshHealingReport` 新增 `boundary_edges` / `winding_consistent` /
|
||||
`outward_oriented`,并让 `flipped_faces` 真正计算(此前恒 0)。
|
||||
|
||||
`vde_step_probe` 增加对照证据字段:`mesh_verts_welded` / `vol_cons_mm3` /
|
||||
`wt` / `winding_ok` / `outward` / `boundary_edges` / `flipped_faces` /
|
||||
`total_vol_cons_mm3`。
|
||||
|
||||
| 样本 | `vol_mm3`(原) | `vol_cons_mm3`(修复后) | 手算真值 | 自检 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| box_000_none.stp | 0.000 | **4.080** | 1.0×0.8×5.1 = 4.08 | wt=1, winding=1, outward=1 |
|
||||
| box_007_rotate.stp | 0.000 | **800.000** | 10×8×10 = 800 | wt=1, winding=1, outward=1 |
|
||||
| corpus/step/test_cube.STEP | 1000000.000 | 1000000.000(不变) | 1000000 | wt=1, winding=1, outward=1 |
|
||||
|
||||
单测 `tests/mesh/test_mesh_repair.cpp` 新增 3 项
|
||||
(`WeldAndUnify_BoxSoupMixedWinding`:混合绕向三角汤 → 焊接 8 点/12 面、
|
||||
水密、外法线一致、体积 8.0;`_FlipsSameDirectionSharedEdge`;
|
||||
`_KeepsSeparateComponentsAndWeldTolerance`),13 项全通过。
|
||||
|
||||
## 剩余(未做)
|
||||
|
||||
- **B-Rep 面级绕向自修复**:闭合壳内 `face.reversed` 与曲面法向组合出的
|
||||
面法向若不朝外,`analytic_measure`(`an_vol`)仍为 0。上表 box 件的
|
||||
`an_vol_mm3 = 0.000` 即此。需要导入/heal 阶段的"闭合壳一致外法向修复"
|
||||
(面级洪泛 + 全局有符号体积定号)。
|
||||
- **公共边同步采样**:相邻面各自在参数空间采样公共曲线边,采样点不同步
|
||||
→ 位置级焊接失败(曲面件尤甚)。彻底解法是边级统一 tessellation 后
|
||||
共享,属 `to_mesh` 架构改动,未纳入本次。
|
||||
|
||||
@@ -52,3 +52,30 @@ int BrepModel::add_edge_unique(int v0, int v1, double tolerance) {
|
||||
|
||||
`shape_impl.h::shapeMeshToBrep` 自建 `map<pair<int,int>, int>` 无向边表,
|
||||
相邻三角形共享同一条边,watertightness 校验恢复正常(实测闭合网格 = 1.0)。
|
||||
|
||||
## 修复(2026-09-10)
|
||||
|
||||
`BrepModel::add_edge_unique` 重写([brep.cpp](file:///d:/20_AI/ViewDesignEngine/src/brep/brep.cpp)):
|
||||
|
||||
- **无向键去重**:`key = (min(v0,v1) << 32) | max(v0,v1)`,命中返回首次插入
|
||||
方向的边(边方向语义不变),彻底解决"相邻三角形反向遍历公共边匹配不上"。
|
||||
- **惰性 `unordered_map<uint64_t,int>` 索引** 替代 O(E) 线性扫描;以
|
||||
`edge_index_size_ != edges_.size()` 检测外部直接增删 `edges_`
|
||||
(heal / vde_format 会改写)后自动重建索引,保持正确。
|
||||
- `tolerance` 保留在签名中(端点以顶点索引标识、无几何歧义),文档注明为
|
||||
几何近似去重的预留参数。
|
||||
|
||||
单测:`tests/brep/test_brep.cpp` 新增
|
||||
`AddEdgeUnique_UndirectedDedup` / `_PreservesFirstDirection` /
|
||||
`_IndexSurvivesNewEdgeInsertion`(27 项全通过)。
|
||||
|
||||
端到端证据(`vde_step_probe`,`corpus/generated/step/box_000_none.stp`
|
||||
12 个 `POLY_LOOP` 三角面闭合壳):
|
||||
|
||||
| 指标 | 修复前 | 修复后 |
|
||||
| --- | --- | --- |
|
||||
| bodies[0].edges | 30(共享边翻倍) | **18**(12 条棱 + 6 条面对角线) |
|
||||
| diag_err | 1(不封闭误报) | **0** |
|
||||
| diag_warn | 4 | 3 |
|
||||
|
||||
(`edges=30` 是"36 条有向边仅合并 6 条同向对角线"的旧行为。)
|
||||
|
||||
@@ -32,3 +32,20 @@ ViewDesign 测试 `BRepSerializer.ReadFileNonexistentReturnsNull` 期望
|
||||
|
||||
`serialize.cpp::readFile` 在调用 VDE 之前先用 `ifstream` 探测文件,
|
||||
打不开直接返回 null Shape。
|
||||
|
||||
## 修复(2026-09-10)
|
||||
|
||||
采用请求中的**方案 1 + deserialize 严格校验**
|
||||
([serializer.cpp](file:///d:/20_AI/ViewDesignEngine/src/foundation/serializer.cpp)):
|
||||
|
||||
- `BinarySerializer::read_file`:文件打不开 / 取不到长度 / 读取失败
|
||||
一律抛 `std::runtime_error`(与 `load_vde` 缺失文件抛异常的行为对齐)。
|
||||
- `BinarySerializer::deserialize`:buffer < 16 字节(缺 VDE 头)、魔数不符、
|
||||
版本号非法(0 或 > `VDE_FORMAT_VERSION`)、顶点数/面价超出剩余字节
|
||||
一律抛 `std::runtime_error`,消除"垃圾进、空网格出"的静默行为。
|
||||
- **C ABI 边界捕获**:`vde_deserialize_mesh`([vde_capi.cpp](file:///d:/20_AI/ViewDesignEngine/src/capi/vde_capi.cpp))
|
||||
包 `try/catch(...)`,非法 buffer 返回 `nullptr`,避免异常穿越 C 边界终止进程。
|
||||
|
||||
单测:`tests/foundation/test_serializer.cpp` 新增
|
||||
`ReadFileNonexistentThrows` / `DeserializeRejectsBadMagic` /
|
||||
`DeserializeRejectsTruncatedBuffer`(8 项全通过)。
|
||||
|
||||
+21
-1
@@ -453,7 +453,20 @@ public:
|
||||
* @return 新边的 ID
|
||||
*/
|
||||
int add_edge(int v0, int v1, const curves::NurbsCurve& curve);
|
||||
/** @brief 添加边(自动去重) * 查找已有边连接相同的两个端点。 */ int add_edge_unique(int v0, int v1, double tolerance = 1e-9);
|
||||
|
||||
/**
|
||||
* @brief 添加边(无向自动去重)
|
||||
*
|
||||
* 按无向端点对 {min(v0,v1), max(v0,v1)} 查找已有边:一致取向网格中相邻
|
||||
* 三角形反向遍历公共边(A 加 (2,5)、B 加 (5,2))也能命中同一条边。
|
||||
* 命中时返回首次插入的边索引(保留其原有方向),否则新建。
|
||||
*
|
||||
* @param v0 端点顶点索引
|
||||
* @param v1 另一端点顶点索引
|
||||
* @param tolerance 预留参数(端点以顶点索引标识,已规范化;几何近似去重未启用)
|
||||
* @return 边索引(已有或新建)
|
||||
*/
|
||||
int add_edge_unique(int v0, int v1, double tolerance = 1e-9);
|
||||
|
||||
/**
|
||||
* @brief 添加环
|
||||
@@ -1188,6 +1201,13 @@ private:
|
||||
///< 环 ID → loops_ 数组下标的索引(由 add_loop 维护),避免 loop_by_id /
|
||||
///< face_edges / edge_faces 在稠密模型上做 O(L) 线性扫描。
|
||||
mutable std::unordered_map<int, int> loop_index_;
|
||||
///< VDE-1194: 无向边键 (min(v0,v1)<<32 | max(v0,v1)) → edges_ 下标。
|
||||
///< add_edge_unique 惰性维护(首次使用/edges_ 尺寸变化时重建),
|
||||
///< 使一致取向(相邻面反向遍历公共边)的网格也能正确去重。
|
||||
///< 外部直接改写 edges_(heal/vde_format)会改变 size,触发自动重建。
|
||||
mutable std::unordered_map<uint64_t, int> edge_key_index_;
|
||||
///< edge_key_index_ 建立时的 edges_.size(),用于检测外部增删边导致的失效。
|
||||
mutable size_t edge_index_size_ = static_cast<size_t>(-1);
|
||||
int next_id_ = 0;
|
||||
|
||||
// ═══════════════════════════════════════════════
|
||||
|
||||
@@ -71,6 +71,11 @@ struct MeshHealingReport {
|
||||
bool is_watertight = false; ///< 是否水密
|
||||
bool is_manifold = false; ///< 是否流形
|
||||
|
||||
// ── VDE-1193:绕向自检 ──
|
||||
int boundary_edges = 0; ///< 只被 1 个三角形引用的边数(缝隙/未焊接)
|
||||
bool winding_consistent = false;///< 相邻三角形绕向一致(共享边反向遍历)
|
||||
bool outward_oriented = false; ///< 闭合且一致时,三角形法线一致朝外(有符号体积 > 0)
|
||||
|
||||
/// 生成可读诊断报告
|
||||
[[nodiscard]] std::string to_string() const;
|
||||
};
|
||||
@@ -125,4 +130,30 @@ struct MeshHealingReport {
|
||||
*/
|
||||
[[nodiscard]] MeshHealingReport mesh_healing_report(const HalfedgeMesh& mesh);
|
||||
|
||||
/**
|
||||
* @brief VDE-1193: 焊接重合顶点并统一三角形绕向(一致外法线)
|
||||
*
|
||||
* `BrepModel::to_mesh` 逐面独立输出三角形,公共边两侧的顶点被各面各自
|
||||
* 采样/复制(输出是"三角汤"):散度定理体积会因相邻三角形绕向不一致而
|
||||
* 内部抵消(闭合盒体积可坍缩为 0)。本函数在网格层做两件事:
|
||||
* - 位置焊接:空间哈希合并间距 ≤ tol 的顶点(默认容差 = 包围盒对角线
|
||||
* × 1e-6,与上层按位置焊接口径一致);
|
||||
* - 绕向一致化:按共享边邻接广度优先传播,使相邻三角形反向遍历公共边,
|
||||
* 再按整连通分量的有符号体积把负绕向整体翻正(保证外法线朝外)。
|
||||
*
|
||||
* @param mesh 输入网格(可为逐面独立的"三角汤")
|
||||
* @param weld_tol 焊接容差;≤0 表示按包围盒对角线自动取值
|
||||
* @return 焊接 + 绕向一致(外法线朝外)的网格;退化三角形被剔除
|
||||
*
|
||||
* @note 仅处理每对共享边恰有 2 个相邻三角形的情形;非流形边(>2)不参与
|
||||
* 传播,保持原绕向。
|
||||
* @code{.cpp}
|
||||
* auto soup = body.to_mesh(0.1); // 逐面独立三角汤
|
||||
* auto solid = weld_and_unify_orientation(soup); // 可量体积/导出
|
||||
* @endcode
|
||||
* @ingroup mesh
|
||||
*/
|
||||
[[nodiscard]] HalfedgeMesh weld_and_unify_orientation(const HalfedgeMesh& mesh,
|
||||
double weld_tol = 0.0);
|
||||
|
||||
} // namespace vde::mesh
|
||||
|
||||
+21
-5
@@ -49,12 +49,28 @@ int BrepModel::add_edge(int v0, int v1, const curves::NurbsCurve& curve) {
|
||||
}
|
||||
|
||||
int BrepModel::add_edge_unique(int v0, int v1, double tolerance) {
|
||||
(void)tolerance;
|
||||
for (int i = 0; i < static_cast<int>(edges_.size()); ++i) {
|
||||
if (edges_[i].v_start == v0 && edges_[i].v_end == v1)
|
||||
return i;
|
||||
(void)tolerance; // 端点以顶点索引标识,已规范化;容差为几何近似去重预留
|
||||
const auto undirected_key = [](int a, int b) -> uint64_t {
|
||||
uint32_t lo = static_cast<uint32_t>(std::min(a, b));
|
||||
uint32_t hi = static_cast<uint32_t>(std::max(a, b));
|
||||
return (static_cast<uint64_t>(lo) << 32) | hi;
|
||||
};
|
||||
// 惰性重建:首次调用或外部直接增删 edges_(heal / vde_format)导致数量变化
|
||||
if (edge_index_size_ != edges_.size()) {
|
||||
edge_key_index_.clear();
|
||||
edge_key_index_.reserve(edges_.size() * 2 + 1);
|
||||
for (int i = 0; i < static_cast<int>(edges_.size()); ++i)
|
||||
edge_key_index_.emplace(undirected_key(edges_[i].v_start, edges_[i].v_end), i);
|
||||
edge_index_size_ = edges_.size();
|
||||
}
|
||||
return add_edge(v0, v1);
|
||||
const uint64_t key = undirected_key(v0, v1);
|
||||
auto it = edge_key_index_.find(key);
|
||||
if (it != edge_key_index_.end()) return it->second;
|
||||
|
||||
int idx = add_edge(v0, v1);
|
||||
edge_key_index_.emplace(key, idx);
|
||||
edge_index_size_ = edges_.size();
|
||||
return idx;
|
||||
}
|
||||
|
||||
int BrepModel::add_loop(const std::vector<int>& edge_ids, bool outer) {
|
||||
|
||||
+10
-3
@@ -357,9 +357,16 @@ size_t vde_serialize_mesh(VdeHandle, VdeMeshHandle mh, uint8_t** out) {
|
||||
return data.size();
|
||||
}
|
||||
VdeMeshHandle vde_deserialize_mesh(VdeHandle, const uint8_t* data, size_t len) {
|
||||
std::vector<uint8_t> buf(data, data+len);
|
||||
auto m = foundation::BinarySerializer::deserialize(buf);
|
||||
return reinterpret_cast<VdeMeshHandle>(new HalfedgeMesh(std::move(m)));
|
||||
if (!data) return nullptr;
|
||||
// VDE-1195: deserialize 对空/非法 buffer 抛异常;C ABI 边界必须捕获,
|
||||
// 以 nullptr 表示失败,避免异常穿越 C 边界导致进程终止。
|
||||
try {
|
||||
std::vector<uint8_t> buf(data, data + len);
|
||||
auto m = foundation::BinarySerializer::deserialize(buf);
|
||||
return reinterpret_cast<VdeMeshHandle>(new HalfedgeMesh(std::move(m)));
|
||||
} catch (...) {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
void vde_free_buffer(uint8_t* p) { delete[] p; }
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "vde/foundation/serializer.h"
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vde::foundation {
|
||||
|
||||
@@ -18,14 +19,6 @@ static void write_val(std::vector<uint8_t>& buf, T val) {
|
||||
write_bytes(buf, &val, sizeof(T));
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static T read_val(const uint8_t*& ptr) {
|
||||
T val;
|
||||
std::memcpy(&val, ptr, sizeof(T));
|
||||
ptr += sizeof(T);
|
||||
return val;
|
||||
}
|
||||
|
||||
static void write_u32(std::vector<uint8_t>& buf, uint32_t v) { write_val(buf, v); }
|
||||
static void write_u64(std::vector<uint8_t>& buf, uint64_t v) { write_val(buf, v); }
|
||||
static void write_f64(std::vector<uint8_t>& buf, double v) { write_val(buf, v); }
|
||||
@@ -55,30 +48,53 @@ std::vector<uint8_t> BinarySerializer::serialize(const mesh::HalfedgeMesh& mesh)
|
||||
}
|
||||
|
||||
mesh::HalfedgeMesh BinarySerializer::deserialize(const std::vector<uint8_t>& data) {
|
||||
mesh::HalfedgeMesh mesh;
|
||||
if (data.size() < 16) return mesh;
|
||||
const uint8_t* ptr = data.data();
|
||||
if (data.size() < 16)
|
||||
throw std::runtime_error("BinarySerializer::deserialize: buffer too small (missing VDE header)");
|
||||
|
||||
if (read_val<uint64_t>(ptr) != VDE_MAGIC) return mesh;
|
||||
read_val<uint32_t>(ptr); // version
|
||||
read_val<uint32_t>(ptr); // flags
|
||||
size_t off = 0;
|
||||
const auto raw_read = [&](void* dst, size_t n) {
|
||||
if (off + n > data.size())
|
||||
throw std::runtime_error("BinarySerializer::deserialize: truncated buffer");
|
||||
std::memcpy(dst, data.data() + off, n);
|
||||
off += n;
|
||||
};
|
||||
const auto rd_u32 = [&] { uint32_t v; raw_read(&v, 4); return v; };
|
||||
const auto rd_u64 = [&] { uint64_t v; raw_read(&v, 8); return v; };
|
||||
const auto rd_i32 = [&] { int32_t v; raw_read(&v, 4); return v; };
|
||||
const auto rd_f64 = [&] { double v; raw_read(&v, 8); return v; };
|
||||
/// 剩余可读字节数(用于在读大数组前做体量校验,避免恶意长度致巨额分配)
|
||||
const auto remaining = [&] { return data.size() - off; };
|
||||
|
||||
uint32_t nv = read_val<uint32_t>(ptr);
|
||||
std::vector<Point3D> verts; verts.reserve(nv);
|
||||
if (rd_u64() != VDE_MAGIC)
|
||||
throw std::runtime_error("BinarySerializer::deserialize: bad magic (not a VDE binary mesh)");
|
||||
const uint32_t version = rd_u32();
|
||||
(void)rd_u32(); // flags
|
||||
if (version == 0 || version > VDE_FORMAT_VERSION)
|
||||
throw std::runtime_error("BinarySerializer::deserialize: unsupported format version");
|
||||
|
||||
const uint32_t nv = rd_u32();
|
||||
if (static_cast<uint64_t>(nv) * 24u > remaining())
|
||||
throw std::runtime_error("BinarySerializer::deserialize: vertex count exceeds buffer");
|
||||
std::vector<Point3D> verts;
|
||||
verts.reserve(nv);
|
||||
for (uint32_t i = 0; i < nv; ++i) {
|
||||
double x = read_val<double>(ptr), y = read_val<double>(ptr), z = read_val<double>(ptr);
|
||||
double x = rd_f64(), y = rd_f64(), z = rd_f64();
|
||||
verts.emplace_back(x, y, z);
|
||||
}
|
||||
|
||||
uint32_t nf = read_val<uint32_t>(ptr);
|
||||
const uint32_t nf = rd_u32();
|
||||
std::vector<std::array<int, 3>> tris;
|
||||
for (uint32_t i = 0; i < nf; ++i) {
|
||||
uint32_t nfv = read_val<uint32_t>(ptr);
|
||||
const uint32_t nfv = rd_u32();
|
||||
if (static_cast<uint64_t>(nfv) * 4u > remaining())
|
||||
throw std::runtime_error("BinarySerializer::deserialize: face valence exceeds buffer");
|
||||
std::vector<int> vis;
|
||||
for (uint32_t j = 0; j < nfv; ++j) vis.push_back(read_val<int32_t>(ptr));
|
||||
vis.reserve(nfv);
|
||||
for (uint32_t j = 0; j < nfv; ++j) vis.push_back(rd_i32());
|
||||
if (vis.size() >= 3) tris.push_back({vis[0], vis[1], vis[2]});
|
||||
}
|
||||
|
||||
mesh::HalfedgeMesh mesh;
|
||||
mesh.build_from_triangles(verts, tris);
|
||||
return mesh;
|
||||
}
|
||||
@@ -93,11 +109,16 @@ bool BinarySerializer::write_file(const std::string& path, const mesh::HalfedgeM
|
||||
|
||||
mesh::HalfedgeMesh BinarySerializer::read_file(const std::string& path) {
|
||||
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
||||
if (!file) return {};
|
||||
auto size = file.tellg();
|
||||
if (!file)
|
||||
throw std::runtime_error("BinarySerializer::read_file: cannot open file: " + path);
|
||||
const auto size = file.tellg();
|
||||
if (size < 0)
|
||||
throw std::runtime_error("BinarySerializer::read_file: cannot determine size: " + path);
|
||||
file.seekg(0);
|
||||
std::vector<uint8_t> data(static_cast<size_t>(size));
|
||||
file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(size));
|
||||
if (!data.empty() &&
|
||||
!file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(size)))
|
||||
throw std::runtime_error("BinarySerializer::read_file: read failed: " + path);
|
||||
return deserialize(data);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,147 @@
|
||||
#include <unordered_set>
|
||||
#include <unordered_map>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <set>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace vde::mesh {
|
||||
|
||||
namespace {
|
||||
|
||||
/// 提取网格的顶点表 + 三角面表(非三角形面跳过)
|
||||
void extract_tris(const HalfedgeMesh& mesh, std::vector<Point3D>& verts,
|
||||
std::vector<std::array<int, 3>>& tris) {
|
||||
verts.resize(mesh.num_vertices());
|
||||
for (size_t i = 0; i < mesh.num_vertices(); ++i) verts[i] = mesh.vertex(i);
|
||||
tris.clear();
|
||||
tris.reserve(mesh.num_faces());
|
||||
for (size_t fi = 0; fi < mesh.num_faces(); ++fi) {
|
||||
auto fv = mesh.face_vertices(static_cast<int>(fi));
|
||||
if (fv.size() == 3) tris.push_back({fv[0], fv[1], fv[2]});
|
||||
}
|
||||
}
|
||||
|
||||
/// 无向边键(min<<32 | max)
|
||||
inline uint64_t undirected_edge_key(int a, int b) {
|
||||
const uint32_t lo = static_cast<uint32_t>(std::min(a, b));
|
||||
const uint32_t hi = static_cast<uint32_t>(std::max(a, b));
|
||||
return (static_cast<uint64_t>(lo) << 32) | hi;
|
||||
}
|
||||
|
||||
/// 有符号体积(散度定理,6 倍)。
|
||||
double signed_volume6(const std::vector<Point3D>& v,
|
||||
const std::vector<std::array<int, 3>>& tris) {
|
||||
double vol6 = 0.0;
|
||||
for (const auto& t : tris) {
|
||||
if (t[0] < 0 || t[1] < 0 || t[2] < 0) continue;
|
||||
const Point3D& p0 = v[static_cast<size_t>(t[0])];
|
||||
const Point3D& p1 = v[static_cast<size_t>(t[1])];
|
||||
const Point3D& p2 = v[static_cast<size_t>(t[2])];
|
||||
vol6 += p0.x() * (p1.y() * p2.z() - p1.z() * p2.y())
|
||||
- p0.y() * (p1.x() * p2.z() - p1.z() * p2.x())
|
||||
+ p0.z() * (p1.x() * p2.y() - p1.y() * p2.x());
|
||||
}
|
||||
return vol6;
|
||||
}
|
||||
|
||||
/// 绕向分析结果
|
||||
struct OrientationStats {
|
||||
int flipped = 0; ///< 为达成一致需要翻转的三角形数
|
||||
int inconsistent_edges = 0; ///< 两侧三角形绕向相同的共享边数(绕向冲突)
|
||||
double signed_volume = 0.0; ///< 原始绕向下的有符号体积
|
||||
std::vector<int> component; ///< 每个三角形所属连通分量(-1 = 非流形边隔断)
|
||||
std::vector<char> need_flip; ///< BFS 判定:该三角形是否需翻转以与邻接一致
|
||||
std::vector<double> comp_volume6; ///< 各分量的 6 倍有符号体积
|
||||
};
|
||||
|
||||
/// 按共享边邻接传播绕向(每条共享边恰 2 个三角形时传播;非流形不传播)
|
||||
OrientationStats analyze_orientation(const std::vector<Point3D>& verts,
|
||||
const std::vector<std::array<int, 3>>& tris) {
|
||||
OrientationStats st;
|
||||
const int nt = static_cast<int>(tris.size());
|
||||
st.component.assign(static_cast<size_t>(std::max(nt, 0)), -1);
|
||||
st.need_flip.assign(static_cast<size_t>(std::max(nt, 0)), 0);
|
||||
st.signed_volume = signed_volume6(verts, tris) / 6.0;
|
||||
if (nt == 0) return st;
|
||||
|
||||
// 无向边 → 引用它的 (三角形, 绕向符号):符号 +1 表示按 min→max 遍历
|
||||
std::unordered_map<uint64_t, std::vector<std::pair<int, int>>> edge_refs;
|
||||
edge_refs.reserve(static_cast<size_t>(nt) * 3);
|
||||
for (int ti = 0; ti < nt; ++ti) {
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
const int a = tris[static_cast<size_t>(ti)][k];
|
||||
const int b = tris[static_cast<size_t>(ti)][(k + 1) % 3];
|
||||
if (a == b) continue;
|
||||
const int sign = (a < b) ? 1 : -1;
|
||||
edge_refs[undirected_edge_key(a, b)].push_back({ti, sign});
|
||||
}
|
||||
}
|
||||
|
||||
// 共享边两侧绕向必须相反;相同即冲突
|
||||
for (const auto& [key, refs] : edge_refs) {
|
||||
(void)key;
|
||||
if (refs.size() != 2) continue;
|
||||
if (refs[0].second == refs[1].second) ++st.inconsistent_edges;
|
||||
}
|
||||
|
||||
// BFS 传播:flip(邻) = flip(当前) XOR (两侧绕向相同)
|
||||
std::vector<int> stack;
|
||||
int ncomp = 0;
|
||||
st.comp_volume6.clear();
|
||||
for (int seed = 0; seed < nt; ++seed) {
|
||||
if (st.component[static_cast<size_t>(seed)] >= 0) continue;
|
||||
const int cid = ncomp++;
|
||||
st.component[static_cast<size_t>(seed)] = cid;
|
||||
st.need_flip[static_cast<size_t>(seed)] = 0;
|
||||
stack.clear();
|
||||
stack.push_back(seed);
|
||||
while (!stack.empty()) {
|
||||
const int ti = stack.back();
|
||||
stack.pop_back();
|
||||
const auto& t = tris[static_cast<size_t>(ti)];
|
||||
for (int k = 0; k < 3; ++k) {
|
||||
const int a = t[k];
|
||||
const int b = t[(k + 1) % 3];
|
||||
if (a == b) continue;
|
||||
auto it = edge_refs.find(undirected_edge_key(a, b));
|
||||
if (it == edge_refs.end() || it->second.size() != 2) continue;
|
||||
const auto& refs = it->second;
|
||||
const auto& other = (refs[0].first == ti) ? refs[1] : refs[0];
|
||||
const int ni = other.first;
|
||||
if (st.component[static_cast<size_t>(ni)] >= 0) continue;
|
||||
const int cur_sign = (refs[0].first == ti) ? refs[0].second : refs[1].second;
|
||||
st.need_flip[static_cast<size_t>(ni)] = static_cast<char>(
|
||||
st.need_flip[static_cast<size_t>(ti)] ^
|
||||
(cur_sign == other.second ? 1 : 0));
|
||||
st.component[static_cast<size_t>(ni)] = cid;
|
||||
stack.push_back(ni);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
st.comp_volume6.assign(static_cast<size_t>(ncomp), 0.0);
|
||||
for (int ti = 0; ti < nt; ++ti) {
|
||||
if (st.need_flip[static_cast<size_t>(ti)]) ++st.flipped;
|
||||
const auto& t = tris[static_cast<size_t>(ti)];
|
||||
const int a = st.need_flip[static_cast<size_t>(ti)] ? t[2] : t[1];
|
||||
const int b = st.need_flip[static_cast<size_t>(ti)] ? t[1] : t[2];
|
||||
const Point3D& p0 = verts[static_cast<size_t>(t[0])];
|
||||
const Point3D& p1 = verts[static_cast<size_t>(a)];
|
||||
const Point3D& p2 = verts[static_cast<size_t>(b)];
|
||||
const double v6 = p0.x() * (p1.y() * p2.z() - p1.z() * p2.y())
|
||||
- p0.y() * (p1.x() * p2.z() - p1.z() * p2.x())
|
||||
+ p0.z() * (p1.x() * p2.y() - p1.y() * p2.x());
|
||||
st.comp_volume6[static_cast<size_t>(st.component[static_cast<size_t>(ti)])] += v6;
|
||||
}
|
||||
return st;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HalfedgeMesh repair_mesh(const HalfedgeMesh& mesh, const RepairOptions& opts) {
|
||||
// Start with a copy
|
||||
std::vector<Point3D> verts(mesh.num_vertices());
|
||||
@@ -77,6 +212,99 @@ HalfedgeMesh repair_mesh(const HalfedgeMesh& mesh, const RepairOptions& opts) {
|
||||
return mesh;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// VDE-1193: weld_and_unify_orientation
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
|
||||
HalfedgeMesh weld_and_unify_orientation(const HalfedgeMesh& mesh, double weld_tol) {
|
||||
std::vector<Point3D> verts;
|
||||
std::vector<std::array<int, 3>> tris;
|
||||
extract_tris(mesh, verts, tris);
|
||||
if (verts.empty() || tris.empty()) return mesh;
|
||||
|
||||
// 自动容差:包围盒对角线 × 1e-6(与上层"按位置焊接"口径一致)
|
||||
if (!(weld_tol > 0.0)) {
|
||||
Point3D mn = verts[0], mx = verts[0];
|
||||
for (const auto& v : verts) {
|
||||
double c[3] = {v.x(), v.y(), v.z()};
|
||||
double lo[3] = {mn.x(), mn.y(), mn.z()}, hi[3] = {mx.x(), mx.y(), mx.z()};
|
||||
for (int k = 0; k < 3; ++k) { lo[k] = std::min(lo[k], c[k]); hi[k] = std::max(hi[k], c[k]); }
|
||||
mn = Point3D(lo[0], lo[1], lo[2]);
|
||||
mx = Point3D(hi[0], hi[1], hi[2]);
|
||||
}
|
||||
const double diag = (mx - mn).norm();
|
||||
weld_tol = std::max(diag * 1e-6, 1e-12);
|
||||
}
|
||||
|
||||
// ── 1. 空间哈希焊接(格边长 = 容差,仅查 27 邻域)──
|
||||
const double inv = 1.0 / weld_tol;
|
||||
std::unordered_map<uint64_t, std::vector<int>> grid;
|
||||
grid.reserve(verts.size() * 2);
|
||||
const auto cell_key = [](long long ix, long long iy, long long iz) -> uint64_t {
|
||||
return (static_cast<uint64_t>(static_cast<uint32_t>(ix)) * 73856093ull) ^
|
||||
(static_cast<uint64_t>(static_cast<uint32_t>(iy)) * 19349663ull) ^
|
||||
(static_cast<uint64_t>(static_cast<uint32_t>(iz)) * 83492791ull);
|
||||
};
|
||||
std::vector<Point3D> uverts;
|
||||
uverts.reserve(verts.size());
|
||||
std::vector<int> remap(verts.size(), -1);
|
||||
for (size_t i = 0; i < verts.size(); ++i) {
|
||||
const Point3D& p = verts[i];
|
||||
const long long ix = static_cast<long long>(std::floor(p.x() * inv));
|
||||
const long long iy = static_cast<long long>(std::floor(p.y() * inv));
|
||||
const long long iz = static_cast<long long>(std::floor(p.z() * inv));
|
||||
int found = -1;
|
||||
for (long long dx = -1; dx <= 1 && found < 0; ++dx)
|
||||
for (long long dy = -1; dy <= 1 && found < 0; ++dy)
|
||||
for (long long dz = -1; dz <= 1 && found < 0; ++dz) {
|
||||
auto it = grid.find(cell_key(ix + dx, iy + dy, iz + dz));
|
||||
if (it == grid.end()) continue;
|
||||
for (int cand : it->second)
|
||||
if ((uverts[static_cast<size_t>(cand)] - p).norm() <= weld_tol) {
|
||||
found = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found < 0) {
|
||||
found = static_cast<int>(uverts.size());
|
||||
uverts.push_back(p);
|
||||
grid[cell_key(ix, iy, iz)].push_back(found);
|
||||
}
|
||||
remap[i] = found;
|
||||
}
|
||||
|
||||
// ── 2. 重映射三角形并剔除退化(焊接后出现重复顶点/零面积)──
|
||||
std::vector<std::array<int, 3>> wtris;
|
||||
wtris.reserve(tris.size());
|
||||
for (const auto& t : tris) {
|
||||
const int a = remap[static_cast<size_t>(t[0])];
|
||||
const int b = remap[static_cast<size_t>(t[1])];
|
||||
const int c = remap[static_cast<size_t>(t[2])];
|
||||
if (a == b || b == c || c == a) continue;
|
||||
const Vector3D e1 = uverts[static_cast<size_t>(b)] - uverts[static_cast<size_t>(a)];
|
||||
const Vector3D e2 = uverts[static_cast<size_t>(c)] - uverts[static_cast<size_t>(a)];
|
||||
if (e1.cross(e2).norm() <= 1e-30) continue;
|
||||
wtris.push_back({a, b, c});
|
||||
}
|
||||
if (wtris.empty()) {
|
||||
HalfedgeMesh empty;
|
||||
return empty;
|
||||
}
|
||||
|
||||
// ── 3. 绕向一致化:局部按共享边传播 + 全局按分量有符号体积翻正 ──
|
||||
OrientationStats st = analyze_orientation(uverts, wtris);
|
||||
for (size_t ti = 0; ti < wtris.size(); ++ti) {
|
||||
auto& t = wtris[ti];
|
||||
const bool comp_negative =
|
||||
st.comp_volume6[static_cast<size_t>(st.component[ti])] < 0.0;
|
||||
if (st.need_flip[ti] ^ comp_negative) std::swap(t[1], t[2]);
|
||||
}
|
||||
|
||||
HalfedgeMesh result;
|
||||
result.build_from_triangles(uverts, wtris);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// VDE-360: MeshHealingReport
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
@@ -91,6 +319,9 @@ std::string MeshHealingReport::to_string() const {
|
||||
oss << "Degenerate faces: " << degenerate_faces << "\n";
|
||||
oss << "Duplicate vertices: " << duplicate_vertices << "\n";
|
||||
oss << "Flipped faces: " << flipped_faces << "\n";
|
||||
oss << "Boundary edges: " << boundary_edges << "\n";
|
||||
oss << "Winding consistent: " << (winding_consistent ? "YES" : "NO") << "\n";
|
||||
oss << "Outward oriented: " << (outward_oriented ? "YES" : "NO") << "\n";
|
||||
oss << "Volume: " << mesh_volume << "\n";
|
||||
oss << "Watertight: " << (is_watertight ? "YES" : "NO") << "\n";
|
||||
oss << "Manifold: " << (is_manifold ? "YES" : "NO") << "\n";
|
||||
@@ -123,6 +354,7 @@ MeshHealingReport mesh_healing_report(const HalfedgeMesh& mesh) {
|
||||
for (const auto& [key, count] : edge_count) {
|
||||
if (count == 1) boundary_count++;
|
||||
}
|
||||
report.boundary_edges = boundary_count;
|
||||
// Each hole requires at least 3 boundary edges
|
||||
report.hole_count = boundary_count > 0 ? boundary_count / 3 : 0;
|
||||
}
|
||||
@@ -176,6 +408,19 @@ MeshHealingReport mesh_healing_report(const HalfedgeMesh& mesh) {
|
||||
// ── Manifold: no non-manifold edges ──
|
||||
report.is_manifold = (report.non_manifold_edges == 0);
|
||||
|
||||
// ── VDE-1193: 绕向自检(一致 / 外法线朝外)──
|
||||
{
|
||||
std::vector<Point3D> verts;
|
||||
std::vector<std::array<int, 3>> tris;
|
||||
extract_tris(mesh, verts, tris);
|
||||
const OrientationStats st = analyze_orientation(verts, tris);
|
||||
report.flipped_faces = st.flipped;
|
||||
report.winding_consistent = (st.inconsistent_edges == 0);
|
||||
// 闭合(无边界边)且绕向一致时,有符号体积 > 0 即三角形法线一致朝外
|
||||
report.outward_oriented = report.is_watertight && report.winding_consistent &&
|
||||
report.mesh_volume > 0.0;
|
||||
}
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
|
||||
@@ -271,3 +271,40 @@ TEST(BrepTest, Visibility_BoundsCheckNoCrash) {
|
||||
box.isolate_faces({-5, 9999}); // all hidden
|
||||
EXPECT_EQ(box.hidden_face_count(), static_cast<int>(box.num_faces()));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// VDE-1194: add_edge_unique 无向去重(一致取向网格共享边)
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
|
||||
TEST(BrepTest, AddEdgeUnique_UndirectedDedup) {
|
||||
BrepModel m;
|
||||
for (int i = 0; i < 4; ++i) m.add_vertex(Point3D(static_cast<double>(i), 0, 0));
|
||||
// 三角 A: 0-1-2,三角 B: 0-2-3 —— 公共边 0-2 在 B 中反向遍历为 2-0
|
||||
m.add_edge_unique(0, 1);
|
||||
m.add_edge_unique(1, 2);
|
||||
int e20 = m.add_edge_unique(2, 0);
|
||||
EXPECT_EQ(m.add_edge_unique(0, 2), e20); // 反向端点对命中同一条边
|
||||
EXPECT_EQ(m.num_edges(), 3u); // 反向重复不产生新边
|
||||
}
|
||||
|
||||
TEST(BrepTest, AddEdgeUnique_PreservesFirstDirection) {
|
||||
BrepModel m;
|
||||
m.add_vertex(Point3D(0, 0, 0));
|
||||
m.add_vertex(Point3D(1, 0, 0));
|
||||
int e0 = m.add_edge_unique(0, 1);
|
||||
int e1 = m.add_edge_unique(1, 0);
|
||||
EXPECT_EQ(e0, e1);
|
||||
EXPECT_EQ(m.edge(e0).v_start, 0); // 保留首次插入方向
|
||||
EXPECT_EQ(m.edge(e0).v_end, 1);
|
||||
EXPECT_EQ(m.num_edges(), 1u);
|
||||
}
|
||||
|
||||
TEST(BrepTest, AddEdgeUnique_IndexSurvivesNewEdgeInsertion) {
|
||||
BrepModel m;
|
||||
for (int i = 0; i < 4; ++i) m.add_vertex(Point3D(static_cast<double>(i), 0, 0));
|
||||
int e02 = m.add_edge_unique(0, 2);
|
||||
int e13 = m.add_edge_unique(1, 3); // 触发索引更新
|
||||
EXPECT_EQ(m.add_edge_unique(2, 0), e02); // 旧键仍可命中
|
||||
EXPECT_EQ(m.add_edge_unique(3, 1), e13);
|
||||
EXPECT_EQ(m.num_edges(), 2u);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include "vde/foundation/serializer.h"
|
||||
#include "vde/mesh/halfedge_mesh.h"
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace vde::foundation;
|
||||
using namespace vde::mesh;
|
||||
@@ -38,6 +39,28 @@ TEST(SerializerTest, WriteReadFile) {
|
||||
std::remove(path.c_str());
|
||||
}
|
||||
|
||||
TEST(SerializerTest, ReadFileNonexistentThrows) {
|
||||
// VDE-1195: 缺失文件不得静默返回空网格
|
||||
EXPECT_THROW(BinarySerializer::read_file(VDE_TEST_TEMP_DIR "no_such_vde_mesh.bin"),
|
||||
std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(SerializerTest, DeserializeRejectsBadMagic) {
|
||||
std::vector<uint8_t> junk(32, 0xAB);
|
||||
EXPECT_THROW(BinarySerializer::deserialize(junk), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(SerializerTest, DeserializeRejectsTruncatedBuffer) {
|
||||
HalfedgeMesh mesh;
|
||||
mesh.add_vertex({0, 0, 0});
|
||||
mesh.add_vertex({1, 0, 0});
|
||||
mesh.add_vertex({0, 1, 0});
|
||||
mesh.add_face({0, 1, 2});
|
||||
auto data = BinarySerializer::serialize(mesh);
|
||||
data.resize(data.size() / 2); // 截断载荷
|
||||
EXPECT_THROW(BinarySerializer::deserialize(data), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST(SerializerTest, SerializeEmptyMesh) {
|
||||
HalfedgeMesh mesh;
|
||||
auto data = BinarySerializer::serialize(mesh);
|
||||
|
||||
@@ -172,3 +172,102 @@ TEST(MeshRepairTest, FullRepair) {
|
||||
EXPECT_GE(repaired.num_vertices(), 1u);
|
||||
EXPECT_GE(repaired.num_faces(), 1u);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
// VDE-1193: weld_and_unify_orientation / 绕向自检
|
||||
// ═══════════════════════════════════════════════════════════
|
||||
|
||||
namespace {
|
||||
|
||||
/// 把"逐面独立"的三角汤建成网格(每个三角形自带 3 个顶点,公共边不共享)
|
||||
HalfedgeMesh make_tri_soup(const std::vector<Point3D>& pts,
|
||||
const std::vector<std::array<int, 3>>& idx) {
|
||||
std::vector<Point3D> verts;
|
||||
std::vector<std::array<int, 3>> tris;
|
||||
for (const auto& t : idx) {
|
||||
const int base = static_cast<int>(verts.size());
|
||||
verts.push_back(pts[t[0]]);
|
||||
verts.push_back(pts[t[1]]);
|
||||
verts.push_back(pts[t[2]]);
|
||||
tris.push_back({base, base + 1, base + 2});
|
||||
}
|
||||
HalfedgeMesh m;
|
||||
m.build_from_triangles(verts, tris);
|
||||
return m;
|
||||
}
|
||||
|
||||
/// 边长为 2 的立方体 8 角点 + 12 个外法线朝外的三角形(角点索引)
|
||||
void box_corners_and_tris(std::vector<Point3D>& pts,
|
||||
std::vector<std::array<int, 3>>& tris) {
|
||||
pts = {Point3D(-1, -1, -1), Point3D(1, -1, -1), Point3D(1, 1, -1), Point3D(-1, 1, -1),
|
||||
Point3D(-1, -1, 1), Point3D(1, -1, 1), Point3D(1, 1, 1), Point3D(-1, 1, 1)};
|
||||
tris = {{0, 2, 1}, {0, 3, 2}, // z = -1
|
||||
{4, 5, 6}, {4, 6, 7}, // z = +1
|
||||
{0, 1, 5}, {0, 5, 4}, // y = -1
|
||||
{3, 7, 6}, {3, 6, 2}, // y = +1
|
||||
{0, 4, 7}, {0, 7, 3}, // x = -1
|
||||
{1, 2, 6}, {1, 6, 5}}; // x = +1
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(MeshRepairTest, WeldAndUnify_BoxSoupMixedWinding) {
|
||||
std::vector<Point3D> pts;
|
||||
std::vector<std::array<int, 3>> tris;
|
||||
box_corners_and_tris(pts, tris);
|
||||
// 人为翻转一半三角形:逐面独立输出 + 绕向混杂 → 散度体积内部抵消
|
||||
for (size_t i = 0; i < tris.size(); i += 2) std::swap(tris[i][1], tris[i][2]);
|
||||
auto soup = make_tri_soup(pts, tris);
|
||||
EXPECT_EQ(soup.num_vertices(), 36u); // 12 × 3:公共边未共享
|
||||
|
||||
auto report = mesh_healing_report(soup);
|
||||
EXPECT_GT(report.boundary_edges, 0);
|
||||
EXPECT_FALSE(report.is_watertight);
|
||||
|
||||
auto solid = weld_and_unify_orientation(soup);
|
||||
EXPECT_EQ(solid.num_vertices(), 8u); // 位置焊接为 8 个角点
|
||||
EXPECT_EQ(solid.num_faces(), 12u); // 三角形数守恒(标量绕向不产生退化)
|
||||
|
||||
auto fixed = mesh_healing_report(solid);
|
||||
EXPECT_EQ(fixed.boundary_edges, 0);
|
||||
EXPECT_TRUE(fixed.is_watertight);
|
||||
EXPECT_TRUE(fixed.winding_consistent);
|
||||
EXPECT_TRUE(fixed.outward_oriented);
|
||||
EXPECT_NEAR(fixed.mesh_volume, 8.0, 1e-9); // 2³ 立方体
|
||||
}
|
||||
|
||||
TEST(MeshRepairTest, WeldAndUnify_FlipsSameDirectionSharedEdge) {
|
||||
// 顶点已共享,但共享边 1-2 被两侧同向遍历 → 绕向不一致
|
||||
HalfedgeMesh m;
|
||||
m.build_from_triangles(
|
||||
{Point3D(0, 0, 0), Point3D(1, 0, 0), Point3D(1, 1, 0), Point3D(0, 1, 0)},
|
||||
{{0, 1, 2}, {3, 1, 2}});
|
||||
|
||||
auto bad = mesh_healing_report(m);
|
||||
EXPECT_FALSE(bad.winding_consistent);
|
||||
EXPECT_GT(bad.flipped_faces, 0);
|
||||
|
||||
auto fixed_mesh = weld_and_unify_orientation(m);
|
||||
auto ok = mesh_healing_report(fixed_mesh);
|
||||
EXPECT_TRUE(ok.winding_consistent);
|
||||
EXPECT_EQ(ok.flipped_faces, 0);
|
||||
EXPECT_EQ(ok.boundary_edges, 4); // 四边形外边界
|
||||
EXPECT_EQ(fixed_mesh.num_vertices(), 4u);
|
||||
EXPECT_EQ(fixed_mesh.num_faces(), 2u);
|
||||
}
|
||||
|
||||
TEST(MeshRepairTest, WeldAndUnify_KeepsSeparateComponentsAndWeldTolerance) {
|
||||
// 两个相距 2 的独立三角形:不应被焊接(容差远小于间距),各自翻正
|
||||
std::vector<Point3D> pts = {Point3D(0, 0, 0), Point3D(1, 0, 0), Point3D(0, 1, 0),
|
||||
Point3D(3, 0, 0), Point3D(4, 0, 0), Point3D(3, 1, 0)};
|
||||
std::vector<std::array<int, 3>> tris = {{0, 1, 2}, {3, 5, 4}};
|
||||
auto soup = make_tri_soup(pts, tris);
|
||||
|
||||
auto solid = weld_and_unify_orientation(soup);
|
||||
EXPECT_EQ(solid.num_vertices(), 6u);
|
||||
EXPECT_EQ(solid.num_faces(), 2u);
|
||||
|
||||
// 显式容差大于间距 → 两个三角形被合并为一点邻域
|
||||
auto merged = weld_and_unify_orientation(soup, 5.0);
|
||||
EXPECT_LT(merged.num_vertices(), 6u);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user