Files
ViewDesignEngine/src/mesh/shape_descriptor.cpp
T

238 lines
8.9 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 shape_descriptor.cpp
* @brief 3D 形状描述符与相似检索实现
*/
#include "vde/mesh/shape_descriptor.h"
#include "vde/brep/brep.h"
#include <algorithm>
#include <cmath>
#include <random>
#include <numeric>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
namespace vde::mesh {
// ═══════════════════════════════════════════════════════════
// ShapeDescriptor 方法
// ═══════════════════════════════════════════════════════════
std::vector<double> ShapeDescriptor::to_vector() const {
std::vector<double> v;
v.reserve(dimension());
v.insert(v.end(), moments.begin(), moments.end());
v.insert(v.end(), d2_histogram.begin(), d2_histogram.end());
v.push_back(compactness);
v.push_back(elongation);
v.push_back(flatness);
v.push_back(volume);
v.push_back(surface_area);
v.push_back(bb_aspect_x);
v.push_back(bb_aspect_z);
return v;
}
double ShapeDescriptor::distance(const ShapeDescriptor& a, const ShapeDescriptor& b) {
// L2 距离(D2 直方图为主,补充几何矩和形状参数)
double sum = 0.0;
// D2 直方图 χ² 距离
for (size_t i = 0; i < 64; ++i) {
double diff = a.d2_histogram[i] - b.d2_histogram[i];
double denom = a.d2_histogram[i] + b.d2_histogram[i] + 1e-10;
sum += diff * diff / denom;
}
// 几何矩 L2
size_t min_mom = std::min(a.moments.size(), b.moments.size());
for (size_t i = 0; i < min_mom; ++i) {
double diff = a.moments[i] - b.moments[i];
sum += diff * diff;
}
// 形状参数
sum += std::pow(a.compactness - b.compactness, 2);
sum += std::pow(a.elongation - b.elongation, 2);
sum += std::pow(a.flatness - b.flatness, 2);
return std::sqrt(sum);
}
double ShapeDescriptor::similarity(const ShapeDescriptor& a, const ShapeDescriptor& b) {
double dist = distance(a, b);
// 映射到 [0, 1]:similarity = exp(-dist)
return std::exp(-dist);
}
// ═══════════════════════════════════════════════════════════
// compute_shape_descriptor
// ═══════════════════════════════════════════════════════════
ShapeDescriptor compute_shape_descriptor(const HalfedgeMesh& mesh, int d2_samples) {
ShapeDescriptor desc;
int nv = mesh.num_vertices();
int nf = mesh.num_faces();
if (nv < 4 || nf < 4) return desc;
// ── 1. 表面积 + 质心 ──
double area = 0.0;
Point3D centroid{0, 0, 0};
int tri_count = 0;
for (int fi = 0; fi < nf; ++fi) {
auto fv = mesh.face_vertices(fi);
if (fv.size() < 3) continue;
Point3D p0 = mesh.vertex(fv[0]);
for (size_t i = 1; i + 1 < fv.size(); ++i) {
Point3D p1 = mesh.vertex(fv[i]);
Point3D p2 = mesh.vertex(fv[i + 1]);
// 三角面面积
area += (p1 - p0).cross(p2 - p0).norm() * 0.5;
// 面质心贡献
centroid = centroid + (p0 + p1 + p2) / 3.0;
tri_count++;
}
}
desc.surface_area = area;
if (tri_count > 0) centroid = centroid / tri_count;
else for (int i = 0; i < nv; ++i) centroid = centroid + mesh.vertex(i);
centroid = centroid / nv;
// ── 1b. 体积(用质心作为参考点,避免法向不一致) ──
double vol = 0.0;
for (int fi = 0; fi < nf; ++fi) {
auto fv = mesh.face_vertices(fi);
if (fv.size() < 3) continue;
Point3D p0 = mesh.vertex(fv[0]);
for (size_t i = 1; i + 1 < fv.size(); ++i) {
Point3D p1 = mesh.vertex(fv[i]);
Point3D p2 = mesh.vertex(fv[i + 1]);
// 四面体体积 = 1/6 * ((p1-ref) × (p2-ref)) · (p0-ref)
Vector3D d0 = p0 - centroid;
Vector3D d1 = p1 - centroid;
Vector3D d2 = p2 - centroid;
vol += std::abs(d1.cross(d2).dot(d0)) / 6.0;
}
}
desc.volume = vol;
// ── 3. 几何矩(0~3阶,归一化) ──
// 协方差矩阵 PCA
Eigen::Matrix3d cov = Eigen::Matrix3d::Zero();
for (int vi = 0; vi < nv; ++vi) {
Vector3D d = mesh.vertex(vi) - centroid;
cov += d * d.transpose();
}
cov /= nv;
Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver(cov);
auto eigenvalues = solver.eigenvalues(); // 升序: λ_min ≤ λ_mid ≤ λ_max
double l_min = std::abs(eigenvalues(0));
double l_mid = std::abs(eigenvalues(1));
double l_max = std::abs(eigenvalues(2));
desc.elongation = (l_mid > 1e-15) ? std::sqrt(l_max / l_mid) : 1.0;
desc.flatness = (l_min > 1e-15) ? std::sqrt(l_mid / l_min) : 1.0;
// 紧凑度 = 36π V² / A³ (球=1)
if (area > 1e-15)
desc.compactness = std::clamp(36.0 * M_PI * desc.volume * desc.volume /
(area * area * area), 0.0, 1.0);
// ── 4. D2 距离分布直方图 ──
std::mt19937 rng(42);
std::uniform_int_distribution<int> vert_dist(0, nv - 1);
// 先采样确定距离范围
double max_dist = 0;
{
auto bb = mesh.bounds();
max_dist = (bb.max() - bb.min()).norm();
}
if (max_dist < 1e-15) max_dist = 1.0;
std::fill(desc.d2_histogram.begin(), desc.d2_histogram.end(), 0.0);
int actual_samples = std::min(d2_samples, nv * nv);
for (int s = 0; s < actual_samples; ++s) {
int i = vert_dist(rng);
int j = vert_dist(rng);
double dist = (mesh.vertex(i) - mesh.vertex(j)).norm() / max_dist;
int bin = static_cast<int>(dist * 64);
if (bin >= 0 && bin < 64)
desc.d2_histogram[bin]++;
}
// 归一化
double total = std::accumulate(desc.d2_histogram.begin(), desc.d2_histogram.end(), 0.0);
if (total > 0)
for (auto& v : desc.d2_histogram) v /= total;
// ── 5. 几何矩向量(归一化矩作为不变量) ──
// 二阶中心矩(对角化后的特征值比)
desc.moments.resize(6);
desc.moments[0] = l_max / (l_min + 1e-15); // 主轴比
desc.moments[1] = l_mid / (l_min + 1e-15);
desc.moments[2] = l_min / (l_max + 1e-15);
desc.moments[3] = desc.compactness;
desc.moments[4] = desc.volume / (max_dist * max_dist * max_dist + 1e-15);
desc.moments[5] = desc.surface_area / (max_dist * max_dist + 1e-15);
// ── 6. 边界框比 ──
auto bb = mesh.bounds();
auto ext = bb.max() - bb.min();
desc.bb_aspect_x = (ext.y() > 1e-15) ? ext.x() / ext.y() : 1.0;
desc.bb_aspect_z = (ext.y() > 1e-15) ? ext.z() / ext.y() : 1.0;
return desc;
}
ShapeDescriptor compute_shape_descriptor_from_brep(const brep::BrepModel& body,
double deflection) {
auto hemesh = body.to_mesh(deflection);
return compute_shape_descriptor(hemesh);
}
// ═══════════════════════════════════════════════════════════
// 相似检索
// ═══════════════════════════════════════════════════════════
std::vector<SimilarityMatch> find_similar_parts(
const ShapeDescriptor& query,
const std::vector<ShapeDescriptor>& library,
int k) {
std::vector<SimilarityMatch> matches;
matches.reserve(library.size());
for (int i = 0; i < static_cast<int>(library.size()); ++i)
matches.push_back({i, ShapeDescriptor::similarity(query, library[i])});
std::sort(matches.begin(), matches.end(),
[](const auto& a, const auto& b) { return a.similarity > b.similarity; });
if (static_cast<int>(matches.size()) > k)
matches.resize(k);
return matches;
}
std::vector<std::vector<int>> detect_duplicates(
const std::vector<ShapeDescriptor>& library,
double similarity_threshold) {
std::vector<std::vector<int>> groups;
std::vector<bool> assigned(library.size(), false);
for (size_t i = 0; i < library.size(); ++i) {
if (assigned[i]) continue;
std::vector<int> group{static_cast<int>(i)};
assigned[i] = true;
for (size_t j = i + 1; j < library.size(); ++j) {
if (assigned[j]) continue;
double sim = ShapeDescriptor::similarity(library[i], library[j]);
if (sim >= similarity_threshold) {
group.push_back(static_cast<int>(j));
assigned[j] = true;
}
}
if (group.size() > 1)
groups.push_back(std::move(group));
}
return groups;
}
} // namespace vde::mesh