# Foundation 模块 API 参考 > 基础模块 — 16 种 CAD/网格/BIM 格式的导入导出 + 数学/容差/谓词/日志基础设施 ## 模块概述 foundation 模块是 ViewDesignEngine 的基础设施与格式转换层,提供: - **网格格式**:STL、OBJ、PLY、glTF/GLB、3MF、COLLADA、AMF、VRML 的导入导出 - **工业 CAD 格式**:JT (ISO 14306)、Parasolid XT、ACIS SAT/SAB、STEP AP242(含 PMI)、PDF 3D (U3D) - **BIM / CAD 2D 格式**:IFC (ISO 16739)、DXF - **VDE 原生格式**:`.vde`(B-Rep 完整数据二进制读写)与 `VDEGEOM` 网格二进制序列化 - **基础设施**:数学类型(Point/Vector/Matrix)、分层容差管理、几何谓词(自适应双精度 + 可选 GMP 后端)、区间算术验证、内存池、结构化日志、统一错误码 --- ## 头文件列表 | 头文件 | 说明 | |--------|------| | `io_gltf.h` | glTF 2.0 / GLB 导入导出(网格 + B-Rep 导出、网格导入) | | `io_dxf.h` | DXF ASCII 解析(12 实体类型)+ DWG 导入/导出通道(`import_dwg` / `export_dwg`) | | `io_dwg.h` | DWG 原生版本识别(R12–R2018 魔数)+ 外部转换器发现 + DWG↔DXF 转换通道 | | `io_dwg_plugin.h` | DWG 插件接口(DwgImporter / DwgBridge,外部 .so/.dll) | | `io_stl.h` | STL 读写(自动检测 ASCII / 二进制,含 float 精度变体) | | `io_obj.h` | Wavefront OBJ 解析与写出 | | `io_collada.h` | COLLADA DAE 导入导出(B-Rep 列表) | | `io_amf.h` | AMF 增材制造格式(ISO/ASTM 52915)导入导出 | | `io_vrml.h` | VRML WRL 导入导出(VRML 1.0 / VRML97) | | `io_ply.h` | PLY 网格读写(ASCII + 二进制小端) | | `io_3mf.h` | 3MF 格式(3D 打印,含逐顶点颜色) | | `industrial_formats.h` | JT / Parasolid XT / ACIS SAT / IFC / STEP AP242 / PDF 3D | | `serializer.h` | 网格二进制序列化(BinarySerializer) | | `vde_format.h` | VDE 原生格式(.vde)B-Rep 二进制读写 | | `format_utils.h` | 格式工具函数(CAD 精度浮点格式化 / IGES 行) | | `math_types.h` | 基础数学类型(Point/Vector/Matrix 别名) | | `tolerance.h` | 分层容差管理(Tolerance / ToleranceScope) | | `error_codes.h` | 统一错误码体系 | | `interval.h` | 双精度区间算术与谓词验证 | | `predicates.h` | 统一几何谓词接口(编译时选择后端) | | `exact_predicates.h` | 自适应精度谓词(Shewchuk 算法) | | `exact_predicates_gmp.h` | GMP 精确谓词后端(可选,`VDE_USE_GMP` 时编译) | | `memory_pool.h` | 固定块内存池 | | `vde_log.h` | 轻量结构化日志(VDE D10) | --- ## 详细 API ### `io_gltf.h` — glTF 2.0 / GLB ```cpp namespace vde::foundation { // 导出选项 struct GltfOptions { bool binary = true; // GLB 单文件 / JSON+bin 分离 bool include_normals = true; // 顶点法线 bool include_colors = false; // 顶点颜色 std::vector vertex_colors; // 逐顶点 RGB(include_colors 时使用) }; // glTF 导出 bool write_gltf(const std::string& filepath, const mesh::HalfedgeMesh& mesh, const GltfOptions& options = GltfOptions{}); bool write_brep_gltf(const std::string& filepath, const brep::BrepModel& model, int tessellation_res = 32); // glTF 导入(VDE-082) struct GltfImportResult { std::vector meshes; // 按 glTF mesh 索引 std::vector mesh_names; size_t total_vertices = 0, total_triangles = 0; bool success = false; std::string error_message; }; [[nodiscard]] GltfImportResult import_gltf(const std::string& path); // 文件导入 [[nodiscard]] GltfImportResult import_gltf_binary(const uint8_t* data, size_t size); // 内存导入 } // namespace vde::foundation ``` ### `io_dxf.h` — DXF 格式 ```cpp namespace vde::foundation { // === 实体类型(12 种) === struct DxfLine { Point3D start, end; std::string layer; }; struct DxfCircle { Point3D center; double radius; std::string layer; }; struct DxfArc { Point3D center; double radius, start_angle, end_angle; std::string layer; }; struct DxfLwPolyline{ struct Vertex { double x,y,bulge; }; std::vector vertices; bool closed; double constant_width, elevation, thickness; std::string layer; }; struct DxfPolyline { struct Vertex { Point3D position; double bulge, start_width, end_width; }; std::vector vertices; bool closed, is_3d; std::string layer; }; struct DxfPoint { Point3D position; std::string layer; }; struct DxfText { std::string text_value; Point3D insertion_point; double height, rotation, width_factor; Point3D bbox_min, bbox_max; bool is_mtext; std::string layer; }; struct DxfInsert { std::string block_name; Point3D insertion_point; double scale_x, scale_y, scale_z, rotation; int column_count, row_count; double column_spacing, row_spacing; std::string layer; }; struct DxfEllipse { Point3D center, major_axis_endpoint; double axis_ratio, start_param, end_param; std::string layer; }; struct DxfSpline { std::vector control_points; std::vector knots, weights; int degree; bool closed, periodic, rational; std::vector fit_points; double fit_tolerance; std::string layer; }; struct Dxf3DFace { Point3D corners[4]; bool invisible[4]; std::string layer; }; struct DxfHatch { struct BoundaryLoop { std::vector points; bool is_closed; }; std::vector boundary_loops; std::string pattern_name; double pattern_scale, pattern_angle; bool is_solid; std::string layer; }; using DxfEntity = std::variant; // 图层/块 struct DxfLayer { std::string name; int color; std::string linetype; bool frozen, locked, off; }; struct DxfBlock { std::string name; Point3D base_point; std::vector entities; }; // 版本 enum class DxfVersion { Unknown, R12, R14, R2000, R2004, R2007, R2010, R2013, R2018 }; // 文档 struct DxfDocument { DxfVersion version; std::string version_string; int insunits; std::vector layers; std::vector blocks; std::vector entities; core::AABB3D extents; int entities_parsed, entities_skipped; [[nodiscard]] bool valid() const; // version 已知且实体列表非空 }; // API [[nodiscard]] DxfDocument import_dxf(const std::string& filepath); // 文件导入 [[nodiscard]] DxfDocument import_dxf_string(const std::string& data); // 字符串导入 [[nodiscard]] mesh::HalfedgeMesh to_mesh(const DxfDocument& document); // 3DFACE/闭合多段线 → 网格 [[nodiscard]] const char* dxf_version_name(DxfVersion version); // DWG 导入/导出(原生识别 + 外部转换器通道;详见 io_dwg.h) struct DwgImportResult { std::vector messages; // 错误/指引/诊断 std::vector bodies; // 插件解析出的 B-Rep(无插件时为空) std::string metadata_json; // 插件返回的元数据(JSON) bool success = false; bool plugin_used = false; // 是否经由运行时插件完成 DwgVersion dwg_version = DwgVersion::Unknown; // 原生识别版本 std::string dwg_version_name; // "R2018" 等 bool converter_used = false; // 是否经由外部转换器(DWG→DXF) bool has_drawing = false; // drawing 是否有效 DxfDocument drawing; // 转换后的 DXF 图元 }; [[nodiscard]] DwgImportResult import_dwg(const std::string& filepath); bool export_dwg(const std::string& filepath, const std::vector& bodies); // DxfDocument 直写 DWG(M3.8):R2000 / R2018,不经三维投影 struct DwgDrawingWriteOptions { DwgVersion version = DwgVersion::R2000; }; struct DwgDrawingWriteReport { bool ok = false; std::string error; int entities_written = 0, entities_skipped = 0, non_ascii_text_skipped = 0; int block_entities_written = 0, block_entities_skipped = 0; std::size_t layers_written = 0, blocks_written = 0; }; bool export_dwg_drawing(const std::string& filepath, const DxfDocument& drawing, const DwgDrawingWriteOptions& options = {}, DwgDrawingWriteReport* report = nullptr); } // namespace vde::foundation ``` ### `io_dwg.h` — DWG 原生识别 + 转换通道 ```cpp namespace vde::foundation { enum class DwgVersion { Unknown, R12, R13, R14, R2000, R2004, R2007, R2010, R2013, R2018 }; const char* dwg_version_name(DwgVersion); // "R2018" const char* dwg_version_magic(DwgVersion); // "AC1032" DwgVersion dwg_version_from_magic(const char* magic6); // 6 字节 ASCII → 版本 DwgVersion dwg_version_from_bytes(const uint8_t* data, std::size_t size); bool dwg_version_is_r2004_plus(DwgVersion); // R2004 起有加密节表+压缩段 struct DwgFileInfo { // inspect_dwg 结果 DwgVersion version; std::string version_magic, version_name; std::uint64_t file_size; bool is_dwg, r2004_plus; std::string error; bool valid() const; }; DwgFileInfo inspect_dwg(const std::string& filepath); // 读文件头 DwgFileInfo inspect_dwg_memory(const uint8_t* data, std::size_t size); // 读内存头 struct DwgConverterInfo { bool found; std::string executable, engine, license, command; }; DwgConverterInfo find_dwg_reader(); // DWG→DXF:VDE_DWG_READ_CMD → PATH 上的 dwg2dxf DwgConverterInfo find_dwg_writer(); // DXF→DWG:VDE_DWG_WRITE_CMD → PATH 上的 dxf2dwg std::string find_executable_on_path(const std::string& name); std::string expand_converter_command(const std::string& tmpl, const std::string& in, const std::string& out); struct DwgConvertResult { bool success; std::string output_path, tool; int exit_code; std::vector messages; }; DwgConvertResult convert_dwg_to_dxf(const std::string& dwg, const std::string& dxf); DwgConvertResult convert_dxf_to_dwg(const std::string& dxf, const std::string& dwg); } // namespace vde::foundation ``` > **三层策略**:①原生识别(`inspect_dwg`,零依赖,始终执行)②通道层 > (`convert_dwg_to_dxf` / `convert_dxf_to_dwg`,**独立子进程**调用外部工具, > GPLv3 不传染)③插件层(`DwgBridge::load`,运行时加载)。外部转换器可通过 > 环境变量 `VDE_DWG_READ_CMD` / `VDE_DWG_WRITE_CMD` 注入自定义模板,占位符 > 为 `{in}` / `{out}`。 ### `io_dwg_plugin.h` — DWG 插件接口 ```cpp namespace vde::foundation { struct DwgResult { bool success = false; std::vector bodies; std::string metadata_json; // 图层/线型/标注等元数据(JSON) std::string error_message; }; class DwgImporter { // 抽象导入器接口(Apache 2.0,外部插件实现) public: virtual ~DwgImporter() = default; virtual const char* name() const = 0; // "libreDWG 0.14" / "ODA 2026" virtual const char* license() const = 0; // "GPLv3" / "Commercial" virtual DwgResult read_file(const std::string& path) = 0; virtual DwgResult read_memory(const uint8_t* data, size_t size) = 0; }; class DwgBridge { // DWG 桥接器:动态加载外部插件 public: static bool load(const std::string& plugin_path); // 加载插件 .so/.dll static void unload(); static bool is_loaded(); static DwgResult import(const std::string& path); // 委托给已加载插件 static std::string plugin_name(); static std::string plugin_license(); }; DwgResult import_dwg_plugin(const std::string& path); // 便捷导入(未加载插件时返回安装指引) } // namespace vde::foundation ``` ### `io_stl.h` — STL 格式 ```cpp namespace vde::foundation { struct StlTriangle { Vector3D normal; // 单位法向量 Point3D v0, v1, v2; // 三个顶点(右手法则 CCW 顺序) // 便捷分量访问:v0x(), v0y(), v0z(), v1x(), ..., v2z() }; std::vector read_stl(const std::string& filepath); // 自动检测 ASCII/二进制;失败抛 std::runtime_error bool write_stl(const std::string& filepath, const std::vector& tris); // 二进制 bool write_stl_ascii(const std::string& filepath, const std::vector& tris); // ASCII // float 精度变体(避免 double↔float 显式转换) struct StlTrianglef { Vector3f normal; Point3f v0, v1, v2; }; StlTrianglef to_stl_trianglef(const StlTriangle& t); StlTriangle from_stl_trianglef(const StlTrianglef& t); } // namespace vde::foundation ``` ### `io_obj.h` — Wavefront OBJ ```cpp namespace vde::foundation { struct ObjMeshData { std::vector vertices; std::vector texcoords; // 可能为空 std::vector normals; // 可能为空 std::vector> faces; // 0-based 顶点索引(始终填充) std::vector> face_texcoords; // 与 faces 等长;无纹理时为空 std::vector> face_normals; // 与 faces 等长;无法线时为空 std::vector face_materials; // usemtl 材质名 [[nodiscard]] bool has_texcoords() const; }; ObjMeshData read_obj(const std::string& filepath); // 失败抛 std::runtime_error bool write_obj(const std::string& filepath, const ObjMeshData& data); // 输出 1-based 索引 } // namespace vde::foundation ``` ### `io_collada.h` — COLLADA DAE ```cpp namespace vde::foundation { // 材质颜色信息(Phong 模型参数) struct ColladaMaterial { std::string name, effect_id; float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f; float specular_r = 0.0f, specular_g = 0.0f, specular_b = 0.0f; float ambient_r = 0.2f, ambient_g = 0.2f, ambient_b = 0.2f; float emission_r = 0.0f, emission_g = 0.0f, emission_b = 0.0f; float shininess = 1.0f, transparency = 1.0f; // 1.0 = 不透明 }; // 导入:每个 geometry 节点生成一个 BrepModel(支持 COLLADA 1.4 / 1.5) [[nodiscard]] std::vector import_collada(const std::string& path); // 导出:每个 BrepModel 对应一个 geometry → visual_scene 节点 bool export_collada(const std::vector& bodies, const std::string& path, const std::vector& materials = {}); } // namespace vde::foundation ``` ### `io_amf.h` — AMF 格式(ISO/ASTM 52915) ```cpp namespace vde::foundation { struct AmfMesh { mesh::HalfedgeMesh mesh; std::string name; // 对象名称 std::string material_name; // 材质名称 float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f, diffuse_a = 1.0f; // RGBA 0.0-1.0 std::string description, author, license; // 元数据 }; [[nodiscard]] brep::BrepModel import_amf(const std::string& path); // 首个 object [[nodiscard]] std::vector import_amf_all(const std::string& path); // 多对象 bool export_amf(const brep::BrepModel& body, const std::string& path, const std::string& name = "Model"); bool export_amf_multi(const std::vector& meshes, const std::string& path); } // namespace vde::foundation ``` ### `io_vrml.h` — VRML ```cpp namespace vde::foundation { struct VrmlMaterial { std::string name; float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f; float specular_r = 0.0f, specular_g = 0.0f, specular_b = 0.0f; float emissive_r = 0.0f, emissive_g = 0.0f, emissive_b = 0.0f; float ambient_intensity = 0.2f, shininess = 0.2f, transparency = 0.0f; // 0.0 = 不透明 }; struct VrmlMeshData { mesh::HalfedgeMesh mesh; VrmlMaterial material; std::string name; }; [[nodiscard]] brep::BrepModel import_vrml(const std::string& path); // 首个 IndexedFaceSet [[nodiscard]] std::vector import_vrml_all(const std::string& path); // 多 Shape bool export_vrml(const brep::BrepModel& body, const std::string& path, const VrmlMaterial& material = VrmlMaterial{}); // VRML 2.0 (VRML97) bool export_vrml_multi(const std::vector& meshes, const std::string& path); } // namespace vde::foundation ``` ### `io_ply.h` — PLY 格式 ```cpp namespace vde::foundation { // 支持 ASCII 与二进制(小端序);元素:vertex(位置/法线/颜色)、face mesh::HalfedgeMesh read_ply(const std::string& filepath); // 失败抛 std::runtime_error void write_ply(const std::string& filepath, const mesh::HalfedgeMesh& mesh); // ASCII 输出 } // namespace vde::foundation ``` ### `io_3mf.h` — 3MF 格式 ```cpp namespace vde::foundation { struct ThreeMFMesh { mesh::HalfedgeMesh mesh; std::string name; std::vector vertex_colors; // 可选逐顶点 RGB(3*nv 个 float) }; [[nodiscard]] std::vector read_3mf(const std::string& filepath); bool write_3mf(const std::string& filepath, const std::vector& meshes, const std::string& creator = "ViewDesignEngine"); // creator 写入元数据 } // namespace vde::foundation ``` ### `industrial_formats.h` — 工业格式(JT/Parasolid/ACIS/IFC/STEP AP242/PDF 3D) ```cpp namespace vde::io { // === JT (ISO 14306) === enum class JTSegmentType : uint8_t { LogicalSceneGraph=1, Part=2, Instance=3, MeshLOD=4, Brep=5, MetaData=6, PMI=7 }; struct JtSegmentHeader { uint32_t segment_type, segment_offset, segment_length, attributes; }; struct JTOptions { bool load_brep=true, load_mesh=true; int max_lod=3; bool load_pmi=false, load_meta=false; }; [[nodiscard]] brep::BrepModel import_jt(const std::string& path, const JTOptions& opts = {}); [[nodiscard]] brep::BrepModel import_jt_binary(const uint8_t* data, size_t size, const JTOptions& opts = {}); bool export_jt(const brep::BrepModel& body, const std::string& path); // === Parasolid XT === enum class ParasolidFormat { Binary, Text, Neutral }; struct XtBinaryHeader { char magic[4]; uint32_t version, float_count, int_count, entity_count, float_offset, int_offset, entity_offset, endian_check; /* parse()/encode() */ }; struct XtBinaryEntity { uint32_t type; uint32_t float_start, float_len; uint32_t int_start, int_len; std::vector refs; }; [[nodiscard]] brep::BrepModel import_parasolid_xt(const std::string& path); // .x_t / .x_b [[nodiscard]] brep::BrepModel import_parasolid_xt_binary(const uint8_t* data, size_t size); void export_parasolid_xt(const brep::BrepModel& body, const std::string& path); // 文本 void export_parasolid_xt_binary(const brep::BrepModel& body, const std::string& path); // 二进制文件 [[nodiscard]] std::string export_parasolid_xt_binary_str(const brep::BrepModel& body); // 二进制字符串 // === ACIS SAT === enum class ACISVersion { V7=700, V16=1600, V21=2100, V27=2700, R2024=2900 }; struct SabHeader { char magic[4]; uint32_t data_size, version, str_table_size; }; [[nodiscard]] brep::BrepModel import_acis_sat(const std::string& path); // .sat / .sab [[nodiscard]] brep::BrepModel import_acis_sat_binary(const uint8_t* data, size_t size); void export_acis_sat(const brep::BrepModel& body, const std::string& path, ACISVersion version = ACISVersion::V27); // === IFC (ISO 16739) === enum class IfcEntityType { Unknown, IfcProject, IfcSite, IfcBuilding, IfcWall, IfcSlab, IfcBeam, IfcColumn, IfcDoor, /* ... */ }; [[nodiscard]] std::vector import_ifc(const std::string& path); // 每个产品一个体 void export_ifc(const std::vector& bodies, const std::string& path); // 轴对齐盒→ExtrudedAreaSolid,其余→FacetedBrep // === STEP AP242 === struct StepPMIAnnotation { std::string type, id, description; double nominal_value, upper_tolerance, lower_tolerance; std::string datum_system; }; struct StepAP242Options { bool include_pmi=true, include_tolerance=true, include_material=true, include_validation=true; }; struct StepAP242ImportResult { std::vector bodies; std::vector annotations; }; [[nodiscard]] std::string export_step_ap242(const std::vector& bodies, const std::vector& annotations = {}, const StepAP242Options& opts = {}); void export_step_ap242_file(const std::string& path, const std::vector& bodies, const std::vector& annotations = {}, const StepAP242Options& opts = {}); [[nodiscard]] StepAP242ImportResult import_step_ap242_from_string(const std::string& step_data); [[nodiscard]] StepAP242ImportResult import_step_ap242(const std::string& path); // .stp / .step // === PDF 3D === struct Pdf3dPmiEntity { std::string id, label, type, text; core::Point3D position; core::Vector3D normal; double nominal_value, tolerance_upper, tolerance_lower; std::string unit, datum_references; }; inline constexpr uint32_t kU3DPmiBlockType = 0xFFFFFFF1u; // U3D 语义实体块(PMI),ECMA-363 未知块可跳过 [[nodiscard]] std::vector export_pdf3d(const brep::BrepModel& body); // U3D 嵌入 (ECMA-363) [[nodiscard]] std::vector export_pdf3d(const brep::BrepModel& body, const std::vector& pmi); // 网格声明块后追加 PMI 语义实体块 void export_pdf3d_file(const std::string& path, const brep::BrepModel& body); void export_pdf3d_file(const std::string& path, const brep::BrepModel& body, const std::vector& pmi); } // namespace vde::io ``` ### `serializer.h` — 网格二进制序列化 ```cpp namespace vde::foundation { // 扁平化网格数据(全部三角形,face_valence 固定为 3) struct SerializedMesh { uint32_t vertex_count, face_count; std::vector vertices; // x0 y0 z0 x1 y1 z1 ... std::vector face_indices; // v0_0 v0_1 v0_2 v1_0 ... std::vector face_valence; // 每面顶点数(当前固定为 3) }; // 二进制序列化器:魔数 "VDEGEOM\0" + 版本号 + 标志位 + 网格数据 class BinarySerializer { public: static std::vector serialize(const mesh::HalfedgeMesh& mesh); static mesh::HalfedgeMesh deserialize(const std::vector& data); // 校验失败抛异常 static bool write_file(const std::string& path, const mesh::HalfedgeMesh& mesh); static mesh::HalfedgeMesh read_file(const std::string& path); // 失败抛异常 }; constexpr uint64_t VDE_MAGIC = 0x56444547454F4D00ULL; // "VDEGEOM\0" constexpr uint32_t VDE_FORMAT_VERSION = 1; } // namespace vde::foundation ``` ### `vde_format.h` — VDE 原生格式(.vde) ```cpp namespace vde::foundation { constexpr uint32_t VDE_MAGIC_FOURCC = 0x31454456; // "VDE1"(小端序) constexpr uint32_t VDE_FILE_VERSION = 1; constexpr uint32_t VDE_FLAG_HAS_HISTORY = 0x00000001; // 含建模历史 constexpr uint32_t VDE_FLAG_HAS_ATTRIBUTES = 0x00000002; // 含属性数据 constexpr uint32_t VDE_FLAG_HAS_TRIMMED = 0x00000004; // 含裁剪曲面 // 32 字节文件头:magic(4) + version(4) + flags(4) + data_offset(4) + reserved(16) struct VdeHeader { uint32_t magic, version, flags, data_offset; uint8_t reserved[16]; VdeHeader(); static VdeHeader parse(const uint8_t* data, size_t size); void encode(std::vector& buf) const; [[nodiscard]] bool is_valid() const; }; // 序列化段类型(每段 [section_id:uint16][section_size:uint64][data...]) enum class SerializationSection : uint16_t { SECTION_HEADER = 0, SECTION_TOPOLOGY = 1, SECTION_GEOMETRY = 2, SECTION_TOLERANCE = 3, SECTION_ATTRIBUTES = 4, SECTION_HISTORY = 5, }; // 属性数据结构 struct VdeVertexAttribute { int vertex_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; }; struct VdeEdgeAttribute { int edge_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; }; struct VdeFaceAttribute { int face_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; }; struct VdeBodyAttribute { int body_id = -1; std::string name; std::string custom_data; }; struct VdeAttributes { std::vector vertex_attrs; std::vector edge_attrs; std::vector face_attrs; std::vector body_attrs; }; // 主 API(失败抛 std::runtime_error) bool save_vde(const brep::BrepModel& body, const std::string& path, const VdeAttributes& attrs = {}, const std::vector* history = nullptr); [[nodiscard]] brep::BrepModel load_vde(const std::string& path); [[nodiscard]] brep::BrepModel load_vde_with_attrs(const std::string& path, VdeAttributes& out_attrs); bool save_vde_json(const brep::BrepModel& body, const std::string& path, const VdeAttributes& attrs = {}); // 人类可读 JSON(调试用) [[nodiscard]] std::vector serialize_vde(const brep::BrepModel& body, const VdeAttributes& attrs = {}, const std::vector* history = nullptr); [[nodiscard]] brep::BrepModel deserialize_vde(const std::vector& data); } // namespace vde::foundation ``` ### `format_utils.h` — 格式工具函数 ```cpp namespace vde::foundation { std::string fmt_double(double v, int precision = 12); // 科学计数法,12 位有效数字;NaN→"0.0",Inf→"1e30"/"-1e30" std::string fmt_iges_real(double v, int precision = 12); // 同 fmt_double,但指数用 'D' 标记(IGES 标准) std::string fmt_point(const core::Point3D& p, bool use_d = false); // "x,y,z" 逗号分隔 std::string pad72(const std::string& s); // 补齐/截断到恰好 72 字符(IGES 行宽) std::string format_iges_line(const std::string& data, char section_char, int seq); // 72 列数据 + 8 列序号 + '\n' } // namespace vde::foundation ``` ### `math_types.h` — 基础数学类型 ```cpp namespace vde::foundation { // 通用模板(Eigen 列向量) template using Point = Eigen::Matrix; template using Vector = Eigen::Matrix; // 语义区分点(位置)/向量(方向) template using Matrix3 = Eigen::Matrix; template using Matrix4 = Eigen::Matrix; using Point2D = Point; using Point3D = Point; using Point2f = Point; using Point3f = Point; using Point4D = Eigen::Matrix; // 齐次点(仿射变换) using Vector2D = Vector; using Vector3D = Vector; using Vector2f = Vector; using Vector3f = Vector; using Matrix3D = Matrix3; using Matrix4D = Matrix4; } // namespace vde::foundation ``` ### `tolerance.h` — 分层容差管理 ```cpp namespace vde::foundation { class Tolerance { public: Tolerance(double absolute = 1e-6, double relative = 1e-8, double angular = 1e-8, double snapping = 1e-4); // 判定 bool points_equal(const Eigen::MatrixXd& a, const Eigen::MatrixXd& b) const; // 欧氏距离 < absolute template bool is_zero(T value) const; // |value| < absolute template bool equals(T a, T b) const; // |a-b| < absolute + relative*max(|a|,|b|) // 访问 double absolute() const; double relative() const; double angular() const; double snapping() const; // 分层:继承并缩放 Tolerance tighten(double factor = 0.1) const; // 收紧(factor < 1) Tolerance relax(double factor = 10.0) const; // 放宽(factor > 1) static Tolerance min(const Tolerance& a, const Tolerance& b); // 每项取 min(更严格) // 全局实例(线程局部存储) static Tolerance& global(); static void set_global(const Tolerance& tol); // 预设精度等级 static constexpr double Modeling() { return 1e-6; } // 建模级 static constexpr double Fitting() { return 1e-3; } // 拟合级 static constexpr double Intersection() { return 1e-8; } // 求交级 static constexpr double Snapping() { return 1e-4; } // 吸附级 }; // 局部容差作用域(RAII:构造设置、析构自动恢复) class ToleranceScope { public: explicit ToleranceScope(const Tolerance& tol); ~ToleranceScope(); }; } // namespace vde::foundation ``` ### `error_codes.h` — 统一错误码 ```cpp namespace vde::foundation { // 分段编码:0=成功;1xxx=foundation;2xxx=core;3xxx=curves;4xxx=mesh;5xxx=brep;6xxx=sdf;7xxx=capi enum class ErrorCode : int32_t { SUCCESS = 0, // 1xxx foundation(文件/格式 IO) ERR_FILE_NOT_FOUND = 1001, ERR_FILE_OPEN_FAILED = 1002, ERR_FILE_WRITE_FAILED = 1003, ERR_FILE_READ_FAILED = 1004, /* ... */ ERR_FILE_ALREADY_EXISTS = 1008, ERR_FORMAT_INVALID = 1101, ERR_FORMAT_UNSUPPORTED = 1102, /* ... */ ERR_FORMAT_MAGIC_MISMATCH = 1106, ERR_VDE_HEADER_INVALID = 1201, /* ... */ ERR_VDE_DESERIALIZE_FAILED = 1207, ERR_STEP_PARSE = 1301, /* ... */ ERR_DXF_PARSE = 1371, // 2xxx core(几何计算 / CAM / 并发) ERR_DEGENERATE_GEOMETRY = 2001, /* ... */ ERR_TRIANGULATION_FAILED = 2106, ERR_CAM_TOOLPATH_GENERATION = 2201, /* ... */ ERR_TRANSACTION_ROLLBACK = 2305, // 3xxx curves(曲线 / 曲面 / IGA) ERR_CURVE_DEGREE_INVALID = 3001, /* ... */ ERR_SURFACE_FAIRING = 3110, ERR_IGA_MESH_INVALID = 3201, ERR_IGA_REFINEMENT_FAILED = 3202, // 4xxx mesh ERR_MESH_EMPTY = 4001, /* ... */ ERR_POINT_CLOUD_NOISE = 4205, // 5xxx brep(拓扑 / 布尔 / 特征 / 装配 / 钣金 / PMI / FFD) ERR_BREP_TOPOLOGY_INVALID = 5001, /* ... */ ERR_FFD_INVALID = 5601, // 6xxx sdf ERR_SDF_EVALUATE_FAILED = 6001, /* ... */ ERR_SDF_PRIMITIVE_INVALID = 6006, // 7xxx capi ERR_CAPI_NULL_HANDLE = 7001, /* ... */ ERR_CAPI_UNKNOWN_ERROR = 7999, }; struct ErrorInfo { ErrorCode code; std::string message; // 中文错误描述 std::string module; // 所属模块 std::string file; int line; // 源位置 ErrorInfo(); // 默认 SUCCESS ErrorInfo(ErrorCode c, std::string msg, std::string mod, std::string f = "", int l = 0); }; std::string error_message(ErrorCode code); // 错误码 → 中文描述 constexpr bool is_error(ErrorCode code) noexcept; // != SUCCESS constexpr bool is_success(ErrorCode code) noexcept; // == SUCCESS std::string error_module(ErrorCode code); // 错误码 → 所属模块名 } // namespace vde::foundation ``` ### `interval.h` — 区间算术与谓词验证 ```cpp namespace vde::foundation { class Interval { public: double lo, hi; Interval(); // 空区间 [0, 0] Interval(double v); // 点区间 [v, v] Interval(double l, double h); // 自动交换保证 lo ≤ hi [[nodiscard]] double mid() const; // (lo+hi)/2 [[nodiscard]] double width() const; // hi-lo [[nodiscard]] bool contains(double v) const; // lo ≤ v ≤ hi [[nodiscard]] bool is_exact(double eps = 1e-12) const; // 宽度 < eps [[nodiscard]] bool overlaps(const Interval& o) const; [[nodiscard]] int cmp(const Interval& o) const; // -1 确定小于 / 1 确定大于 / 0 重叠无法确定 Interval operator+(const Interval& o) const; // [lo+o.lo, hi+o.hi] Interval operator-(const Interval& o) const; // [lo-o.hi, hi-o.lo] Interval operator*(const Interval& o) const; // 四项乘积取 min/max Interval operator/(const Interval& o) const; // 除区间跨零时返回极大区间 Interval operator-() const; [[nodiscard]] Interval sqrt() const; static Interval from_double(double v, double error = 0); // 含误差带 static Interval from_coord(double v); // 含 ULP 误差带:|v|*2.22e-16 + 1e-300 }; // 二维定向行列式的区间验证 inline Interval orient_2d_interval(double ax, double ay, double bx, double by, double cx, double cy); inline int orient_2d_verified(double ax, double ay, double bx, double by, double cx, double cy); // 返回 -1 = 确认 Clockwise;1 = 确认 CounterClockwise;0 = 无法确定(需升级 GMP/自适应精度) } // namespace vde::foundation ``` ### `predicates.h` — 统一谓词接口 ```cpp namespace vde::foundation { // 编译时选择后端:定义 VDE_USE_GMP → exact::GmpExact(零误差),否则 AdaptiveDouble(默认) struct Predicates { using Backend = /* exact::GmpExact 或 AdaptiveDouble */; static exact::Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c); static exact::Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d); static exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d); }; // 便捷封装(推荐的对外 API) inline exact::Orientation orient(const Point2D& a, const Point2D& b, const Point2D& c); inline exact::Orientation orient(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d); inline exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d); } // namespace vde::foundation ``` ### `exact_predicates.h` — 自适应精度谓词(Shewchuk 算法) ```cpp namespace vde::foundation::exact { enum class Orientation { Clockwise, CounterClockwise, Collinear }; enum class CircleTest { Inside, On, Outside }; // 自适应浮点精度:先用双精度计算行列式,结果不可靠时逐步提高精度直至确定符号 Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c); Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d); CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d); // 另有标量重载:orient_2d(ax,ay,bx,by,cx,cy) 等,避免构造临时 Point } // namespace vde::foundation::exact namespace vde::foundation { // 自适应双精度后端(默认),封装 exact::* 函数 struct AdaptiveDouble { static exact::Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c); static exact::Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d); static exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d); }; } // namespace vde::foundation ``` ### `exact_predicates_gmp.h` — GMP 精确谓词后端(可选) ```cpp // 仅在定义 VDE_USE_GMP 宏且链接 GMP 库时编译(性能约为自适应双精度的 1/10 ~ 1/50) namespace vde::foundation::exact { struct GmpExact { // 基于 mpq_class 有理数运算,零舍入误差 using Rational = mpq_class; static Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c); static Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d); static CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d); }; } // namespace vde::foundation::exact ``` ### `memory_pool.h` — 固定块内存池 ```cpp namespace vde::foundation { // 空闲链表实现 O(1) 分配/释放;不调用构造函数/析构函数,仅管理原始内存 // 适合 POD 类型或通过 placement new 手动管理生命周期的对象(如半边网格的顶点/面) template class MemoryPool { public: explicit MemoryPool(size_t chunk_size = 1024); // 每块可容纳对象数 ~MemoryPool(); // 统一释放所有 chunk T* allocate(size_t n = 1); // O(1);空闲链表为空时自动分配新 chunk void deallocate(T* p, size_t = 1); // O(1);归还到空闲链表头部 }; } // namespace vde::foundation ``` ### `vde_log.h` — 轻量结构化日志(VDE D10) ```cpp namespace vde::foundation { enum class LogLevel : int { Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Critical = 5, Off = 6 }; const char* log_level_label(LogLevel level); // 短标签:"I" / "W" / "E" const char* log_level_name(LogLevel level); // 完整名称:"INFO" / "WARN" LogLevel log_level_from_string(const std::string& name); // 解析失败返回 Info struct LogMessage { LogLevel level; std::string module, event, message; // 模块标签 / 事件名 / 消息 std::vector> fields; // 键值字段 int64_t timestamp_us; // Unix 微秒时间戳 uint64_t sequence; // 全局序号 [[nodiscard]] std::string to_string() const; // 单行 key=value 风格 }; namespace vde_log { void set_level(LogLevel level); // 全局最小级别 LogLevel level(); void set_output(std::ostream* os); // 默认 std::cout;nullptr 关闭 void set_sink(std::function sink); // 自定义接收器;空函数清除 bool set_output_file(const std::string& path); // 追加模式写文件 void log(LogLevel level, const std::string& module, const std::string& event, const std::string& message, const std::vector>& fields); // 便捷 API(模块标签 + 事件名 + 消息 + 可选字段) template void trace(const std::string& module, const std::string& event, const std::string& message, const Field&... fields); // debug / info / warn / error / critical 同构 // 字段构造辅助(std::string / const char* / long long / int / double / bool 重载) inline std::pair field(const std::string& key, const std::string& value); // field(key, value) 用法:vde_log::info("brep", "boolean_union", "ok", vde_log::field("faces", 12)); } // namespace vde_log } // namespace vde::foundation ``` --- ## 代码示例 ### 示例 1: glTF 导入与再导出 ```cpp #include #include using namespace vde; // 导入 glTF auto result = foundation::import_gltf("model.glb"); if (result.success) { for (auto& mesh : result.meshes) { std::cout << "Faces: " << mesh.num_faces() << "\n"; } // 重新导出为 GLB(含法线) foundation::GltfOptions opts; opts.binary = true; opts.include_normals = true; foundation::write_gltf("model_out.glb", result.meshes[0], opts); } ``` ### 示例 2: DXF 解析与处理 ```cpp #include using namespace vde; // 解析 DXF auto doc = foundation::import_dxf("floor_plan.dxf"); std::cout << "DXF 版本: " << foundation::dxf_version_name(doc.version) << "\n"; std::cout << "实体数量: " << doc.entities.size() << "\n"; std::cout << "图层数量: " << doc.layers.size() << "\n"; // 统计各类型实体 for (auto& ent : doc.entities) { std::visit([](const auto& e) { using T = std::decay_t; if constexpr (std::is_same_v) { // 线段实体 } else if constexpr (std::is_same_v) { // 圆形实体 } }, ent); } // 转为网格 auto mesh = foundation::to_mesh(doc); ``` ### 示例 3: 工业格式导入 ```cpp #include using namespace vde; // JT 导入 auto jt_model = io::import_jt("assembly.jt"); // Parasolid 导入 auto xt_model = io::import_parasolid_xt("part.x_t"); // IFC BIM 导入 auto ifc_bodies = io::import_ifc("building.ifc"); // STEP AP242 导出(含 PMI) std::vector annotations = { /* ... */ }; auto step_data = io::export_step_ap242({jt_model}, annotations); ``` ### 示例 4: 结构化日志 ```cpp #include using namespace vde; // 设置全局级别并写文件 foundation::vde_log::set_level(foundation::LogLevel::Debug); foundation::vde_log::set_output_file("vde.log"); // 结构化输出(模块标签 + 事件名 + 键值字段) foundation::vde_log::info("brep", "boolean_union", "union completed", foundation::vde_log::field("faces_a", 12), foundation::vde_log::field("faces_b", 8), foundation::vde_log::field("duration_ms", 3.25)); ```