61 lines
2.7 KiB
Python
61 lines
2.7 KiB
Python
"""Measure the supplied STEP and export its exact surface as an STL in metres."""
|
|
import json
|
|
from pathlib import Path
|
|
from project_paths import configured_path
|
|
from OCP.STEPControl import STEPControl_Reader
|
|
from OCP.Bnd import Bnd_Box
|
|
from OCP.BRepBndLib import BRepBndLib
|
|
from OCP.BRepGProp import BRepGProp
|
|
from OCP.GProp import GProp_GProps
|
|
from OCP.TopExp import TopExp_Explorer
|
|
from OCP.TopAbs import TopAbs_FACE
|
|
from OCP.TopoDS import TopoDS
|
|
from OCP.BRepAdaptor import BRepAdaptor_Surface
|
|
from OCP.GeomAbs import GeomAbs_Plane, GeomAbs_Cylinder
|
|
from OCP.gp import gp_Trsf, gp_Pnt
|
|
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
|
|
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
|
from OCP.StlAPI import StlAPI_Writer
|
|
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
SOURCE=configured_path('HAND_ADAPTER_STEP', 'external/hand_adapter.STEP')
|
|
|
|
|
|
def limits(box):
|
|
a,b=box.CornerMin(),box.CornerMax()
|
|
return [a.X(),a.Y(),a.Z(),b.X(),b.Y(),b.Z()]
|
|
|
|
|
|
def main():
|
|
dest=ROOT/'assets/hand_adapter';dest.mkdir(exist_ok=True)
|
|
reader=STEPControl_Reader()
|
|
if int(reader.ReadFile(str(SOURCE)))!=1:raise RuntimeError('STEP read failed')
|
|
reader.TransferRoots();shape=reader.OneShape()
|
|
box=Bnd_Box();BRepBndLib.Add_s(shape,box)
|
|
planes=[];cylinders=[];exp=TopExp_Explorer(shape,TopAbs_FACE)
|
|
while exp.More():
|
|
face=TopoDS.Face(exp.Current());surface=BRepAdaptor_Surface(face)
|
|
if surface.GetType()==GeomAbs_Cylinder:
|
|
cylinder=surface.Cylinder();p=cylinder.Location();n=cylinder.Axis().Direction()
|
|
bounds=Bnd_Box();BRepBndLib.Add_s(face,bounds)
|
|
cylinders.append({'radius_mm':cylinder.Radius(),'point_mm':[p.X(),p.Y(),p.Z()],
|
|
'axis':[n.X(),n.Y(),n.Z()],'bbox_mm':limits(bounds)})
|
|
if surface.GetType()==GeomAbs_Plane:
|
|
plane=surface.Plane();p=plane.Location();n=plane.Axis().Direction()
|
|
props=GProp_GProps();BRepGProp.SurfaceProperties_s(face,props)
|
|
planes.append({'area_mm2':props.Mass(),'point_mm':[p.X(),p.Y(),p.Z()],
|
|
'normal':[n.X(),n.Y(),n.Z()]})
|
|
exp.Next()
|
|
planes.sort(key=lambda p:-p['area_mm2'])
|
|
scale=gp_Trsf();scale.SetScale(gp_Pnt(0,0,0),.001)
|
|
metric=BRepBuilderAPI_Transform(shape,scale,True).Shape()
|
|
BRepMesh_IncrementalMesh(metric,.00005,False,.2,True)
|
|
if not StlAPI_Writer().Write(metric,str(dest/'adapter_m.stl')):raise RuntimeError('STL export failed')
|
|
info={'source':str(SOURCE),'bbox_mm':limits(box),'largest_planes':planes[:12], 'cylinders':cylinders,
|
|
'mesh_units':'m','assembly_transform_verified':False}
|
|
(dest/'cad_measurements.json').write_text(json.dumps(info,indent=2))
|
|
print(json.dumps(info,indent=2))
|
|
|
|
|
|
if __name__=='__main__':main()
|