Files
ViewDesignEngine/tools/vde_brep_check.cpp
T

2621 lines
126 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 vde_brep_check.cpp
* @brief 单个 CAD 文件的 B-Rep 健康/解析诊断 CLI。
*
* 用法:
* vde_brep_check <file|dir> [--heal] [--pinch] [--deep] [--json] [--strict] [--quick] [--stream] [--out <dir>]
*
* 默认输出:
* - 统一导入结果、格式消息、STEP 解析诊断;
* - 每个 body 的 validate 指标;
* - diagnose_body 的错误/警告(含关联面索引)。
*
* --heal 额外执行 automatic_heal,并输出修复前后状态;
* --deep 额外执行 tolerance_analysis / watertight_verification。
*
* 目录模式:递归扫描支持的 CAD 扩展名,逐文件输出一行诊断摘要;
* 目录模式不接受 --heal;--jobs N 做文件级并行(每个 worker
* 导入完立即释放 body,内存只受同时在飞的 N 个导入约束)。
* --json 输出 ImportDiagnostic JSON(单文件对象/目录数组);不与 --heal 组合。
* --strict 把警告/可修复项也视为失败(默认仅错误/无效 B-Rep 失败)。
* --quick 只做 import_cad 解析级诊断,不做逐 body validate/diagnose(大目录快速筛查;
* 单文件与目录模式行为一致,JSON 中 bodies_complete=false 表示诊断不完整)。
* --split-shells 将混合开/闭壳 body 拆成闭合实体 + 各开放壳,逐 part 复检(单文件)。
* --orient 先执行 fix_shell_orientation_strict 统一壳方向;可与 --heal/--pinch 组合。
* --pinch 与 --heal 组合:先 heal_split_pinch_vertices 拆分重合双棱,再 automatic_heal。
* --out 与 --heal 组合:把修复后的每个 body 保存为 <dir>/<stem>_bodyN.vde。
*
* 退出码:0=全部有效,1=存在 B-Rep 缺陷,2=导入失败,3=用法错误,
* 124=TIMEOUT/76 预算超限(--timeout-exit-code 可改)。仅当解析被预算
* 中止(ok=false)时返回 124;若几何已解析完成、仅后置诊断预算不足
* (ok=true、budget_exceeded=true),按几何结果返回,诊断不完整由 JSON
* budget_exceeded 字段与 budget.time issue 标记。
*/
#include "vde/brep/advanced_healing.h"
#include "vde/brep/brep_heal.h"
#include "vde/brep/brep_validate.h"
#include "vde/brep/measure.h"
#include "vde/brep/solid_features.h"
#include "vde/brep/brep_face_split.h"
#include "vde/brep/analytic_trim.h"
#include "vde/brep/exact_face_trim.h"
#include "vde/brep/direct_modeling.h"
#include "vde/brep/brep_boolean.h"
#include "vde/brep/modeling.h"
#include "vde/brep/measure.h"
#include "vde/mesh/halfedge_mesh.h"
#include "vde/mesh/mesh_diagnostics.h"
#include "vde/brep/tolerant_modeling.h"
#include "vde/brep/mesh_to_brep.h"
#include "vde/core/transform.h"
#include "vde/brep/format_io.h"
#include "vde/brep/step_import.h"
#include "vde/brep/step_index.h"
#include "vde/brep/seam_rebuild.h"
#include "vde/curves/surface_analysis.h"
#include "vde/foundation/vde_format.h"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <functional>
#include <limits>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <thread>
#include <vector>
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <shellapi.h>
#endif
using namespace vde::brep;
namespace {
std::filesystem::path u8_path(const std::string& value) {
#if defined(__cpp_char8_t)
return std::filesystem::path(reinterpret_cast<const char8_t*>(value.c_str()));
#else
return std::filesystem::u8path(value);
#endif
}
/// P0-1:CLI 参数统一 UTF-8;文件系统/导入 API 使用平台 native 路径。
/// Windows 的 narrow ifstream 遇到 ∅/中文等不可表示字符会抛异常并
/// abort(0xC0000409);有 8.3 短路径时改走短路径。
std::string native_path(const std::string& utf8) {
bool ascii = true;
for (unsigned char c : utf8) {
if (c >= 0x80) { ascii = false; break; }
}
if (ascii) return utf8;
#if defined(_WIN32)
const int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
if (wlen > 0) {
std::wstring wide(static_cast<size_t>(wlen), L'\0');
if (MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, wide.data(), wlen) > 0) {
const DWORD n = GetShortPathNameW(wide.c_str(), nullptr, 0);
if (n > 0) {
std::wstring short_path(static_cast<size_t>(n), L'\0');
if (GetShortPathNameW(wide.c_str(), short_path.data(), n) > 0) {
const int alen = WideCharToMultiByte(CP_ACP, 0, short_path.c_str(), -1,
nullptr, 0, nullptr, nullptr);
if (alen > 0) {
std::string out(static_cast<size_t>(alen - 1), '\0');
WideCharToMultiByte(CP_ACP, 0, short_path.c_str(), -1, out.data(),
alen, nullptr, nullptr);
if (out.find('?') == std::string::npos) return out;
}
}
}
// 8.3 短路径不可用:把文件复制到纯 ASCII 临时路径再导入。
wchar_t temp_dir[MAX_PATH]{};
const DWORD tlen = GetTempPathW(MAX_PATH, temp_dir);
if (tlen > 0) {
static unsigned counter = 0;
const std::wstring ext =
std::filesystem::path(wide).extension().wstring();
const std::wstring temp = std::wstring(temp_dir) +
L"vde_unicode_" + std::to_wstring(GetCurrentProcessId()) + L"_" +
std::to_wstring(++counter) + ext;
if (CopyFileW(wide.c_str(), temp.c_str(), FALSE)) {
const int alen = WideCharToMultiByte(CP_ACP, 0, temp.c_str(), -1,
nullptr, 0, nullptr, nullptr);
if (alen > 0) {
std::string out(static_cast<size_t>(alen - 1), '\0');
WideCharToMultiByte(CP_ACP, 0, temp.c_str(), -1, out.data(),
alen, nullptr, nullptr);
return out;
}
}
}
}
}
#endif
try {
return u8_path(utf8).string();
} catch (...) {
return utf8;
}
}
#if defined(_WIN32)
std::string wide_to_utf8(const wchar_t* text) {
if (text == nullptr) return {};
const int len = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
if (len <= 0) return {};
std::string out(static_cast<size_t>(len - 1), '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, out.data(), len, nullptr, nullptr);
return out;
}
#endif
bool has_ext(const std::string& path, const char* a, const char* b = nullptr) {
auto dot = path.find_last_of('.');
if (dot == std::string::npos) return false;
std::string ext = path.substr(dot);
for (auto& c : ext) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return ext == a || (b && ext == b);
}
void print_validation(const char* tag, const ValidationResult& v) {
std::printf(" %s: %s wt=%.4f self=%.4f E=%zu F=%zu "
"nm=%zu dgl=%zu ori=%zu euler=%d err=%zu warn=%zu\n",
tag, v.valid ? "VALID" : "INVALID", v.watertightness,
v.self_intersection_free, v.total_edges, v.total_faces,
v.non_manifold_edges, v.dangling_edges,
v.inconsistent_orientations, v.euler_characteristic,
v.errors.size(), v.warnings.size());
for (size_t i = 0; i < v.errors.size() && i < 8; ++i)
std::printf(" error[%zu]: %s\n", i, v.errors[i].c_str());
for (size_t i = 0; i < v.warnings.size() && i < 8; ++i)
std::printf(" warn[%zu]: %s\n", i, v.warnings[i].c_str());
}
void print_diag(const BodyDiagnostics& d) {
std::printf(" diagnose: %s errors=%d warnings=%d wt=%.4f self=%.4f "
"penetration_pairs=%zu\n",
d.valid ? "OK" : "ERRORS", d.error_count, d.warning_count,
d.watertightness, d.self_intersection_free,
d.intra_shell_penetration_pairs);
for (size_t i = 0; i < d.errors.size() && i < 10; ++i) {
std::printf(" E%d faces=", static_cast<int>(i));
if (d.errors[i].faces.empty()) std::printf("-");
for (int f : d.errors[i].faces) std::printf("%d,", f);
std::printf(" %s\n", d.errors[i].message.c_str());
}
for (size_t i = 0; i < d.warnings.size() && i < 10; ++i) {
std::printf(" W%d faces=", static_cast<int>(i));
if (d.warnings[i].faces.empty()) std::printf("-");
for (int f : d.warnings[i].faces) std::printf("%d,", f);
std::printf(" %s\n", d.warnings[i].message.c_str());
}
}
bool supported_file(const std::string& path) {
static const char* exts[] = {
".step", ".stp", ".p21", ".igs", ".iges", ".xt", ".x_t", ".x_b",
".sat", ".jt", ".ifc", ".vda", ".3dm", ".3dxml", ".vde",
".stl", ".obj", ".ply", ".3mf", ".gltf", ".glb", ".wrl", ".dae",
".amf", ".pdf", ".dwg", ".dxf", ".dwt", ".dws", ".dwfx",
".sldprt", ".sldasm", ".catpart", ".catproduct", ".prt", ".ipt",
".asm"};
auto dot = path.find_last_of('.');
if (dot == std::string::npos) return false;
std::string ext = path.substr(dot);
for (auto& c : ext) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
for (const char* e : exts)
if (ext == e) return true;
return false;
}
std::vector<std::string> collect_files(const std::string& dir) {
std::vector<std::string> files;
std::error_code ec;
for (std::filesystem::recursive_directory_iterator it(
u8_path(dir),
std::filesystem::directory_options::skip_permission_denied, ec),
end;
it != end; it.increment(ec)) {
if (ec) break;
if (!it->is_regular_file(ec) || ec) continue;
// C++20 下 path::u8string() 返回 char8_t 字符串;用 data()+size 避免
// char8_t 无法直接构造 std::string(MinGW/UCRT 同 gcc 行为)。
const auto u8p = it->path().u8string();
const std::string p(reinterpret_cast<const char*>(u8p.data()), u8p.size());
if (supported_file(p)) files.push_back(p);
}
std::sort(files.begin(), files.end());
return files;
}
bool body_defect(const ImportDiagnostic& d) {
for (const auto& b : d.body_diagnostics)
if (!(b.valid && b.watertightness > 0.99)) return true;
return false;
}
int diagnostic_exit(const ImportDiagnostic& d, bool strict = false,
int budget_exit_code = 124) {
// 预算退出码只表示「导入结果不完整」:解析/转换被预算中止时 ok=false。
// 后置诊断预算不足但几何已完整解析(ok=true)时按几何结果返回,
// 由 budget_exceeded/budget.time 显式标记诊断不完整(verifier 151 P3①)。
if (d.budget_exceeded && !d.ok) return budget_exit_code;
if (d.analysis_only) return 0; // AP209 等分析模型:SKIP,不是 B-Rep 失败
if (!d.ok) return 2;
if (d.has_errors()) return 1;
for (const auto& b : d.body_diagnostics)
if (!(b.valid && b.watertightness > 0.99)) return 1;
if (strict && d.has_warnings()) return 1;
return 0;
}
/// 目录扫描的逐文件导入:每个文件导入完成后立即释放 body,只保留诊断;
/// jobs>1 时按文件并行,峰值内存受“同时在飞的 jobs 个导入”约束。
std::vector<ImportDiagnostic> import_directory_files(
const std::vector<std::string>& files, unsigned jobs, bool quick,
const CadImportOptions& import_options) {
std::vector<ImportDiagnostic> diags(files.size());
auto import_one = [&](std::size_t i) {
CadImportOptions opts = import_options;
// --quick 只做解析级诊断:逐 body validate/diagnose 会把大文件快速
// 筛查拖成分钟级(462MB STEP 实测 >15min/文件),目录扫描必须遵守
// --quick 的语义。body_count 由 bodies.size() 填充,不依赖该开关。
opts.collect_body_diagnostics = !quick;
try {
CadImportResult imported = import_cad(native_path(files[i]), opts);
imported.diagnostic.path = files[i]; // JSON path 用 UTF-8 原参数
diags[i] = std::move(imported.diagnostic);
} catch (const std::exception& e) {
diags[i].path = files[i];
diags[i].format = "Unknown";
diags[i].ok = false;
diags[i].issues.push_back({ImportIssueSeverity::Error,
"import.exception", e.what(), {}});
} catch (...) {
diags[i].path = files[i];
diags[i].format = "Unknown";
diags[i].ok = false;
diags[i].issues.push_back({ImportIssueSeverity::Error,
"import.exception", "unknown error", {}});
}
};
if (jobs <= 1 || files.size() <= 1) {
for (std::size_t i = 0; i < files.size(); ++i) import_one(i);
return diags;
}
// 文件级并行:import_cad 的 STEP 诊断已改为 thread_local;每个 worker
// 导入完立即析构 bodies,因此内存不随目录规模累计增长。
std::atomic<std::size_t> next{0};
const unsigned workers = std::min<unsigned>(
jobs, static_cast<unsigned>(files.size()));
std::vector<std::thread> threads;
threads.reserve(workers);
for (unsigned w = 0; w < workers; ++w) {
threads.emplace_back([&]() {
for (;;) {
const std::size_t i = next.fetch_add(1);
if (i >= files.size()) break;
import_one(i);
}
});
}
for (auto& t : threads) t.join();
return diags;
}
int check_directory_json(const std::string& dir, bool strict, bool quick,
unsigned jobs, const CadImportOptions& import_options,
int budget_exit_code) {
const auto files = collect_files(dir);
if (files.empty()) {
std::fprintf(stderr, "no supported CAD files under: %s\n", dir.c_str());
return 2;
}
const auto diags = import_directory_files(files, jobs, quick, import_options);
int worst = 0;
std::printf("[");
for (std::size_t i = 0; i < diags.size(); ++i) {
if (i) std::printf(",");
const ImportDiagnostic& d = diags[i];
std::printf("%s", d.to_json().c_str());
const int exit_code = diagnostic_exit(d, strict, budget_exit_code);
if (d.budget_exceeded && !d.ok) worst = budget_exit_code;
else worst = std::max(worst, exit_code);
}
std::printf("]\n");
return worst;
}
int check_directory(const std::string& dir, bool strict, bool quick,
unsigned jobs, const CadImportOptions& import_options,
int budget_exit_code) {
const auto files = collect_files(dir);
if (files.empty()) {
std::fprintf(stderr, "no supported CAD files under: %s\n", dir.c_str());
return 2;
}
const auto diags = import_directory_files(files, jobs, quick, import_options);
int total = 0, pass = 0, warn = 0, defect = 0, failed = 0, healable = 0;
int budget_exceeded = 0;
std::map<std::string, int> issue_counts;
for (size_t fi = 0; fi < diags.size(); ++fi) {
const auto& d = diags[fi];
const auto& f = files[fi];
++total;
if (d.budget_exceeded) ++budget_exceeded;
const bool hard = (!d.ok && !d.analysis_only) || d.has_errors() ||
(!quick && body_defect(d));
const bool soft = !hard && (d.has_warnings() || d.can_heal() || d.analysis_only);
if (!d.ok && !d.analysis_only) ++failed;
else if (hard) ++defect;
else if (soft) ++warn;
else ++pass;
if (d.can_heal()) ++healable;
for (const auto& i : d.issues)
if (i.severity != ImportIssueSeverity::Info)
++issue_counts[i.code];
const char* status = hard ? "FAIL" : (soft ? "WARN" : "PASS");
std::printf("[%s] %s format=%s bodies=%d E=%d W=%d repairs=%zu heal=%d\n",
status, f.c_str(), d.format.c_str(),
d.body_count, d.error_count(), d.warning_count(),
d.repairs.size(), d.can_heal() ? 1 : 0);
int shown = 0;
for (const auto& i : d.issues) {
if (i.severity != ImportIssueSeverity::Error) continue;
if (++shown > 3) break;
std::printf(" E %s: %s\n", i.code.c_str(), i.message.c_str());
}
if (quick) {
int warned = 0;
for (const auto& i : d.issues) {
if (i.severity != ImportIssueSeverity::Warning) continue;
if (++warned > 2) break;
std::printf(" W %s: %s\n", i.code.c_str(), i.message.c_str());
}
}
if (d.can_heal()) {
for (const auto& r : d.repairs) {
if (!r.automatic) continue;
std::printf(" repair[auto] %s\n", r.description.c_str());
break;
}
}
}
std::printf("\nsummary: total=%d pass=%d warn=%d defect=%d import_failed=%d "
"healable=%d budget_exceeded=%d quick=%d\n",
total, pass, warn, defect, failed, healable, budget_exceeded,
quick ? 1 : 0);
if (!issue_counts.empty()) {
std::vector<std::pair<int, std::string>> top;
for (const auto& kv : issue_counts) top.emplace_back(kv.second, kv.first);
std::sort(top.begin(), top.end(), [](const auto& a, const auto& b) {
if (a.first != b.first) return a.first > b.first;
return a.second < b.second;
});
std::printf("issues:");
for (size_t i = 0; i < top.size() && i < 8; ++i)
std::printf(" %s×%d", top[i].second.c_str(), top[i].first);
std::printf("\n");
}
// 只有解析被预算中止(ok=false)才返回预算退出码;仅诊断预算不足时仍按
// 几何结果返回(1.0.139,verifier 151 P3①)。
for (const auto& d : diags)
if (d.budget_exceeded && !d.ok) return budget_exit_code;
return failed > 0 ? 2 : ((defect > 0 || (strict && warn > 0)) ? 1 : 0);
}
int split_shells_report(const CadImportResult& imported,
const std::string& out_dir, bool heal_parts) {
int bad = 0;
std::error_code ec;
if (!out_dir.empty()) std::filesystem::create_directories(out_dir, ec);
for (size_t bi = 0; bi < imported.bodies.size(); ++bi) {
auto parts = split_open_shells(imported.bodies[bi]);
std::printf("\n[body %zu] split -> %zu part(s)\n", bi, parts.size());
for (size_t pi = 0; pi < parts.size(); ++pi) {
if (heal_parts) {
AutoHealReport hr = automatic_heal(parts[pi]);
std::printf(" part %zu heal score=%d degraded=%d\n", pi,
hr.overall_score, hr.degraded ? 1 : 0);
}
const auto v = validate(parts[pi]);
std::printf(" part %zu: F=%zu S=%zu %s wt=%.4f\n", pi,
parts[pi].num_faces(), parts[pi].all_shells().size(),
v.valid ? "VALID" : "INVALID", v.watertightness);
if (!(v.valid && v.watertightness > 0.99)) ++bad;
if (!out_dir.empty()) {
const auto stem = std::filesystem::path(imported.diagnostic.path).stem().string();
const auto path = std::filesystem::path(out_dir) /
(stem + "_body" + std::to_string(bi) + "_part" +
std::to_string(pi) + ".vde");
if (vde::foundation::save_vde(parts[pi], path.string()))
std::printf(" saved: %s\n", path.string().c_str());
}
}
}
return bad == 0 ? 0 : 1;
}
} // namespace
bool point_inside_mesh(const vde::mesh::HalfedgeMesh& mesh, const Point3D& p,
double eps = 1e-9) {
int hits = 0;
for (size_t fi = 0; fi < mesh.num_faces(); ++fi) {
const auto fv = mesh.face_vertices(static_cast<int>(fi));
if (fv.size() < 3) continue;
const Point3D a = mesh.vertex(fv[0]);
const Point3D b = mesh.vertex(fv[1]);
const Point3D c = mesh.vertex(fv[2]);
const Vector3D e1{b.x() - a.x(), b.y() - a.y(), b.z() - a.z()};
const Vector3D e2{c.x() - a.x(), c.y() - a.y(), c.z() - a.z()};
const Vector3D dir{1, 0, 0};
const Vector3D pv{p.x() - a.x(), p.y() - a.y(), p.z() - a.z()};
const Vector3D h{dir.y() * e2.z() - dir.z() * e2.y(),
dir.z() * e2.x() - dir.x() * e2.z(),
dir.x() * e2.y() - dir.y() * e2.x()};
const double det = e1.x() * h.x() + e1.y() * h.y() + e1.z() * h.z();
if (std::fabs(det) < 1e-14) continue;
const double inv = 1.0 / det;
const double u = (pv.x() * h.x() + pv.y() * h.y() + pv.z() * h.z()) * inv;
if (u < 0.0 || u > 1.0) continue;
const Vector3D q{pv.y() * e1.z() - pv.z() * e1.y(),
pv.z() * e1.x() - pv.x() * e1.z(),
pv.x() * e1.y() - pv.y() * e1.x()};
const double v = (dir.x() * q.x() + dir.y() * q.y() + dir.z() * q.z()) * inv;
if (v < 0.0 || u + v > 1.0) continue;
const double t = (e2.x() * q.x() + e2.y() * q.y() + e2.z() * q.z()) * inv;
if (t > eps) ++hits;
}
return (hits & 1) != 0;
}
BrepModel build_face_subset(const BrepModel& src, const std::vector<bool>& keep);
BrepModel search_target_face_subset(const BrepModel& src, double target) {
const size_t nf = src.all_faces().size();
if (nf == 0 || nf > 24) return src;
std::vector<std::vector<int>> fe(nf);
for (size_t fi = 0; fi < nf; ++fi) {
for (int lid : src.all_faces()[fi].loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < src.all_loops().size())
lp = &src.all_loops()[lid];
if (!lp)
for (const auto& l : src.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
int ei = eid;
if (ei < 0 || ei >= static_cast<int>(src.all_edges().size())) ei = -1;
if (ei < 0)
for (size_t k = 0; k < src.all_edges().size(); ++k)
if (src.all_edges()[k].id == eid) { ei = static_cast<int>(k); break; }
if (ei >= 0) fe[fi].push_back(ei);
}
}
}
BrepModel best = src;
double best_diff = 1e300;
const std::uint32_t total = 1u << nf;
for (std::uint32_t mask = 1; mask < total; ++mask) {
int pc = 0;
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i)) ++pc;
if (pc < 4) continue;
std::vector<int> cnt(src.all_edges().size(), 0);
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i))
for (int ei : fe[i]) ++cnt[ei];
bool ok = true;
for (int c : cnt)
if (c != 0 && c != 2) { ok = false; break; }
if (!ok) continue;
std::vector<bool> keep(nf, false);
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i)) keep[i] = true;
BrepModel cand = build_face_subset(src, keep);
const auto m = analytic_measure(cand, 0.05);
if (m.degraded()) continue;
const double diff = std::abs(m.volume - target);
if (diff < best_diff) { best_diff = diff; best = std::move(cand); }
}
return best;
}
BrepModel build_face_subset(const BrepModel& src, const std::vector<bool>& keep) {
BrepModel out;
std::map<int, int> vmap, emap, smap;
std::vector<int> new_faces;
for (size_t fi = 0; fi < src.all_faces().size(); ++fi) {
if (fi >= keep.size() || !keep[fi]) continue;
const TopoFace& f = src.all_faces()[fi];
int sid = -1;
if (f.surface_id >= 0 &&
static_cast<size_t>(f.surface_id) < src.num_surfaces()) {
auto it = smap.find(f.surface_id);
if (it == smap.end()) {
sid = out.add_surface(src.surface(f.surface_id));
smap[f.surface_id] = sid;
} else {
sid = it->second;
}
}
if (sid < 0) continue;
std::vector<int> new_loops;
bool ok = true;
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < src.all_loops().size())
lp = &src.all_loops()[lid];
if (!lp)
for (const auto& l : src.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) { ok = false; break; }
std::vector<int> es;
for (int eid : lp->edges) {
int ei = eid;
if (ei < 0 || ei >= static_cast<int>(src.all_edges().size()))
ei = -1;
if (ei < 0)
for (size_t k = 0; k < src.all_edges().size(); ++k)
if (src.all_edges()[k].id == eid) { ei = static_cast<int>(k); break; }
if (ei < 0) { ok = false; break; }
auto it = emap.find(ei);
if (it != emap.end()) { es.push_back(it->second); continue; }
const TopoEdge& e = src.all_edges()[ei];
int nv[2] = {-1, -1};
for (int s = 0; s < 2; ++s) {
const int ov = (s == 0) ? e.v_start : e.v_end;
int vi = ov;
if (vi < 0 || vi >= static_cast<int>(src.all_vertices().size()))
vi = -1;
if (vi < 0)
for (size_t k = 0; k < src.all_vertices().size(); ++k)
if (src.all_vertices()[k].id == ov) { vi = static_cast<int>(k); break; }
if (vi < 0) { ok = false; break; }
auto vit = vmap.find(vi);
if (vit == vmap.end()) {
const int nid = out.add_vertex(src.vertex(vi).point);
vmap[vi] = nid;
nv[s] = nid;
} else {
nv[s] = vit->second;
}
}
if (!ok) break;
const int ne = e.curve ? out.add_edge(nv[0], nv[1], *e.curve)
: out.add_edge(nv[0], nv[1]);
if (e.reversed) out.set_edge_reversed(ne, true);
emap[ei] = ne;
es.push_back(ne);
}
if (!ok) break;
new_loops.push_back(out.add_loop(es, lp->is_outer));
}
if (!ok || new_loops.empty()) continue;
const int nf = out.add_face(sid, new_loops);
out.set_face_reversed(nf, f.reversed);
new_faces.push_back(nf);
}
if (!new_faces.empty()) {
const int sh = out.add_shell(new_faces, true);
out.add_body({sh}, "subset");
}
return out;
}
bool circle_intersection_points(const ssi::ExactCurve& a, const ssi::ExactCurve& b,
Point3D& p0, Point3D& p1) {
const Vector3D d = a.normal.cross(b.normal);
const double dd = d.dot(d);
if (dd < 1e-18) return false;
const double d1 = a.normal.dot(a.center);
const double d2 = b.normal.dot(b.center);
const Vector3D base{
(d1 * b.normal.cross(d).x() + d2 * d.cross(a.normal).x()) / dd,
(d1 * b.normal.cross(d).y() + d2 * d.cross(a.normal).y()) / dd,
(d1 * b.normal.cross(d).z() + d2 * d.cross(a.normal).z()) / dd};
const Vector3D dir = d.normalized();
const Vector3D w{base.x() - a.center.x(), base.y() - a.center.y(),
base.z() - a.center.z()};
const double B = 2.0 * dir.dot(w);
const double C = w.dot(w) - a.a * a.a;
const double disc = B * B - 4.0 * C;
if (disc <= 1e-18) return false;
const double s = std::sqrt(disc);
const double t0 = (-B - s) / 2.0;
const double t1 = (-B + s) / 2.0;
p0 = Point3D{base.x() + dir.x() * t0, base.y() + dir.y() * t0,
base.z() + dir.z() * t0};
p1 = Point3D{base.x() + dir.x() * t1, base.y() + dir.y() * t1,
base.z() + dir.z() * t1};
return true;
}
std::vector<std::vector<int>> trace_boundary_loops(const BrepModel& body) {
std::map<int, int> use;
auto edge_index = [&](int eid) -> int {
if (eid >= 0 && static_cast<size_t>(eid) < body.all_edges().size()) return eid;
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) return static_cast<int>(k);
return -1;
};
for (const auto& f : body.all_faces()) {
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
const int ei = edge_index(eid);
if (ei >= 0) ++use[body.all_edges()[ei].id];
}
}
}
std::vector<int> bnd;
std::map<int, std::vector<int>> incident;
for (size_t k = 0; k < body.all_edges().size(); ++k) {
const auto& e = body.all_edges()[k];
if (use[e.id] != 1) continue;
bnd.push_back(static_cast<int>(k));
incident[e.v_start].push_back(static_cast<int>(k));
incident[e.v_end].push_back(static_cast<int>(k));
}
std::set<int> visited;
std::vector<std::vector<int>> loops;
for (int seed : bnd) {
if (visited.count(seed)) continue;
const auto& se = body.all_edges()[seed];
const int start_v = se.v_start;
int cur_v = se.v_end;
std::vector<int> loop{seed};
visited.insert(seed);
[[maybe_unused]] bool closed = false; // 开链由调用方补边封闭,这里仅记录
for (int guard = 0; guard < static_cast<int>(bnd.size()) + 4; ++guard) {
if (cur_v == start_v) { closed = true; break; }
int next = -1;
for (int cand : incident[cur_v])
if (!visited.count(cand)) { next = cand; break; }
if (next < 0) break;
visited.insert(next);
const auto& ne = body.all_edges()[next];
loop.push_back(next);
cur_v = (ne.v_start == cur_v) ? ne.v_end : ne.v_start;
}
if (loop.size() >= 2) loops.push_back(std::move(loop));
}
return loops;
}
double mesh_abs_volume(const BrepModel& body, double defl = 0.02) {
const auto mesh = body.to_mesh(defl);
double s6 = 0.0;
for (size_t i = 0; i < mesh.num_faces(); ++i) {
const auto fv = mesh.face_vertices(static_cast<int>(i));
if (fv.size() < 3) continue;
const auto a = mesh.vertex(fv[0]);
const auto b = mesh.vertex(fv[1]);
const auto c = mesh.vertex(fv[2]);
s6 += a.dot(b.cross(c));
}
return std::abs(s6 / 6.0);
}
int run_check(int argc, char** argv) {
if (argc >= 3 && std::strcmp(argv[1], "--scan") == 0) {
namespace fs = std::filesystem;
const fs::path root = native_path(argv[2]);
const int limit = argc >= 4 ? std::atoi(argv[3]) : 0;
int seen = 0;
std::error_code ec;
for (fs::recursive_directory_iterator it(root, ec), end; it != end && !ec; it.increment(ec)) {
if (!it->is_regular_file()) continue;
const std::string ext = it->path().extension().string();
if (ext != ".stp" && ext != ".step" && ext != ".STEP" && ext != ".STP") continue;
if (it->file_size() > (1u << 20)) continue;
if (limit > 0 && seen >= limit) break;
++seen;
try {
CadImportOptions scan_opts;
scan_opts.collect_body_diagnostics = false;
CadImportResult imp = import_cad(it->path().string(), scan_opts);
for (std::size_t bi = 0; bi < imp.bodies.size(); ++bi) {
const auto mesh = imp.bodies[bi].to_mesh(0.05);
const auto loops = vde::mesh::extract_boundary_loops(mesh);
if (loops.size() == 1) {
const auto arcs = vde::mesh::fit_boundary_arcs(mesh, loops[0]);
if (arcs.size() == 3) {
std::printf("CANDIDATE3 %s body=%zu faces=%zu points=%zu\n",
it->path().string().c_str(), bi,
imp.bodies[bi].num_faces(),
loops[0].vertices.size());
}
}
int sph = 0, tor = 0;
for (int fi = 0; fi < static_cast<int>(imp.bodies[bi].num_faces()); ++fi) {
const auto t = imp.bodies[bi].face_type(fi);
if (t == FaceType::Sphere) ++sph;
else if (t == FaceType::Torus) ++tor;
}
if ((sph > 0 || tor > 0) && imp.bodies[bi].num_faces() <= 12)
std::printf("SURF %s body=%zu faces=%zu sphere=%d torus=%d\n",
it->path().string().c_str(), bi,
imp.bodies[bi].num_faces(), sph, tor);
}
} catch (...) {
}
}
std::fprintf(stderr, "scanned=%d\n", seen);
return 0;
}
std::string path;
bool heal = false;
bool pinch = false;
bool orient = false;
bool deep = false;
bool json = false;
bool strict = false;
bool quick = false;
bool curvature = false;
bool volume_check = false;
bool boundary_report = false;
bool cap_boundary = false;
bool bad_sheets = false;
bool move_seam = false;
bool split_shells = false;
bool auto_heal = false;
bool dump_faces = false;
bool dump_pairs = false;
std::vector<long> delete_face_ids;
std::string save_modified;
int split_face = -1, cut_plane_face = -1;
int ssi_face_a = -1, ssi_face_b = -1;
int trim_sphere_face = -1, trim_plane_face = -1;
int planar_trim_face = -1, planar_trim_sphere = -1;
bool dump_regions = false;
bool dump_nonmanifold = false;
bool select_closed_subset = false;
bool list_bodies = false;
bool mesh_volume = false;
bool body_label = false;
bool scan_sldprt = false;
bool check_target = false;
double scan_volume = 311.342;
int scan_faces = 19;
std::string scan_name;
std::vector<std::string> scan_skips;
int surface_info = -1;
int wedge_sphere = -1, wedge_plane_a = -1, wedge_plane_b = -1;
int build_caps_sphere = -1, build_caps_a = -1, build_caps_b = -1;
double build_caps_shift = 0.0;
double build_caps_shift_b = std::numeric_limits<double>::quiet_NaN();
bool build_caps_reverse = false;
bool build_caps_swap = false;
bool mesh_repair = false;
double wedge_shift = 0.0;
bool boolean_smoke = false;
int duplicate_body = -1;
double target_volume = 0.0;
bool classify_internal = false;
bool fill_boundary = false;
bool patch_boundary = false;
bool trim_nonmanifold = false;
bool drop_spurs = false;
bool collapse_spurs = false;
double tolerant_stitch = 0.0;
int fill_sphere_surface = -1;
bool fill_sphere_reverse = false;
int fill_circle_plane = -1, fill_circle_sphere = -1;
int lens_plane_a = -1, lens_plane_b = -1, lens_sphere = -1;
bool index_only = false;
long body_index = -1;
long body_count = 1;
std::string save_body;
unsigned jobs = 1;
std::string out_dir;
double max_seconds = 0.0;
double diagnostics_max_seconds = 0.0;
std::size_t max_bytes = 0;
int budget_exit_code = 124;
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--heal") == 0) heal = true;
else if (std::strcmp(argv[i], "--pinch") == 0) pinch = true;
else if (std::strcmp(argv[i], "--orient") == 0) orient = true;
else if (std::strcmp(argv[i], "--deep") == 0) deep = true;
else if (std::strcmp(argv[i], "--json") == 0) json = true;
else if (std::strcmp(argv[i], "--strict") == 0) strict = true;
else if (std::strcmp(argv[i], "--quick") == 0) quick = true;
else if (std::strcmp(argv[i], "--curvature") == 0) curvature = true;
else if (std::strcmp(argv[i], "--volume-check") == 0) volume_check = true;
else if (std::strcmp(argv[i], "--boundary") == 0) boundary_report = true;
else if (std::strcmp(argv[i], "--cap-boundary") == 0) cap_boundary = true;
else if (std::strcmp(argv[i], "--bad-sheets") == 0) bad_sheets = true;
else if (std::strcmp(argv[i], "--move-seam") == 0) move_seam = true;
else if (std::strcmp(argv[i], "--stream") == 0) {
// 大 STEP:on_body 流式交付,降低峰值内存(不保留 bodies)。
#ifdef _WIN32
_putenv_s("VDE_STEP_STREAM", "1");
#else
setenv("VDE_STEP_STREAM", "1", 1);
#endif
}
else if (std::strcmp(argv[i], "--jobs") == 0 && i + 1 < argc)
jobs = static_cast<unsigned>(std::strtoul(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--split-shells") == 0) split_shells = true;
else if (std::strcmp(argv[i], "--auto-heal") == 0) auto_heal = true;
else if (std::strcmp(argv[i], "--dump-faces") == 0) dump_faces = true;
else if (std::strcmp(argv[i], "--dump-pairs") == 0) dump_pairs = true;
else if (std::strcmp(argv[i], "--delete-face") == 0 && i + 1 < argc)
delete_face_ids.push_back(std::strtol(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--save-modified") == 0 && i + 1 < argc)
save_modified = argv[++i];
else if (std::strcmp(argv[i], "--split-face-by-plane") == 0 && i + 2 < argc) {
split_face = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
cut_plane_face = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--exact-ssi") == 0 && i + 2 < argc) {
ssi_face_a = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
ssi_face_b = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--trim-sphere") == 0 && i + 2 < argc) {
trim_sphere_face = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
trim_plane_face = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--regions") == 0) dump_regions = true;
else if (std::strcmp(argv[i], "--dump-nonmanifold") == 0) dump_nonmanifold = true;
else if (std::strcmp(argv[i], "--closed-subset") == 0)
select_closed_subset = true;
else if (std::strcmp(argv[i], "--list-bodies") == 0) list_bodies = true;
else if (std::strcmp(argv[i], "--mesh-volume") == 0) mesh_volume = true;
else if (std::strcmp(argv[i], "--body-label") == 0) body_label = true;
else if (std::strcmp(argv[i], "--scan-sldprt") == 0) scan_sldprt = true;
else if (std::strcmp(argv[i], "--check-target") == 0) check_target = true;
else if (std::strcmp(argv[i], "--scan-volume") == 0 && i + 1 < argc)
scan_volume = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--scan-faces") == 0 && i + 1 < argc)
scan_faces = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--scan-name") == 0 && i + 1 < argc)
scan_name = argv[++i];
else if (std::strcmp(argv[i], "--scan-skip") == 0 && i + 1 < argc)
scan_skips.push_back(argv[++i]);
else if (std::strcmp(argv[i], "--surface-info") == 0 && i + 1 < argc)
surface_info = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--boolean-smoke") == 0) boolean_smoke = true;
else if (std::strcmp(argv[i], "--build-sphere-caps") == 0 && i + 3 < argc) {
build_caps_sphere = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
build_caps_a = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
build_caps_b = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--caps-shift") == 0 && i + 1 < argc)
build_caps_shift = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--caps-shift-b") == 0 && i + 1 < argc)
build_caps_shift_b = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--caps-reverse") == 0)
build_caps_reverse = true;
else if (std::strcmp(argv[i], "--caps-swap") == 0)
build_caps_swap = true;
else if (std::strcmp(argv[i], "--mesh-repair") == 0)
mesh_repair = true;
else if (std::strcmp(argv[i], "--wedge-shift") == 0 && i + 1 < argc)
wedge_shift = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--wedge-sphere") == 0 && i + 3 < argc) {
wedge_sphere = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
wedge_plane_a = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
wedge_plane_b = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--find-duplicates") == 0 && i + 1 < argc)
duplicate_body = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--target-volume") == 0 && i + 1 < argc)
target_volume = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--classify-internal") == 0)
classify_internal = true;
else if (std::strcmp(argv[i], "--fill-boundary") == 0)
fill_boundary = true;
else if (std::strcmp(argv[i], "--patch-boundary") == 0)
patch_boundary = true;
else if (std::strcmp(argv[i], "--trim-nonmanifold") == 0)
trim_nonmanifold = true;
else if (std::strcmp(argv[i], "--drop-spurs") == 0)
drop_spurs = true;
else if (std::strcmp(argv[i], "--collapse-spurs") == 0)
collapse_spurs = true;
else if (std::strcmp(argv[i], "--tolerant-stitch") == 0 && i + 1 < argc)
tolerant_stitch = std::strtod(argv[++i], nullptr);
else if (std::strcmp(argv[i], "--fill-sphere") == 0 && i + 1 < argc)
fill_sphere_surface = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
else if (std::strcmp(argv[i], "--fill-sphere-reverse") == 0)
fill_sphere_reverse = true;
else if (std::strcmp(argv[i], "--fill-circle") == 0 && i + 2 < argc) {
fill_circle_plane = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
fill_circle_sphere = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--fill-lens") == 0 && i + 3 < argc) {
lens_plane_a = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
lens_plane_b = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
lens_sphere = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--exact-planar-trim") == 0 && i + 2 < argc) {
planar_trim_face = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
planar_trim_sphere = static_cast<int>(std::strtol(argv[++i], nullptr, 10));
}
else if (std::strcmp(argv[i], "--index") == 0) index_only = true;
else if (std::strcmp(argv[i], "--body-index") == 0 && i + 1 < argc) {
body_index = std::strtol(argv[++i], nullptr, 10);
if (body_index < 0) {
std::fprintf(stderr, "invalid --body-index\n");
return 3;
}
}
else if (std::strcmp(argv[i], "--body-count") == 0 && i + 1 < argc) {
body_count = std::strtol(argv[++i], nullptr, 10);
if (body_count < 1) body_count = 1;
}
else if (std::strcmp(argv[i], "--save-body") == 0 && i + 1 < argc) {
save_body = argv[++i];
}
else if (std::strcmp(argv[i], "--out") == 0 && i + 1 < argc)
out_dir = argv[++i];
else if (std::strcmp(argv[i], "--max-seconds") == 0 && i + 1 < argc) {
char* end = nullptr;
const double v = std::strtod(argv[++i], &end);
if (end == argv[i] || *end != '\0' || v < 0.0 || !std::isfinite(v)) {
std::fprintf(stderr, "invalid --max-seconds: %s\n", argv[i]);
return 3;
}
max_seconds = v;
} else if (std::strcmp(argv[i], "--diagnostics-max-seconds") == 0 && i + 1 < argc) {
char* end = nullptr;
const double v = std::strtod(argv[++i], &end);
if (end == argv[i] || *end != '\0' || v < 0.0 || !std::isfinite(v)) {
std::fprintf(stderr, "invalid --diagnostics-max-seconds: %s\n", argv[i]);
return 3;
}
diagnostics_max_seconds = v;
} else if (std::strcmp(argv[i], "--max-bytes") == 0 && i + 1 < argc) {
char* end = nullptr;
const unsigned long long v = std::strtoull(argv[++i], &end, 10);
if (end == argv[i] || *end != '\0') {
std::fprintf(stderr, "invalid --max-bytes: %s\n", argv[i]);
return 3;
}
max_bytes = static_cast<std::size_t>(v);
} else if (std::strcmp(argv[i], "--timeout-exit-code") == 0 && i + 1 < argc) {
char* end = nullptr;
const long v = std::strtol(argv[++i], &end, 10);
if (end == argv[i] || *end != '\0' || v <= 0 || v > 255) {
std::fprintf(stderr, "invalid --timeout-exit-code: %s\n", argv[i]);
return 3;
}
budget_exit_code = static_cast<int>(v);
}
else if (argv[i][0] == '-') {
std::fprintf(stderr, "unknown option: %s\n", argv[i]);
return 3;
} else if (path.empty()) path = argv[i];
else {
std::fprintf(stderr, "multiple input files are not supported\n");
return 3;
}
}
if (path.empty()) {
std::fprintf(stderr,
"usage: vde_brep_check <file|dir> [--heal] [--pinch] [--orient] [--deep] [--json] [--strict] [--quick] [--jobs N] [--index] [--split-shells] [--out <dir>] [--max-seconds N] [--diagnostics-max-seconds N] [--max-bytes N] [--timeout-exit-code N]\n");
return 3;
}
if (json && heal) {
std::fprintf(stderr, "--json cannot be combined with --heal\n");
return 3;
}
// R4(P0-5):--json --deep 不能静默忽略;JSON schema 尚未承载 deep 字段。
if (json && deep) {
std::fprintf(stderr,
"--json --deep is not supported: deep diagnostics are not represented "
"in ImportDiagnostic JSON; run --deep without --json\n");
return 3;
}
if (quick && heal) {
std::fprintf(stderr, "--quick cannot be combined with --heal\n");
return 3;
}
if (index_only) {
if (std::filesystem::is_directory(u8_path(path))) {
std::fprintf(stderr, "--index requires a single STEP file\n");
return 3;
}
const auto idx = vde::brep::index_step_parallel(path, jobs);
std::printf("index: ok=%d bytes=%llu threads=%u entities=%zu ms=%.1f%s%s\n",
idx.ok ? 1 : 0,
static_cast<unsigned long long>(idx.bytes), idx.threads,
idx.entities.size(), idx.elapsed_ms,
idx.error.empty() ? "" : " error=", idx.error.c_str());
return idx.ok ? 0 : 1;
}
if (!out_dir.empty() && !heal && !split_shells) {
std::fprintf(stderr, "--out requires --heal or --split-shells\n");
return 3;
}
std::error_code dir_ec;
if (scan_sldprt && std::filesystem::is_directory(u8_path(path), dir_ec) && !dir_ec) {
size_t scanned = 0, hits = 0;
CadImportOptions opt;
opt.collect_body_diagnostics = false;
for (const auto& entry :
std::filesystem::recursive_directory_iterator(u8_path(path))) {
if (!entry.is_regular_file()) continue;
std::string ext = entry.path().extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (ext != ".sldprt") continue;
const std::wstring fname = entry.path().filename().native();
if (!scan_name.empty()) {
const std::wstring wname(scan_name.begin(), scan_name.end());
if (fname.find(wname) == std::wstring::npos) continue;
}
bool skipped = false;
for (const auto& s : scan_skips) {
const std::wstring ws(s.begin(), s.end());
if (!s.empty() && fname.find(ws) != std::wstring::npos) {
skipped = true;
break;
}
}
if (skipped) continue;
std::error_code szec;
const auto fsz = std::filesystem::file_size(entry.path(), szec);
if (szec || fsz > 32ull * 1024 * 1024) continue;
++scanned;
std::fprintf(stderr, "scan file=%s\n", entry.path().string().c_str());
std::fflush(stderr);
try {
CadImportResult r = import_cad(entry.path().string(), opt);
for (const auto& b : r.bodies) {
const int nf = static_cast<int>(b.num_faces());
if (std::abs(nf - scan_faces) > 3) continue;
const auto m = analytic_measure(b, 0.05);
if (m.degraded()) continue;
if (std::abs(m.volume - scan_volume) / scan_volume < 0.02) {
++hits;
std::printf("HIT %s body_faces=%d volume=%.6f\n",
entry.path().string().c_str(), nf, m.volume);
std::fflush(stdout);
}
}
} catch (...) {
}
if ((scanned % 500) == 0) {
std::fprintf(stderr, "scanned=%zu hits=%zu\n", scanned, hits);
std::fflush(stderr);
}
}
std::printf("scan done scanned=%zu hits=%zu\n", scanned, hits);
return 0;
}
if (std::filesystem::is_directory(u8_path(path), dir_ec) && !dir_ec) {
if (heal || pinch || split_shells || !out_dir.empty()) {
std::fprintf(stderr, "--heal/--pinch/--split-shells/--out are only supported for a single file\n");
return 3;
}
CadImportOptions directory_options;
directory_options.max_seconds = max_seconds;
directory_options.diagnostics_max_seconds = diagnostics_max_seconds;
directory_options.max_file_bytes = max_bytes;
return json ? check_directory_json(path, strict, quick, jobs,
directory_options, budget_exit_code)
: check_directory(path, strict, quick, jobs, directory_options,
budget_exit_code);
}
CadImportOptions import_options;
import_options.max_seconds = max_seconds;
import_options.diagnostics_max_seconds = diagnostics_max_seconds;
import_options.max_file_bytes = max_bytes;
if (body_index >= 0) import_options.collect_body_diagnostics = false;
if (quick) {
// W3-7:--quick 对大 STEP 默认走流式,避免 2003 body 常驻导致 2GB+ 峰值。
std::error_code szec;
const auto sz = std::filesystem::file_size(native_path(path), szec);
if (!szec && sz > 256ull * 1024 * 1024) {
#ifdef _WIN32
_putenv_s("VDE_STEP_STREAM", "1");
#else
setenv("VDE_STEP_STREAM", "1", 1);
#endif
}
// --quick 的 JSON 仍由 fill_import_diagnostic 填 body_count(bodies.size),
// 不能为 JSON 打开逐 body diagnose_body:大模型 analytic_volume 可跑分钟级,
// 会把“快速筛查”变成新的超时源(真实语料 462MB STEP 实测)。
import_options.collect_body_diagnostics = false;
CadImportResult imported = import_cad(native_path(path), import_options);
imported.diagnostic.path = path; // JSON path 保持 UTF-8
if (!json && imported.diagnostic.analysis_only)
std::printf("result: SKIP (analysis-only)\n");
if (json) {
std::printf("%s\n", imported.diagnostic.to_json().c_str());
} else {
std::printf("diagnostic: %s\n", imported.diagnostic.summary().c_str());
for (const auto& issue : imported.diagnostic.issues)
std::printf(" %s %s\n",
issue.severity == ImportIssueSeverity::Error ? "E"
: issue.severity == ImportIssueSeverity::Warning ? "W" : "I",
issue.message.c_str());
for (const auto& repair : imported.diagnostic.repairs)
std::printf(" repair[%s] %s\n",
repair.automatic ? "auto" : "manual",
repair.description.c_str());
}
return diagnostic_exit(imported.diagnostic, strict, budget_exit_code);
}
if (json) {
import_options.collect_body_diagnostics = true;
CadImportResult imported = import_cad(native_path(path), import_options);
imported.diagnostic.path = path;
if (bad_sheets) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto ids = find_bad_sheets(imported.bodies[bi]);
std::fprintf(stderr, "body[%zu] bad_sheets=%zu", bi, ids.size());
for (std::size_t k = 0; k < ids.size() && k < 8; ++k)
std::fprintf(stderr, " #%d", ids[k]);
std::fprintf(stderr, "\n");
}
}
if (move_seam) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const int moved = heal_move_seam_vertices(imported.bodies[bi]);
const auto v = validate(imported.bodies[bi]);
std::fprintf(stderr,
"body[%zu] move_seam=%d valid=%d wt=%.6f\n",
bi, moved, v.valid ? 1 : 0, v.watertightness);
}
}
if (cap_boundary) {
for (auto& b : imported.bodies) {
const int before = static_cast<int>(b.num_faces());
const int capped = cap_boundary_loops(b);
const auto v = validate(b);
std::fprintf(stderr,
"body cap before=%d capped=%d after=%d valid=%d wt=%.6f\n",
before, capped, static_cast<int>(b.num_faces()),
v.valid ? 1 : 0, v.watertightness);
}
}
if (curvature) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto r = vde::curves::analyze_body_curvature(imported.bodies[bi], 8, 8);
std::fprintf(stderr, "body[%zu] curvature %s\n", bi, r.to_json().c_str());
}
}
if (volume_check) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto c = check_volume_consistency(imported.bodies[bi]);
std::fprintf(stderr, "body[%zu] volume analytic=%.6f mesh=%.6f ratio=%.3f consistent=%d\n",
bi, c.analytic_volume, c.mesh_volume, c.ratio,
c.consistent ? 1 : 0);
}
}
if (boundary_report) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto mesh = imported.bodies[bi].to_mesh(0.02);
const auto m = vde::mesh::analyze_mesh_boundary(mesh);
std::fprintf(stderr, "body[%zu] boundary edges=%zu loops=%zu nm=%zu tris=%zu\n",
bi, m.boundary_edges, m.boundary_loops, m.nonmanifold_edges,
m.triangles);
const auto loops = vde::mesh::extract_boundary_loops(mesh);
for (std::size_t li = 0; li < loops.size(); ++li) {
const auto arcs = vde::mesh::fit_boundary_arcs(mesh, loops[li]);
std::fprintf(stderr, " loop[%zu] points=%zu arcs=%zu",
li, loops[li].vertices.size(), arcs.size());
for (const auto& a : arcs)
std::fprintf(stderr, " r=%.3f sweep=%.3f", a.radius, a.sweep);
std::fprintf(stderr, "\n");
}
}
}
std::printf("%s\n", imported.diagnostic.to_json().c_str());
return diagnostic_exit(imported.diagnostic, strict, budget_exit_code);
}
std::printf("file: %s\n", path.c_str());
CadImportResult imported;
import_options.collect_body_diagnostics =
(body_index < 0 && !list_bodies && duplicate_body < 0 && !check_target);
try {
imported = import_cad(native_path(path), import_options);
} catch (const std::exception& e) {
std::printf("import exception: %s\n", e.what());
return 2;
}
imported.diagnostic.path = path; // JSON/文本 path 使用 UTF-8
if (move_seam) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const int moved = heal_move_seam_vertices(imported.bodies[bi]);
const auto v = validate(imported.bodies[bi]);
std::printf("body[%zu] move_seam=%d valid=%d wt=%.6f\n",
bi, moved, v.valid ? 1 : 0, v.watertightness);
}
}
if (bad_sheets) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto ids = find_bad_sheets(imported.bodies[bi]);
std::printf("body[%zu] bad_sheets=%zu", bi, ids.size());
for (std::size_t k = 0; k < ids.size() && k < 8; ++k)
std::printf(" #%d", ids[k]);
std::printf("\n");
}
}
if (cap_boundary) {
for (auto& b : imported.bodies) {
const int before = static_cast<int>(b.num_faces());
const int capped = cap_boundary_loops(b);
const auto v = validate(b);
std::printf("body cap before=%d capped=%d after=%d valid=%d wt=%.6f\n",
before, capped, static_cast<int>(b.num_faces()),
v.valid ? 1 : 0, v.watertightness);
}
}
if (curvature) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto r = vde::curves::analyze_body_curvature(imported.bodies[bi], 8, 8);
std::printf("body[%zu] curvature %s\n", bi, r.to_json().c_str());
}
}
if (volume_check) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto c = check_volume_consistency(imported.bodies[bi]);
std::printf("body[%zu] volume analytic=%.6f mesh=%.6f ratio=%.3f consistent=%d\n",
bi, c.analytic_volume, c.mesh_volume, c.ratio,
c.consistent ? 1 : 0);
}
}
if (boundary_report) {
for (std::size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto mesh = imported.bodies[bi].to_mesh(0.02);
const auto m = vde::mesh::analyze_mesh_boundary(mesh);
const auto loops = vde::mesh::extract_boundary_loops(mesh);
double len = 0.0;
for (const auto& l : loops) len += l.length;
std::printf("body[%zu] boundary edges=%zu loops=%zu nm=%zu tris=%zu length=%.6f\n",
bi, m.boundary_edges, m.boundary_loops, m.nonmanifold_edges,
m.triangles, len);
}
}
if (check_target) {
for (const auto& b : imported.bodies) {
const int nf = static_cast<int>(b.num_faces());
if (std::abs(nf - scan_faces) > 3) continue;
const auto m = analytic_measure(b, 0.05);
if (m.degraded()) continue;
if (std::abs(m.volume - scan_volume) / scan_volume < 0.02) {
std::printf("HIT %s faces=%d volume=%.6f\n", path.c_str(), nf,
m.volume);
return 0;
}
}
return 0;
}
if (body_index >= 0) {
if (static_cast<size_t>(body_index) >= imported.bodies.size()) {
std::printf("body-index out of range: %ld/%zu\n", body_index,
imported.bodies.size());
return 3;
}
if (body_label) {
std::printf("body %ld label=%s\n", body_index,
imported.bodies[body_index].label().c_str());
return 0;
}
if (mesh_volume) {
const auto mesh = imported.bodies[body_index].to_mesh(0.01);
double s6 = 0.0;
for (size_t i = 0; i < mesh.num_faces(); ++i) {
const auto fv = mesh.face_vertices(static_cast<int>(i));
if (fv.size() < 3) continue;
const auto a = mesh.vertex(fv[0]);
const auto b = mesh.vertex(fv[1]);
const auto c = mesh.vertex(fv[2]);
s6 += a.dot(b.cross(c));
}
std::printf("body %ld mesh_tri=%zu mesh_volume=%.6f\n", body_index,
mesh.num_faces(), std::abs(s6 / 6.0));
return 0;
}
if (!save_body.empty()) {
if (vde::foundation::save_vde(imported.bodies[body_index], save_body))
std::printf("saved body %ld to %s\n", body_index, save_body.c_str());
}
const long end = std::min<long>(
static_cast<long>(imported.bodies.size()), body_index + body_count);
for (long bi = body_index; bi < end; ++bi) {
std::printf("diagnose body %ld\n", bi);
std::fflush(stdout);
ValidationResult v;
try {
BodyDiagnostics bd =
diagnose_body(imported.bodies[bi], nullptr, &v);
print_diag(bd);
std::printf("body %ld diagnose: %s E=%d W=%d vol=%.3f\n", bi,
bd.valid ? "OK" : "BAD", bd.error_count,
bd.warning_count, bd.volume);
} catch (const std::exception& e) {
std::printf("body %ld diagnose exception: %s\n", bi, e.what());
} catch (...) {
std::printf("body %ld diagnose unknown exception\n", bi);
}
std::fflush(stdout);
}
return 0;
}
if (has_ext(path, ".step", ".stp") && step_import_diagnostic().has_issues()) {
std::printf("STEP diagnostic:\n%s\n",
step_import_diagnostic().report().c_str());
}
for (const auto& m : imported.messages)
std::printf("import message: %s\n", m.c_str());
std::printf("import: %s bodies=%zu drawing=%d converter=%d\n",
imported.ok ? "OK" : "FAILED", imported.bodies.size(),
imported.has_drawing ? 1 : 0, imported.converter_used ? 1 : 0);
std::printf("diagnostic: %s\n", imported.diagnostic.summary().c_str());
for (const auto& issue : imported.diagnostic.issues) {
const char* sev = issue.severity == ImportIssueSeverity::Error ? "E"
: issue.severity == ImportIssueSeverity::Warning ? "W" : "I";
std::printf(" %s %-22s %s\n", sev, issue.code.c_str(),
issue.message.c_str());
}
for (const auto& repair : imported.diagnostic.repairs)
std::printf(" repair[%s] %s\n", repair.automatic ? "auto" : "manual",
repair.description.c_str());
if (imported.diagnostic.budget_exceeded) {
std::printf("result: FAIL (budget exceeded; elapsed_ms=%.3f)\n",
imported.diagnostic.elapsed_ms);
return budget_exit_code;
}
if (imported.diagnostic.analysis_only) {
std::printf("result: SKIP (analysis-only; no B-Rep, drawing entities=%d)\n",
imported.diagnostic.drawing_entity_count);
return 0;
}
if (!imported.ok) return 2;
if (imported.bodies.empty()) {
std::printf("result: PASS (no B-Rep; drawing entities=%d)\n",
imported.diagnostic.drawing_entity_count);
return 0;
}
if (split_shells) return split_shells_report(imported, out_dir, heal);
int bad = 0;
if (duplicate_body >= 0 &&
duplicate_body < static_cast<int>(imported.bodies.size())) {
auto signature = [](const BrepModel& b) {
std::vector<std::size_t> hs;
for (const auto& f : b.all_faces()) {
std::size_t h = 1469598103934665603ull;
if (f.surface_id >= 0 &&
static_cast<std::size_t>(f.surface_id) < b.num_surfaces()) {
const auto& s = b.surface(f.surface_id);
for (const auto& row : s.control_points())
for (const auto& p : row) {
h ^= std::hash<double>{}(p.x()) + 0x9e3779b9;
h *= 1099511628211ull;
h ^= std::hash<double>{}(p.y()) + 0x9e3779b9;
h *= 1099511628211ull;
h ^= std::hash<double>{}(p.z()) + 0x9e3779b9;
h *= 1099511628211ull;
}
}
hs.push_back(h);
}
std::sort(hs.begin(), hs.end());
std::size_t out = 1469598103934665603ull;
for (std::size_t h : hs) {
out ^= h + 0x9e3779b9;
out *= 1099511628211ull;
}
return out;
};
const std::size_t target_sig = signature(imported.bodies[duplicate_body]);
std::printf("target body=%d faces=%zu sig=%016zx\n", duplicate_body,
imported.bodies[duplicate_body].num_faces(), target_sig);
for (size_t bi = 0; bi < imported.bodies.size(); ++bi) {
if (static_cast<int>(bi) == duplicate_body) continue;
if (imported.bodies[bi].num_faces() !=
imported.bodies[duplicate_body].num_faces())
continue;
if (signature(imported.bodies[bi]) == target_sig)
std::printf("duplicate body=%zu faces=%zu\n", bi,
imported.bodies[bi].num_faces());
}
return 0;
}
if (list_bodies) {
for (size_t bi = 0; bi < imported.bodies.size(); ++bi) {
const auto m = analytic_measure(imported.bodies[bi], 0.05);
std::printf("body %zu faces=%zu volume=%.6f degraded=%d\n", bi,
imported.bodies[bi].num_faces(), m.volume, m.degraded() ? 1 : 0);
}
return 0;
}
for (size_t bi = 0; bi < imported.bodies.size(); ++bi) {
BrepModel& body = imported.bodies[bi];
if (surface_info >= 0 &&
static_cast<size_t>(surface_info) < body.num_surfaces()) {
const auto s = ssi::detect_analytic_surface(body.surface(surface_info));
if (s) {
std::printf("surface %d kind=%d o=(%.6f,%.6f,%.6f) z=(%.6f,%.6f,%.6f) r1=%.6f r2=%.6f h=%.6f\n",
surface_info, static_cast<int>(s->kind), s->o.x(), s->o.y(),
s->o.z(), s->z.x(), s->z.y(), s->z.z(), s->r1, s->r2, s->h);
}
}
const auto& shells = body.all_shells();
bool any_closed = false;
for (const auto& sh : shells) any_closed = any_closed || sh.closed;
const bool pure_surface = !shells.empty() && !any_closed;
std::printf("\n[body %zu] V=%zu E=%zu F=%zu S=%zu%s\n", bi,
body.num_vertices(), body.num_edges(), body.num_faces(),
shells.size(), pure_surface ? " surface" : "");
for (size_t si = 0; si < shells.size() && si < 16; ++si)
std::printf(" shell[%zu] faces=%zu closed=%d\n", si,
shells[si].faces.size(), shells[si].closed ? 1 : 0);
if (shells.size() > 16)
std::printf(" ... %zu more shells\n", shells.size() - 16);
if (dump_pairs) {
std::vector<std::array<int, 2>> pen, touch, intra, inter;
(void)validate(body, &pen, &touch, &intra, &inter);
std::printf(" penetration_pairs=%zu intra=%zu inter=%zu touch=%zu\n",
pen.size(), intra.size(), inter.size(), touch.size());
for (const auto& pr : intra)
std::printf(" intra (%d, %d)\n", pr[0], pr[1]);
for (const auto& pr : inter)
std::printf(" inter (%d, %d)\n", pr[0], pr[1]);
}
if (dump_faces) {
const auto& all_faces = body.all_faces();
for (size_t fi = 0; fi < all_faces.size(); ++fi) {
const auto& f = all_faces[fi];
const auto fm = face_measure(body, static_cast<int>(fi), 0.01, 200000);
const char* tn = "Other";
switch (body.face_type(static_cast<int>(fi))) {
case FaceType::Plane: tn = "Plane"; break;
case FaceType::Cylinder: tn = "Cylinder"; break;
case FaceType::Cone: tn = "Cone"; break;
case FaceType::Sphere: tn = "Sphere"; break;
case FaceType::Torus: tn = "Torus"; break;
case FaceType::Spline: tn = "Spline"; break;
default: break;
}
std::size_t sh = 1469598103934665603ull;
auto mix = [&](double v) {
sh ^= std::hash<double>{}(v);
sh *= 1099511628211ull;
};
int cps = 0;
if (f.surface_id >= 0 &&
static_cast<size_t>(f.surface_id) < body.num_surfaces()) {
const auto& s = body.surface(f.surface_id);
const auto nc = s.num_control_points();
cps = nc[0] * nc[1];
for (const auto& row : s.control_points())
for (const auto& pt : row) { mix(pt.x()); mix(pt.y()); mix(pt.z()); }
for (const auto& row : s.weights())
for (double w : row) mix(w);
}
std::size_t bh = 0;
int loop_found = 0, edge_found = 0, vert_found = 0;
for (int loop_id : f.loops) {
const TopoLoop* lp = nullptr;
if (loop_id >= 0 &&
static_cast<size_t>(loop_id) < body.all_loops().size())
lp = &body.all_loops()[loop_id];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == loop_id) { lp = &l; break; }
if (!lp) continue;
++loop_found;
for (int edge_id : lp->edges) {
const TopoEdge* ep = nullptr;
if (edge_id >= 0 &&
static_cast<size_t>(edge_id) < body.all_edges().size())
ep = &body.all_edges()[edge_id];
if (!ep)
for (const auto& e : body.all_edges())
if (e.id == edge_id) { ep = &e; break; }
if (!ep) continue;
++edge_found;
for (int v : {ep->v_start, ep->v_end}) {
const TopoVertex* vp = nullptr;
if (v >= 0 &&
static_cast<size_t>(v) < body.all_vertices().size())
vp = &body.all_vertices()[v];
if (!vp)
for (const auto& vv : body.all_vertices())
if (vv.id == v) { vp = &vv; break; }
if (!vp) continue;
++vert_found;
const auto& pt = vp->point;
bh ^= std::hash<double>{}(pt.x()) + 0x9e3779b9;
bh ^= std::hash<double>{}(pt.y()) + 0x9e3779b9;
bh ^= std::hash<double>{}(pt.z()) + 0x9e3779b9;
}
}
}
std::printf(" face %zu id=%d surface=%d reversed=%d loops=%zu area=%.6f type=%s cp=%d sh=%016zx bh=%016zx lf=%d ef=%d vf=%d\n",
fi, f.id, f.surface_id, f.reversed ? 1 : 0,
f.loops.size(), fm.area, tn, cps, sh, bh,
loop_found, edge_found, vert_found);
}
}
if (dump_regions) {
const size_t nf = body.all_faces().size();
std::vector<int> parent(nf);
for (size_t i = 0; i < nf; ++i) parent[i] = static_cast<int>(i);
std::function<int(int)> find = [&](int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
auto unite = [&](int a, int b) {
a = find(a); b = find(b);
if (a != b) parent[b] = a;
};
std::unordered_map<int, int> edge_owner;
for (size_t fi = 0; fi < nf; ++fi) {
for (int loop_id : body.all_faces()[fi].loops) {
const TopoLoop* lp = nullptr;
if (loop_id >= 0 &&
static_cast<size_t>(loop_id) < body.all_loops().size())
lp = &body.all_loops()[loop_id];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == loop_id) { lp = &l; break; }
if (!lp) continue;
for (int edge_id : lp->edges) {
int key = edge_id;
const TopoEdge* ep = nullptr;
if (edge_id >= 0 &&
static_cast<size_t>(edge_id) < body.all_edges().size())
ep = &body.all_edges()[edge_id];
if (ep) key = ep->id;
auto it = edge_owner.find(key);
if (it == edge_owner.end())
edge_owner.emplace(key, static_cast<int>(fi));
else
unite(it->second, static_cast<int>(fi));
}
}
}
std::map<int, std::vector<int>> groups;
for (size_t fi = 0; fi < nf; ++fi)
groups[find(static_cast<int>(fi))].push_back(static_cast<int>(fi));
std::printf(" regions=%zu\n", groups.size());
for (const auto& g : groups) {
std::printf(" region root=%d faces=%zu:", g.first, g.second.size());
for (size_t k = 0; k < g.second.size() && k < 40; ++k)
std::printf(" %d", g.second[k]);
if (g.second.size() > 40) std::printf(" ...");
std::printf("\n");
}
}
if (dump_nonmanifold) {
std::map<int, std::vector<int>> ef;
for (size_t fi = 0; fi < body.all_faces().size(); ++fi) {
for (int lid : body.all_faces()[fi].loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
int ei = eid;
if (ei < 0 || ei >= static_cast<int>(body.all_edges().size()))
ei = -1;
if (ei < 0)
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) { ei = static_cast<int>(k); break; }
if (ei >= 0) ef[ei].push_back(static_cast<int>(fi));
}
}
}
int nm = 0, bd = 0;
for (const auto& e : ef) {
if (e.second.size() > 2) {
++nm;
std::printf(" nonmanifold edge idx=%d faces=", e.first);
for (int f : e.second) std::printf(" %d", f);
std::printf("\n");
} else if (e.second.size() == 1) {
++bd;
std::printf(" boundary edge idx=%d face=%d\n", e.first,
e.second.front());
}
}
std::printf(" nonmanifold_edges=%d boundary_edges=%d\n", nm, bd);
}
if (classify_internal) {
const auto mesh = body.to_mesh(0.05);
int internal = 0;
for (size_t fi = 0; fi < body.num_faces(); ++fi) {
if (body.face_type(static_cast<int>(fi)) != FaceType::Plane)
continue;
const auto& f = body.all_faces()[fi];
if (f.surface_id < 0 ||
static_cast<size_t>(f.surface_id) >= body.num_surfaces())
continue;
const auto& s = body.surface(f.surface_id);
const auto& cp = s.control_points();
if (cp.size() < 2 || cp[0].size() < 2) continue;
const Point3D p0 = cp[0][0];
const Point3D p1 = cp[0].back();
const Point3D p2 = cp.back()[0];
Vector3D nrm{p1.x() - p0.x(), p1.y() - p0.y(), p1.z() - p0.z()};
const Vector3D dv{p2.x() - p0.x(), p2.y() - p0.y(), p2.z() - p0.z()};
nrm = Vector3D{nrm.y() * dv.z() - nrm.z() * dv.y(),
nrm.z() * dv.x() - nrm.x() * dv.z(),
nrm.x() * dv.y() - nrm.y() * dv.x()};
const double len = std::sqrt(nrm.x() * nrm.x() + nrm.y() * nrm.y() +
nrm.z() * nrm.z());
if (len < 1e-12) continue;
nrm = Vector3D{nrm.x() / len, nrm.y() / len, nrm.z() / len};
Point3D c{0, 0, 0};
int nv = 0;
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
const TopoEdge* ep = nullptr;
if (eid >= 0 && static_cast<size_t>(eid) < body.all_edges().size())
ep = &body.all_edges()[eid];
if (!ep)
for (const auto& e : body.all_edges())
if (e.id == eid) { ep = &e; break; }
if (!ep) continue;
for (int v : {ep->v_start, ep->v_end}) {
const TopoVertex* vp = nullptr;
if (v >= 0 && static_cast<size_t>(v) < body.all_vertices().size())
vp = &body.all_vertices()[v];
if (!vp)
for (const auto& vv : body.all_vertices())
if (vv.id == v) { vp = &vv; break; }
if (!vp) continue;
c = Point3D{c.x() + vp->point.x(), c.y() + vp->point.y(),
c.z() + vp->point.z()};
++nv;
}
}
}
if (nv == 0) continue;
c = Point3D{c.x() / nv, c.y() / nv, c.z() / nv};
const double eps = 1e-3;
const Point3D plus{c.x() + nrm.x() * eps, c.y() + nrm.y() * eps,
c.z() + nrm.z() * eps};
const Point3D minus{c.x() - nrm.x() * eps, c.y() - nrm.y() * eps,
c.z() - nrm.z() * eps};
const bool in_plus = point_inside_mesh(mesh, plus);
const bool in_minus = point_inside_mesh(mesh, minus);
if (in_plus && in_minus) ++internal;
std::printf(" internal? face=%zu area? plus=%d minus=%d\n", fi,
in_plus ? 1 : 0, in_minus ? 1 : 0);
}
std::printf(" internal_faces=%d\n", internal);
}
if (boolean_smoke) {
BrepModel s = make_sphere(5.0, 32, 16, Point3D(0, 0, 0));
BrepModel b = make_box(10.0, 10.0, 10.0, Point3D(5.0, 0, 0));
BrepModel d = brep_difference(s, b);
const auto sm = analytic_measure(s, 0.02);
const auto bm = analytic_measure(b, 0.02);
const auto dm = analytic_measure(d, 0.02);
std::printf(" boolean-smoke sphere=%.3f box=%.3f diff=%.3f faces=%zu\n",
sm.volume, bm.volume, dm.volume, d.num_faces());
}
bool body_modified = false;
if (mesh_repair) {
const auto mesh = body.to_mesh(0.02);
BrepModel repaired = mesh_to_brep_model(mesh);
const auto rv = validate(repaired);
std::printf(" mesh-repair tris=%zu faces=%zu volume=%.6f mesh=%.6f valid=%d wt=%.3f\n",
mesh.num_faces(), repaired.num_faces(),
analytic_measure(repaired, 0.02).volume,
mesh_abs_volume(repaired), rv.valid ? 1 : 0,
rv.watertightness);
body = std::move(repaired);
body_modified = true;
}
if (build_caps_sphere >= 0 && build_caps_a >= 0 && build_caps_b >= 0) {
const auto ss = ssi::detect_analytic_surface(body.surface(build_caps_sphere));
const auto pa = ssi::detect_analytic_surface(body.surface(build_caps_a));
const auto pb = ssi::detect_analytic_surface(body.surface(build_caps_b));
if (ss && pa && pb) {
ssi::Surface sha = *pa;
ssi::Surface shb = *pb;
if (build_caps_shift != 0.0) {
sha.o = Point3D{sha.o.x() + sha.z.x() * build_caps_shift,
sha.o.y() + sha.z.y() * build_caps_shift,
sha.o.z() + sha.z.z() * build_caps_shift};
const double sb = std::isnan(build_caps_shift_b)
? build_caps_shift
: build_caps_shift_b;
shb.o = Point3D{shb.o.x() + shb.z.x() * sb,
shb.o.y() + shb.z.y() * sb,
shb.o.z() + shb.z.z() * sb};
}
auto ca = ssi::exact_intersection(sha, *ss);
auto cb = ssi::exact_intersection(shb, *ss);
if (ca && cb) {
BrepModel m;
const int sid = m.add_surface(body.surface(build_caps_sphere));
auto make_loop = [&](const ssi::ExactCurve& c, bool outer) {
constexpr double kPi = 3.14159265358979323846;
std::vector<int> es;
for (int k = 0; k < 4; ++k) {
const double t0 = k * kPi / 2.0;
const double t1 = (k + 1) * kPi / 2.0;
const int v0 = m.add_vertex_unique(ssi::exact_curve_point(c, t0), 1e-6);
const int v1 = m.add_vertex_unique(ssi::exact_curve_point(c, t1), 1e-6);
es.push_back(m.add_edge(v0, v1, ssi::exact_curve_nurbs(c, t0, t1)));
}
return m.add_loop(es, outer);
};
const int la = make_loop(*ca, !build_caps_swap);
const int lb = make_loop(*cb, build_caps_swap);
const int sf = m.add_face(sid, {la, lb});
if (build_caps_reverse) m.set_face_reversed(sf, true);
auto add_disk = [&](const ssi::ExactCurve& c, int loop) {
const Point3D org{c.center.x() - c.u.x() * c.a - c.v.x() * c.b,
c.center.y() - c.u.y() * c.a - c.v.y() * c.b,
c.center.z() - c.u.z() * c.a - c.v.z() * c.b};
const int psid = m.add_surface(vde::curves::NurbsSurface::plane(
org, c.u, c.v, 2 * c.a, 2 * c.b));
const int f = m.add_face(psid, {loop});
m.set_face_reversed(f, true);
return f;
};
add_disk(*ca, la);
add_disk(*cb, lb);
std::vector<int> faces;
for (const auto& f : m.all_faces()) faces.push_back(f.id);
const int sh = m.add_shell(faces, true);
m.add_body({sh}, "sphere_caps");
const auto v = validate(m);
std::printf(" build-sphere-caps faces=%zu volume=%.6f mesh=%.6f valid=%d wt=%.3f\n",
m.num_faces(), analytic_measure(m, 0.02).volume,
mesh_abs_volume(m), v.valid ? 1 : 0, v.watertightness);
body = std::move(m);
body_modified = true;
}
}
}
if (wedge_sphere >= 0 && wedge_plane_a >= 0 && wedge_plane_b >= 0) {
const auto ss = ssi::detect_analytic_surface(body.surface(wedge_sphere));
const auto pa = ssi::detect_analytic_surface(body.surface(wedge_plane_a));
const auto pb = ssi::detect_analytic_surface(body.surface(wedge_plane_b));
if (ss && pa && pb) {
const double R = ss->r1;
BrepModel sph = make_sphere(R, 32, 16, ss->o);
auto cut = [&](BrepModel in, const ssi::Surface& pl, double sign) {
Vector3D n = pl.z.normalized();
const double dist = n.dot(ss->o - pl.o);
Point3D anchor{ss->o.x() - n.x() * dist,
ss->o.y() - n.y() * dist,
ss->o.z() - n.z() * dist};
anchor = Point3D{anchor.x() + n.x() * wedge_shift,
anchor.y() + n.y() * wedge_shift,
anchor.z() + n.z() * wedge_shift};
if (n.dot(ss->o - anchor) < 0.0)
n = Vector3D{-n.x(), -n.y(), -n.z()};
const double L = 4.0 * R;
const double D = 3.0 * R;
const Vector3D xaxis{1, 0, 0};
Vector3D axis = xaxis.cross(n);
double angle = std::acos(std::max(-1.0, std::min(1.0, xaxis.dot(n))));
vde::core::Transform3D Rm = vde::core::Transform3D::Identity();
if (axis.norm() > 1e-12)
Rm = vde::core::rotate(axis, angle);
const vde::core::Transform3D to_local =
Rm.inverse() * vde::core::translate(-anchor);
BrepModel local = in.transformed(to_local);
BrepModel box = make_box(L, 2 * D, 2 * D,
Point3D(L / 2, 0, 0));
BrepModel diff = brep_difference(local, box);
auto parts = split_open_shells(diff);
if (parts.size() > 1) {
size_t best = 0;
double best_vol = -1.0;
for (size_t k = 0; k < parts.size(); ++k) {
const double v = mesh_abs_volume(parts[k]);
if (v > best_vol) { best_vol = v; best = k; }
}
diff = std::move(parts[best]);
}
return diff.transformed(to_local.inverse());
};
BrepModel r = cut(sph, *pa, -1.0);
const double m1 = mesh_abs_volume(r);
std::printf(" wedge-one mesh_volume=%.6f faces=%zu\n", m1, r.num_faces());
r = cut(r, *pb, -1.0);
heal_merge_vertices(r, 0.01);
heal_merge_edges(r, 0.01);
heal_split_pinch_vertices(r, 0.01);
heal_slivers(r);
heal_gaps(r, 0.1);
heal_orientation(r);
heal_topology(r, 0.1);
auto closed_parts = split_open_shells(r);
if (closed_parts.size() > 1) {
size_t best = 0;
double best_vol = -1.0;
for (size_t k = 0; k < closed_parts.size(); ++k) {
const auto pv = validate(closed_parts[k]);
if (pv.watertightness < 0.99) continue;
const double v = mesh_abs_volume(closed_parts[k]);
if (v > best_vol) { best_vol = v; best = k; }
}
if (best_vol >= 0.0) r = std::move(closed_parts[best]);
}
const double m = mesh_abs_volume(r);
const auto v = validate(r);
std::printf(" wedge-sphere R=%.6f mesh_volume=%.6f valid=%d wt=%.3f faces=%zu\n",
R, m, v.valid ? 1 : 0, v.watertightness,
r.num_faces());
body = std::move(r);
body_modified = true;
}
}
bool any_open = false;
for (const auto& sh : shells) any_open = any_open || !sh.closed;
if (!heal && !pinch && !orient && !deep && any_closed && any_open) {
// B:混合壳按闭合实体/开放曲面拆分,分别判定。
const auto parts = split_open_shells(body);
std::printf(" mixed -> %zu part(s)\n", parts.size());
for (size_t pi = 0; pi < parts.size(); ++pi) {
const auto pv = validate(parts[pi]);
bool part_closed = false;
for (const auto& sh : parts[pi].all_shells())
part_closed = part_closed || sh.closed;
const bool part_bad =
part_closed && !(pv.valid && pv.watertightness > 0.99);
std::printf(" part %zu: F=%zu closed=%d %s wt=%.4f\n", pi,
parts[pi].num_faces(), part_closed ? 1 : 0,
part_bad ? "BAD" : (part_closed ? "SOLID" : "SURFACE"),
pv.watertightness);
if (part_bad) ++bad;
}
continue;
}
if (ssi_face_a >= 0 && ssi_face_b >= 0) {
const auto& fa = body.all_faces()[static_cast<size_t>(ssi_face_a)];
const auto& fb = body.all_faces()[static_cast<size_t>(ssi_face_b)];
auto sa = ssi::detect_analytic_surface(body.surface(fa.surface_id));
auto sb = ssi::detect_analytic_surface(body.surface(fb.surface_id));
std::printf(" exact-ssi faces %d/%d: analytic a=%d b=%d\n",
ssi_face_a, ssi_face_b, sa ? 1 : 0, sb ? 1 : 0);
if (sa && sb) {
auto c = ssi::exact_intersection(*sa, *sb);
if (!c) {
std::printf(" no exact intersection\n");
} else {
std::printf(" type=%s center=(%.6f,%.6f,%.6f) n=(%.6f,%.6f,%.6f) a=%.6f b=%.6f\n",
c->type == ssi::ExactCurve::Type::Circle ? "circle" : "ellipse",
c->center.x(), c->center.y(), c->center.z(),
c->normal.x(), c->normal.y(), c->normal.z(), c->a, c->b);
const auto pts = ssi::sample_exact_curve(*c, 8);
for (size_t k = 0; k < pts.size(); ++k)
std::printf(" p%zu=(%.6f,%.6f,%.6f)\n", k,
pts[k].x(), pts[k].y(), pts[k].z());
const auto nc = ssi::exact_curve_nurbs(*c, 0.0, 2.0 * 3.14159265358979323846);
std::printf(" nurbs degree=%d cp=%zu\n", nc.degree(),
nc.control_points().size());
}
}
}
if (split_face >= 0 && cut_plane_face >= 0) {
const auto& cf = body.all_faces()[static_cast<size_t>(cut_plane_face)];
const auto& s = body.surface(cf.surface_id);
const auto& cp = s.control_points();
if (cp.size() >= 2 && cp[0].size() >= 2) {
const Point3D p0 = cp[0][0];
const Point3D p1 = cp[0].back();
const Point3D p2 = cp.back()[0];
const Vector3D du{p1.x() - p0.x(), p1.y() - p0.y(), p1.z() - p0.z()};
const Vector3D dv{p2.x() - p0.x(), p2.y() - p0.y(), p2.z() - p0.z()};
const Vector3D nrm{du.y() * dv.z() - du.z() * dv.y(),
du.z() * dv.x() - du.x() * dv.z(),
du.x() * dv.y() - du.y() * dv.x()};
auto frags = split_face_by_plane(body, split_face, p0, nrm);
std::printf(" split-face %d by plane %d -> %zu fragment(s)\n",
split_face, cut_plane_face, frags.size());
for (size_t k = 0; k < frags.size(); ++k) {
double area = 0.0;
for (size_t ff = 0; ff < frags[k].all_faces().size(); ++ff)
area += face_measure(frags[k], static_cast<int>(ff), 0.01, 100000).area;
std::printf(" frag %zu: F=%zu area=%.6f\n", k,
frags[k].num_faces(), area);
}
}
}
if (planar_trim_face >= 0 && planar_trim_sphere >= 0) {
const auto& pf = body.all_faces()[static_cast<size_t>(planar_trim_face)];
const auto& sf = body.all_faces()[static_cast<size_t>(planar_trim_sphere)];
auto ps = ssi::detect_analytic_surface(body.surface(pf.surface_id));
auto ss = ssi::detect_analytic_surface(body.surface(sf.surface_id));
if (ps && ss) {
auto cc = ssi::exact_intersection(*ps, *ss);
if (cc && cc->type == ssi::ExactCurve::Type::Circle) {
const auto tr = ssi::split_planar_face_by_exact_conic(
body, planar_trim_face, *cc);
std::printf(" exact-planar-trim face=%d: ok=%d err=%s area=%.6f inside=%.6f outside=%.6f arcs=%d/%d\n",
planar_trim_face, tr.ok ? 1 : 0, tr.error.c_str(),
tr.area_face, tr.area_inside, tr.area_outside,
tr.inside_arc_edges, tr.outside_arc_edges);
}
}
}
if (trim_sphere_face >= 0 && trim_plane_face >= 0) {
const auto& sf = body.all_faces()[static_cast<size_t>(trim_sphere_face)];
const auto& pf = body.all_faces()[static_cast<size_t>(trim_plane_face)];
auto ss = ssi::detect_analytic_surface(body.surface(sf.surface_id));
auto ps = ssi::detect_analytic_surface(body.surface(pf.surface_id));
if (ss && ps) {
auto cc = ssi::exact_intersection(*ss, *ps);
if (cc && cc->type == ssi::ExactCurve::Type::Circle) {
constexpr double kPi = 3.14159265358979323846;
std::vector<int> edges;
for (int k = 0; k < 4; ++k) {
const double t0 = k * kPi / 2.0;
const double t1 = (k + 1) * kPi / 2.0;
const auto p0 = ssi::exact_curve_point(*cc, t0);
const auto p1 = ssi::exact_curve_point(*cc, t1);
const int v0 = body.add_vertex_unique(p0, 1e-6);
const int v1 = body.add_vertex_unique(p1, 1e-6);
const auto nc = ssi::exact_curve_nurbs(*cc, t0, t1);
edges.push_back(body.add_edge(v0, v1, nc));
}
const int loop = body.add_loop(edges, true);
body.set_face_loops(trim_sphere_face, {loop});
// 平面侧共用同一精确圆弧环,形成闭合球冠。
body.set_face_loops(trim_plane_face, {loop});
body_modified = true;
std::printf(" trim-sphere face %d by plane %d: r=%.6f edges=%zu loop=%d\n",
trim_sphere_face, trim_plane_face, cc->a,
edges.size(), loop);
} else {
std::printf(" trim-sphere: no exact circle\n");
}
}
}
for (long id : delete_face_ids) {
const size_t before = body.num_faces();
body = delete_face(body, static_cast<int>(id));
body_modified = true;
std::printf(" deleted face id=%ld: faces %zu -> %zu\n", id, before,
body.num_faces());
}
if (fill_circle_plane >= 0 && fill_circle_sphere >= 0 &&
fill_circle_plane < static_cast<int>(body.num_faces())) {
const auto& pf = body.all_faces()[static_cast<size_t>(fill_circle_plane)];
auto ps = ssi::detect_analytic_surface(body.surface(pf.surface_id));
auto ss = ssi::detect_analytic_surface(body.surface(fill_circle_sphere));
if (ps && ss) {
auto cc = ssi::exact_intersection(*ps, *ss);
if (cc && cc->type == ssi::ExactCurve::Type::Circle) {
constexpr double kPi = 3.14159265358979323846;
std::vector<int> es;
for (int k = 0; k < 4; ++k) {
const double t0 = k * kPi / 2.0;
const double t1 = (k + 1) * kPi / 2.0;
const int v0 = body.add_vertex_unique(
ssi::exact_curve_point(*cc, t0), 1e-6);
const int v1 = body.add_vertex_unique(
ssi::exact_curve_point(*cc, t1), 1e-6);
es.push_back(body.add_edge(
v0, v1, ssi::exact_curve_nurbs(*cc, t0, t1)));
}
const int nl = body.add_loop(es, true);
const int nf = body.add_face(fill_circle_sphere, {nl});
if (fill_sphere_reverse) body.set_face_reversed(nf, true);
std::printf(" fill-circle plane=%d sphere=%d r=%.6f face=%d\n",
fill_circle_plane, fill_circle_sphere, cc->a, nf);
body.rebuild_single_shell(true);
body_modified = true;
}
}
}
if (lens_plane_a >= 0 && lens_plane_b >= 0 && lens_sphere >= 0 &&
lens_plane_a < static_cast<int>(body.num_faces()) &&
lens_plane_b < static_cast<int>(body.num_faces())) {
const auto sa = ssi::detect_analytic_surface(
body.surface(body.all_faces()[lens_plane_a].surface_id));
const auto sb = ssi::detect_analytic_surface(
body.surface(body.all_faces()[lens_plane_b].surface_id));
const auto ss = ssi::detect_analytic_surface(body.surface(lens_sphere));
if (sa && sb && ss) {
auto ca = ssi::exact_intersection(*sa, *ss);
auto cb = ssi::exact_intersection(*sb, *ss);
if (ca && cb) {
Point3D p0{0, 0, 0}, p1{0, 0, 0};
if (circle_intersection_points(*ca, *cb, p0, p1)) {
double ta0 = ssi::exact_curve_param_of(*ca, p0);
double ta1 = ssi::exact_curve_param_of(*ca, p1);
if (ta1 <= ta0) ta1 += 2.0 * 3.14159265358979323846;
double tb0 = ssi::exact_curve_param_of(*cb, p1);
double tb1 = ssi::exact_curve_param_of(*cb, p0);
if (tb1 <= tb0) tb1 += 2.0 * 3.14159265358979323846;
const int v0 = body.add_vertex_unique(p0, 1e-6);
const int v1 = body.add_vertex_unique(p1, 1e-6);
const int e0 = body.add_edge(
v0, v1, ssi::exact_curve_nurbs(*ca, ta0, ta1));
const int e1 = body.add_edge(
v1, v0, ssi::exact_curve_nurbs(*cb, tb0, tb1));
const int nl = body.add_loop({e0, e1}, true);
const int nf = body.add_face(lens_sphere, {nl});
std::printf(" fill-lens planes=%d/%d sphere=%d face=%d\n",
lens_plane_a, lens_plane_b, lens_sphere, nf);
body.rebuild_single_shell(true);
body_modified = true;
}
}
}
}
if (fill_boundary || fill_sphere_surface >= 0) {
std::map<int, int> use;
auto edge_index = [&](int eid) -> int {
if (eid >= 0 && static_cast<size_t>(eid) < body.all_edges().size())
return eid;
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) return static_cast<int>(k);
return -1;
};
for (const auto& f : body.all_faces()) {
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
const int ei = edge_index(eid);
if (ei >= 0) ++use[body.all_edges()[ei].id];
}
}
}
std::vector<int> bnd;
std::map<int, std::vector<int>> incident;
for (size_t k = 0; k < body.all_edges().size(); ++k) {
const auto& e = body.all_edges()[k];
if (use[e.id] != 1) continue;
bnd.push_back(static_cast<int>(k));
incident[e.v_start].push_back(static_cast<int>(k));
incident[e.v_end].push_back(static_cast<int>(k));
}
std::set<int> visited;
int filled = 0;
for (int seed : bnd) {
if (visited.count(seed)) continue;
const auto& se = body.all_edges()[seed];
const int start_v = se.v_start;
int cur_v = se.v_end;
std::vector<int> loop{seed};
visited.insert(seed);
bool closed = false;
for (int guard = 0; guard < static_cast<int>(bnd.size()) + 4; ++guard) {
if (cur_v == start_v) { closed = true; break; }
int next = -1;
for (int cand : incident[cur_v]) {
if (!visited.count(cand)) { next = cand; break; }
}
if (next < 0) break;
visited.insert(next);
const auto& ne = body.all_edges()[next];
loop.push_back(next);
cur_v = (ne.v_start == cur_v) ? ne.v_end : ne.v_start;
}
if (closed && loop.size() >= 3) {
if (fill_sphere_surface >= 0) {
const int nl = body.add_loop(loop, false);
const int nf = body.add_face(fill_sphere_surface, {nl});
if (fill_sphere_reverse) body.set_face_reversed(nf, true);
std::printf(" fill-sphere edges=%zu face=%d rev=%d\n", loop.size(), nf,
fill_sphere_reverse ? 1 : 0);
++filled;
} else {
const auto fr = fill_hole(body, loop);
std::printf(" fill-hole edges=%zu success=%d\n", loop.size(),
fr.success ? 1 : 0);
if (fr.success) { body = fr.body; ++filled; }
}
}
}
if (fill_sphere_surface >= 0 && filled > 0)
body.rebuild_single_shell(true);
std::printf(" filled_holes=%d boundary_edges=%zu\n", filled, bnd.size());
body_modified = true;
}
if (select_closed_subset) {
const size_t nf = body.all_faces().size();
if (nf <= 24) {
std::vector<std::vector<int>> fe(nf);
for (size_t fi = 0; fi < nf; ++fi) {
for (int lid : body.all_faces()[fi].loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
int ei = eid;
if (ei < 0 || ei >= static_cast<int>(body.all_edges().size()))
ei = -1;
if (ei < 0)
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) { ei = static_cast<int>(k); break; }
if (ei >= 0) fe[fi].push_back(ei);
}
}
}
std::vector<int> best;
int best_count = -1;
BrepModel target_body;
double target_diff = 1e300;
int target_faces = 0;
const std::uint32_t total = 1u << nf;
for (std::uint32_t mask = 1; mask < total; ++mask) {
int pc = 0;
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i)) ++pc;
if (target_volume <= 0.0 && pc <= best_count) continue;
std::vector<int> cnt(body.all_edges().size(), 0);
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i))
for (int ei : fe[i]) ++cnt[ei];
bool ok = true;
for (int c : cnt)
if (c != 0 && c != 2) { ok = false; break; }
if (!ok) continue;
if (false) {
std::vector<bool> keep(nf, false);
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i)) keep[i] = true;
BrepModel cand = build_face_subset(body, keep);
const auto cm = analytic_measure(cand, 0.02);
if (!cm.degraded()) {
const double diff = std::abs(cm.volume - target_volume);
if (diff < target_diff) {
target_diff = diff;
target_body = cand;
target_faces = pc;
}
}
}
if (pc > best_count) {
best_count = pc;
best.clear();
for (size_t i = 0; i < nf; ++i)
if (mask & (1u << i)) best.push_back(static_cast<int>(i));
}
}
std::printf(" closed-subset: faces=%zu best=%d target=%d diff=%.6f\n", nf,
best_count, target_faces, target_diff);
if (target_faces > 0) {
body = std::move(target_body);
body_modified = true;
std::printf(" closed-subset target kept=%d\n", target_faces);
} else if (best_count > 0) {
std::vector<bool> keep(nf, false);
for (int fi : best) keep[fi] = true;
body = build_face_subset(body, keep);
body_modified = true;
if (target_volume > 0.0) {
BrepModel tb = search_target_face_subset(body, target_volume);
if (tb.num_faces() > 0) body = std::move(tb);
}
std::printf(" closed-subset kept=%d\n", best_count);
}
}
}
if (collapse_spurs) {
std::map<int, int> use;
auto edge_index = [&](int eid) -> int {
if (eid >= 0 && static_cast<size_t>(eid) < body.all_edges().size()) return eid;
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) return static_cast<int>(k);
return -1;
};
for (const auto& f : body.all_faces())
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
const int ei = edge_index(eid);
if (ei >= 0) ++use[body.all_edges()[ei].id];
}
}
std::map<int, int> bdeg;
for (const auto& e : body.all_edges())
if (use[e.id] == 1) { ++bdeg[e.v_start]; ++bdeg[e.v_end]; }
int collapsed = 0;
for (const auto& e : body.all_edges()) {
if (use[e.id] != 1) continue;
if (bdeg[e.v_start] != 1 || bdeg[e.v_end] != 1) continue;
if (e.v_start < 0 || e.v_end < 0) continue;
if (static_cast<size_t>(e.v_start) >= body.all_vertices().size() ||
static_cast<size_t>(e.v_end) >= body.all_vertices().size())
continue;
body.set_vertex_position(e.v_end, body.all_vertices()[e.v_start].point);
++collapsed;
}
heal_merge_vertices(body, 1e-9);
heal_merge_edges(body, 1e-9);
body.rebuild_single_shell(true);
body_modified = true;
std::printf(" collapse-spurs collapsed=%d\n", collapsed);
}
if (drop_spurs) {
std::map<int, int> use;
auto edge_index = [&](int eid) -> int {
if (eid >= 0 && static_cast<size_t>(eid) < body.all_edges().size()) return eid;
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) return static_cast<int>(k);
return -1;
};
for (const auto& f : body.all_faces())
for (int lid : f.loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
const int ei = edge_index(eid);
if (ei >= 0) ++use[body.all_edges()[ei].id];
}
}
std::map<int, int> bdeg;
for (const auto& e : body.all_edges())
if (use[e.id] == 1) {
++bdeg[e.v_start];
++bdeg[e.v_end];
}
std::vector<std::pair<int, std::vector<int>>> updates;
for (const auto& lp : body.all_loops()) {
std::vector<int> kept;
for (int eid : lp.edges) {
const int ei = edge_index(eid);
if (ei >= 0) {
const auto& e = body.all_edges()[ei];
if (use[e.id] == 1 && bdeg[e.v_start] == 1 && bdeg[e.v_end] == 1)
continue;
}
kept.push_back(eid);
}
if (kept.size() != lp.edges.size() && kept.size() >= 3)
updates.emplace_back(lp.id, std::move(kept));
}
for (auto& u : updates) body.set_loop_edges(u.first, u.second);
std::printf(" drop-spurs loops_updated=%zu\n", updates.size());
body.rebuild_single_shell(true);
body_modified = true;
}
if (tolerant_stitch > 0.0) {
body = tolerant_stitching({body}, tolerant_stitch);
body.rebuild_single_shell(true);
body_modified = true;
std::printf(" tolerant-stitch tol=%.6f\n", tolerant_stitch);
}
if (trim_nonmanifold) {
const size_t nf = body.all_faces().size();
std::vector<std::vector<int>> fe(nf);
for (size_t fi = 0; fi < nf; ++fi) {
for (int lid : body.all_faces()[fi].loops) {
const TopoLoop* lp = nullptr;
if (lid >= 0 && static_cast<size_t>(lid) < body.all_loops().size())
lp = &body.all_loops()[lid];
if (!lp)
for (const auto& l : body.all_loops())
if (l.id == lid) { lp = &l; break; }
if (!lp) continue;
for (int eid : lp->edges) {
int ei = eid;
if (ei < 0 || ei >= static_cast<int>(body.all_edges().size()))
ei = -1;
if (ei < 0)
for (size_t k = 0; k < body.all_edges().size(); ++k)
if (body.all_edges()[k].id == eid) { ei = static_cast<int>(k); break; }
if (ei >= 0) fe[fi].push_back(ei);
}
}
}
std::vector<bool> dropped(nf, false);
for (int iter = 0; iter < 200; ++iter) {
std::vector<int> cnt(body.all_edges().size(), 0);
for (size_t fi = 0; fi < nf; ++fi)
if (!dropped[fi])
for (int ei : fe[fi]) ++cnt[ei];
std::vector<int> inc(nf, 0);
bool any = false;
for (size_t ei = 0; ei < cnt.size(); ++ei) {
if (cnt[ei] <= 2) continue;
any = true;
for (size_t fi = 0; fi < nf; ++fi)
if (!dropped[fi])
for (int x : fe[fi])
if (x == static_cast<int>(ei)) { ++inc[fi]; break; }
}
if (!any) break;
int pick = -1, best = 0;
for (size_t fi = 0; fi < nf; ++fi)
if (!dropped[fi] && inc[fi] > best) { best = inc[fi]; pick = static_cast<int>(fi); }
if (pick < 0) break;
dropped[pick] = true;
}
std::vector<bool> keep(nf, false);
int kept = 0;
for (size_t fi = 0; fi < nf; ++fi)
if (!dropped[fi]) { keep[fi] = true; ++kept; }
body = build_face_subset(body, keep);
body.rebuild_single_shell(true);
body_modified = true;
std::printf(" trim-nonmanifold kept=%d/%zu\n", kept, nf);
}
if (patch_boundary) {
const auto loops = trace_boundary_loops(body);
std::printf(" patch-boundary loops=%zu\n", loops.size());
for (auto loop : loops) {
const int start_v = body.all_edges()[loop.front()].v_start;
int cur_v = body.all_edges()[loop.front()].v_end;
for (size_t k = 1; k < loop.size(); ++k) {
const auto& e = body.all_edges()[loop[k]];
cur_v = (e.v_start == cur_v) ? e.v_end : e.v_start;
}
if (cur_v != start_v) {
const int ne = body.add_edge(cur_v, start_v);
loop.push_back(ne);
std::printf(" closed open chain with edge=%d\n", ne);
}
std::vector<Point3D> pts;
for (int ei : loop) {
if (ei < 0 || static_cast<size_t>(ei) >= body.all_edges().size())
continue;
const auto& e = body.all_edges()[ei];
const auto& v = body.all_vertices()[e.v_start];
pts.push_back(v.point);
}
if (pts.size() < 3) continue;
Point3D center{0, 0, 0};
for (const auto& p : pts)
center = Point3D{center.x() + p.x(), center.y() + p.y(),
center.z() + p.z()};
center = Point3D{center.x() / pts.size(), center.y() / pts.size(),
center.z() / pts.size()};
Vector3D nrm = (pts[1] - pts[0]).cross(pts[2] - pts[0]);
if (nrm.norm() < 1e-12) nrm = Vector3D{0, 0, 1};
nrm = nrm.normalized();
Vector3D u = (pts[1] - pts[0]);
if (u.norm() < 1e-12) u = Vector3D{1, 0, 0};
u = (u - nrm * u.dot(nrm)).normalized();
const Vector3D v = nrm.cross(u);
double radius = 0.0;
for (const auto& p : pts) {
const double d = (p - center).norm();
radius = std::max(radius, d);
}
const double w = std::max(2.0 * radius, 1e-3);
const Point3D origin{center.x() - u.x() * w / 2 - v.x() * w / 2,
center.y() - u.y() * w / 2 - v.y() * w / 2,
center.z() - u.z() * w / 2 - v.z() * w / 2};
const int sid = body.add_surface(
vde::curves::NurbsSurface::plane(origin, u, v, w, w));
const int nl = body.add_loop(loop, true);
const int nf = body.add_face(sid, {nl});
std::printf(" patch face=%d edges=%zu\n", nf, loop.size());
}
body.rebuild_single_shell(true);
heal_split_pinch_vertices(body, 0.01);
heal_slivers(body);
body_modified = true;
}
if (!save_modified.empty()) {
if (vde::foundation::save_vde(body, save_modified))
std::printf(" saved modified body to %s\n", save_modified.c_str());
else
std::printf(" save modified failed: %s\n", save_modified.c_str());
}
const auto v0 = validate(body);
if (orient) {
try {
const auto rep = fix_shell_orientation_strict(body);
std::printf(" orient: flipped=%d ok=%d\n", rep.flipped_faces, rep.ok ? 1 : 0);
} catch (const std::exception& e) {
std::printf(" orient exception: %s\n", e.what());
}
const auto vo = validate(body);
print_validation("orient", vo);
if (!deep && !heal && !pinch) {
if (!pure_surface && !(vo.valid && vo.watertightness > 0.99)) ++bad;
continue;
}
}
print_validation("raw", v0);
bool diag_valid = v0.valid && v0.errors.empty();
double diag_wt = v0.watertightness;
if (!body_modified &&
bi < imported.diagnostic.body_diagnostics.size()) {
const auto& bd = imported.diagnostic.body_diagnostics[bi];
diag_valid = bd.valid && bd.error_count == 0;
diag_wt = bd.watertightness;
print_diag(bd);
} else {
const BodyDiagnostics fresh = diagnose_body(body);
diag_valid = fresh.valid && fresh.error_count == 0;
diag_wt = fresh.watertightness;
print_diag(fresh);
}
bool deep_tolerance_bad = false;
if (deep) {
const auto tol = tolerance_analysis(body);
deep_tolerance_bad = !tol.overall_pass;
std::printf(" tolerance: %s pass=%zu fail=%zu gap_viol=%zu "
"degenerate_e=%zu degenerate_f=%zu near=%zu\n",
tol.overall_pass ? "PASS" : "FAIL", tol.items_passed,
tol.items_failed, tol.gap_violations,
tol.degenerate_edges, tol.degenerate_faces,
tol.near_degenerate_elements);
const auto wt = watertight_verification(body);
std::printf(" watertight: %s score=%.4f boundary=%zu nm=%zu dgl=%zu "
"gaps=%zu\n",
wt.is_watertight ? "YES" : "NO", wt.watertight_score,
wt.boundary_edges, wt.non_manifold_edges,
wt.dangling_edges, wt.gaps.size());
}
if (pure_surface)
std::printf(" surface: open-only body; not counted as solid defect\n");
const bool body_bad =
(!pure_surface && !(diag_valid && diag_wt > 0.99)) ||
deep_tolerance_bad;
if (body_bad) ++bad;
if (body_bad && auto_heal && !heal && !pinch && !orient) {
// B:默认对缺陷实体做一次自愈,成功则不计缺陷。
try {
const AutoHealReport hr = automatic_heal(body);
const auto vh = validate(body);
std::printf(" auto-heal: score=%d fixed=%d degraded=%d %s wt=%.4f\n",
hr.overall_score, hr.total_fixed(),
hr.degraded ? 1 : 0,
vh.valid ? "VALID" : "INVALID",
vh.watertightness);
if (vh.valid && vh.watertightness > 0.99) --bad;
} catch (const std::exception& e) {
std::printf(" auto-heal exception: %s\n", e.what());
}
}
if (pinch && !heal) {
int n = 0;
try {
n = heal_split_pinch_vertices(body);
} catch (const std::exception& e) {
std::printf(" pinch split exception: %s\n", e.what());
}
std::printf(" pinch split: %d\n", n);
const auto vp = validate(body);
print_validation("pinch", vp);
if (body_bad && vp.valid && vp.watertightness > 0.99) --bad;
continue;
}
if (heal) {
if (pinch) {
int n = 0;
try {
n = heal_split_pinch_vertices(body);
} catch (const std::exception& e) {
std::printf(" pinch split exception: %s\n", e.what());
}
std::printf(" pinch split: %d\n", n);
const auto vp = validate(body);
print_validation("pinch", vp);
}
AutoHealReport hr;
try {
hr = automatic_heal(body);
} catch (const std::exception& e) {
std::printf(" heal exception: %s\n", e.what());
++bad;
continue;
}
std::printf(" heal: score=%d fixed=%d steps=%d degraded=%d "
"faces=%zu->%zu reason=%s\n",
hr.overall_score, hr.total_fixed(), hr.successful_steps(),
hr.degraded ? 1 : 0, hr.num_faces_before, hr.num_faces_after,
hr.degrade_reason.c_str());
for (const auto& w : hr.warnings)
std::printf(" heal-warn: %s\n", w.c_str());
const auto v1 = validate(body);
print_validation("healed", v1);
if (!out_dir.empty()) {
std::error_code ec;
std::filesystem::create_directories(out_dir, ec);
const auto stem = std::filesystem::path(path).stem().string();
const auto out_path = std::filesystem::path(out_dir) /
(stem + "_body" + std::to_string(bi) + ".vde");
if (vde::foundation::save_vde(body, out_path.string()))
std::printf(" saved: %s\n", out_path.string().c_str());
else
std::printf(" save failed: %s\n", out_path.string().c_str());
}
if (body_bad && v1.valid && v1.watertightness > 0.99) --bad; // 修复成功
}
}
if (strict && imported.diagnostic.has_warnings()) ++bad;
std::printf("\nresult: %s (%d body defect(s))\n", bad == 0 ? "PASS" : "FAIL", bad);
return bad == 0 ? 0 : 1;
}
// P0-1:Windows 用 CommandLineToArgvW 取得原始 Unicode 参数并转 UTF-8;
// 其余平台 argv 已是 UTF-8。JSON 的 path/消息在 to_json() 前统一为 UTF-8。
int main(int argc, char** argv) {
if (std::getenv("VDE_UNBUFFERED_OUTPUT") != nullptr) {
std::setvbuf(stdout, nullptr, _IONBF, 0);
}
#if defined(_WIN32)
int wide_argc = 0;
LPWSTR* wide_argv = CommandLineToArgvW(GetCommandLineW(), &wide_argc);
if (wide_argv == nullptr) return 3;
std::vector<std::string> utf8_args;
utf8_args.reserve(static_cast<size_t>(wide_argc));
for (int i = 0; i < wide_argc; ++i) utf8_args.push_back(wide_to_utf8(wide_argv[i]));
LocalFree(wide_argv);
std::vector<char*> arg_ptrs;
arg_ptrs.reserve(utf8_args.size());
for (auto& arg : utf8_args) arg_ptrs.push_back(arg.data());
return run_check(static_cast<int>(arg_ptrs.size()), arg_ptrs.data());
#else
return run_check(argc, argv);
#endif
}