Files
ViewDesignEngine/dbg_io_probe.cpp
T
hm b378b191da
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
build(io/brep): VDE-006/013/067 依赖环解除 + 模块开关接线 + 裸 mesh:: 清理
VDE-006:新增集成层 vde_io 归集跨层 TU,依赖图变严格单向
io→brep→{sdf,mesh}→{curves,collision}→spatial→core→foundation,删除
-Wl,--start-group;BrepModel 桥接(brep_to_mesh/mesh_bridge)归 vde_brep。
移除兜底后暴露并修复两处反向依赖:core/icp.cpp→vde_spatial,
brep/parallel_boolean.cpp→vde::boolean(VDE_DEPS_brep 增 boolean)。

VDE-013:顶层解析 VDE_BUILD_*→VDE_ENABLE_*,VDE_DEPS_* 级联关闭,
src/ 与 tests/ 按 VDE_ENABLE_* 门控,使模块开关真正生效。

VDE-067:全仓裸 mesh:: 清理为完全限定名 vde::mesh::(正则命中 0)。

回归:全量构建 EXIT 0;test_icp/test_parallel_boolean/test_geometry_completion
全绿。既有缺陷(FEA 球面网格挂起、CAM in_range 哨兵、3MF 装配、时序竞态)
经取证与本批无关,记入 docs/reference/audit-feedback.md §5。
2026-10-07 06:39:07 +08:00

1027 lines
51 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 dbg_io_probe.cpp
* @brief 单文件 I/O 计时 + 网格健康探针(32-大文件导入进度取消与网格导出诊断)
*
* 用法:
* dbg_io_probe <file> [--heal] [--glb-out <base>] [--weld-snap <mm>]
*
* - 按扩展名分发:.step/.stp/.p21 → import_step;.stl → read_stl;
* .3mf → read_3mf;.glb/.gltf → import_gltf。
* - 环境变量:
* VDE_TIMING_STEP=1 库内打印 [step-timing] parse= / convert= / repair(parse 与
* convert 的耗时占比即进度钩子与优化依据)
* VDE_GLB_RES=<n> GLB 导出弦分段数(默认 32,等价 write_brep_gltf 默认)
* - --heal:对每个导入的 BrepModel 跑 automatic_heal(计 heal 耗时)。
* - --glb-out <base>:导出 GLB(STEP→write_brep_gltf;网格→write_gltf),随后用
* import_gltf 回读并打印网格健康(边界边/反向对/非流形/退化三角)——
* 用于判断"引擎导出的网格文件"是否产生破洞/法向翻转(用户问题 2)。
* - --glb-export-progress:打印 write_brep_gltf 各阶段(Tessellate/BuildMesh/Write)
* 进度回调(验证导出进度上报)。
* - --glb-cancel-after-ms <N>:GLB 导出启动 N ms 后置位取消,验证返回 false
* 且不写文件(协作式取消)。
* - --weld-snap <mm>:对 boundary_edges>0 的网格做空间哈希焊接量化——把间距
* < snap 的顶点合并重建后重数边界边。boundary 在小 snap(如 1e-3mm)即归零
* ⇒ 缝是"未焊接的重合顶点"(可焊);需很大 snap 才消 ⇒ 真实裂缝/T 型接缝。
*
* 输出行统一 [probe] 前缀;各阶段毫秒计时。
*/
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#ifdef _WIN32
#include <io.h> // _findfirst/_findnext(MinGW GCC8 <filesystem> 不可用)
#endif
#include "vde/brep/step_import.h"
#include "vde/brep/brep_heal.h"
#include "vde/foundation/io_stl.h"
#include "vde/foundation/io_3mf.h"
#include "vde/foundation/io_gltf.h"
using namespace vde::brep;
using namespace vde::foundation;
using namespace vde::core;
using namespace vde::mesh;
namespace {
using Clock = std::chrono::steady_clock;
double ms_since(Clock::time_point t0) {
return std::chrono::duration<double, std::milli>(Clock::now() - t0).count();
}
std::string ext_lower(const std::string& p) {
auto pos = p.find_last_of(".\\/");
if (pos == std::string::npos || p[pos] != '.') return {};
std::string e = p.substr(pos);
std::transform(e.begin(), e.end(), e.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return e;
}
/// 网格健康:纯拓扑检查 + 退化三角(相邻顶点重复)。
/// boundary>0 ⇒ 破洞/开口(缺面);flip>0 ⇒ 法向翻转(黑面);nonman>0 ⇒ 非流形。
struct MeshHealth {
size_t nv = 0, nf = 0, ne = 0;
size_t boundary_edges = 0; ///< 只被 1 个面使用的边
size_t nonmanifold = 0; ///< 被 ≥3 个面使用的边
size_t flipped_pairs = 0; ///< 两个相邻面同向经过同一条边(法向翻转对)
size_t degenerate = 0; ///< 面内有重复顶点
void report(const std::string& tag) const {
std::cerr << "[probe] health " << tag << ": nv=" << nv << " nf=" << nf
<< " ne=" << ne << " boundary_edges=" << boundary_edges
<< " flipped_pairs=" << flipped_pairs
<< " nonmanifold=" << nonmanifold << " degenerate=" << degenerate << "\n";
}
};
MeshHealth check_health(const vde::mesh::HalfedgeMesh& m) {
MeshHealth h;
h.nv = m.num_vertices();
h.nf = m.num_faces();
h.ne = m.num_edges();
using Key = std::pair<long long, long long>;
std::map<Key, std::pair<int, int>> edges; // key -> {uses, forward_uses}
for (int fi = 0; fi < static_cast<int>(m.num_faces()); ++fi) {
auto vv = m.face_vertices(fi);
for (size_t i = 0; i < vv.size(); ++i) {
long long a = vv[i], b = vv[(i + 1) % vv.size()];
if (a == b) { ++h.degenerate; continue; }
bool fwd = a < b;
Key k = fwd ? Key(a, b) : Key(b, a);
auto& e = edges[k];
++e.first;
if (fwd) ++e.second;
}
}
for (const auto& kv : edges) {
const int uses = kv.second.first, fwd = kv.second.second;
if (uses == 1) ++h.boundary_edges;
else if (uses >= 3) ++h.nonmanifold;
// 双向各一次 = 正确相反走向;同向出现 ⇒ 相邻面法向翻转
if (uses == 2 && (fwd == 0 || fwd == 2)) ++h.flipped_pairs;
}
return h;
}
/// 空间哈希焊接(O(n)):把彼此距离 < snap 的顶点合并为一个,重建三角。
/// 用于量化 boundary 边到底是"未焊接的重合顶点缝"(小 snap 即消失)
/// 还是"真实裂缝/T 型接缝"(snap 需达到边长量级才消失)。
struct WeldStats {
size_t nv = 0, boundary = 0;
};
WeldStats weld_health(const vde::mesh::HalfedgeMesh& m, double snap) {
const size_t n = m.num_vertices();
std::vector<Point3D> wv;
std::vector<int> remap(n, -1);
using Key3 = std::array<long long, 3>;
std::map<Key3, std::vector<int>> cells;
auto ck = [snap](const Point3D& p) {
return Key3{static_cast<long long>(std::floor(p.x() / snap)),
static_cast<long long>(std::floor(p.y() / snap)),
static_cast<long long>(std::floor(p.z() / snap))};
};
for (size_t i = 0; i < n; ++i) {
const Point3D& p = m.vertex(i);
const Key3 k = ck(p);
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 = cells.find(Key3{k[0] + dx, k[1] + dy, k[2] + dz});
if (it == cells.end()) continue;
for (int wi : it->second) {
if ((p - wv[static_cast<size_t>(wi)]).norm() < snap) {
found = wi;
break;
}
}
}
if (found >= 0) {
remap[i] = found;
} else {
remap[i] = static_cast<int>(wv.size());
wv.push_back(p);
cells[k].push_back(remap[i]);
}
}
std::vector<std::array<int, 3>> tris;
for (size_t fi = 0; fi < m.num_faces(); ++fi) {
auto fv = m.face_vertices(static_cast<int>(fi));
for (size_t t = 0; t + 2 < fv.size(); ++t) {
int a = remap[fv[0]], b = remap[fv[t + 1]], c = remap[fv[t + 2]];
if (a != b && b != c && c != a) tris.push_back({a, b, c});
}
}
using EdgeKey = std::pair<int, int>;
std::map<EdgeKey, int> ec;
for (const auto& tr : tris)
for (int e = 0; e < 3; ++e) {
int a = tr[e], b = tr[(e + 1) % 3];
if (a > b) std::swap(a, b);
++ec[{a, b}];
}
WeldStats ws;
ws.nv = wv.size();
for (const auto& kv : ec)
if (kv.second == 1) ++ws.boundary;
return ws;
}
double g_weld_snap = 0.0; // >0: 对 boundary>0 的网格做焊接量化(--weld-snap <mm>)
/// 网格化几何校验(VDE_GEOSANITY=1 时逐 body 打印):
/// 把 to_mesh 结果的 bbox 与"拓扑真值 bbox"(环顶点 + 每条边曲线 33 点采样)
/// 比较。mesh 明显超出真值(> max(1mm, 2%*diag))⇒ 多余几何(如卡座 z<0
/// 凸出 / UV 炸开的假几何)。曲面鼓出等合理凸起在余量内不误报。
void geocheck_body(const vde::brep::BrepModel& b, size_t body_idx) {
double mn[3] = {1e300, 1e300, 1e300};
double mx[3] = {-1e300, -1e300, -1e300};
auto grow = [&](const Point3D& p) {
const double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
mn[k] = std::min(mn[k], c[k]);
mx[k] = std::max(mx[k], c[k]);
}
};
for (int fi = 0; fi < static_cast<int>(b.num_faces()); ++fi) {
const auto& f = b.face(fi);
for (int li : f.loops) {
const auto& lop = b.loop_by_id(li);
for (int ei : lop.edges) {
const auto& e = b.edge(ei);
grow(b.vertex_by_id(e.v_start).point);
grow(b.vertex_by_id(e.v_end).point);
if (e.curve) {
const auto& ks = e.curve->knots();
const double t0 = ks.empty() ? 0.0 : ks.front();
const double t1 = ks.empty() ? 1.0 : ks.back();
for (int s = 0; s <= 32; ++s)
grow(e.curve->evaluate(t0 + (t1 - t0) * s / 32.0));
}
}
}
}
double diag = 0.0;
for (int k = 0; k < 3; ++k) diag = std::max(diag, mx[k] - mn[k]);
auto m = b.to_mesh();
double mmn[3] = {1e300, 1e300, 1e300};
double mmx[3] = {-1e300, -1e300, -1e300};
for (size_t vi = 0; vi < m.num_vertices(); ++vi) {
const auto& p = m.vertex(vi);
const double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
mmn[k] = std::min(mmn[k], c[k]);
mmx[k] = std::max(mmx[k], c[k]);
}
}
// 鲁棒校验:网格 bbox 必须落在"边曲线采样 bbox + 余量"内。
// 注:部分 STEP 含超域构造边曲线(±1000),会放大 mn/mx——此时该
// 校验只对极端炸面(uv 展开到构造域之外)生效;对正常零件(曲线与
// 网格尺度一致,如带轮 body2)仍能捕获多余凸出。仅顶点 bbox 会因
// 整圆环起终点同顶点而过小,不可作真值。
const char* axisN[3] = {"x", "y", "z"};
double exceed = 0.0;
int ax = -1;
int dir = 0; // 0=lo(mesh 更低) 1=hi(mesh 更高)
for (int k = 0; k < 3; ++k) {
if (mn[k] - mmn[k] > exceed) { exceed = mn[k] - mmn[k]; ax = k; dir = 0; }
if (mmx[k] - mx[k] > exceed) { exceed = mmx[k] - mx[k]; ax = k; dir = 1; }
}
const double margin = std::max(2.0, 0.05 * diag);
std::cerr << "[probe] geocheck body[" << body_idx << "]: faces "
<< b.num_faces() << " nv " << m.num_vertices() << " nf "
<< m.num_faces() << " mesh "
<< mmn[0] << " " << mmn[1] << " " << mmn[2] << " .. " << mmx[0]
<< " " << mmx[1] << " " << mmx[2] << "\n";
if (exceed > margin && ax >= 0)
std::cerr << "[probe] geocheck-body[" << body_idx << "] EXTRA_GEOM exceed="
<< exceed << "mm axis=" << axisN[ax]
<< " side=" << (dir ? "hi" : "lo")
<< " (curve diag " << diag << ", margin " << margin << ")\n";
if (m.num_faces() == 0)
std::cerr << "[probe] geocheck-body[" << body_idx
<< "] EMPTY_MESH faces=" << b.num_faces() << "\n";
}
void health_meshes(const std::vector<vde::mesh::HalfedgeMesh>& meshes,
const std::string& tag, double weld_snap) {
for (size_t i = 0; i < meshes.size(); ++i) {
const vde::mesh::HalfedgeMesh& m = meshes[i];
MeshHealth h = check_health(m);
h.report(tag + "[" + std::to_string(i) + "]");
if (weld_snap > 0.0 && h.boundary_edges > 0) {
auto t = Clock::now();
WeldStats ws = weld_health(m, weld_snap);
std::cerr << "[probe] weld-snap " << weld_snap << "mm " << tag << "["
<< i << "]: nv " << h.nv << " -> " << ws.nv
<< " boundary " << h.boundary_edges << " -> " << ws.boundary
<< " in " << ms_since(t) << "ms\n";
}
}
}
void write_glb_back_and_health(const std::string& path, const std::string& tag) {
auto t = Clock::now();
auto res = import_gltf(path);
std::cerr << "[probe] glb-readback " << path << " in " << ms_since(t) << "ms"
<< " meshes=" << res.meshes.size()
<< " verts=" << res.total_vertices << " tris=" << res.total_triangles
<< " ok=" << res.success << "\n";
if (res.success && !res.meshes.empty())
health_meshes(res.meshes, tag + "-readback", g_weld_snap);
else if (!res.error_message.empty())
std::cerr << "[probe] glb-readback error: " << res.error_message << "\n";
}
std::string file_name(const std::string& p) {
auto pos = p.find_last_of("\\/");
return pos == std::string::npos ? p : p.substr(pos + 1);
}
/// 目录批量筛查(--dir):遍历 .step/.stp/.STEP/.p21,逐个 import,
/// 输出一行汇总(bodies/faces/开放边/耗时)。单进程避免海量进程启动开销;
/// 单文件异常被捕获后继续,不影响整体。
void batch_dir_run(const std::string& dir) {
std::vector<std::string> files;
#ifdef _WIN32
_finddata_t fd;
const std::string pat = dir + "\\*";
intptr_t h = _findfirst(pat.c_str(), &fd);
if (h == -1) {
std::cerr << "[batch] dir open failed: " << pat << "\n";
return;
}
do {
if (fd.attrib & _A_SUBDIR) continue;
std::string name = fd.name;
const std::string e = ext_lower(name);
if (e == ".step" || e == ".stp" || e == ".p21" || e == ".stpnc")
files.push_back(dir + "\\" + name);
} while (_findnext(h, &fd) == 0);
_findclose(h);
#else
std::cerr << "[batch] non-Windows enumeration not implemented\n";
return;
#endif
std::sort(files.begin(), files.end());
std::cerr << "[batch] dir " << dir << " step_files " << files.size() << "\n";
int n_ok = 0, n_err = 0, n_empty = 0;
for (const auto& f : files) {
const auto name = file_name(f);
auto t0 = Clock::now();
try {
auto bodies = vde::brep::import_step(f, {});
const auto err = step_last_error();
size_t faces = 0, topo_open = 0, topo_multi = 0;
for (const auto& b : bodies) {
faces += static_cast<size_t>(b.num_faces());
using EKey = std::pair<long long, long long>;
std::map<EKey, int> tu;
for (int fi2 = 0; fi2 < static_cast<int>(b.num_faces()); ++fi2) {
const auto& fc = b.face(fi2);
for (int li : fc.loops) {
const auto& lop = b.loop_by_id(li);
for (int ei : lop.edges) {
const auto& e = b.edge(ei);
long long a = e.v_start, c = e.v_end;
if (a > c) std::swap(a, c);
++tu[{a, c}];
}
}
}
for (const auto& kv : tu) {
if (kv.second == 1) ++topo_open;
else if (kv.second > 2) ++topo_multi;
}
}
const bool hard_err = (err != vde::brep::StepError::Ok);
std::cerr << "[batch] " << name << " bodies=" << bodies.size()
<< " faces=" << faces << " err=" << static_cast<int>(err)
<< " topo_open=" << topo_open << " topo_multi=" << topo_multi
<< " in=" << ms_since(t0) << "ms\n";
if (hard_err) ++n_err;
else if (bodies.empty()) ++n_empty;
else ++n_ok;
} catch (const std::exception& e) {
std::cerr << "[batch] " << name << " EXCEPTION: " << e.what() << "\n";
++n_err;
} catch (...) {
std::cerr << "[batch] " << name << " UNKNOWN_EXCEPTION\n";
++n_err;
}
}
std::cerr << "[batch] done ok=" << n_ok << " empty=" << n_empty
<< " err=" << n_err << " total=" << files.size() << "\n";
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::cerr << "usage: dbg_io_probe <file> [--heal] [--glb-out <base>]\n"
<< " dbg_io_probe --dir <dir> (batch import scan)\n";
return 2;
}
if (std::string(argv[1]) == "--dir") {
if (argc < 3) {
std::cerr << "usage: dbg_io_probe --dir <dir>\n";
return 2;
}
batch_dir_run(argv[2]);
return 0;
}
const std::string file = argv[1];
bool do_heal = false;
bool do_progress = false;
int cancel_after_ms = 0; // >0: 导入阶段取消测试(毫秒后置位)
int heal_cancel_after_ms = 0; // >0: heal 启动后毫秒置位(验证管道中止 + body 恢复)
std::string glb_base;
std::string batch_dir; // --dir <path>:目录批量筛查(import-only)
bool glb_export_progress = false;
int glb_cancel_after_ms = 0; // >0: GLB 导出启动毫秒后置位取消(验证不写文件)
int res = 32;
if (const char* e = std::getenv("VDE_GLB_RES")) {
char* end = nullptr;
const long v = std::strtol(e, &end, 10);
if (end != e && v > 0) res = static_cast<int>(v);
}
for (int i = 2; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--heal") do_heal = true;
else if (a == "--progress") do_progress = true;
else if (a == "--heal-cancel-after-ms" && i + 1 < argc) {
heal_cancel_after_ms = std::atoi(argv[++i]);
}
else if (a == "--cancel-after-ms" && i + 1 < argc) {
cancel_after_ms = std::atoi(argv[++i]);
}
else if (a == "--glb-out" && i + 1 < argc) glb_base = argv[++i];
else if (a == "--glb-export-progress") glb_export_progress = true;
else if (a == "--glb-cancel-after-ms" && i + 1 < argc) {
glb_cancel_after_ms = std::atoi(argv[++i]);
}
else if (a == "--weld-snap" && i + 1 < argc) {
g_weld_snap = std::atof(argv[++i]);
}
else if (a == "--dir" && i + 1 < argc) batch_dir = argv[++i];
else { std::cerr << "unknown arg: " << a << "\n"; return 2; }
}
if (!batch_dir.empty()) {
batch_dir_run(batch_dir);
return 0;
}
// STEP 导入进度/取消选项(验证新 API;仅在 STEP/STP/P21 路径使用)
std::atomic<bool> cancel_flag{false};
std::thread canceller;
if (cancel_after_ms > 0)
canceller = std::thread([&] {
std::this_thread::sleep_for(std::chrono::milliseconds(cancel_after_ms));
cancel_flag.store(true);
});
vde::brep::StepImportOptions sopt;
long cb_count = 0;
if (do_progress) {
sopt.progress = [&cb_count](vde::brep::StepPhase ph, int pct, const std::string&) {
++cb_count;
std::cerr << "[probe] progress " << (ph == vde::brep::StepPhase::Parse ? "Parse" : "Convert")
<< " " << pct << "%\n";
};
}
if (cancel_after_ms > 0) sopt.cancel = &cancel_flag;
const std::string ext = ext_lower(file);
auto t0 = Clock::now();
try {
if (ext == ".step" || ext == ".stp" || ext == ".p21") {
auto bodies = import_step(file, sopt);
const auto err = step_last_error();
std::cerr << "[probe] STEP import " << file << " in " << ms_since(t0)
<< "ms bodies=" << bodies.size()
<< " cb=" << cb_count
<< " err=" << static_cast<int>(err)
<< (err == vde::brep::StepError::Cancelled
? " (Cancelled)" : "") << "\n";
if (canceller.joinable()) canceller.join();
if (err == vde::brep::StepError::Cancelled) return 0;
// B-rep 拓扑闭合性:每条拓扑边(顶点对)被多少面环使用。
// 全部 ==2 ⇒ CAD 模型是闭合实体,mesh 的 boundary_edges 纯属网格化伪缝;
// 存在 ==1 ⇒ 模型自身带开口(缺面)。
for (size_t bi = 0; bi < bodies.size(); ++bi) {
const auto& b = bodies[bi];
using EKey = std::pair<long long, long long>;
std::map<EKey, int> topo_use;
for (int fi2 = 0; fi2 < static_cast<int>(b.num_faces()); ++fi2) {
const auto& f = b.face(fi2);
for (int li : f.loops) {
const auto& lop = b.loop_by_id(li);
for (int ei : lop.edges) {
const auto& e = b.edge(ei);
long long a = e.v_start, c = e.v_end;
if (a > c) std::swap(a, c);
++topo_use[{a, c}];
}
}
}
size_t open1 = 0, multi = 0;
for (const auto& kv : topo_use) {
if (kv.second == 1) ++open1;
else if (kv.second > 2) ++multi;
}
std::cerr << "[probe] brep-topo body[" << bi << "]: faces "
<< b.num_faces() << " topo_edges " << topo_use.size()
<< " open(use=1)=" << open1
<< " nonmanifold(use>2)=" << multi << "\n";
}
if (std::getenv("VDE_VALIDATE")) {
for (size_t bi = 0; bi < bodies.size(); ++bi) {
const auto& b = bodies[bi];
auto tval = Clock::now();
ValidationResult vr = validate(b);
std::cerr << "[probe] brep-validate body[" << bi << "] in "
<< ms_since(tval) << "ms: valid=" << vr.valid
<< " errors=" << vr.errors.size()
<< " warnings=" << vr.warnings.size()
<< " watertight=" << vr.watertightness
<< " nonmanifold_edges=" << vr.non_manifold_edges
<< " dangling_edges=" << vr.dangling_edges
<< " inconsistent_orient=" << vr.inconsistent_orientations
<< " euler=" << vr.euler_characteristic
<< " intra_self=" << vr.intra_shell_intersect_pairs
<< " inter_self=" << vr.inter_shell_intersect_pairs
<< " penetration=" << vr.penetration_face_pairs
<< " boundary_touch=" << vr.boundary_touch_face_pairs
<< "\n";
for (const auto& e : vr.errors)
std::cerr << "[probe] validate-error: " << e << "\n";
}
}
if (std::getenv("VDE_GEOSANITY")) {
for (size_t bi = 0; bi < bodies.size(); ++bi)
geocheck_body(bodies[bi], bi);
}
// 逐面"网格盒 vs 环盒"飞片定位:面网格包围盒若明显超出该面
// 环顶点包围盒,说明裁剪失效多铺了几何(用户截图里的弧形薄片)。
if (std::getenv("VDE_FACE_MESH")) {
for (size_t bi = 0; bi < bodies.size(); ++bi) {
const auto& b = bodies[bi];
int flagged = 0;
for (int fi = 0; fi < static_cast<int>(b.num_faces()); ++fi) {
const auto& f = b.face(fi);
// 环顶点盒(含边曲线采样点:圆弧边会鼓出顶点盒,
// 不采样会把合法的弧面误报为飞片)
double lmn[3] = {1e300, 1e300, 1e300};
double lmx[3] = {-1e300, -1e300, -1e300};
auto eat = [&](const Point3D& p) {
double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
lmn[k] = std::min(lmn[k], c[k]);
lmx[k] = std::max(lmx[k], c[k]);
}
};
for (int li : f.loops) {
const auto& lop = b.loop_by_id(li);
for (int ei : lop.edges) {
const auto& e = b.edge(ei);
eat(b.vertex_by_id(e.v_start).point);
eat(b.vertex_by_id(e.v_end).point);
if (e.curve) {
auto dom = e.curve->domain();
for (int s = 1; s < 24; ++s)
eat(e.curve->evaluate(
dom.first + (dom.second - dom.first) *
s / 24.0));
}
}
}
// 面网格盒(与 to_mesh 相同的单面路径)
std::vector<Point3D> fv;
std::vector<std::array<int, 3>> ft;
int st = b.mesh_face_diag(fi, 0.01, fv, ft);
double mmn[3] = {1e300, 1e300, 1e300};
double mmx[3] = {-1e300, -1e300, -1e300};
for (const auto& p : fv) {
double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
mmn[k] = std::min(mmn[k], c[k]);
mmx[k] = std::max(mmx[k], c[k]);
}
}
if (fv.empty()) continue;
double ldia = std::max(
{lmx[0] - lmn[0], lmx[1] - lmn[1], lmx[2] - lmn[2]});
// 超出量:网格盒每侧比环盒外扩的最大值
double exceed = 0.0;
for (int k = 0; k < 3; ++k)
exceed = std::max(
exceed, std::max(lmn[k] - mmn[k], mmx[k] - lmx[k]));
// 阈值:绝对 0.5mm 或环直径 5%,取大者(避免曲边加密误报)
double thr = std::max(0.5, 0.05 * ldia);
if (exceed > thr) {
++flagged;
std::cerr << "[facemesh] body " << bi << " face " << fi
<< " st=" << st << " surfId=" << f.surface_id
<< " tsId=" << f.trimmed_surface_id
<< " nv=" << fv.size() << " nf=" << ft.size()
<< " loopDia=" << ldia
<< " exceed=" << exceed
<< " lb " << lmn[0] << " " << lmn[1] << " "
<< lmn[2] << " .. " << lmx[0] << " "
<< lmx[1] << " " << lmx[2]
<< " mb " << mmn[0] << " " << mmn[1] << " "
<< mmn[2] << " .. " << mmx[0] << " "
<< mmx[1] << " " << mmx[2] << "\n";
}
// 绝对尺寸标志:网格盒对角线超 500mm(模型仅 ~120mm),
// 即使环盒同样爆炸(边曲线含 ±1e6 采样)也能抓出飞片面。
double mdia = std::max(
{mmx[0] - mmn[0], mmx[1] - mmn[1], mmx[2] - mmn[2]});
if (mdia > 500.0) {
++flagged;
std::cerr << "[facemesh-huge] body " << bi << " face "
<< fi << " st=" << st
<< " surfId=" << f.surface_id
<< " tsId=" << f.trimmed_surface_id
<< " nv=" << fv.size() << " nf=" << ft.size()
<< " loopDia=" << ldia << " meshDia=" << mdia
<< " mb " << mmn[0] << " " << mmn[1] << " "
<< mmn[2] << " .. " << mmx[0] << " "
<< mmx[1] << " " << mmx[2] << "\n";
}
}
std::cerr << "[facemesh] body " << bi << " flagged=" << flagged
<< " / " << b.num_faces() << "\n";
}
}
// VDE_FACE_STL="i,j,k":把指定面按 to_mesh 单面路径导出 ASCII STL
// (face_<i>.stl),可在 demo/查看器里单独观察嫌疑面的网格形态。
if (const char* fl = std::getenv("VDE_FACE_STL")) {
std::vector<int> want;
{
std::string s(fl);
size_t pos = 0;
while (pos <= s.size()) {
size_t comma = s.find(',', pos);
std::string tok =
s.substr(pos, comma == std::string::npos
? std::string::npos
: comma - pos);
if (!tok.empty()) want.push_back(std::atoi(tok.c_str()));
if (comma == std::string::npos) break;
pos = comma + 1;
}
}
for (size_t bi = 0; bi < bodies.size(); ++bi) {
const auto& b = bodies[bi];
for (int fi : want) {
std::vector<Point3D> fv;
std::vector<std::array<int, 3>> ft;
int st = b.mesh_face_diag(fi, 0.01, fv, ft);
// 附加:绑定曲面信息(判断网格来源曲面是否正确)
{
const auto& f = b.face(fi);
std::cerr << "[facestl] face " << fi
<< " surface_id=" << f.surface_id
<< " num_surfaces=" << b.num_surfaces()
<< " tsId=" << f.trimmed_surface_id
<< " loops=" << f.loops.size();
if (f.surface_id >= 0 &&
f.surface_id <
static_cast<int>(b.num_surfaces())) {
const auto& s = b.surface(f.surface_id);
auto cps = s.control_points();
std::cerr << " cprows=" << cps.size()
<< " cpcols="
<< (cps.empty() ? 0
: cps[0].size());
if (!cps.empty() && !cps[0].empty())
std::cerr << " cp00=(" << cps[0][0].x()
<< "," << cps[0][0].y() << ","
<< cps[0][0].z() << ")";
}
std::cerr << "\n";
}
std::string name = "face_" + std::to_string(bi) + "_" +
std::to_string(fi) + ".stl";
std::ofstream os(name);
os << "solid face\n";
for (const auto& t : ft) {
const Point3D& a = fv[t[0]];
const Point3D& c1 = fv[t[1]];
const Point3D& c2 = fv[t[2]];
Vector3D n = (c1 - a).cross(c2 - a);
double nl = n.norm();
if (nl > 1e-30) n = n / nl;
os << " facet normal " << n.x() << " " << n.y() << " "
<< n.z() << "\n outer loop\n";
for (int vi : {t[0], t[1], t[2]})
os << " vertex " << fv[vi].x() << " "
<< fv[vi].y() << " " << fv[vi].z() << "\n";
os << " endloop\n endfacet\n";
}
std::cerr << "[facestl] face " << fi << " st=" << st
<< " nv=" << fv.size() << " nf=" << ft.size()
<< " -> " << name << "\n";
}
}
}
if (std::getenv("VDE_DIAG_FACES")) {
for (size_t bi = 0; bi < bodies.size(); ++bi) {
const auto& b = bodies[bi];
std::cerr << "[diag] body " << bi << " faces " << b.num_faces()
<< " surfaces " << b.num_surfaces()
<< " ts " << b.num_trimmed_surfaces() << "\n";
for (int fi2 = 0; fi2 < static_cast<int>(b.num_faces()); ++fi2) {
const auto& f = b.face(fi2);
double mn[3] = {1e300, 1e300, 1e300};
double mx[3] = {-1e300, -1e300, -1e300};
for (int li : f.loops) {
const auto& lop = b.loop_by_id(li);
for (int ei : lop.edges) {
const auto& e = b.edge(ei);
for (int vid : {e.v_start, e.v_end}) {
const auto& p = b.vertex_by_id(vid).point;
double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
mn[k] = std::min(mn[k], c[k]);
mx[k] = std::max(mx[k], c[k]);
}
}
}
}
double loopDia = std::max(
{mx[0] - mn[0], mx[1] - mn[1], mx[2] - mn[2]});
double tsDia = 0.0;
if (f.trimmed_surface_id >= 0 &&
f.trimmed_surface_id <
static_cast<int>(b.num_trimmed_surfaces())) {
auto tm = b.trimmed_surface(f.trimmed_surface_id)
.to_mesh(1e-3);
double tmn[3] = {1e300, 1e300, 1e300};
double tmx[3] = {-1e300, -1e300, -1e300};
for (size_t vi = 0; vi < tm.num_vertices(); ++vi) {
const auto& p = tm.vertex(vi);
double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
tmn[k] = std::min(tmn[k], c[k]);
tmx[k] = std::max(tmx[k], c[k]);
}
}
tsDia = std::max(
{tmx[0] - tmn[0], tmx[1] - tmn[1],
tmx[2] - tmn[2]});
}
if (loopDia > 200 || tsDia > 200 ||
f.trimmed_surface_id < 0) {
std::cerr << "[diag] face " << fi2
<< " loopDia " << loopDia << " tsDia "
<< tsDia << " tsId "
<< f.trimmed_surface_id << " surfId "
<< f.surface_id << " lb "
<< mn[0] << " " << mn[1] << " " << mn[2]
<< " .. " << mx[0] << " " << mx[1]
<< " " << mx[2] << "\n";
}
}
int noTs = 0, emptyLoop = 0, hasTs = 0;
for (int fi3 = 0; fi3 < static_cast<int>(b.num_faces()); ++fi3) {
const auto& f = b.face(fi3);
if (f.trimmed_surface_id >= 0 &&
f.trimmed_surface_id <
static_cast<int>(b.num_trimmed_surfaces()))
++hasTs;
else
++noTs;
if (f.loops.empty()) ++emptyLoop;
}
std::cerr << "[diag] hasTs " << hasTs << " noTs " << noTs
<< " emptyLoop " << emptyLoop << "\n";
// 深挖问题面无裁剪面时的真实环/曲面几何
for (int fid : {10, 24, 25, 48}) {
if (fid >= static_cast<int>(b.num_faces())) continue;
const auto& f = b.face(fid);
std::cerr << "[dump] face " << fid << " surfId "
<< f.surface_id << " tsId "
<< f.trimmed_surface_id << " reversed "
<< f.reversed << "\n";
for (int li : f.loops) {
const auto& lop = b.loop_by_id(li);
std::cerr << "[dump] loop " << li << " outer "
<< lop.is_outer << " edges "
<< lop.edges.size() << "\n";
std::vector<Point3D> pts;
if (!lop.edges.empty()) {
int cur = b.edge(lop.edges[0]).v_start;
pts.push_back(b.vertex_by_id(cur).point);
std::vector<char> used(lop.edges.size(), 0);
for (size_t st = 0;
st < lop.edges.size() && pts.size() <=
lop.edges.size(); ++st) {
bool fnd = false;
for (size_t k = 0; k < lop.edges.size(); ++k) {
if (used[k]) continue;
const auto& e = b.edge(lop.edges[k]);
if (e.v_start == cur) cur = e.v_end;
else if (e.v_end == cur) cur = e.v_start;
else continue;
used[k] = 1; fnd = true; break;
}
if (!fnd) break;
pts.push_back(b.vertex_by_id(cur).point);
}
}
if (pts.size() >= 2 && (pts.front() - pts.back()).norm() < 1e-9)
pts.pop_back();
for (size_t k = 0; k < pts.size(); ++k)
std::cerr << "[dump] pt " << k << " "
<< pts[k].x() << " " << pts[k].y()
<< " " << pts[k].z() << "\n";
if (pts.size() >= 3) {
Point3D p0 = pts[0];
Vector3D nv(0, 0, 0);
double area2 = 0.0;
for (size_t k = 0; k < pts.size(); ++k) {
Vector3D a = pts[k] - p0;
Vector3D b2 = pts[(k + 1) % pts.size()] - p0;
nv = nv + a.cross(b2);
area2 +=
a.cross(b2).norm() * 0.5;
}
double mx = 0;
for (size_t k = 0; k < pts.size(); ++k)
mx = std::max(
mx, std::abs(
(pts[k] - p0).dot(nv.normalized())));
std::cerr << "[dump] area ~" << area2
<< " newell (" << nv.x() << " "
<< nv.y() << " " << nv.z()
<< ") maxDevFromPlane " << mx
<< "\n";
}
}
if (f.surface_id >= 0 &&
f.surface_id < static_cast<int>(b.num_surfaces())) {
const auto& ss = b.surface(f.surface_id);
const auto& cps = ss.control_points();
std::cerr << "[dump] surf cp "
<< cps.size() << "x"
<< (cps.empty() ? 0 : cps[0].size())
<< " degU " << ss.degree_u() << " degV "
<< ss.degree_v() << "\n";
for (size_t ci = 0; ci < cps.size(); ++ci) {
std::cerr << "[dump] cprow " << ci;
for (size_t cj = 0;
cj < cps[ci].size(); ++cj)
std::cerr << " (" << cps[ci][cj].x()
<< " " << cps[ci][cj].y()
<< " " << cps[ci][cj].z()
<< ")";
std::cerr << "\n";
}
}
}
auto bm = b.to_mesh();
std::cerr << "[diag] body.to_mesh verts " << bm.num_vertices()
<< " faces " << bm.num_faces() << "\n";
for (double defl : {1e-3, 1e-2, 0.05}) {
auto m2 = b.to_mesh(defl);
double mn[3] = {1e300, 1e300, 1e300};
double mx[3] = {-1e300, -1e300, -1e300};
for (size_t vi = 0; vi < m2.num_vertices(); ++vi) {
const auto& p = m2.vertex(vi);
double c[3] = {p.x(), p.y(), p.z()};
for (int k = 0; k < 3; ++k) {
mn[k] = std::min(mn[k], c[k]);
mx[k] = std::max(mx[k], c[k]);
}
}
std::cerr << "[diag] to_mesh defl " << defl
<< " verts " << m2.num_vertices() << " faces "
<< m2.num_faces() << " xmin " << mn[0]
<< " xmax " << mx[0] << " ymin " << mn[1]
<< " ymax " << mx[1] << " zmin " << mn[2]
<< " zmax " << mx[2] << "\n";
}
{
std::vector<double> vx, vy, vz;
for (size_t vi = 0; vi < bm.num_vertices(); ++vi) {
const auto& p = bm.vertex(vi);
vx.push_back(p.x()); vy.push_back(p.y());
vz.push_back(p.z());
}
auto pct = [](std::vector<double> v, double q) {
std::sort(v.begin(), v.end());
return v[std::min<size_t>(
v.size() - 1, static_cast<size_t>(
q * (v.size() - 1) / 100.0))];
};
for (const auto& pr : {std::make_pair("x", vx),
std::make_pair("y", vy),
std::make_pair("z", vz)}) {
const auto& v = pr.second;
std::cerr << "[diag] mesh " << pr.first
<< " min " << pct(v, 0) << " p0.1 "
<< pct(v, 0.1) << " p99.9 "
<< pct(v, 99.9) << " max "
<< pct(v, 100) << "\n";
}
}
}
}
if (do_heal) {
auto th = Clock::now();
AutoHealOptions hopts;
long hcb = 0;
int hcancelled = 0;
std::thread heal_canceller;
if (do_progress) {
hopts.progress = [&hcb](HealStage st, int pct, const std::string&) {
++hcb;
std::cerr << "[probe] heal-progress stage=" << static_cast<int>(st)
<< " " << pct << "%\n";
};
}
if (heal_cancel_after_ms > 0) {
hopts.cancel = &cancel_flag;
// heal 启动后置位 cancel:验证 automatic_heal 管道阶段中止、
// body 恢复入口状态(前后 face 数一致)。
heal_canceller = std::thread([&] {
std::this_thread::sleep_for(
std::chrono::milliseconds(heal_cancel_after_ms));
cancel_flag.store(true);
});
}
size_t fi = 0;
for (auto& b : bodies) {
const size_t f_before = b.num_faces();
auto rep = automatic_heal(b, hopts);
const size_t f_after = b.num_faces();
bool cancelled = false;
for (const auto& w : rep.warnings)
if (w.find("cancelled") != std::string::npos) cancelled = true;
if (cancelled) hcancelled = 1;
std::cerr << "[probe] heal body[" << fi++ << "] faces " << f_before
<< " -> " << f_after
<< (cancelled ? " (cancelled)" : "") << "\n";
}
if (heal_canceller.joinable()) heal_canceller.join();
std::cerr << "[probe] heal in " << ms_since(th) << "ms cb=" << hcb
<< " cancelled=" << hcancelled << "\n";
}
if (!glb_base.empty()) {
auto te = Clock::now();
std::atomic<bool> glb_cancel{false};
std::thread glb_canceller;
if (glb_cancel_after_ms > 0)
glb_canceller = std::thread([&] {
std::this_thread::sleep_for(
std::chrono::milliseconds(glb_cancel_after_ms));
glb_cancel.store(true);
});
long ecb = 0;
bool any_cancelled = false;
for (size_t i = 0; i < bodies.size(); ++i) {
const std::string out = glb_base + "_" + std::to_string(i) + ".glb";
GltfExportOptions eopt;
eopt.tessellation_res = res;
if (glb_export_progress) {
eopt.progress = [&ecb](ExportPhase ph, int pct,
const std::string&) {
++ecb;
std::cerr << "[probe] glb-progress phase="
<< static_cast<int>(ph) << " " << pct << "%\n";
};
}
if (glb_cancel_after_ms > 0) eopt.cancel = &glb_cancel;
auto t1 = Clock::now();
const bool ok = write_brep_gltf(out, bodies[i], eopt);
const bool cancelled = glb_cancel.load();
if (!ok && cancelled) any_cancelled = true;
std::cerr << "[probe] glb-export " << out << " ok=" << ok
<< " cb=" << ecb << " in " << ms_since(t1) << "ms"
<< (cancelled ? " (cancelled)" : "") << "\n";
if (ok) write_glb_back_and_health(out, "step");
}
if (glb_canceller.joinable()) glb_canceller.join();
std::cerr << "[probe] glb-export total in " << ms_since(te) << "ms"
<< " cancelled=" << (any_cancelled ? 1 : 0) << "\n";
}
} else if (ext == ".stl") {
auto tris = read_stl(file);
std::cerr << "[probe] STL import " << file << " in " << ms_since(t0)
<< "ms tris=" << tris.size() << "\n";
if (!glb_base.empty()) {
std::vector<Point3D> pts;
std::vector<std::array<int, 3>> faces;
pts.reserve(tris.size() * 3);
faces.reserve(tris.size());
for (const auto& t : tris) {
const int b = static_cast<int>(pts.size());
pts.push_back(t.v0); pts.push_back(t.v1); pts.push_back(t.v2);
faces.push_back({b, b + 1, b + 2});
}
vde::mesh::HalfedgeMesh m;
m.build_from_triangles(pts, faces);
check_health(m).report("stl-source");
const std::string out = glb_base + "_0.glb";
auto te = Clock::now();
bool ok = write_gltf(out, m);
std::cerr << "[probe] glb-export " << out << " ok=" << ok
<< " in " << ms_since(te) << "ms\n";
if (ok) write_glb_back_and_health(out, "stl");
}
} else if (ext == ".3mf") {
auto meshes = read_3mf(file);
std::cerr << "[probe] 3MF import " << file << " in " << ms_since(t0)
<< "ms meshes=" << meshes.size() << "\n";
std::vector<vde::mesh::HalfedgeMesh> hs;
for (const auto& mm : meshes) { check_health(mm.mesh).report("3mf-source"); hs.push_back(mm.mesh); }
if (!glb_base.empty()) {
auto te = Clock::now();
for (size_t i = 0; i < hs.size(); ++i) {
const std::string out = glb_base + "_" + std::to_string(i) + ".glb";
bool ok = write_gltf(out, hs[i]);
std::cerr << "[probe] glb-export " << out << " ok=" << ok << "\n";
if (ok) write_glb_back_and_health(out, "3mf");
}
std::cerr << "[probe] glb-export total in " << ms_since(te) << "ms\n";
}
} else if (ext == ".glb" || ext == ".gltf") {
auto r = import_gltf(file);
std::cerr << "[probe] GLB import " << file << " in " << ms_since(t0)
<< "ms meshes=" << r.meshes.size() << " verts=" << r.total_vertices
<< " tris=" << r.total_triangles << " ok=" << r.success << "\n";
health_meshes(r.meshes, "glb-source", g_weld_snap);
} else {
std::cerr << "[probe] unsupported extension: " << ext << "\n";
if (canceller.joinable()) canceller.join();
return 2;
}
} catch (const std::exception& e) {
std::cerr << "[probe] EXCEPTION: " << e.what() << "\n";
if (canceller.joinable()) canceller.join();
return 1;
} catch (...) {
std::cerr << "[probe] unknown exception\n";
if (canceller.joinable()) canceller.join();
return 1;
}
if (canceller.joinable()) canceller.join();
std::cerr << "[probe] total " << ms_since(t0) << "ms\n";
return 0;
}