52 lines
2.4 KiB
Python
52 lines
2.4 KiB
Python
"""Export only round-trip verified solids, including offset spline surfaces."""
|
|
from pathlib import Path
|
|
|
|
from build123d import Part, export_step, export_stl, import_step
|
|
|
|
|
|
def _check_roundtrip(source, restored):
|
|
solids = restored.solids()
|
|
if not solids or len(solids) != len(source.solids()) or not restored.is_valid or any(not s.is_valid for s in solids):
|
|
raise ValueError("STEP 回读后实体缺失或无效")
|
|
if abs(restored.volume - source.volume) > max(0.01, abs(source.volume) * 0.001):
|
|
raise ValueError("STEP 回读体积与原实体不一致")
|
|
before, after = source.bounding_box(), restored.bounding_box()
|
|
if any(abs(a - b) > 0.02 for a, b in zip((*before.min, *before.max), (*after.min, *after.max))):
|
|
raise ValueError("STEP 回读包络与原实体不一致")
|
|
|
|
|
|
def export_verified(shape, step_path, stl_path):
|
|
"""OCCT can silently omit offset surfaces; convert their representation on failure.
|
|
|
|
NURBS conversion preserves the modeled surfaces, rather than replacing them
|
|
with a mesh or redesigning the part. Always check the converted file against
|
|
the original solid, not just against the intermediate conversion.
|
|
"""
|
|
step_path, stl_path = Path(step_path), Path(stl_path)
|
|
temporary_step = step_path.with_name(step_path.stem + '.checking.step')
|
|
temporary_stl = stl_path.with_name(stl_path.stem + '.checking.stl')
|
|
mode = 'native'
|
|
try:
|
|
try:
|
|
export_step(shape, str(temporary_step))
|
|
_check_roundtrip(shape, import_step(str(temporary_step)))
|
|
except Exception:
|
|
from OCP.BRepBuilderAPI import BRepBuilderAPI_NurbsConvert
|
|
converted = Part(BRepBuilderAPI_NurbsConvert(shape.wrapped, True).Shape())
|
|
converted.label = shape.label
|
|
export_step(converted, str(temporary_step))
|
|
_check_roundtrip(shape, import_step(str(temporary_step)))
|
|
mode = 'nurbs'
|
|
from .meshing import ensure_mesh
|
|
ensure_mesh(shape, .001, .1)
|
|
if not export_stl(shape, str(temporary_stl)):
|
|
raise ValueError('STL 导出失败')
|
|
temporary_step.replace(step_path)
|
|
temporary_stl.replace(stl_path)
|
|
return {'step_roundtrip_valid': True, 'surface_representation': mode}
|
|
except Exception as exc:
|
|
raise ValueError(f'EXPORT_VALIDATION_FAILED: {exc}') from exc
|
|
finally:
|
|
temporary_step.unlink(missing_ok=True)
|
|
temporary_stl.unlink(missing_ok=True)
|