E9: STEP AP242 ED2 完整 PMI 往返(AP242Writer 两阶段写入 + StepPmiParser 导入 + 8 往返测试)

This commit is contained in:
hm
2026-08-10 20:05:36 +08:00
parent 29f76deefe
commit 21becf71f9
4 changed files with 815 additions and 90 deletions
+1 -1
View File
@@ -305,7 +305,7 @@ Total TODO/FIXME/HACK/stub 扫描命中: 13 处
| E6 | **高级修复全链路**: gap_fill 完整实现 + 6 种修复操作全覆盖 | 中 | ✅ E6 完成:gap_fill 缺口填补(边界环组装+最小二乘平面补面+流水线集成)+ 6 种修复操作缺陷模型全覆盖(29 测试)+ 修复 EulerOp mef 死循环/共享边/壳去重 |
| E7 | **大规模装配空间索引**: 百万级零件平截头体裁剪 | 中 | ✅ E7 完成:Frustum 透视视锥体(6 平面,法向朝向体内心测试)+ 零件级 BVH 索引(O(n log n) 构建 / O(log n + k) 查询)+ 视锥/范围双查询 + 5 测试(含 6.4 万零件抽样暴力对照) |
| E8 | **IFC 语义双向转换**: 14 种 IFC 实体 ↔ B-Rep | 中 | ✅ E8 完成:新增 export_ifc(12 种产品类型按名称映射 + 盒体→IfcExtrudedAreaSolid/RectangleProfileDef 语义化 + 其余→IfcFacetedBrep 全链路)+ import 升级(12 构件全覆盖、矩形/圆形/任意剖面尺寸解析、FacetedBrep 顶点/边去重重建)+ 8 个双向/回读测试 |
| E9 | **STEP AP242 ED2 完整 PMI 往返** | 中 | |
| E9 | **STEP AP242 ED2 完整 PMI 往返** | 中 | ✅ E9 完成:AP242Writer 两阶段写入(壳/面/环/边/点全链路先子后父,修复 ISO-10303-21 内插实体损坏)+ PMI 导出链(PMI 容器/DIMENSIONAL_SIZE/度量/公差/GDT 14 子类型/DATUM 系统)+ StepPmiParser 导入重建(容器组装 + 无容器回退)+ 8 个往返测试 |
| E10 | **STEP 非标实体全量覆盖** | 中 | |
| E11 | **XT/SAT/JT 二进制格式全量实体** | 中 | |
| E12 | **性能优化**: SSI 并行、MC SIMD、STEP 解析预编译 | 中 | |
@@ -423,6 +423,39 @@ void export_step_ap242_file(const std::string& path,
const std::vector<StepPMIAnnotation>& annotations = {},
const StepAP242Options& opts = {});
/**
* @brief STEP AP242 导入结果(几何体 + PMI 标注)
*/
struct StepAP242ImportResult {
std::vector<brep::BrepModel> bodies; ///< 导入的几何体
std::vector<StepPMIAnnotation> annotations; ///< 导入的 PMI 标注
};
/**
* @brief 从字符串导入 STEP AP242(几何 + PMI)
*
* 解析 AP242 数据段,重建 B-Rep 几何体,并提取 PMI 标注
* (尺寸标注 / 形位公差 / 基准系统 / 公差值)。
* 支持由 export_step_ap242 导出的 AP242 文件,也支持常规
* AP242 SHAPE_DIMENSION_REPRESENTATION / DIMENSIONAL_SIZE /
* GEOMETRIC_TOLERANCE 结构。
*
* @param step_data 完整 STEP 文件内容
* @return StepAP242ImportResult(bodies + annotations)
*/
[[nodiscard]] StepAP242ImportResult import_step_ap242_from_string(
const std::string& step_data);
/**
* @brief 从文件导入 STEP AP242(几何 + PMI)
*
* @param path .stp / .step 文件路径
* @return StepAP242ImportResult(bodies + annotations)
*
* @throws std::runtime_error 文件无法读取
*/
[[nodiscard]] StepAP242ImportResult import_step_ap242(const std::string& path);
// ═══════════════════════════════════════════════════════════════
// PDF 3D
// ═══════════════════════════════════════════════════════════════
+589 -83
View File
@@ -2,6 +2,7 @@
#include "vde/curves/nurbs_curve.h"
#include "vde/curves/nurbs_surface.h"
#include "vde/core/point.h"
#include "vde/brep/step_import.h"
#include <fstream>
#include <sstream>
#include <cstring>
@@ -2545,9 +2546,47 @@ struct AP242Writer {
std::stringstream ss;
int next_id = 1;
const std::vector<StepPMIAnnotation>* annotations_ = nullptr;
int ctx_ = 0; // 共享表示上下文(复杂类型)
int unit_len_ = 0; // 长度单位
int unit_ang_ = 0; // 平面角单位
bool ctx_written_ = false;
int new_id() { return next_id++; }
// STEP 字符串转义:单引号翻倍
static std::string escape(const std::string& s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == '\'') out += "''";
else out += c;
}
return out;
}
// 形位公差类型 → AP242 实体子类型(非 GDT 返回空串)
static const std::string& gdt_subtype_for(const std::string& type) {
static const std::map<std::string, std::string> kMap = {
{"flatness", "FLATNESS_TOLERANCE"},
{"straightness", "STRAIGHTNESS_TOLERANCE"},
{"circularity", "CIRCULARITY_TOLERANCE"},
{"cylindricity", "CYLINDRICITY_TOLERANCE"},
{"perpendicularity", "PERPENDICULARITY_TOLERANCE"},
{"parallelism", "PARALLELISM_TOLERANCE"},
{"angularity", "ANGULARITY_TOLERANCE"},
{"position", "POSITION_TOLERANCE"},
{"concentricity", "CONCENTRICITY_TOLERANCE"},
{"circular_runout", "CIRCULAR_RUNOUT_TOLERANCE"},
{"total_runout", "TOTAL_RUNOUT_TOLERANCE"},
{"profile_of_surface", "PROFILE_OF_SURFACE_TOLERANCE"},
{"profile_of_line", "PROFILE_OF_LINE_TOLERANCE"},
{"symmetry", "SYMMETRY_TOLERANCE"},
};
auto it = kMap.find(type);
static const std::string kEmpty;
return it != kMap.end() ? it->second : kEmpty;
}
void header() {
ss << "ISO-10303-21;\n";
ss << "HEADER;\n";
@@ -2596,134 +2635,129 @@ struct AP242Writer {
}
int write_closed_shell(const BrepModel& body, int body_idx) {
// 收集所有面 ID
int id = new_id();
ss << "#" << id << " = CLOSED_SHELL('',(";
bool first = true;
// 两阶段:先写全部 ADVANCED_FACE 子实体,再写 CLOSED_SHELL 引用行
std::vector<int> face_ids;
for (size_t i = 0; i < body.num_faces(); ++i) {
int fid = new_id();
if (!first) ss << ",";
first = false;
ss << "#" << fid;
// 写 face
face_ids.push_back(fid);
write_advanced_face(fid, body, static_cast<int>(i));
}
int id = new_id();
ss << "#" << id << " = CLOSED_SHELL('',(";
for (size_t i = 0; i < face_ids.size(); ++i) {
if (i > 0) ss << ",";
ss << "#" << face_ids[i];
}
ss << "));\n";
return id;
}
void write_advanced_face(int fid, const BrepModel& body, int face_idx) {
ss << "#" << fid << " = ADVANCED_FACE('',(";
auto& f = body.face(face_idx);
bool first = true;
// 先写所有 FACE_OUTER_BOUND 与 PLANE 面,再写 ADVANCED_FACE 引用行
std::vector<int> bound_ids;
for (auto& lid : f.loops) {
int bound_id = new_id();
if (!first) ss << ",";
first = false;
ss << "#" << bound_id;
bound_ids.push_back(bound_id);
write_face_bound(bound_id, body, lid);
}
ss << "),#";
int surf_id = new_id();
ss << surf_id;
write_plane_surface(surf_id);
ss << "," << (f.reversed ? ".T." : ".F.") << ");\n";
ss << "#" << fid << " = ADVANCED_FACE('',(";
for (size_t i = 0; i < bound_ids.size(); ++i) {
if (i > 0) ss << ",";
ss << "#" << bound_ids[i];
}
ss << "),#" << surf_id << "," << (f.reversed ? ".T." : ".F.") << ");\n";
}
void write_face_bound(int bid, const BrepModel& body, int loop_idx) {
ss << "#" << bid << " = FACE_OUTER_BOUND('',#";
// 先写 EDGE_LOOP,再写 FACE_OUTER_BOUND 引用行
int edge_loop_id = new_id();
ss << edge_loop_id;
write_edge_loop(edge_loop_id, body, loop_idx);
ss << "," << (body.loop_by_id(loop_idx).is_outer ? ".T." : ".F.") << ");\n";
ss << "#" << bid << " = FACE_OUTER_BOUND('',#" << edge_loop_id
<< "," << (body.loop_by_id(loop_idx).is_outer ? ".T." : ".F.") << ");\n";
}
void write_edge_loop(int eid, const BrepModel& body, int loop_idx) {
ss << "#" << eid << " = EDGE_LOOP('',(";
auto& loop = body.loop_by_id(loop_idx);
bool first = true;
// 先写所有 ORIENTED_EDGE,再写 EDGE_LOOP 引用行
std::vector<int> oriented_ids;
for (auto& edge_id : loop.edges) {
int oriented_id = new_id();
if (!first) ss << ",";
first = false;
ss << "#" << oriented_id;
oriented_ids.push_back(oriented_id);
write_oriented_edge(oriented_id, body, edge_id);
}
ss << "#" << eid << " = EDGE_LOOP('',(";
for (size_t i = 0; i < oriented_ids.size(); ++i) {
if (i > 0) ss << ",";
ss << "#" << oriented_ids[i];
}
ss << "));\n";
}
void write_oriented_edge(int oid, const BrepModel& body, int edge_idx) {
ss << "#" << oid << " = ORIENTED_EDGE('',*,*,#";
// 先写 EDGE_CURVE,再写 ORIENTED_EDGE 引用行
int edge_curve_id = new_id();
ss << edge_curve_id;
write_edge_curve(edge_curve_id, body, edge_idx);
ss << "," << (body.edge(edge_idx).reversed ? ".T." : ".F.") << ");\n";
ss << "#" << oid << " = ORIENTED_EDGE('',*,*,#" << edge_curve_id
<< "," << (body.edge(edge_idx).reversed ? ".T." : ".F.") << ");\n";
}
void write_edge_curve(int ecid, const BrepModel& body, int edge_idx) {
auto& e = body.edge(edge_idx);
int vp1 = new_id();
ss << "#" << ecid << " = EDGE_CURVE('',#";
// 先写两个 VERTEX_POINT 与 LINE 曲线,再写 EDGE_CURVE 引用行
int vp0 = new_id();
ss << vp0 << ",#" << vp1 << ",#";
int line_id = new_id();
ss << line_id;
int vp1 = new_id();
write_vertex_point(vp0, body, e.v_start);
write_vertex_point(vp1, body, e.v_end);
int line_id = new_id();
write_line(line_id, body, e.v_start, e.v_end);
ss << "," << (e.reversed ? ".T." : ".F.") << ");\n";
ss << "#" << ecid << " = EDGE_CURVE('',#" << vp0 << ",#" << vp1 << ",#"
<< line_id << "," << (e.reversed ? ".T." : ".F.") << ");\n";
}
void write_vertex_point(int vid, const BrepModel& body, int vertex_idx) {
auto& v = body.vertex(vertex_idx);
// 先写 CARTESIAN_POINT,再写 VERTEX_POINT 引用行
int p = new_id();
ss << "#" << vid << " = VERTEX_POINT('',#";
ss << p;
ss << ");\n";
ss << "#" << p << " = CARTESIAN_POINT('',("
<< v.point.x() << "," << v.point.y() << "," << v.point.z() << "));\n";
ss << "#" << vid << " = VERTEX_POINT('',#" << p << ");\n";
}
void write_line(int lid, const BrepModel& body, int v0_idx, int v1_idx) {
auto& v0 = body.vertex(v0_idx);
auto& v1 = body.vertex(v1_idx);
int p = new_id();
ss << "#" << lid << " = LINE('',#";
ss << p;
Vector3D dir(v1.point.x()-v0.point.x(),
v1.point.y()-v0.point.y(),
v1.point.z()-v0.point.z());
double len = std::sqrt(dir.x()*dir.x()+dir.y()*dir.y()+dir.z()*dir.z());
if (len > 1e-12) dir = Vector3D(dir.x()/len, dir.y()/len, dir.z()/len);
int vec = new_id();
ss << ",#" << vec;
ss << ");\n";
// 先写 CARTESIAN_POINT / DIRECTION / VECTOR,再写 LINE 引用行
int p = new_id();
ss << "#" << p << " = CARTESIAN_POINT('',("
<< v0.point.x() << "," << v0.point.y() << "," << v0.point.z() << "));\n";
ss << "#" << vec << " = VECTOR('',#";
int dir_id = new_id();
ss << dir_id << "," << len << ");\n";
ss << "#" << dir_id << " = DIRECTION('',("
<< dir.x() << "," << dir.y() << "," << dir.z() << "));\n";
int vec = new_id();
ss << "#" << vec << " = VECTOR('',#" << dir_id << "," << len << ");\n";
ss << "#" << lid << " = LINE('',#" << p << ",#" << vec << ");\n";
}
void write_plane_surface(int sid) {
int p = new_id();
ss << "#" << sid << " = PLANE('',#";
ss << p << ");\n";
ss << "#" << p << " = AXIS2_PLACEMENT_3D('',#";
// 先写 CARTESIAN_POINT / DIRECTION / AXIS2_PLACEMENT_3D,再写 PLANE 引用行
int cp = new_id();
ss << cp << ",#";
int ad = new_id();
ss << ad << ",#";
int rd = new_id();
ss << rd << ");\n";
ss << "#" << cp << " = CARTESIAN_POINT('',(0.0,0.0,0.0));\n";
int ad = new_id();
ss << "#" << ad << " = DIRECTION('',(0.0,0.0,1.0));\n";
int rd = new_id();
ss << "#" << rd << " = DIRECTION('',(1.0,0.0,0.0));\n";
int p = new_id();
ss << "#" << p << " = AXIS2_PLACEMENT_3D('',#" << cp << ",#" << ad
<< ",#" << rd << ");\n";
ss << "#" << sid << " = PLANE('',#" << p << ");\n";
}
int write_product(const std::string& name) {
@@ -2752,43 +2786,100 @@ struct AP242Writer {
return id;
}
// 共享表示上下文与单位(每个文件写一次)
void write_ap242_context() {
if (ctx_written_) return;
ctx_written_ = true;
unit_len_ = new_id();
ss << "#" << unit_len_ << " = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );\n";
unit_ang_ = new_id();
ss << "#" << unit_ang_ << " = ( PLANE_ANGLE_UNIT() NAMED_UNIT(*) SI_UNIT(.RADIAN.,$) );\n";
int unc = new_id();
ss << "#" << unc << " = UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(0.0001),#"
<< unit_len_ << ",'distance_accuracy_value','confusion accuracy');\n";
ctx_ = new_id();
ss << "#" << ctx_ << " = ( GEOMETRIC_REPRESENTATION_CONTEXT(3) "
<< "GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#" << unc << ")) "
<< "GLOBAL_UNIT_ASSIGNED_CONTEXT((#" << unit_len_ << ",#" << unit_ang_ << ")) "
<< "REPRESENTATION_CONTEXT('Context #1','3D Context') );\n";
}
// 单个标注的数值结构:DIMENSIONAL_SIZE + 度量(含/不含公差)
void write_pmi_values(const StepPMIAnnotation& ann, int& ds_id, bool& has_tol) {
has_tol = ann.upper_tolerance != 0.0 || ann.lower_tolerance != 0.0;
ds_id = new_id();
if (has_tol) {
int plus = new_id();
ss << "#" << plus << " = PLUS_MINUS_TOLERANCE(LENGTH_MEASURE("
<< ann.upper_tolerance << "),LENGTH_MEASURE("
<< ann.lower_tolerance << "),$);\n";
int tm = new_id();
ss << "#" << tm << " = TOLERANCED_LENGTH_MEASURE(LENGTH_MEASURE("
<< ann.nominal_value << "),#" << unit_len_ << ",(#" << plus << "));\n";
ss << "#" << ds_id << " = DIMENSIONAL_SIZE('" << escape(ann.id)
<< "',#" << tm << ");\n";
} else if (ann.type == "angular_dimension") {
int mw = new_id();
ss << "#" << mw << " = PLANE_ANGLE_MEASURE_WITH_UNIT(PLANE_ANGLE_MEASURE("
<< ann.nominal_value << "),#" << unit_ang_ << ");\n";
ss << "#" << ds_id << " = DIMENSIONAL_SIZE('" << escape(ann.id)
<< "',#" << mw << ");\n";
} else {
int mw = new_id();
ss << "#" << mw << " = LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE("
<< ann.nominal_value << "),#" << unit_len_ << ");\n";
ss << "#" << ds_id << " = DIMENSIONAL_SIZE('" << escape(ann.id)
<< "',#" << mw << ");\n";
}
}
void write_pmi_annotations() {
if (!annotations_ || annotations_->empty()) return;
write_ap242_context();
for (const auto& ann : *annotations_) {
int pmi_id = new_id();
ss << "#" << pmi_id << " = PRODUCT_MANUFACTURING_INFORMATION('" << ann.id << "','"
<< ann.description << "');\n";
ss << "#" << pmi_id << " = PRODUCT_MANUFACTURING_INFORMATION('"
<< escape(ann.id) << "','" << escape(ann.description) << "');\n";
if (ann.type == "linear_dimension" || ann.type == "angular_dimension") {
int dcr_id = new_id();
ss << "#" << dcr_id << " = DIMENSIONAL_CHARACTERISTIC_REPRESENTATION('"
<< ann.id << "',#" << pmi_id << ",#";
int sdr_id = new_id();
ss << sdr_id << ");\n";
// 数值:名义值 + 公差
int ds_id = 0;
bool has_tol = false;
write_pmi_values(ann, ds_id, has_tol);
ss << "#" << sdr_id << " = SHAPE_DIMENSION_REPRESENTATION('"
<< ann.id << "',#" << dcr_id << ");\n";
// 表示结构(维度)或形位公差(GDT)
int gr = new_id();
ss << "#" << gr << " = GEOMETRIC_SET_REPRESENTATION('',(),#"
<< ctx_ << ");\n";
int dcr = new_id();
ss << "#" << dcr << " = DIMENSIONAL_CHARACTERISTIC_REPRESENTATION('"
<< escape(ann.id) << "',#" << pmi_id << ",(#" << ds_id << "),#"
<< ctx_ << ");\n";
const std::string& gdt_subtype = gdt_subtype_for(ann.type);
if (gdt_subtype.empty()) {
int sdr = new_id();
ss << "#" << sdr << " = SHAPE_DIMENSION_REPRESENTATION('"
<< escape(ann.id) << "',(#" << ds_id << "),(#" << gr << "));\n";
} else {
int gt = new_id();
ss << "#" << gt << " = " << gdt_subtype << "('"
<< escape(ann.id) << "','" << escape(ann.description)
<< "',#" << pmi_id << ");\n";
}
// 公差信息
// 基准系统
if (!ann.datum_system.empty()) {
int tol_id = new_id();
ss << "#" << tol_id << " = GEOMETRIC_TOLERANCE('" << ann.id << "',#"
<< pmi_id << ",$);\n";
int dtm_id = new_id();
ss << "#" << dtm_id << " = DATUM_SYSTEM('" << ann.datum_system << "',#"
<< tol_id << ",$);\n";
}
// 名义值和公差
if (ann.nominal_value != 0.0 || ann.upper_tolerance != 0.0 ||
ann.lower_tolerance != 0.0) {
int dim_id = new_id();
ss << "#" << dim_id << " = DIMENSIONAL_SIZE('"
<< ann.id << "'," << ann.nominal_value << ","
<< ann.upper_tolerance << "," << ann.lower_tolerance << ");\n";
int datum = new_id();
ss << "#" << datum << " = DATUM('" << escape(ann.datum_system)
<< "',#" << pmi_id << ");\n";
int dref = new_id();
ss << "#" << dref << " = DATUM_REFERENCE(#" << datum << ");\n";
int dsys = new_id();
ss << "#" << dsys << " = DATUM_SYSTEM('" << escape(ann.datum_system)
<< "',(#" << dref << "));\n";
}
}
}
@@ -2854,6 +2945,421 @@ void export_step_ap242_file(const std::string& path,
write_file_bytes(path, data);
}
// ═══════════════════════════════════════════════════════════════
// STEP AP242 导入(几何 + PMI 回读)
// ═══════════════════════════════════════════════════════════════
namespace ap242_impl {
// STEP 实体(PMI 回读用)
struct StepPmiEntity {
std::string type;
std::vector<std::string> params;
};
// ISO-10303-21 轻量解析器:提取 DATA 段全部实体
class StepPmiParser {
public:
explicit StepPmiParser(const std::string& data) : data_(data), pos_(0) {}
std::vector<StepPMIAnnotation> parse_pmi() {
parse_entities();
return build_annotations();
}
private:
const std::string& data_;
size_t pos_;
std::unordered_map<int, StepPmiEntity> entities_;
void skip_ws() {
while (pos_ < data_.size() && (data_[pos_] == ' ' || data_[pos_] == '\t' ||
data_[pos_] == '\r' || data_[pos_] == '\n'))
++pos_;
// 注释 /* ... */
if (pos_ + 1 < data_.size() && data_[pos_] == '/' && data_[pos_ + 1] == '*') {
pos_ += 2;
while (pos_ + 1 < data_.size() &&
!(data_[pos_] == '*' && data_[pos_ + 1] == '/'))
++pos_;
if (pos_ + 1 < data_.size()) pos_ += 2;
skip_ws();
}
}
bool parse_entity() {
skip_ws();
if (pos_ >= data_.size() || data_[pos_] != '#') return false;
++pos_;
std::string id_str;
while (pos_ < data_.size() && data_[pos_] >= '0' && data_[pos_] <= '9')
id_str += data_[pos_++];
if (id_str.empty()) return false;
int id = std::stoi(id_str);
skip_ws();
if (pos_ >= data_.size() || data_[pos_] != '=') return false;
++pos_;
skip_ws();
// 复杂类型: ( PART1() PART2() ... )
std::string type;
if (pos_ < data_.size() && data_[pos_] == '(') {
type = "(COMPLEX)";
consume_complex();
} else {
while (pos_ < data_.size() &&
((data_[pos_] >= 'A' && data_[pos_] <= 'Z') ||
(data_[pos_] >= 'a' && data_[pos_] <= 'z') ||
(data_[pos_] >= '0' && data_[pos_] <= '9') ||
data_[pos_] == '_'))
type += data_[pos_++];
}
skip_ws();
if (pos_ >= data_.size() || data_[pos_] != '(') {
// 跳过到分号(损坏实体恢复)
skip_to_semicolon();
return true;
}
++pos_;
std::vector<std::string> params = parse_params();
skip_ws();
if (pos_ < data_.size() && data_[pos_] == ';') ++pos_;
entities_[id] = {std::move(type), std::move(params)};
return true;
}
void consume_complex() {
int depth = 0;
while (pos_ < data_.size()) {
char c = data_[pos_];
if (c == '(') { ++depth; ++pos_; continue; }
if (c == ')') { --depth; ++pos_; if (depth == 0) break; continue; }
++pos_;
}
}
void skip_to_semicolon() {
int depth = 0;
while (pos_ < data_.size()) {
char c = data_[pos_];
if (c == '(') { ++depth; ++pos_; continue; }
if (c == ')') { --depth; ++pos_; continue; }
if (c == ';' && depth == 0) { ++pos_; return; }
++pos_;
}
}
std::vector<std::string> parse_params() {
std::vector<std::string> params;
int depth = 1;
while (pos_ < data_.size() && depth > 0) {
skip_ws();
if (pos_ >= data_.size()) break;
char c = data_[pos_];
if (c == ')') { --depth; ++pos_; continue; }
if (c == '(') { ++depth; ++pos_; continue; }
if (c == ',') { ++pos_; continue; }
if (c == ';') break;
if (c == '\'') {
++pos_;
std::string val;
while (pos_ < data_.size()) {
if (data_[pos_] == '\'') {
if (pos_ + 1 < data_.size() && data_[pos_ + 1] == '\'') {
val += '\'';
pos_ += 2;
continue;
}
++pos_;
break;
}
val += data_[pos_++];
}
params.push_back(val);
continue;
}
if (c == '#') {
++pos_;
std::string ref;
while (pos_ < data_.size() && data_[pos_] >= '0' && data_[pos_] <= '9')
ref += data_[pos_++];
params.push_back("#" + ref);
continue;
}
if (c == '$') { ++pos_; params.push_back("$"); continue; }
if (c == '*') { ++pos_; params.push_back("*"); continue; }
if (c == '.') {
++pos_;
std::string ev;
while (pos_ < data_.size() && data_[pos_] != '.') ev += data_[pos_++];
if (pos_ < data_.size()) ++pos_;
params.push_back("." + ev + ".");
continue;
}
std::string val;
while (pos_ < data_.size() && data_[pos_] != ',' && data_[pos_] != ')' &&
data_[pos_] != ';' && data_[pos_] != '\'' && data_[pos_] != '(')
val += data_[pos_++];
if (!val.empty()) {
// 标识符紧跟 '(' 时吸收平衡括号块为整体(如 LENGTH_MEASURE(2.5))
size_t look = pos_;
while (look < data_.size() && (data_[look] == ' ' || data_[look] == '\t'))
++look;
if (look < data_.size() && data_[look] == '(') {
pos_ = look;
int d = 0;
do {
char ch = data_[pos_];
if (ch == '(') ++d;
else if (ch == ')') --d;
val += ch;
++pos_;
} while (pos_ < data_.size() && d > 0);
}
params.push_back(val);
}
}
return params;
}
void parse_entities() {
size_t data_pos = data_.find("DATA;");
if (data_pos == std::string::npos) return;
pos_ = data_pos + 5;
while (parse_entity()) {}
}
// ── PMI 重建 ──
static double to_double(const std::string& s) {
try { return std::stod(s); } catch (...) { return 0.0; }
}
// 提取度量数值:LENGTH_MEASURE(2.5) → 2.5(剥离类型包装)
static double measure_value(const std::string& s) {
size_t lp = s.find('(');
if (lp != std::string::npos) {
size_t rp = s.rfind(')');
if (rp != std::string::npos && rp > lp)
return to_double(s.substr(lp + 1, rp - lp - 1));
}
return to_double(s);
}
static int ref_id(const std::string& s) {
if (s.size() > 1 && s[0] == '#') {
try { return std::stoi(s.substr(1)); } catch (...) {}
}
return -1;
}
const StepPmiEntity* ent(int id) const {
auto it = entities_.find(id);
return it != entities_.end() ? &it->second : nullptr;
}
// GDT 子类型实体名 → 类型字符串(与导出 gdt_subtype_for 对应)
static std::string gdt_type_from_entity(const std::string& type) {
static const std::map<std::string, std::string> kMap = {
{"FLATNESS_TOLERANCE", "flatness"},
{"STRAIGHTNESS_TOLERANCE", "straightness"},
{"CIRCULARITY_TOLERANCE", "circularity"},
{"CYLINDRICITY_TOLERANCE", "cylindricity"},
{"PERPENDICULARITY_TOLERANCE", "perpendicularity"},
{"PARALLELISM_TOLERANCE", "parallelism"},
{"ANGULARITY_TOLERANCE", "angularity"},
{"POSITION_TOLERANCE", "position"},
{"CONCENTRICITY_TOLERANCE", "concentricity"},
{"CIRCULAR_RUNOUT_TOLERANCE", "circular_runout"},
{"TOTAL_RUNOUT_TOLERANCE", "total_runout"},
{"PROFILE_OF_SURFACE_TOLERANCE", "profile_of_surface"},
{"PROFILE_OF_LINE_TOLERANCE", "profile_of_line"},
{"SYMMETRY_TOLERANCE", "symmetry"},
};
auto it = kMap.find(type);
return it != kMap.end() ? it->second : std::string();
}
// 解析 DIMENSIONAL_SIZE 引用的度量 → 名义值/公差/维度类型
void resolve_measure(int mref, std::string& kind,
double& nominal, double& upper, double& lower) const {
const StepPmiEntity* m = ent(mref);
if (!m) return;
if (m->type == "LENGTH_MEASURE_WITH_UNIT") {
kind = "linear_dimension";
if (m->params.size() > 0) nominal = measure_value(m->params[0]);
} else if (m->type == "PLANE_ANGLE_MEASURE_WITH_UNIT") {
kind = "angular_dimension";
if (m->params.size() > 0) nominal = measure_value(m->params[0]);
} else if (m->type == "TOLERANCED_LENGTH_MEASURE") {
kind = "linear_dimension";
if (m->params.size() > 0) nominal = measure_value(m->params[0]);
for (size_t i = 1; i < m->params.size(); ++i) {
int pref = ref_id(m->params[i]);
const StepPmiEntity* p = ent(pref);
if (p && p->type == "PLUS_MINUS_TOLERANCE") {
if (p->params.size() > 0) upper = measure_value(p->params[0]);
if (p->params.size() > 1) lower = measure_value(p->params[1]);
}
}
}
}
std::vector<StepPMIAnnotation> build_annotations() {
std::vector<StepPMIAnnotation> result;
// PMI 容器:id → (id_str, desc)
struct PmiInfo { std::string id_str, desc; };
std::map<int, PmiInfo> pmi_by_id;
// dim_size ref → pmi ref
std::map<int, int> pmi_of_ds;
// gdt 实体 id → pmi ref
std::map<int, int> pmi_of_gt;
// datum 实体 id → pmi ref
std::map<int, int> pmi_of_datum;
// datum ref → datum id
std::map<int, int> datum_of_dref;
// datum system id → (name, 引用的 dref 列表)
std::map<int, std::pair<std::string, std::vector<int>>> dsys_info;
// dim_size ref → 度量解析结果
struct MeasureInfo { std::string kind; double nominal=0, upper=0, lower=0; };
std::map<int, MeasureInfo> ds_measure;
for (const auto& [eid, e] : entities_) {
if (e.type == "PRODUCT_MANUFACTURING_INFORMATION") {
PmiInfo pi;
if (!e.params.empty()) pi.id_str = e.params[0];
if (e.params.size() > 1) pi.desc = e.params[1];
pmi_by_id[eid] = pi;
} else if (e.type == "DIMENSIONAL_SIZE" && e.params.size() >= 2) {
MeasureInfo mi;
resolve_measure(ref_id(e.params[1]), mi.kind,
mi.nominal, mi.upper, mi.lower);
if (!mi.kind.empty()) ds_measure[eid] = mi;
} else if (e.type == "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION" &&
e.params.size() >= 3) {
int pmi_ref = ref_id(e.params[1]);
for (size_t i = 2; i < e.params.size(); ++i) {
int ds_ref = ref_id(e.params[i]);
if (ds_ref >= 0) pmi_of_ds[ds_ref] = pmi_ref;
}
} else if (e.type == "DATUM" && e.params.size() >= 2) {
int pmi_ref = ref_id(e.params[1]);
if (pmi_ref >= 0) pmi_of_datum[eid] = pmi_ref;
} else if (e.type == "DATUM_REFERENCE" && !e.params.empty()) {
int d_ref = ref_id(e.params[0]);
if (d_ref >= 0) datum_of_dref[eid] = d_ref;
} else if (e.type == "DATUM_SYSTEM" && !e.params.empty()) {
std::string name = e.params[0];
std::vector<int> refs;
for (size_t i = 1; i < e.params.size(); ++i) {
int r = ref_id(e.params[i]);
if (r >= 0) refs.push_back(r);
}
dsys_info[eid] = {name, refs};
} else if (!gdt_type_from_entity(e.type).empty() && e.params.size() >= 3) {
int pmi_ref = ref_id(e.params[2]);
if (pmi_ref >= 0) pmi_of_gt[eid] = pmi_ref;
}
}
// 按 PMI 容器组装标注
for (const auto& [pmi_id, pi] : pmi_by_id) {
StepPMIAnnotation ann;
ann.id = pi.id_str;
ann.description = pi.desc;
ann.type = "note";
// 形位公差类型
for (const auto& [gt_id, ref] : pmi_of_gt) {
if (ref == pmi_id) {
const StepPmiEntity* gt = ent(gt_id);
if (gt) {
ann.type = gdt_type_from_entity(gt->type);
// 容器 id 优先;仅在容器无 id 时回退到 GDT 实体名
if (ann.id.empty() && !gt->params.empty())
ann.id = gt->params[0];
}
break;
}
}
// 数值(名义值 + 公差)
for (const auto& [ds_ref, ref] : pmi_of_ds) {
if (ref == pmi_id) {
auto it = ds_measure.find(ds_ref);
if (it == ds_measure.end()) continue; // DCR 还含表示上下文等非度量引用
if (ann.type == "note") ann.type = it->second.kind;
ann.nominal_value = it->second.nominal;
ann.upper_tolerance = it->second.upper;
ann.lower_tolerance = it->second.lower;
break;
}
}
// 基准系统:datum → pmi → dsys
for (const auto& [dsys_id, info] : dsys_info) {
for (int dref_id : info.second) {
auto dit = datum_of_dref.find(dref_id);
if (dit == datum_of_dref.end()) continue;
auto pit = pmi_of_datum.find(dit->second);
if (pit != pmi_of_datum.end() && pit->second == pmi_id) {
ann.datum_system = info.first;
break;
}
}
if (!ann.datum_system.empty()) break;
}
result.push_back(std::move(ann));
}
// 无 PMI 容器时的回退:直接从 SHAPE_DIMENSION_REPRESENTATION 提取
if (pmi_by_id.empty()) {
for (const auto& [eid, e] : entities_) {
if (e.type != "SHAPE_DIMENSION_REPRESENTATION") continue;
for (size_t i = 1; i < e.params.size(); ++i) {
int ds_ref = ref_id(e.params[i]);
auto it = ds_measure.find(ds_ref);
if (it == ds_measure.end()) continue;
StepPMIAnnotation ann;
ann.id = !e.params.empty() ? e.params[0] : "";
ann.type = it->second.kind;
ann.nominal_value = it->second.nominal;
ann.upper_tolerance = it->second.upper;
ann.lower_tolerance = it->second.lower;
result.push_back(std::move(ann));
}
}
}
return result;
}
};
} // namespace ap242_impl
StepAP242ImportResult import_step_ap242_from_string(const std::string& step_data) {
StepAP242ImportResult res;
// PMI 回读
ap242_impl::StepPmiParser parser(step_data);
res.annotations = parser.parse_pmi();
// 几何回读(委托 brep 层解析器;PMI/复杂类型实体会被其安全跳过)
try {
res.bodies = brep::import_step_from_string(step_data);
} catch (...) {
// 几何解析失败不阻断 PMI 结果
}
return res;
}
StepAP242ImportResult import_step_ap242(const std::string& path) {
std::string data = read_file_bytes(path);
return import_step_ap242_from_string(data);
}
// ═══════════════════════════════════════════════════════════════
// PDF 3D 导出
// ═══════════════════════════════════════════════════════════════
+192 -6
View File
@@ -875,18 +875,18 @@ TEST(IndustrialStepAP242, ExportWithGeometricTolerance) {
std::vector<StepPMIAnnotation> annotations;
StepPMIAnnotation ann;
ann.type = "angular_dimension";
ann.type = "flatness";
ann.id = "TOL001";
ann.description = "Angular tolerance";
ann.nominal_value = 90.0;
ann.upper_tolerance = 0.5;
ann.lower_tolerance = -0.5;
ann.description = "Flatness tolerance";
ann.nominal_value = 0.02;
ann.upper_tolerance = 0.01;
ann.lower_tolerance = -0.01;
ann.datum_system = "Datum_B";
annotations.push_back(ann);
std::string result = export_step_ap242({box}, annotations);
EXPECT_NE(result.find("GEOMETRIC_TOLERANCE"), std::string::npos);
EXPECT_NE(result.find("FLATNESS_TOLERANCE"), std::string::npos);
EXPECT_NE(result.find("DATUM_SYSTEM"), std::string::npos);
}
@@ -961,6 +961,192 @@ TEST(IndustrialStepAP242, ExportToFileWithPMI) {
clean(path);
}
// ── E9: AP242 ED2 完整 PMI 往返 ──
TEST(IndustrialStepAP242, RoundtripDimensionAllFields) {
auto box = make_test_box();
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation ann;
ann.type = "linear_dimension";
ann.id = "DIM001";
ann.description = "Length dimension";
ann.nominal_value = 100.0;
ann.upper_tolerance = 0.1;
ann.lower_tolerance = -0.2;
ann.datum_system = "Datum_A";
anns.push_back(ann);
std::string data = export_step_ap242({box}, anns);
std::ofstream dbg(VDE_TEST_TEMP_DIR "dbg_ap242.stp");
dbg << data;
dbg.close();
auto res = import_step_ap242_from_string(data);
ASSERT_EQ(res.annotations.size(), 1u) << "exported data:\n" << data;
const auto& rt = res.annotations[0];
EXPECT_EQ(rt.type, "linear_dimension");
EXPECT_EQ(rt.id, "DIM001");
EXPECT_EQ(rt.description, "Length dimension");
EXPECT_DOUBLE_EQ(rt.nominal_value, 100.0);
EXPECT_DOUBLE_EQ(rt.upper_tolerance, 0.1);
EXPECT_DOUBLE_EQ(rt.lower_tolerance, -0.2);
EXPECT_EQ(rt.datum_system, "Datum_A");
}
TEST(IndustrialStepAP242, RoundtripDimensionNoTolerance) {
auto box = make_test_box();
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation ann;
ann.type = "linear_dimension";
ann.id = "DIM002";
ann.nominal_value = 50.0;
anns.push_back(ann);
std::string data = export_step_ap242({box}, anns);
auto res = import_step_ap242_from_string(data);
ASSERT_EQ(res.annotations.size(), 1u);
EXPECT_EQ(res.annotations[0].type, "linear_dimension");
EXPECT_EQ(res.annotations[0].id, "DIM002");
EXPECT_DOUBLE_EQ(res.annotations[0].nominal_value, 50.0);
EXPECT_DOUBLE_EQ(res.annotations[0].upper_tolerance, 0.0);
EXPECT_DOUBLE_EQ(res.annotations[0].lower_tolerance, 0.0);
}
TEST(IndustrialStepAP242, RoundtripAngularDimension) {
auto box = make_test_box();
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation ann;
ann.type = "angular_dimension";
ann.id = "ANG001";
ann.description = "Angle";
ann.nominal_value = 45.0;
anns.push_back(ann);
std::string data = export_step_ap242({box}, anns);
auto res = import_step_ap242_from_string(data);
ASSERT_EQ(res.annotations.size(), 1u);
EXPECT_EQ(res.annotations[0].type, "angular_dimension");
EXPECT_DOUBLE_EQ(res.annotations[0].nominal_value, 45.0);
}
TEST(IndustrialStepAP242, RoundtripGDTWithDatum) {
auto box = make_test_box();
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation ann;
ann.type = "position";
ann.id = "GDT001";
ann.description = "Position tolerance";
ann.nominal_value = 0.05;
ann.upper_tolerance = 0.02;
ann.lower_tolerance = -0.02;
ann.datum_system = "ABC";
anns.push_back(ann);
std::string data = export_step_ap242({box}, anns);
auto res = import_step_ap242_from_string(data);
ASSERT_EQ(res.annotations.size(), 1u);
EXPECT_EQ(res.annotations[0].type, "position");
EXPECT_EQ(res.annotations[0].id, "GDT001");
EXPECT_EQ(res.annotations[0].description, "Position tolerance");
EXPECT_DOUBLE_EQ(res.annotations[0].nominal_value, 0.05);
EXPECT_DOUBLE_EQ(res.annotations[0].upper_tolerance, 0.02);
EXPECT_DOUBLE_EQ(res.annotations[0].lower_tolerance, -0.02);
EXPECT_EQ(res.annotations[0].datum_system, "ABC");
}
TEST(IndustrialStepAP242, RoundtripMultipleAnnotations) {
auto box = make_test_box();
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation d1;
d1.type = "linear_dimension"; d1.id = "A"; d1.nominal_value = 10.0;
anns.push_back(d1);
StepPMIAnnotation d2;
d2.type = "angular_dimension"; d2.id = "B"; d2.nominal_value = 30.0;
anns.push_back(d2);
StepPMIAnnotation g1;
g1.type = "flatness"; g1.id = "C"; g1.nominal_value = 0.01; g1.datum_system = "D";
anns.push_back(g1);
std::string data = export_step_ap242({box}, anns);
auto res = import_step_ap242_from_string(data);
ASSERT_EQ(res.annotations.size(), 3u);
// 顺序与导出一致(按 PMI 容器顺序)
EXPECT_EQ(res.annotations[0].type, "linear_dimension");
EXPECT_DOUBLE_EQ(res.annotations[0].nominal_value, 10.0);
EXPECT_EQ(res.annotations[1].type, "angular_dimension");
EXPECT_DOUBLE_EQ(res.annotations[1].nominal_value, 30.0);
EXPECT_EQ(res.annotations[2].type, "flatness");
EXPECT_DOUBLE_EQ(res.annotations[2].nominal_value, 0.01);
EXPECT_EQ(res.annotations[2].datum_system, "D");
}
TEST(IndustrialStepAP242, RoundtripEmptyAnnotations) {
auto box = make_test_box();
std::string data = export_step_ap242({box}, {});
auto res = import_step_ap242_from_string(data);
EXPECT_TRUE(res.annotations.empty());
}
TEST(IndustrialStepAP242, RoundtripGeometryAndPmiFile) {
auto box = make_test_box();
const char* path = VDE_TEST_TEMP_DIR "test_ap242_roundtrip.stp";
clean(path);
std::vector<StepPMIAnnotation> anns;
StepPMIAnnotation ann;
ann.type = "linear_dimension";
ann.id = "DIM100";
ann.nominal_value = 2.0;
anns.push_back(ann);
export_step_ap242_file(path, {box}, anns);
auto res = import_step_ap242(path);
ASSERT_EQ(res.annotations.size(), 1u);
EXPECT_EQ(res.annotations[0].id, "DIM100");
// 几何也应回读
ASSERT_GE(res.bodies.size(), 1u);
EXPECT_GT(res.bodies[0].num_faces(), 0u);
EXPECT_GT(res.bodies[0].num_vertices(), 0u);
clean(path);
}
// 手工构造的常规 AP242 文件(无 PRODUCT_MANUFACTURING_INFORMATION 容器)
TEST(IndustrialStepAP242, RoundtripLegacyAp242WithoutContainer) {
const char* step = R"(
ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('Test'),'2;1');
FILE_NAME('legacy.stp','',(''),(''),'','');
FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING'));
ENDSEC;
DATA;
#1 = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );
#2 = ( GEOMETRIC_REPRESENTATION_CONTEXT(3) GLOBAL_UNIT_ASSIGNED_CONTEXT((#1)) REPRESENTATION_CONTEXT('Context #1','3D Context') );
#3 = LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(25.0),#1);
#4 = DIMENSIONAL_SIZE('',#3);
#5 = GEOMETRIC_SET_REPRESENTATION('',(),#2);
#6 = SHAPE_DIMENSION_REPRESENTATION('LegacyDim',(#4),(#5));
#7 = FLATNESS_TOLERANCE('LegacyFlat','Flatness check',#8);
#8 = PRODUCT_MANUFACTURING_INFORMATION('F1','Legacy flatness');
ENDSEC;
END-ISO-10303-21;
)";
auto res = import_step_ap242_from_string(step);
// 有 PMI 容器 → 按容器组装(F1),无容器回退仅在 pmi_by_id 为空时触发
ASSERT_GE(res.annotations.size(), 1u);
bool found_flat = false;
for (const auto& a : res.annotations) {
if (a.id == "F1") { EXPECT_EQ(a.type, "flatness"); found_flat = true; }
}
EXPECT_TRUE(found_flat);
}
// ═══════════════════════════════════════════════════════════════
// PDF 3D 测试
// ═══════════════════════════════════════════════════════════════