CADRec / process /StepParser.py
Kang2691196427's picture
Upload 6 files
f7d3a87 verified
Raw
History Blame Contribute Delete
6.73 kB
from OCC.Core.BRepBndLib import brepbndlib
from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.TopAbs import TopAbs_COMPOUND, TopAbs_SOLID, TopAbs_SHELL
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Display.SimpleGui import init_display
from OCC.Core.Quantity import Quantity_Color, Quantity_NOC_RED
from OCC.Core.Quantity import Quantity_TOC_RGB # 颜色类型枚举
from OCC.Core.TopAbs import (TopAbs_COMPOUND, TopAbs_SOLID,
TopAbs_SHELL, TopAbs_FACE,
TopAbs_WIRE, TopAbs_EDGE,
TopAbs_VERTEX)
from OCC.Core.Bnd import Bnd_Box
from OCC.Core.gp import gp_Pnt
import numpy as np
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeEdge
from tqdm import tqdm
class StepParser:
def __init__(self, stepfile):
self.stepfile = stepfile
def analyze_shape(shape):
"""分析形状类型和子组件"""
shape_type = shape.ShapeType()
type_names = {
TopAbs_COMPOUND: "Compound",
TopAbs_SOLID: "Solid",
TopAbs_SHELL: "Shell",
TopAbs_FACE: "Face",
TopAbs_WIRE: "Wire",
TopAbs_EDGE: "Edge",
TopAbs_VERTEX: "Vertex"
}
return type_names.get(shape_type, "Unknown")
def _extract_subshapes(shape, output_list):
"""递归提取子形状"""
shape_type = shape.ShapeType()
#如果是复合体/壳体则展开,否则直接添加
if shape_type in [TopAbs_COMPOUND, TopAbs_SHELL]:
explorer = TopExp_Explorer(shape, TopAbs_SOLID) # 也可扩展其他类型
while explorer.More():
sub_shape = explorer.Current()
output_list.append(sub_shape)
explorer.Next()
else:
output_list.append(shape)
def parse_step_file(file_path, expand_compounds=True):
"""改进的STEP解析函数,支持展开复合体"""
reader = STEPControl_Reader()
reader.ReadFile(file_path)
reader.TransferRoots()
all_shapes = []
for i in range(reader.NbShapes()):
root_shape = reader.Shape(i + 1)
if expand_compounds:
# 递归展开复合体
StepParser._extract_subshapes(root_shape, all_shapes)
else:
all_shapes.append(root_shape)
return all_shapes
def visualize_single_shape(shapes, index=0):
"""交互式单实体可视化"""
# 参数校验
if not 0 <= index < len(shapes):
raise ValueError(f"索引 {index} 超出范围 (0-{len(shapes) - 1})")
# 初始化显示
display, start_display, _, _ = init_display()
display.EraseAll() # 清除之前的内容
# 获取目标实体
target_shape = shapes[index]
# 显示基本信息
shape_type = StepParser.analyze_shape(target_shape)
print(f"正在显示实体 {index}:")
print(f" - 类型: {shape_type}")
# print(f" - 子组件数: {count_subshapes(target_shape)}")
# 显示实体本身(红色高亮)
display.DisplayShape(target_shape, color=Quantity_NOC_RED)
# 显示包围盒(白色线框)
bbox = Bnd_Box()
brepbndlib.Add(target_shape, bbox)
StepParser.display_bounding_box(display, bbox, color="white")
# 自动适配视角
display.FitAll()
start_display()
# 交互式查看函数
def interactive_viewer(shapes):
"""交互式实体查看器"""
while True:
try:
# 显示当前统计信息
print(f"\n当前文件包含 {len(shapes)} 个实体")
print("输入要查看的实体索引 (q退出): ", end="")
# 获取用户输入
user_input = input().strip()
if user_input.lower() == 'q':
break
index = int(user_input)
StepParser.visualize_single_shape(shapes, index)
except ValueError as e:
print(f"错误输入: {e}")
except KeyboardInterrupt:
break
def visualize_shapes(shapes):
"""可视化所有解析出的形状"""
display, start_display, add_menu, add_function = init_display()
# 颜色生成函数
def random_color():
return Quantity_Color(*np.random.rand(3), Quantity_TOC_RGB)
# 递归显示复合体内容
def display_compound(compound, color=None):
explorer = TopExp_Explorer(compound, TopAbs_SOLID)
while explorer.More():
solid = explorer.Current()
display.DisplayShape(solid, color=color or random_color())
explorer.Next()
for idx, shape in enumerate(shapes):
shape_type = StepParser.analyze_shape(shape)
print(f"Shape {idx}: {shape_type}")
try:
# 根据类型处理
if shape_type == "Compound":
display_compound(shape) # 显示复合体内的所有实体
else:
display.DisplayShape(shape, color=random_color())
except Exception as e:
print(f"Error displaying shape {idx}: {str(e)}")
display.FitAll()
start_display()
def display_bounding_box(display, bbox, color="white"):
"""将包围盒转换为线框显示"""
min_corner = bbox.CornerMin()
max_corner = bbox.CornerMax()
# 创建包围盒8个顶点
pnts = [
gp_Pnt(min_corner.X(), min_corner.Y(), min_corner.Z()),
gp_Pnt(max_corner.X(), min_corner.Y(), min_corner.Z()),
gp_Pnt(max_corner.X(), max_corner.Y(), min_corner.Z()),
gp_Pnt(min_corner.X(), max_corner.Y(), min_corner.Z()),
gp_Pnt(min_corner.X(), min_corner.Y(), max_corner.Z()),
gp_Pnt(max_corner.X(), min_corner.Y(), max_corner.Z()),
gp_Pnt(max_corner.X(), max_corner.Y(), max_corner.Z()),
gp_Pnt(min_corner.X(), max_corner.Y(), max_corner.Z())
]
# 创建12条边
edges = []
indices = [(0, 1), (1, 2), (2, 3), (3, 0),
(4, 5), (5, 6), (6, 7), (7, 4),
(0, 4), (1, 5), (2, 6), (3, 7)]
for i, j in indices:
edge = BRepBuilderAPI_MakeEdge(pnts[i], pnts[j]).Edge()
display.DisplayShape(edge, color=color)