Files
ViewDesignEngine/tests/mesh/test_marching_cubes.cpp
hm 281ca1d394
Build & Test / build-and-test (push) Canceled after 0s
VDE Build & Test / build-and-test (push) Canceled after 0s
Build & Test / python-bindings (push) Canceled after 0s
fix(mesh,boolean): VDE-893 修复 sdf_smooth_subtraction/smooth_hc_laplacian 坏实现并补判别性测试
sdf_smooth_subtraction: 参数顺序反转(等价 op_smooth_difference(d2,d1,k),与文档 d1-d2 及规范相反)+ k<=0 除零/NaN;改为 op_smooth_difference(d1,d2,k) 一致式并加 k<=0 锐利退化守卫。sdf_smooth_union 同补守卫。

smooth_hc_laplacian: 回推项误用顶点上一轮自身位移(契约应为 avg(neighbor_b)),单尖峰 5 轮由 1.0 放大到 1.99(发散);改为标准 Vollmer HC 两步,修复后 0.68 且不越界放大。

补 fit_nurbs_least_squares(平面点云拟合逐点复算)与 clip_mesh(裁剪保留面独立质心分类复算)判别性测试;复核 collision/sketch/mesh/boolean 清单假阳性并更新审计(未测试 160->140)。
2026-10-06 09:28:30 +08:00

334 lines
14 KiB
C++
Raw Permalink 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.
#include <gtest/gtest.h>
#include "vde/mesh/marching_cubes.h"
#include "vde/mesh/halfedge_mesh.h"
#include "vde/sdf/sdf_operations.h"
#include <set>
#include <map>
#include <algorithm>
#include <cmath>
using namespace vde::mesh;
namespace {
// 立方体 12 条边的端角点
constexpr int kCornerPairs[12][2] = {
{0,1},{1,2},{2,3},{3,0},{4,5},{5,6},{6,7},{7,4},{0,4},{1,5},{2,6},{3,7}
};
// 由角点配置计算边表掩码(与 kEdgeTable 语义一致)
int edge_mask_from_cube_index(int cube_index) {
int mask = 0;
for (int e = 0; e < 12; ++e) {
bool in0 = (cube_index >> kCornerPairs[e][0]) & 1;
bool in1 = (cube_index >> kCornerPairs[e][1]) & 1;
if (in0 != in1) mask |= (1 << e);
}
return mask;
}
// 单立方体内的三角化必须是「三角化圆盘」的并集:
// - 每条相交边至少被使用 1 次(表面必须穿过它)
// - 每条非相交边不得被使用
// - 每条几何边(两个边中点之间)被使用 1 次(圆盘边界)或 2 次(内部弦)
// - 边界边构成闭合环(每个边界顶点度 = 2)
// - Euler 公式:V - E + F = 圆盘数(= 边界环数)
// 注意:这不是「每条相交边恰好 2 次」——经典 MC 中三角形边是圆盘边界,
// 相邻立方体在共享面上补足另一半,故单立方体内相交边出现 1 次即正确。
struct DiskCheck {
bool ok = true;
std::string msg;
};
DiskCheck check_disk_triangulation(const std::vector<std::array<int, 3>>& tris, int mask) {
DiskCheck r;
// 1) 退化三角形 / 非相交边 / 相交边使用次数
std::array<int, 12> usage{};
for (const auto& t : tris) {
if (t[0] == t[1] || t[1] == t[2] || t[0] == t[2]) {
r.ok = false; r.msg += "degenerate-tri ";
}
for (int e : t) {
if (!(mask & (1 << e))) { r.ok = false; r.msg += "uncut-edge-used "; }
++usage[e];
}
}
for (int e = 0; e < 12; ++e) {
if ((mask & (1 << e)) && usage[e] == 0) {
r.ok = false; r.msg += "cut-edge-unused ";
}
}
// 2) 几何边使用计数((a,b) 无序对)
std::map<std::pair<int, int>, int> gedge;
for (const auto& t : tris) {
for (int k = 0; k < 3; ++k) {
int a = t[k], b = t[(k + 1) % 3];
if (a > b) std::swap(a, b);
++gedge[{a, b}];
}
}
for (const auto& [key, cnt] : gedge) {
if (cnt != 1 && cnt != 2) {
r.ok = false; r.msg += "geom-edge-cnt" + std::to_string(cnt) + " ";
}
}
// 3) 边界子图(使用 1 次的几何边):顶点度必须 = 2(闭合环)
std::array<std::vector<int>, 12> boundary;
for (const auto& [key, cnt] : gedge) {
if (cnt != 1) continue;
boundary[key.first].push_back(key.second);
boundary[key.second].push_back(key.first);
}
for (int e = 0; e < 12; ++e)
if (boundary[e].size() == 1 || boundary[e].size() > 2) {
r.ok = false; r.msg += "boundary-deg" + std::to_string(boundary[e].size()) + " ";
}
// 4) Euler:V - E + F = 边界环数(每个圆盘恰好 1 个闭合边界)
int V = 0, F = static_cast<int>(tris.size());
for (int e = 0; e < 12; ++e)
if (usage[e]) ++V;
int E = static_cast<int>(gedge.size());
int nloops = 0;
std::array<bool, 12> bvis{};
for (int e = 0; e < 12; ++e) {
if (boundary[e].empty() || bvis[e]) continue;
++nloops;
int cur = e, prev = -1;
while (true) {
bvis[cur] = true;
if (boundary[cur].size() != 2) break;
int nxt = boundary[cur][0] == prev ? boundary[cur][1] : boundary[cur][0];
if (nxt == e) break;
prev = cur;
cur = nxt;
}
}
if (V - E + F != nloops) {
r.ok = false; r.msg += "euler(V=" + std::to_string(V) + ",E=" + std::to_string(E) +
",F=" + std::to_string(F) + ",loops=" + std::to_string(nloops) + ") ";
}
return r;
}
} // namespace
/// 测试 sdf_sphere 的基本计算
TEST(MarchingCubesTest, SdfSphereAtCenter) {
// 在球心处,距离 = -r(内部)
double d = sdf_sphere(0, 0, 0, 0, 0, 0, 1.0);
EXPECT_DOUBLE_EQ(d, -1.0);
}
TEST(MarchingCubesTest, SdfSphereOnSurface) {
// 在球面上,距离 = 0
double d = sdf_sphere(1, 0, 0, 0, 0, 0, 1.0);
EXPECT_NEAR(d, 0.0, 1e-9);
}
TEST(MarchingCubesTest, SdfSphereOutside) {
// 外部点
double d = sdf_sphere(3, 0, 0, 0, 0, 0, 1.0);
EXPECT_NEAR(d, 2.0, 1e-9);
}
TEST(MarchingCubesTest, SdfBoxCenter) {
// 在立方体中心,距离 = -min(hx,hy,hz)(内部)
double d = sdf_box(0, 0, 0, 1.0, 1.0, 1.0);
EXPECT_NEAR(d, -1.0, 1e-9);
}
TEST(MarchingCubesTest, MarchingCubesSphere) {
// 提取球面等值面
auto f = [](double x, double y, double z) {
return sdf_sphere(x, y, z, 0, 0, 0, 1.0);
};
auto mesh = marching_cubes(f, 0.0,
Point3D(-2, -2, -2), Point3D(2, 2, 2), 16);
// 应有顶点和三角形
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
TEST(MarchingCubesTest, MarchingCubesBox) {
// 提取立方体等值面
auto f = [](double x, double y, double z) {
return sdf_box(x, y, z, 1.0, 1.0, 1.0);
};
auto mesh = marching_cubes(f, 0.0,
Point3D(-2, -2, -2), Point3D(2, 2, 2), 16);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
// ═══════════════════════════════════════════════════════════
// 无查表三角化(mc_triangulate_case)完整性与正确性测试
// ═══════════════════════════════════════════════════════════
TEST(MarchingCubesTest, TriangulateAllConfigsValidDisk) {
// 遍历全部 256 种配置:单立方体内三角化必须是三角化圆盘的并集
// (相交边 ≥1 次、非相交边 0 次、几何边 1/2 次、边界闭合环、Euler 校验)
for (int cube_index = 0; cube_index < 256; ++cube_index) {
int mask = edge_mask_from_cube_index(cube_index);
auto tris = mc_triangulate_case(mask, cube_index);
if (mask == 0) {
EXPECT_TRUE(tris.empty()) << "cube_index=" << cube_index;
continue;
}
ASSERT_FALSE(tris.empty()) << "cube_index=" << cube_index;
auto r = check_disk_triangulation(tris, mask);
EXPECT_TRUE(r.ok) << "cube_index=" << cube_index << " mask=0x" << std::hex << mask
<< std::dec << " " << r.msg;
}
}
TEST(MarchingCubesTest, TriangulateSingleCornerCases) {
// 单角点在内部:经典查表已知结果(作为基准校验)
// cube_index bit c 置位 = 角点 c 在内部
struct Case { int idx; std::array<int, 3> tri; };
std::vector<Case> cases = {
{1, {0, 8, 3}}, // 角点 0
{2, {0, 1, 9}}, // 角点 1
{4, {1, 2, 10}}, // 角点 2
{8, {3, 11, 2}}, // 角点 3
{16, {4, 7, 8}}, // 角点 4
{32, {9, 5, 4}}, // 角点 5
{64, {10, 6, 5}}, // 角点 6
{128,{6, 7, 11}}, // 角点 7
};
for (const auto& c : cases) {
int mask = edge_mask_from_cube_index(c.idx);
auto tris = mc_triangulate_case(mask, c.idx);
ASSERT_EQ(tris.size(), 1u) << "cube_index=" << c.idx;
std::set<int> got{tris[0][0], tris[0][1], tris[0][2]};
std::set<int> want{c.tri[0], c.tri[1], c.tri[2]};
EXPECT_EQ(got, want) << "cube_index=" << c.idx;
}
}
TEST(MarchingCubesTest, SphereWatertightSerial) {
// 串行 MC:球面应完全水密(无边界边),证明跨立方体方向一致
auto f = [](double x, double y, double z) {
return sdf_sphere(x, y, z, 0, 0, 0, 1.0);
};
auto mesh = marching_cubes(f, 0.0,
Point3D(-2, -2, -2), Point3D(2, 2, 2), 48);
ASSERT_GT(mesh.triangles.size(), 0u);
HalfedgeMesh hemesh;
hemesh.build_from_triangles(mesh.vertices, mesh.triangles);
int boundary = 0;
for (size_t hei = 0; hei < hemesh.num_edges() * 2; ++hei)
if (hemesh.is_boundary_edge(static_cast<int>(hei))) ++boundary;
EXPECT_EQ(boundary, 0);
}
TEST(MarchingCubesTest, VoxelGridWatertight) {
// VoxelGrid 路径同样应水密。
// 注意:网格角点范围 = [origin, origin+(n-1)*cell_size](n 个体素仅 n-1 个间隔),
// 必须覆盖整个球面(半径 1),否则等值面被网格边界裁剪 → 非水密。
VoxelGrid grid;
grid.nx = grid.ny = grid.nz = 32;
grid.cell_size = 2.0 / (grid.nx - 1); // 角点恰好覆盖 [-1, 1]
grid.origin = Point3D(-1, -1, -1);
grid.values.resize(grid.size());
for (int z = 0; z < grid.nz; ++z)
for (int y = 0; y < grid.ny; ++y)
for (int x = 0; x < grid.nx; ++x) {
auto c = grid.voxel_center(x, y, z);
grid.values[grid.index(x, y, z)] =
sdf_sphere(c.x(), c.y(), c.z(), 0, 0, 0, 1.0);
}
auto mesh = marching_cubes(grid, 0.0);
ASSERT_GT(mesh.triangles.size(), 0u);
HalfedgeMesh hemesh;
hemesh.build_from_triangles(mesh.vertices, mesh.triangles);
int boundary = 0;
for (size_t hei = 0; hei < hemesh.num_edges() * 2; ++hei)
if (hemesh.is_boundary_edge(static_cast<int>(hei))) ++boundary;
EXPECT_EQ(boundary, 0);
}
// ═══════════════════════════════════════════════════════════
// VDE-893: SDF 平滑并集 / 差集 判别性测试
// ═══════════════════════════════════════════════════════════
namespace {
/// 独立参考实现:平滑并集 = 多项式 smin(本测试内独立写出,不复用被测代码)
double ref_smooth_union(double a, double b, double k) {
if (k <= 0.0) return std::min(a, b);
double h = std::clamp(0.5 + 0.5 * (a - b) / k, 0.0, 1.0);
return a * (1.0 - h) + b * h - k * h * (1.0 - h);
}
/// 独立参考实现:平滑差集 = o(a - b),即多项式 smax(a, -b)
double ref_smooth_difference(double a, double b, double k) {
if (k <= 0.0) return std::max(a, -b);
double h = std::clamp(0.5 - 0.5 * (a + b) / k, 0.0, 1.0);
return a * (1.0 - h) + (-b) * h + k * h * (1.0 - h);
}
} // namespace
TEST(MarchingCubesSdfBlendVDE893Test, SmoothUnion_MatchesIndependentFormula) {
const double k = 0.4;
for (double d1 = -2.0; d1 <= 2.0; d1 += 0.25)
for (double d2 = -2.0; d2 <= 2.0; d2 += 0.25) {
EXPECT_NEAR(sdf_smooth_union(d1, d2, k), ref_smooth_union(d1, d2, k), 1e-12)
<< "d1=" << d1 << " d2=" << d2;
// 与 sdf 模块的规范实现逐点一致(跨模块口径统一)
EXPECT_NEAR(sdf_smooth_union(d1, d2, k),
vde::sdf::op_smooth_union(d1, d2, k), 1e-12);
}
}
TEST(MarchingCubesSdfBlendVDE893Test, SmoothUnion_SaturatesToMinAndBulgesByKQuarter) {
const double k = 0.5;
// 两值分离 >= k 时退化为精确 min
EXPECT_NEAR(sdf_smooth_union(3.0, 0.0, k), 0.0, 1e-12); // min(3,0)=0
EXPECT_NEAR(sdf_smooth_union(-0.5, 2.5, k), -0.5, 1e-12); // min(-0.5,2.5)=-0.5
// d1 == d2 == d 时向下偏移 k/4(多项式 smin 的解析性质)
EXPECT_NEAR(sdf_smooth_union(1.3, 1.3, k), 1.3 - k / 4.0, 1e-12);
// 结果恒不高于 min(平滑并集只会“鼓出”)
EXPECT_LE(sdf_smooth_union(1.3, 1.3, k), 1.3 + 1e-12);
}
TEST(MarchingCubesSdfBlendVDE893Test, SmoothSubtraction_MatchesIndependentAndCanonical) {
const double k = 0.4;
for (double d1 = -2.0; d1 <= 2.0; d1 += 0.25)
for (double d2 = -2.0; d2 <= 2.0; d2 += 0.25) {
EXPECT_NEAR(sdf_smooth_subtraction(d1, d2, k),
ref_smooth_difference(d1, d2, k), 1e-12)
<< "d1=" << d1 << " d2=" << d2;
// 关键判别:与规范 op_smooth_difference(d1,d2,k) 一致 = “d1 减 d2”
// (修复前实现等价于 op_smooth_difference(d2,d1,k),本断言即失败)
EXPECT_NEAR(sdf_smooth_subtraction(d1, d2, k),
vde::sdf::op_smooth_difference(d1, d2, k), 1e-12)
<< "d1=" << d1 << " d2=" << d2;
}
}
TEST(MarchingCubesSdfBlendVDE893Test, SmoothSubtraction_SaturatesToMaxOfD1AndMinusD2) {
const double k = 0.5;
// d1 + d2 >= k → 结果 = d1;d1 + d2 <= -k → 结果 = -d2
EXPECT_NEAR(sdf_smooth_subtraction(5.0, 0.0, k), 5.0, 1e-12); // max(5, 0)
EXPECT_NEAR(sdf_smooth_subtraction(-5.0, 0.0, k), 0.0, 1e-12); // max(-5, 0)
EXPECT_NEAR(sdf_smooth_subtraction(2.0, -3.0, k), 3.0, 1e-12); // max(2, 3)
// 非对称性:交换参数结果一般不同(排除“对称假实现”)
EXPECT_NE(std::abs(sdf_smooth_subtraction(2.0, 0.0, k)
- sdf_smooth_subtraction(0.0, 2.0, k)), 0.0);
}
TEST(MarchingCubesSdfBlendVDE893Test, NonPositiveK_FallsBackToSharpOps) {
// k = 0 时不得出现除零/NaN,应退化为精确 min / max
EXPECT_DOUBLE_EQ(sdf_smooth_union(3.0, -1.0, 0.0), -1.0);
EXPECT_DOUBLE_EQ(sdf_smooth_subtraction(3.0, -1.0, 0.0), 3.0); // max(3, 1)
EXPECT_DOUBLE_EQ(sdf_smooth_union(1.0, 1.0, 0.0), 1.0);
EXPECT_TRUE(std::isfinite(sdf_smooth_union(1.0, 1.0, 0.0)));
EXPECT_TRUE(std::isfinite(sdf_smooth_subtraction(1.0, 1.0, 0.0)));
// 负 k 同样走锐利退化
EXPECT_DOUBLE_EQ(sdf_smooth_union(2.0, 5.0, -1.0), 2.0);
EXPECT_DOUBLE_EQ(sdf_smooth_subtraction(2.0, 5.0, -1.0), 2.0); // max(2, -5)
}