Files

340 lines
12 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 "vde/sdf/sdf_to_mesh.h"
#include <gtest/gtest.h>
using namespace vde::sdf;
using vde::core::Point3D;
TEST(SdfToMesh, SphereProducesValidMesh) {
auto sphere = SdfNode::sphere(2.0);
auto mesh = sdf_to_mesh(sphere, 32, 0.0);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
// All vertices should be near the sphere surface (r ≈ 2)
for (const auto& v : mesh.vertices) {
double r = v.norm();
EXPECT_NEAR(r, 2.0, 1.0); // coarse resolution → loose tolerance
}
// Each triangle should have 3 indices
for (const auto& tri : mesh.triangles) {
for (int i = 0; i < 3; ++i) {
EXPECT_GE(tri[i], 0);
EXPECT_LT(tri[i], static_cast<int>(mesh.vertices.size()));
}
}
}
TEST(SdfToMesh, UnionOfTwoSpheres) {
auto s1 = SdfNode::translate(SdfNode::sphere(1.0), Point3D(-1.5, 0, 0));
auto s2 = SdfNode::translate(SdfNode::sphere(1.0), Point3D(1.5, 0, 0));
auto tree = SdfNode::op_union(std::move(s1), std::move(s2));
auto mesh = sdf_to_mesh(tree, 32, 0.0);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
TEST(SdfToMesh, BoxProducesValidMesh) {
auto box = SdfNode::box(Point3D(1, 1, 1));
auto mesh = sdf_to_mesh(box, 32, 0.0);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
TEST(SdfToMesh, HigherResolutionProducesMoreTriangles) {
auto sphere = SdfNode::sphere(1.0);
auto low = sdf_to_mesh(sphere, 16, 0.0);
auto high = sdf_to_mesh(sphere, 32, 0.0);
EXPECT_GT(high.vertices.size(), low.vertices.size());
}
TEST(SdfToMesh, LambdaSphere) {
auto mesh = sdf_to_mesh_lambda(
[](double x, double y, double z) {
return std::sqrt(x*x + y*y + z*z) - 2.0;
},
Point3D(-3, -3, -3), Point3D(3, 3, 3),
32, 0.0
);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
TEST(SdfToMesh, LambdaBox) {
auto mesh = sdf_to_mesh_lambda(
[](double x, double y, double z) {
double dx = std::abs(x) - 1.0;
double dy = std::abs(y) - 1.0;
double dz = std::abs(z) - 1.0;
return std::sqrt(std::max(dx, 0.0) * std::max(dx, 0.0) +
std::max(dy, 0.0) * std::max(dy, 0.0) +
std::max(dz, 0.0) * std::max(dz, 0.0)) +
std::min(std::max({dx, dy, dz}), 0.0);
},
Point3D(-2, -2, -2), Point3D(2, 2, 2),
32, 0.0
);
EXPECT_GT(mesh.vertices.size(), 0u);
EXPECT_GT(mesh.triangles.size(), 0u);
}
// ═══════════════════════════════════════════════════════════
// Phase-2: NEW mesh → SDF sampler (include/vde/sdf/sdf_from_mesh.h)
// ═══════════════════════════════════════════════════════════
#include "vde/sdf/sdf_from_mesh.h"
#include "vde/mesh/halfedge_mesh.h"
#include "vde/mesh/subdivision.h"
#include <cmath>
#include <limits>
#include <random>
#include <vector>
#if defined(VDE_TEST_HAS_COMPUTE)
#include "vde/compute/gpu_bvh.h"
#endif
namespace {
vde::mesh::HalfedgeMesh p2s_cube_mesh() {
const double h = 0.5;
vde::mesh::HalfedgeMesh m;
m.build_from_triangles(
{{-h,-h,-h},{h,-h,-h},{h,h,-h},{-h,h,-h},{-h,-h,h},{h,-h,h},{h,h,h},{-h,h,h}},
{{0,3,2},{0,2,1},{4,5,6},{4,6,7},{0,1,5},{0,5,4},
{3,7,6},{3,6,2},{0,4,7},{0,7,3},{1,2,6},{1,6,5}});
return m;
}
vde::mesh::HalfedgeMesh p2s_sphere_mesh() {
auto m = p2s_cube_mesh();
for (int i = 0; i < 3; ++i) m = vde::mesh::loop_subdivide(m);
for (size_t i = 0; i < m.num_vertices(); ++i) {
auto p = m.vertex(i);
p.normalize();
m.set_vertex(i, p);
}
m.update_normals();
return m;
}
} // namespace
TEST(Phase2SdfFromMesh, UnitCubeKnownDistances) {
auto cube = p2s_cube_mesh();
auto f = sdf_from_mesh(cube);
EXPECT_NEAR(f(Point3D(0, 0, 0)), -0.5, 1e-9); // inside
EXPECT_NEAR(f(Point3D(2, 0, 0)), 1.5, 1e-9); // outside
EXPECT_NEAR(f(Point3D(0.5, 0, 0)), 0.0, 1e-9); // on surface
}
TEST(Phase2SdfFromMesh, SphereMeshMatchesAnalytic) {
auto sphere = p2s_sphere_mesh();
auto f = sdf_from_mesh(sphere);
EXPECT_NEAR(f(Point3D(0, 0, 0)), -1.0, 0.05);
EXPECT_NEAR(f(Point3D(2, 0, 0)), 1.0, 0.05);
EXPECT_NEAR(f(Point3D(1, 0, 0)), 0.0, 0.03);
// Band clamping
auto g = sdf_from_mesh(sphere, 0.25);
EXPECT_NEAR(g(Point3D(3, 0, 0)), 0.25, 1e-9);
}
// ═══════════════════════════════════════════════════════════
// VDE-1296: BVH 加速与批量采样回归(语义必须与逐点 O(F) 版一致)
// ═══════════════════════════════════════════════════════════
namespace {
using vde::core::Vector3D;
// 测试内独立复刻旧 O(F) 实现(Ericson 最近点 + Möller–Trumbore 奇偶),作为语义基准。
vde::core::Point3D ref_closest_on_tri(const vde::core::Point3D& p,
const vde::core::Point3D& a,
const vde::core::Point3D& b,
const vde::core::Point3D& c) {
const Vector3D ab = b - a, ac = c - a, ap = p - a;
const double d1 = ab.dot(ap), d2 = ac.dot(ap);
if (d1 <= 0.0 && d2 <= 0.0) return a;
const Vector3D bp = p - b;
const double d3 = ab.dot(bp), d4 = ac.dot(bp);
if (d3 >= 0.0 && d4 <= d3) return b;
const double vc = d1 * d4 - d3 * d2;
if (vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0) return a + ab * (d1 / (d1 - d3));
const Vector3D cp = p - c;
const double d5 = ab.dot(cp), d6 = ac.dot(cp);
if (d6 >= 0.0 && d5 <= d6) return c;
const double vb = d5 * d2 - d1 * d6;
if (vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0) return a + ac * (d2 / (d2 - d6));
const double va = d3 * d6 - d5 * d4;
if (va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0)
return b + (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6)));
const double denom = va + vb + vc;
if (std::abs(denom) < 1e-30) return a;
return a + ab * (vb / denom) + ac * (vc / denom);
}
bool ref_ray_hits(const vde::core::Point3D& o, const Vector3D& dir,
const vde::core::Point3D& a, const vde::core::Point3D& b,
const vde::core::Point3D& c) {
const Vector3D e1 = b - a, e2 = c - a;
const Vector3D pvec = dir.cross(e2);
const double det = e1.dot(pvec);
if (std::abs(det) < 1e-14) return false;
const double inv = 1.0 / det;
const Vector3D tvec = o - a;
const double u = tvec.dot(pvec) * inv;
if (u < 0.0 || u > 1.0) return false;
const Vector3D qvec = tvec.cross(e1);
const double v = dir.dot(qvec) * inv;
if (v < 0.0 || u + v > 1.0) return false;
return e2.dot(qvec) * inv > 1e-9;
}
struct RefTri {
vde::core::Point3D a, b, c;
};
std::vector<RefTri> ref_collect(const vde::mesh::HalfedgeMesh& mesh) {
std::vector<RefTri> tris;
for (std::size_t fi = 0; fi < mesh.num_faces(); ++fi) {
auto fv = mesh.face_vertices(static_cast<int>(fi));
if (fv.size() != 3) continue;
tris.push_back({mesh.vertex(static_cast<std::size_t>(fv[0])),
mesh.vertex(static_cast<std::size_t>(fv[1])),
mesh.vertex(static_cast<std::size_t>(fv[2]))});
}
return tris;
}
double ref_sdf(const std::vector<RefTri>& tris, const vde::core::Point3D& p) {
if (tris.empty()) return std::numeric_limits<double>::max();
static const Vector3D dir =
Vector3D(1.0, 0.6180339887498949, 0.3819660112501051).normalized();
double best_sq = std::numeric_limits<double>::max();
for (const auto& t : tris) {
const double d2 = (p - ref_closest_on_tri(p, t.a, t.b, t.c)).squaredNorm();
if (d2 < best_sq) best_sq = d2;
}
int hits = 0;
for (const auto& t : tris)
if (ref_ray_hits(p, dir, t.a, t.b, t.c)) ++hits;
const double dist = std::sqrt(best_sq);
return (hits % 2) ? -dist : dist;
}
std::vector<vde::core::Point3D> sample_box_points(std::size_t count, double lo,
double hi, unsigned seed) {
std::mt19937 rng(seed);
std::uniform_real_distribution<double> dist(lo, hi);
std::vector<vde::core::Point3D> pts;
pts.reserve(count);
for (std::size_t i = 0; i < count; ++i)
pts.emplace_back(dist(rng), dist(rng), dist(rng));
return pts;
}
} // namespace
TEST(Phase2SdfFromMesh, BvhMatchesBruteForceReference) {
auto sphere = p2s_sphere_mesh(); // 12 * 4^3 = 768 三角
ASSERT_EQ(sphere.num_faces(), 768u);
auto ref = ref_collect(sphere);
auto f = sdf_from_mesh(sphere);
const auto pts = sample_box_points(200, -1.6, 1.6, 20261105);
double max_diff = 0.0;
for (const auto& p : pts) {
const double expected = ref_sdf(ref, p);
const double actual = f(p);
max_diff = std::max(max_diff, std::abs(actual - expected));
EXPECT_DOUBLE_EQ(actual, expected) << "point " << p.x() << "," << p.y() << "," << p.z();
}
EXPECT_EQ(max_diff, 0.0); // BVH 只改遍历顺序,叶节点仍用原始几何原语
}
TEST(Phase2SdfFromMesh, BatchCpuMatchesSinglePointSampler) {
auto sphere = p2s_sphere_mesh();
auto f = sdf_from_mesh(sphere);
std::vector<vde::core::Point3D> pts = {
vde::core::Point3D(0, 0, 0), // inside
vde::core::Point3D(2, 0, 0), // outside
vde::core::Point3D(1, 0, 0), // on surface
vde::core::Point3D(0.3, -0.4, 0.5), // inside
vde::core::Point3D(-1.4, 0.9, 0.2), // outside
};
MeshSdfOptions opts;
opts.use_gpu = false;
MeshSdfBatchInfo info;
const auto batch = sample_mesh_sdf(sphere, pts, opts, &info);
ASSERT_EQ(batch.size(), pts.size());
EXPECT_FALSE(info.gpu);
EXPECT_EQ(info.backend, "cpu-bvh");
EXPECT_EQ(info.triangle_count, 768u);
EXPECT_EQ(info.point_count, pts.size());
for (std::size_t i = 0; i < pts.size(); ++i)
EXPECT_NEAR(batch[i], f(pts[i]), 1e-12) << "index " << i;
// band 截断与逐点版一致
MeshSdfOptions clamped = opts;
clamped.band = 0.25;
auto g = sdf_from_mesh(sphere, 0.25);
const auto batch_clamped = sample_mesh_sdf(sphere, pts, clamped, nullptr);
for (std::size_t i = 0; i < pts.size(); ++i)
EXPECT_NEAR(batch_clamped[i], g(pts[i]), 1e-12) << "index " << i;
}
TEST(Phase2SdfFromMesh, BatchGpuMatchesCpuWhenAvailable) {
auto sphere = p2s_sphere_mesh();
const auto pts = sample_box_points(256, -1.5, 1.5, 20261106);
MeshSdfOptions cpu_opts;
cpu_opts.use_gpu = false;
const auto cpu = sample_mesh_sdf(sphere, pts, cpu_opts, nullptr);
#if defined(VDE_TEST_HAS_COMPUTE)
if (!vde::compute::GpuBvh::gpu_supported()) {
GTEST_SKIP() << "本机无可用 GPU/OpenCL 设备";
}
MeshSdfOptions gpu_opts;
gpu_opts.use_gpu = true;
gpu_opts.gpu_min_triangles = 1; // 强制走 GPU 距离查询
gpu_opts.verify_gpu = true;
MeshSdfBatchInfo info;
const auto gpu = sample_mesh_sdf(sphere, pts, gpu_opts, &info);
ASSERT_EQ(gpu.size(), pts.size());
EXPECT_TRUE(info.gpu) << "backend=" << info.backend;
EXPECT_EQ(info.backend, "opencl-bvh+cpu-parity");
EXPECT_FALSE(info.device_name.empty());
for (std::size_t i = 0; i < pts.size(); ++i) {
ASSERT_TRUE(std::isfinite(gpu[i]));
EXPECT_NEAR(gpu[i], cpu[i], 1e-12) << "index " << i;
}
#else
GTEST_SKIP() << "build 未链接 compute 模块";
#endif
}
TEST(Phase2SdfFromMesh, BatchEmptyMeshReturnsMaxDouble) {
vde::mesh::HalfedgeMesh empty;
const std::vector<vde::core::Point3D> pts = {
vde::core::Point3D(0, 0, 0), vde::core::Point3D(1, 2, 3)};
MeshSdfBatchInfo info;
const auto values = sample_mesh_sdf(empty, pts, {}, &info);
ASSERT_EQ(values.size(), 2u);
for (double v : values)
EXPECT_EQ(v, std::numeric_limits<double>::max());
EXPECT_EQ(info.triangle_count, 0u);
EXPECT_FALSE(info.gpu);
}
TEST(Phase2SdfFromMesh, BatchEmptyPointListIsNoOp) {
auto cube = p2s_cube_mesh();
MeshSdfBatchInfo info;
const auto values = sample_mesh_sdf(cube, {}, {}, &info);
EXPECT_TRUE(values.empty());
EXPECT_EQ(info.point_count, 0u);
EXPECT_EQ(info.triangle_count, 12u);
}