def align_planes_byNormal(shp_add, normalDir_base, normalDir_add): """[summary] Arguments: shp_add {topoDS_Shape} -- [description] normalDir_base {gp_Dir} -- [description] normalDir_add {gp_Dir} -- [description] rotateAng [deg]{float} -- [description] """ if not normalDir_base.IsParallel(normalDir_add, radians(0.01)): rotateAxDir = normalDir_base.Crossed(normalDir_add) # determin rotate angle rotRelAng = degrees( normalDir_base.AngleWithRef(normalDir_add, rotateAxDir)) if rotRelAng > 89.99: rotRelAng -= 180 elif rotRelAng < -89.99: rotRelAng += 180 rotateAx1 = gp_Ax1(centerOfMass(shp_add), rotateAxDir) ax3 = gp_Ax3(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)) ax3 = ax3.Rotated(rotateAx1, radians(rotRelAng)) shp2Trsf = gp_Trsf() shp2Trsf.SetTransformation(ax3) shp2Toploc = TopLoc_Location(shp2Trsf) shp_add.Move(shp2Toploc) else: logging.debug("Planes are already parallel to each other")
def match_singleHole(solid_add, solid_base): cyls_sel_base, cyls_sel_add, projPln = selectCylinderFromClosestPln( solid_add, solid_base) pntList_base = [] for i in cyls_sel_base: loc = BRepAdaptor_Surface(i).Cylinder().Location() pnt = gp_Pnt(loc.X(), loc.Y(), loc.Z()) pntList_base.append(pnt) pntList_add = [] for i in cyls_sel_add: loc = BRepAdaptor_Surface(i).Cylinder().Location() pnt = gp_Pnt(loc.X(), loc.Y(), loc.Z()) pntList_add.append(pnt) pntList_base_proj = [ ais_ProjectPointOnPlane(pnt, projPln) for pnt in pntList_base ] pntList_add_proj = [ ais_ProjectPointOnPlane(pnt, projPln) for pnt in pntList_add ] mvVec = get_shortest_vec(pntList_add_proj, pntList_base_proj) trsf = gp_Trsf() trsf.SetTranslation(mvVec) solid_add.Move(TopLoc_Location(trsf))
def simple_mesh(occshape, mesh_incremental_float=0.8): #TODO: figure out why is it that some surfaces do not work occshape = TopoDS_Shape(occshape) bt = BRep_Tool() BRepMesh_IncrementalMesh(occshape, mesh_incremental_float) occshape_face_list = fetch.geom_explorer(occshape, "face") occface_list = [] for occshape_face in occshape_face_list: location = TopLoc_Location() #occshape_face = modify.fix_face(occshape_face) facing = bt.Triangulation(occshape_face, location).GetObject() if facing: tab = facing.Nodes() tri = facing.Triangles() for i in range(1, facing.NbTriangles() + 1): trian = tri.Value(i) index1, index2, index3 = trian.Get() #print index1, index2, index3 pypt1 = fetch.occpt2pypt(tab.Value(index1)) pypt2 = fetch.occpt2pypt(tab.Value(index2)) pypt3 = fetch.occpt2pypt(tab.Value(index3)) #print pypt1, pypt2, pypt3 occface = make_polygon([pypt1, pypt2, pypt3]) occface_list.append(occface) return occface_list
def add_labels(product, lr, st): if product.links: for link in product.links: if link.product.doc_id != product.doc_id: if not link.product.label_reference: lr_2 = TDF_LabelSequence() si = StepImporter(link.product.doc_path) shape_tool = si.shape_tool shape_tool.GetFreeShapes(lr_2) add_labels(link.product, lr_2.Value(1), shape_tool) link.product.label_reference = lr_2.Value(1) # FIXME: free memory del si gc.collect() for d in range(link.quantity): transformation = gp_Trsf() loc = link.locations[d] transformation.SetValues(loc.x1, loc.x2, loc.x3, loc.x4, loc.y1, loc.y2, loc.y3, loc.y4, loc.z1, loc.z2, loc.z3, loc.z4, 1, 1) new_label = st.AddComponent( lr, link.product.label_reference, TopLoc_Location(transformation)) set_label_name(new_label, link.names[d])
def occ_triangle_mesh(event=None): # # Mesh the shape # BRepMesh_IncrementalMesh(aShape, 0.1) builder = BRep_Builder() Comp = TopoDS_Compound() builder.MakeCompound(Comp) ex = TopExp_Explorer(aShape, TopAbs_FACE) while ex.More(): F = topods_Face(ex.Current()) L = TopLoc_Location() facing = (BRep_Tool().Triangulation(F, L)).GetObject() tab = facing.Nodes() tri = facing.Triangles() for i in range(1, facing.NbTriangles() + 1): trian = tri.Value(i) #print trian index1, index2, index3 = trian.Get() for j in range(1, 4): if j == 1: M = index1 N = index2 elif j == 2: N = index3 elif j == 3: M = index2 ME = BRepBuilderAPI_MakeEdge(tab.Value(M), tab.Value(N)) if ME.IsDone(): builder.Add(Comp, ME.Edge()) ex.Next() display.DisplayShape(Comp, update=True)
def wavefront_xyz(x, y, z, axs=gp_Ax3()): phas = surf_spl(x, y, z) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) loc_face = TopLoc_Location(trf) phas.Location(loc_face) return phas
def rotate(shape, axis, angle): tr = gp_Trsf() point = axis[0] vec = axis[1] axis = gp.gp_Ax1(gp.gp_Pnt(*point), gp.gp_Dir(*vec)) tr.SetRotation(axis, angle) loc = TopLoc_Location(tr) return shape.Moved(loc)
def _add_random_cylinder_fired(self, old, new): brep = BRepPrimAPI_MakeCylinder(random.random() * 50, random.random() * 50).Shape() trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(random.random() * 100, random.random() * 100, random.random() * 100)) brep.Move(TopLoc_Location(trsf)) self.shapes.append(brep)
def mv2CMass(shp, pnt): # ipdb.set_trace() # ais_shp2 = frame.display.DisplayShape(shp2, update=True) # the point want to be origin express in local # the local Z axis expressed in local system expressed in global coordinates shp2Trsf = gp_Trsf() vec = gp_Vec(pnt, gp_Pnt(0, 0, 0)) shp2Trsf.SetTranslation(vec) shp2Toploc = TopLoc_Location(shp2Trsf) shp.Move(shp2Toploc) return shp
def glue_solids_edges(event=None): display.EraseAll() display.Context.RemoveAll() # With common edges S3 = BRepPrimAPI_MakeBox(500., 400., 300.).Shape() S4 = BRepPrimAPI_MakeBox(gp_Pnt(0., 0., 300.), gp_Pnt(200., 200., 500.)).Shape() faces_S3 = get_faces(S3) faces_S4 = get_faces(S4) # tagging allows to visually find the right faces to glue tag_faces(faces_S3, "BLUE", "s3") tag_faces(faces_S4, "GREEN", "s4") F3, F4 = faces_S3[5], faces_S4[4] glue2 = BRepFeat_Gluer(S4, S3) glue2.Bind(F4, F3) glue2.Build() shape = glue2.Shape() # move the glued shape, such to be able to inspect input and output # of glueing operation trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(750, 0, 0)) shape.Move(TopLoc_Location(trsf)) common_edges = LocOpe_FindEdges(F4, F3) common_edges.InitIterator() n = 0 while common_edges.More(): edge_from = common_edges.EdgeFrom() edge_to = common_edges.EdgeTo() center_pt_edge_to = center_boundingbox(edge_to) center_pt_edge_from = center_boundingbox(edge_from) red = (1, 0, 0) display.DisplayMessage(center_pt_edge_from, "edge_{0}_from".format(n), message_color=red) display.DisplayMessage(center_pt_edge_to, "edge_{0}_to".format(n), message_color=red) glue2.Bind(edge_from, edge_to) common_edges.Next() n += 1 tag_faces(get_faces(shape), "BLACK", "") display.FitAll()
def rotate_shp(ais_shp): ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) aCubeTrsf = gp_Trsf() angle = 0.0 #tA = time.time() n_rotations = 200 for i in range(n_rotations): aCubeTrsf.SetRotation(ax1, angle) aCubeToploc = TopLoc_Location(aCubeTrsf) display.Context.SetLocation(ais_shp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2 * pi / n_rotations
def wavefront(rxy=[1000, 1000], axs=gp_Ax3()): px = np.linspace(-1, 1, 100) * 10 py = np.linspace(-1, 1, 100) * 10 mesh = np.meshgrid(px, py) rx_0 = curvature(mesh[0], rxy[0], 0) ry_0 = curvature(mesh[1], rxy[1], 0) ph_0 = rx_0 + ry_0 phas = surf_spl(*mesh, ph_0) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) loc_face = TopLoc_Location(trf) phas.Location(loc_face) return phas
def rotating_cube_1_axis(event=None): display.EraseAll() ais_boxshp = build_shape() ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) aCubeTrsf = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): aCubeTrsf.SetRotation(ax1, angle) aCubeToploc = TopLoc_Location(aCubeTrsf) display.Context.SetLocation(ais_boxshp, aCubeToploc) display.Context.UpdateCurrentViewer() angle += 2 * pi / n_rotations print("%i rotations took %f" % (n_rotations, time.time() - tA))
def simple_mesh(): # # Create the shape # shape = BRepPrimAPI_MakeBox(200, 200, 200).Shape() theBox = BRepPrimAPI_MakeBox(200, 60, 60).Shape() theSphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape() shape = BRepAlgoAPI_Fuse(theSphere, theBox).Shape() # # Mesh the shape # BRepMesh_IncrementalMesh(shape, 0.8) builder = BRep_Builder() comp = TopoDS_Compound() builder.MakeCompound(comp) bt = BRep_Tool() ex = TopExp_Explorer(shape, TopAbs_FACE) while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() facing = (bt.Triangulation(face, location)).GetObject() tab = facing.Nodes() tri = facing.Triangles() for i in range(1, facing.NbTriangles()+1): trian = tri.Value(i) index1, index2, index3 = trian.Get() for j in range(1, 4): if j == 1: m = index1 n = index2 elif j == 2: n = index3 elif j == 3: m = index2 me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n)) if me.IsDone(): builder.Add(comp, me.Edge()) ex.Next() display.EraseAll() display.DisplayShape(shape) display.DisplayShape(comp, update=True)
def vstep(step_str): step = int(step_str) positions = dpos_data[nbobjs * step:nbobjs * step + nbobjs, 2:] builder = BRep_Builder() comp = TopoDS_Compound() builder.MakeCompound(comp) for _id in range(positions.shape[0]): q0, q1, q2, q3, q4, q5, q6 = [float(x) for x in positions[_id, :]] obj = obj_by_id[_id + 1] q = Quaternion((q3, q4, q5, q6)) for shape_name, avatar in zip(io.instances()[obj], avatars(obj)): offset = get_offset(obj, shape_name) p = q.rotate(offset[0]) r = q * Quaternion(offset[1]) tr = gp_Trsf() qocc = gp_Quaternion(r[1], r[2], r[3], r[0]) tr.SetRotation(qocc) xyz = gp_XYZ(q0 + p[0], q1 + p[1], q2 + p[2]) vec = gp_Vec(xyz) tr.SetTranslationPart(vec) loc = TopLoc_Location(tr) display.Context.SetLocation(avatar, loc) moved_shape = BRepBuilderAPI_Transform( avatar.GetObject().Shape(), tr, True).Shape() builder.Add(comp, moved_shape) display.Context.UpdateCurrentViewer() write_step((step_str, comp))
def glue_solids(event=None): display.EraseAll() display.Context.RemoveAll() # Without common edges S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.), gp_Pnt(100., 250., 300.)).Shape() facesA = get_faces(S1) tag_faces(facesA, "BLUE", "facesA") # the face to glue F1 = facesA[5] S2 = BRepPrimAPI_MakeBox(gp_Pnt(400., 400., 300.), gp_Pnt(200., 300., 500.)).Shape() facesB = get_faces(S2) tag_faces(facesB, "GREEN", "facesB") # the face to glue of the opposite shape F2 = facesB[4] # perform glueing operation glue1 = BRepFeat_Gluer(S2, S1) glue1.Bind(F2, F1) shape = glue1.Shape() display.SetModeHLR() # move the glued shape, such to be able to inspect input and output # of glueing operation trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(500, 0, 0)) shape.Move(TopLoc_Location(trsf)) tag_faces(get_faces(shape), "BLACK", "") # render glued shape display.DisplayShape(shape) display.FitAll()
def discretize(shape, tol): """This method discretizes the OpenCascade shape. :param shape: Shape to discretize :type shape: :return: discretized face; profile coordinates; id of the surface the\ coordinates belong to :rtype: OCC.TopoDS.TopoDS_Compound; numpy.ndarray; numpy.ndarray """ BRepMesh_IncrementalMesh(shape, tol, False, 5) builder = BRep_Builder() comp = TopoDS_Compound() builder.MakeCompound(comp) bt = BRep_Tool() ex = TopExp_Explorer(shape, TopAbs_EDGE) edge_coords = np.zeros([0, 3]) edge_ids = np.zeros([0], dtype=int) edge_id = 0 while ex.More(): edge = topods_Edge(ex.Current()) location = TopLoc_Location() edging = (bt.Polygon3D(edge, location)).GetObject() tab = edging.Nodes() for i in range(1, edging.NbNodes() + 1): p = tab.Value(i) edge_coords = np.append(edge_coords, [[p.X(), p.Y(), p.Z()]], axis=0) edge_ids = np.append(edge_ids, edge_id) mv = BRepBuilderAPI_MakeVertex(p) if mv.IsDone(): builder.Add(comp, mv.Vertex()) edge_id += 1 ex.Next() edge_coords = np.round(edge_coords, 8) return edge_coords, edge_ids
def getSubShapes(lab, loc): global cnt, lvl cnt += 1 print("\n[%d] level %d, handling LABEL %s\n" % (cnt, lvl, get_label_name(lab))) print() print(lab.DumpToString()) print() print("Is Assembly :", shape_tool.IsAssembly(lab)) print("Is Free :", shape_tool.IsFree(lab)) print("Is Shape :", shape_tool.IsShape(lab)) print("Is Compound :", shape_tool.IsCompound(lab)) print("Is Component :", shape_tool.IsComponent(lab)) print("Is SimpleShape :", shape_tool.IsSimpleShape(lab)) print("Is Reference :", shape_tool.IsReference(lab)) users = TDF_LabelSequence() users_cnt = shape_tool.GetUsers(lab, users) print("Nr Users :", users_cnt) l_subss = TDF_LabelSequence() shape_tool.GetSubShapes(lab, l_subss) print("Nb subshapes :", l_subss.Length()) l_comps = TDF_LabelSequence() shape_tool.GetComponents(lab, l_comps) print("Nb components :", l_comps.Length()) print() if shape_tool.IsAssembly(lab): l_c = TDF_LabelSequence() shape_tool.GetComponents(lab, l_c) for i in range(l_c.Length()): label = l_c.Value(i + 1) if shape_tool.IsReference(label): print("\n######## reference label :", label) label_reference = TDF_Label() shape_tool.GetReferredShape(label, label_reference) loc = shape_tool.GetLocation(label) print(" loc :", loc) trans = loc.Transformation() print(" tran form :", trans.Form()) rot = trans.GetRotation() print(" rotation :", rot) print(" X :", rot.X()) print(" Y :", rot.Y()) print(" Z :", rot.Z()) print(" W :", rot.W()) tran = trans.TranslationPart() print(" translation :", tran) print(" X :", tran.X()) print(" Y :", tran.Y()) print(" Z :", tran.Z()) locs.append(loc) print(">>>>") lvl += 1 getSubShapes(label_reference, loc) lvl -= 1 print("<<<<") locs.pop() elif shape_tool.IsSimpleShape(lab): print("\n######## simpleshape label :", lab) shape = shape_tool.GetShape(lab) print(" all ass locs :", locs) loc = TopLoc_Location() for i in range(len(locs)): print(" take loc :", locs[i]) loc = loc.Multiplied(locs[i]) trans = loc.Transformation() print(" FINAL loc :") print(" tran form :", trans.Form()) rot = trans.GetRotation() print(" rotation :", rot) print(" X :", rot.X()) print(" Y :", rot.Y()) print(" Z :", rot.Z()) print(" W :", rot.W()) tran = trans.TranslationPart() print(" translation :", tran) print(" X :", tran.X()) print(" Y :", tran.Y()) print(" Z :", tran.Z()) shape = BRepBuilderAPI_Transform(shape, loc.Transformation()).Shape() c = Quantity_Color() colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c) for i in range(l_subss.Length()): lab = l_subss.Value(i + 1) print("\n######## simpleshape subshape label :", lab) shape = shape_tool.GetShape(lab) c = Quantity_Color() colorSet = False if (color_tool.GetInstanceColor(shape, 0, c) or color_tool.GetInstanceColor(shape, 1, c) or color_tool.GetInstanceColor(shape, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) colorSet = True n = c.Name(c.Red(), c.Green(), c.Blue()) print(' instance color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) if not colorSet: if (color_tool.GetColor(lab, 0, c) or color_tool.GetColor(lab, 1, c) or color_tool.GetColor(lab, 2, c)): for i in (0, 1, 2): color_tool.SetInstanceColor(shape, i, c) n = c.Name(c.Red(), c.Green(), c.Blue()) print(' shape color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # n = c.Name(c.Red(), c.Green(), c.Blue()) # print(' color Name & RGB: ', c, n, c.Red(), c.Green(), c.Blue()) # Display shape display.DisplayColoredShape(shape, c)
def translate(shape, vector): tr = gp_Trsf() tr.SetTranslation(gp_Vec(*vector)) loc = TopLoc_Location(tr) return shape.Moved(loc)
def __init__(self, file_path, id=None): self.file = file_path.encode("utf-8") self.id = id self.shapes_simples = [] self.main_product = None basename = os.path.basename(self.file) self.fileName = os.path.splitext(basename)[0] self.STEPReader = STEPCAFControl_Reader() if self.STEPReader.ReadFile(self.file) != 1: raise OCCReadingStepError self.h_doc = TDocStd.Handle_TDocStd_Document() self.app = XCAFApp.GetApplication().GetObject() self.app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), self.h_doc) self.STEPReader.Transfer(self.h_doc) self.doc = self.h_doc.GetObject() self.h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_ShapeTool( self.doc.Main()) self.h_colors_tool = XCAFDoc.XCAFDoc_DocumentTool_ColorTool( self.doc.Main()) self.shape_tool = self.h_shape_tool.GetObject() self.color_tool = self.h_colors_tool.GetObject() self.shapes = TDF_LabelSequence() self.shape_tool.GetShapes(self.shapes) for i in range(self.shapes.Length()): shape = self.shapes.Value(i + 1) if self.shape_tool.IsSimpleShape(shape): compShape = self.shape_tool.GetShape(shape) t = Topo(compShape) if t.number_of_vertices() > 0: label = get_label_name(shape) color = find_color(shape, self.color_tool, self.shape_tool) self.shapes_simples.append( SimpleShape(label, compShape, color)) roots = TDF_LabelSequence() self.shape_tool.GetFreeShapes(roots) self.thumbnail_valid = False if roots.Length() == 1: shape = self.shape_tool.GetShape(roots.Value(1)) t = Topo(shape) if t.number_of_vertices() > 0: bbox = Bnd_Box() gap = 0 bbox.SetGap(gap) BRepMesh_Mesh(shape, get_mesh_precision(shape, 1)) faces_iterator = Topo(shape).faces() for F in faces_iterator: face_location = TopLoc_Location() BRep_Tool_Triangulation(F, face_location) BRepBndLib_Add(shape, bbox) x_min, y_min, z_min, x_max, y_max, z_max = bbox.Get() diagonal = max(x_max - x_min, y_max - y_min, z_max - z_min) if diagonal > 0: self.scale = 200. / diagonal self.trans = ((x_max - x_min) / 2. - x_max, (y_max - y_min) / 2. - y_max, (z_max - z_min) / 2. - z_max) self.thumbnail_valid = True ws = self.STEPReader.Reader().WS().GetObject() model = ws.Model().GetObject() model.Clear()
def align_closest_planes(shp, mvVec): shp2Trsf = gp_Trsf() shp2Trsf.SetTranslation(mvVec) shp2Toploc = TopLoc_Location(shp2Trsf) shp.Move(shp2Toploc)
def __init__(self, shape): from OCC.BRep import BRep_Tool from OCC.BRepMesh import BRepMesh_IncrementalMesh from OCC.TopAbs import TopAbs_FACE, TopAbs_VERTEX from OCC.TopExp import TopExp_Explorer from OCC.TopLoc import TopLoc_Location from OCC.TopoDS import topods_Face, topods_Vertex, TopoDS_Iterator vertices = [] # a (nested) list of vec3 triangles = [] # a (flat) list of integers normals = [] uv = [] # Mesh the shape linDeflection = 0.8 BRepMesh_IncrementalMesh(shape, linDeflection) bt = BRep_Tool() # Explore the faces of the shape # each face is triangulated, we need to collect all the parts expFac = TopExp_Explorer(shape, TopAbs_FACE) while expFac.More(): face = topods_Face(expFac.Current()) location = TopLoc_Location() facing = (bt.Triangulation(face, location)).GetObject() try: tri = facing.Triangles() nTri = facing.NbTriangles() ver = facing.Nodes() except: tri = None nTri = None ver = None # store origin of the face's local coordinates transf = face.Location().Transformation() # iterate over triangles and store indices of vertices defining each triangle # OCC uses one-based indexing for i in range(1, nTri + 1): # each triangle is defined by three points # each point is defined by its index in the list of vertices index1, index2, index3 = tri.Value(i).Get() indices = [index1, index2, index3] # python uses zero-based indexing # for each vertex of a triangle, check whether it is already known # then store it (or not) and update the index for idx in [0, 1, 2]: # read global coordinates of each point vec3 = [ ver.Value(indices[idx]).Transformed(transf).X(), ver.Value(indices[idx]).Transformed(transf).Y(), ver.Value(indices[idx]).Transformed(transf).Z() ] if vec3 not in vertices: vertices.append(vec3) indices[idx] = vertices.index(vec3) triangles.extend(indices) expFac.Next() self.shape = shape self.vertices = vertices self.triangles = triangles self.normals = normals self.uv = uv
def surf_trf (axs, face): trf = gp_Trsf() trf.SetTransformation (axs, gp_Ax3()) srf = face.Moved (TopLoc_Location (trf)) return srf
def surf_trf(pnt, vec, face): axs = gp_Ax3(pnt, vec_to_dir(vec)) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) srf = face.Moved(TopLoc_Location(trf)) return srf
def align_mutiHoles(shp, matched_hole_pairs): # matching points pntsA = [i[0].projLocation for i in matched_hole_pairs] pntsB = [i[1].projLocation for i in matched_hole_pairs] normal = gp_Vec(matched_hole_pairs[0][1].direction) pntsA_noDuplicates = list(set(pntsA)) pntsB_noDuplicates = list(set(pntsB)) if len(pntsA_noDuplicates) != len(pntsA) or len(pntsB_noDuplicates) != len( pntsB): logging.warn( "[WARN] There are duplicated pairs(i.e. [A,B], [B, A]) in the given matched_hole_pairs" ) assert len(pntsA_noDuplicates) == len( pntsB_noDuplicates), "[Error] data are not pairwise" assert len(pntsA_noDuplicates) >= 2 or len( pntsB_noDuplicates ) >= 2, "[FATEL] input hole pairs should be more than 2" # Create the 3rd point on the project plane in the perpandicular diretion from the 1st to the 2nd point # [TODO] More test # Now 3rd point was added in the middle, so there will be sysmetry problem? if (len(pntsA_noDuplicates) == 2 and len(pntsB_noDuplicates) == 2): logging.warn( "[WARN] only 2 hole pairs found, add a dummpy pair to constrain rotating along the normal project plane" ) # distance between two points, which is used as a scale dist = pntsA_noDuplicates[0].Distance(pntsA_noDuplicates[1]) / 2.0 vecA = gp_Vec(pntsA_noDuplicates[0], pntsA_noDuplicates[1]) # Translation vector from orignal mid-points to the 3rd point(dummy points) translateVecA = vecA.Crossed(normal).Normalized().Scaled(dist) dummyPntA = centerOfMass_pnts(pntsA_noDuplicates).Translated( translateVecA) pntsA_noDuplicates.append(dummyPntA) vecB = gp_Vec(pntsB_noDuplicates[0], pntsB_noDuplicates[1]) translateVecB = vecB.Crossed(normal).Normalized().Scaled(dist) dummyPntB = centerOfMass_pnts(pntsB_noDuplicates).Translated( translateVecB) pntsB_noDuplicates.append(dummyPntB) # center of Mass cenA = centerOfMass_pnts(pntsA_noDuplicates) cenB = centerOfMass_pnts(pntsB_noDuplicates) # translation vector from centerOfMass to origin mvVecA2O = gp_Vec(cenA, gp_Pnt(0, 0, 0)) mvVecB2O = gp_Vec(cenB, gp_Pnt(0, 0, 0)) # translate all points, with rigid movement to move solid's center of Mass to origin newPntsA = [i.Translated(mvVecA2O) for i in pntsA_noDuplicates] newPntsB = [i.Translated(mvVecB2O) for i in pntsB_noDuplicates] if newPntsB[1].X() * newPntsA[1].X() < 0: ttmp = newPntsB[0] newPntsB[0] = newPntsB[1] newPntsB[1] = ttmp # matching 2 points set by SVD, transform from B to A npMatA = [gpVec2npMat((gp_Vec(gp_Pnt(0, 0, 0), i))) for i in newPntsA] npMatB = [gpVec2npMat(gp_Vec(gp_Pnt(0, 0, 0), i)) for i in newPntsB] varMat = np.asmatrix(np.zeros((3, 3))) for i in range(0, len(npMatA)): varMat += npMatB[i] * npMatA[i].transpose() linAlg = np.linalg U, s, Vh = linAlg.svd(varMat, full_matrices=True) R = Vh.transpose() * U.transpose() # if R has determinant -1, then R is a rotation plus a reflection if linAlg.det(R) < 0: # [ToDo] Don't know why third column or row should multiply -1 reverseMat = np.matrix([(1, 0, 0), (0, 1, 0), (0, 0, -1)]) logging.info('det(R) is < 0, change the sign of last column of Vh') R = reverseMat * (Vh.transpose()) * U.transpose() # q = quaternion_from_matrix(R) R = np.array(R) RgpMat = gp_Mat(R[0][0], R[0][1], R[0][2], R[1][0], R[1][1], R[1][2], R[2][0], R[2][1], R[2][2]) # RgpMat = gp_Mat(gp_XYZ(R[0][0], R[1][0], R[2][0]), gp_XYZ(R[0][1], R[1][1], R[2][1]), gp_XYZ(R[0][2], R[1][2], R[2][2])) q = gp_Quaternion(RgpMat) # gp_Extrinsic_XYZ = 2 # q.GetEulerAngles(2) # qq = gp_Quaternion() # qq.SetVectorAndAngle(gp_Vec(gp_Dir(gp_XYZ(0,0,1))), q.GetEulerAngles(2)[2]) trsf = gp_Trsf() trsf.SetTranslation(mvVecB2O) toploc = TopLoc_Location(trsf) shp.Move(toploc) trsf = gp_Trsf() trsf.SetRotation(q) toploc = TopLoc_Location(trsf) shp.Move(toploc) trsf = gp_Trsf() trsf.SetTranslation(mvVecA2O.Reversed()) toploc = TopLoc_Location(trsf) shp.Move(toploc)
def setTranslation(self): """ Creates an axis in x, y or z depending on user preference. gp_Ax1 describes an axis in 3D space. An axis is defined by a point (gp_Pnt) and a direction (gp_Dir) reference @return None """ if self._exceptionCatch(): return rotataxis_index_combo = self.op_viewer.ui_shape_rotataxis_combo.currentIndex( ) if self.op_viewer.ui_shape_rotataxis_combo.currentText() == "Z": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0, 0, 1)) elif self.op_viewer.ui_shape_rotataxis_combo.currentText() == "Y": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0, 1, 0)) elif self.op_viewer.ui_shape_rotataxis_combo.currentText() == "X": ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(1, 0, 0)) # Retrieve the displacements set by user x = float(self.op_viewer.ui_shape_xdispl_dspn.value()) y = float(self.op_viewer.ui_shape_ydispl_dspn.value()) z = float(self.op_viewer.ui_shape_zdispl_dspn.value()) teta = float(self.op_viewer.ui_shape_tetarotat_dspn.value()) * pi / 180 # creates objects of shape transformation (Returns the identity transformation), # one for axial and other for x, y, z coordinates transf_teta = gp_Trsf() transf_xyz = gp_Trsf() transf_teta.SetRotation(ax1, teta) transf_xyz.SetTranslation(gp_Vec(x, y, z)) # Calculates the transformation matrix with respect of both transformations. transf_matrix = transf_xyz * transf_teta # Constructs an local coordinate system object. Note: A Location constructed from a default datum is said # to be "empty". # ref: https://www.opencascade.com/doc/occt-6.9.1/refman/html/class_top_loc___location.html cube_toploc = TopLoc_Location(transf_matrix) # Then applies the local coordinate to the current shape for i in range(0, len(self.op_viewer.current_h_ais_shape)): self.op_viewer.display.Context.SetLocation( self.op_viewer.current_h_ais_shape[i], cube_toploc) if self.op_viewer.selectionMode == "surf": # If the selected items is the majority of the list, then the property is set to the whole Case if self.op_viewer.ui_subcase_list.count() / 2 < len( self.op_viewer.ui_subcase_list.selectedIndexes()): self.op_viewer.case_node.setShapeTransformation(x, 0) self.op_viewer.case_node.setShapeTransformation(y, 1) self.op_viewer.case_node.setShapeTransformation(z, 2) self.op_viewer.case_node.setShapeTransformation( teta / pi * 180, 3) self.op_viewer.case_node.setShapeTransformation( rotataxis_index_combo, 4) for i in range( 0, len(self.op_viewer.ui_subcase_list.selectedIndexes())): index = self.op_viewer.ui_subcase_list.selectedIndexes()[i] self.op_viewer.case_node.subshape[index.row()][0] = [ x, y, z, teta / pi * 180, rotataxis_index_combo ] if self.op_viewer.selectionMode == "shape": for i in range(0, len(self.op_viewer.case_node.subshape)): self.op_viewer.case_node.subshape[i][0][0] = x self.op_viewer.case_node.subshape[i][0][1] = y self.op_viewer.case_node.subshape[i][0][2] = z self.op_viewer.case_node.subshape[i][0][3] = teta / pi * 180 self.op_viewer.case_node.subshape[i][0][ 4] = rotataxis_index_combo self.op_viewer.display.Context.UpdateCurrentViewer() return
def location_from_vector(x, y, z): trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(500, 0, 0)) loc = TopLoc_Location(trsf) return loc
def _write_faces(self, output, pov_file, identifier): """ Triangulates all faces and writes them to *output* (javascript) and *pov_file* (POVRay). """ BRepMesh_Mesh(self.topo_shape, self._precision) _points = kjDict() faces_iterator = Topo(self.topo_shape).faces() index = 0 for F in faces_iterator: face_location = TopLoc_Location() triangulation = BRep_Tool_Triangulation(F, face_location) if triangulation.IsNull() == False: facing = triangulation.GetObject() tab = facing.Nodes() tri = facing.Triangles() the_normal = TColgp_Array1OfDir(tab.Lower(), tab.Upper()) StdPrs_ToolShadedShape_Normal(F, Poly_Connect(facing.GetHandle()), the_normal) for i in range(1, facing.NbTriangles() + 1): trian = tri.Value(i) if F.Orientation() == TopAbs_REVERSED: index1, index3, index2 = trian.Get() else: index1, index2, index3 = trian.Get() P1 = tab.Value(index1).Transformed( face_location.Transformation()) P2 = tab.Value(index2).Transformed( face_location.Transformation()) P3 = tab.Value(index3).Transformed( face_location.Transformation()) p1_coord = P1.XYZ().Coord() p2_coord = P2.XYZ().Coord() p3_coord = P3.XYZ().Coord() if self._triangle_is_valid(P1, P2, P3): for point in (p1_coord, p2_coord, p3_coord): if not _points.has_key(point): _points.add(point, index) output.write( vertice_fmt % (identifier, point[0], point[1], point[2])) index += 1 n1 = the_normal(index1) n2 = the_normal(index2) n3 = the_normal(index2) output.write(face_fmt % ( identifier, _points.neighbors(p1_coord)[0], _points.neighbors(p2_coord)[0], _points.neighbors(p3_coord)[0], n1.X(), n1.Y(), n1.Z(), n2.X(), n2.Y(), n2.Z(), n3.X(), n3.Y(), n3.Z(), )) pov_file.write(triangle_fmt % ( p1_coord[0], p1_coord[1], p1_coord[2], n1.X(), n1.Y(), n1.Z(), p2_coord[0], p2_coord[1], p2_coord[2], n2.X(), n2.Y(), n2.Z(), p3_coord[0], p3_coord[1], p3_coord[2], n3.X(), n3.Y(), n3.Z(), )) self.triangle_count += 1