def rotate(self, x=0.0, y=0.0, z=0.0): trsf = gp_Trsf() if (x != 0.0): axx = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(1., 0., 0.)) a_trsf1 = gp_Trsf() a_trsf1.SetRotation(axx, math.radians(x)) #trsf = trsf*a_trsf1 trsf = a_trsf1 * trsf if (y != 0.0): axy = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.)) a_trsf2 = gp_Trsf() a_trsf2.SetRotation(axy, math.radians(y)) #trsf = trsf*a_trsf2 trsf = a_trsf2 * trsf if (z != 0.0): axz = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) a_trsf3 = gp_Trsf() a_trsf3.SetRotation(axz, math.radians(z)) #trsf = trsf*a_trsf3 trsf = a_trsf3 * trsf for c in self.children: c.propagate_trsf(trsf)
def euler_to_gp_trsf(euler_zxz=None, unit="deg"): """ returns a rotation-only gp_Trsf given Euler angles :param euler_zxz: a list of three intrinsic Euler angles in zxz-convention :param unit: If "deg", the euler angles are in degrees, otherwise radians :return: A rotation-only gp_Trsf """ if euler_zxz is None: euler_zxz = [0, 0, 0] if unit == "deg": # convert angle to radians euler_zxz = [radians(a) for a in euler_zxz] x = gp_Ax1(gp_Pnt(), gp_Dir(1, 0, 0)) z = gp_Ax1(gp_Pnt(), gp_Dir(0, 0, 1)) trns = gp_Trsf() trns.SetRotation(z, euler_zxz[2]) trns_next = gp_Trsf() trns_next.SetRotation(x, euler_zxz[1]) trns = trns *trns_next trns_next = gp_Trsf() trns_next.SetRotation(z, euler_zxz[0]) return trns *trns_next
def htransform2(tpnt, tvx, tvy, tvz, pnt, vx, vy, vz): tvx = tvy.Crossed(tvz) tvy = tvz.Crossed(tvx) tvx.Normalize() tvy.Normalize() tvz.Normalize() tpnt = gp_Pnt((gp_Vec(tpnt.XYZ()) + tvz * 0.1).XYZ()) vx = vy.Crossed(vz) vy = vz.Crossed(vx) vx.Normalize() vy.Normalize() vz.Normalize() Tt = gp_GTrsf( gp_Mat(tvx.X(), tvy.X(), tvz.X(), tvx.Y(), tvy.Y(), tvz.Y(), tvx.Z(), tvy.Z(), tvz.Z()), gp_XYZ(tpnt.X(), tpnt.Y(), tpnt.Z())) Tt.Invert() rott = gp_Mat(tvx.X(), tvy.X(), tvz.X(), tvx.Y(), tvy.Y(), tvz.Y(), tvx.Z(), tvy.Z(), tvz.Z()) rott.Transpose() quatt = gp_Quaternion(rott) dispt = gp_Vec(Tt.TranslationPart().X(), Tt.TranslationPart().Y(), Tt.TranslationPart().Z()) trsft = gp_Trsf() trsft.SetTransformation(quatt, dispt) rotp = gp_Mat(vx.X(), vy.X(), vz.X(), vx.Y(), vy.Y(), vz.Y(), vx.Z(), vy.Z(), vz.Z()) quatp = gp_Quaternion(rotp) dispp = gp_Vec(gp_Pnt(0, 0, 0), pnt) trsfp = gp_Trsf() trsfp.SetTransformation(quatp, dispp) trsfo = trsfp.Multiplied(trsft) loco = TopLoc_Location(trsfo) return loco
def __init__(self, matrix=None): if matrix is None: self.wrapped = gp_Trsf() elif isinstance(matrix, gp_Trsf): self.wrapped = matrix elif isinstance(matrix, (list, tuple)): # Validate matrix size & 4x4 last row value valid_sizes = all( (isinstance(row, (list, tuple)) and (len(row) == 4)) for row in matrix) and len(matrix) in (3, 4) if not valid_sizes: raise TypeError( "Matrix constructor requires 2d list of 4x3 or 4x4, but got: {!r}" .format(matrix)) elif (len(matrix) == 4) and (tuple(matrix[3]) != (0, 0, 0, 1)): raise ValueError( "Expected the last row to be [0,0,0,1], but got: {!r}". format(matrix[3])) # Assign values to matrix self.wrapped = gp_Trsf() flattened = [e for row in matrix[:3] for e in row] self.wrapped.SetValues(*flattened) else: raise TypeError( "Invalid param to matrix constructor: {}".format(matrix))
def _calcTransforms(self): """Computes transformation matrices to convert between coordinates Computes transformation matrices to convert between local and global coordinates. """ # r is the forward transformation matrix from world to local coordinates # ok i will be really honest, i cannot understand exactly why this works # something bout the order of the translation and the rotation. # the double-inverting is strange, and I don't understand it. forward = Matrix() inverse = Matrix() forwardT = gp_Trsf() inverseT = gp_Trsf() global_coord_system = gp_Ax3() local_coord_system = gp_Ax3( gp_Pnt(*self.origin.toTuple()), gp_Dir(*self.zDir.toTuple()), gp_Dir(*self.xDir.toTuple()), ) forwardT.SetTransformation(global_coord_system, local_coord_system) forward.wrapped = gp_GTrsf(forwardT) inverseT.SetTransformation(local_coord_system, global_coord_system) inverse.wrapped = gp_GTrsf(inverseT) # TODO verify if this is OK self.lcs = local_coord_system self.rG = inverse self.fG = forward
def filling(self, name_body, coord_centres, coord_centres_2): ''' :param name_body: :param coord_centres: 0 - угол поворота x (градусы) 1 - угол поворота y (градусы) 2 - угол поворота z (градусы) 3 - смещенмие по x 4 - смещенмие по y 5 - смещенмие по z :return: ''' # print(name_body, coord_centres) # shape = self.modules[name_body] # print(body) cp = BRepBuilderAPI_Copy(self.reserv_models[name_body]) cp.Perform(self.reserv_models[name_body]) shape = cp.Shape() # print(shape) r = R.from_euler( 'xyz', [coord_centres[0], coord_centres[1], coord_centres[2]], degrees=True) Rot = r.as_dcm() trsf = gp_Trsf() Mat = gp_Mat(Rot[0][0], Rot[0][1], Rot[0][2], Rot[1][0], Rot[1][1], Rot[1][2], Rot[2][0], Rot[2][1], Rot[2][2]) trsf.SetRotation(gp_Quaternion(Mat)) shape.Move(TopLoc_Location(trsf)) r = R.from_euler( 'xyz', [coord_centres_2[0], coord_centres_2[1], coord_centres_2[2]], degrees=True) Rot = r.as_dcm() trsf = gp_Trsf() Mat = gp_Mat(Rot[0][0], Rot[0][1], Rot[0][2], Rot[1][0], Rot[1][1], Rot[1][2], Rot[2][0], Rot[2][1], Rot[2][2]) trsf.SetRotation(gp_Quaternion(Mat)) shape.Move(TopLoc_Location(trsf)) trsf = gp_Trsf() trsf.SetTranslation( gp_Vec(coord_centres[3], coord_centres[4], coord_centres[5])) shape.Move(TopLoc_Location(trsf)) self.modules[name_body] = shape
def create_section_box(self): top_left_corner = gp.gp_Pnt( self.section_box["top_left_corner"][0], self.section_box["top_left_corner"][1], self.section_box["top_left_corner"][2], ) axis = gp.gp_Ax2( top_left_corner, gp.gp_Dir( self.section_box["projection"][0], self.section_box["projection"][1], self.section_box["projection"][2] ), gp.gp_Dir(self.section_box["x_axis"][0], self.section_box["x_axis"][1], self.section_box["x_axis"][2]), ) section_box = BRepPrimAPI.BRepPrimAPI_MakeBox( axis, self.section_box["x"], self.section_box["y"], self.section_box["z"] ) self.section_box["shape"] = section_box.Shape() self.section_box["face"] = section_box.BottomFace() source = gp.gp_Ax3(axis) self.transformation_data = { "top_left_corner": self.section_box["top_left_corner"], "projection": self.section_box["projection"], "x_axis": self.section_box["x_axis"], } destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1), gp.gp_Dir(1, 0, 0)) self.transformation_dest = destination self.transformation = gp.gp_Trsf() self.transformation.SetDisplacement(source, destination)
def create_section_box(self): top_left_corner = gp.gp_Pnt(self.section_box['top_left_corner'][0], self.section_box['top_left_corner'][1], self.section_box['top_left_corner'][2]) axis = gp.gp_Ax2( top_left_corner, gp.gp_Dir(self.section_box['projection'][0], self.section_box['projection'][1], self.section_box['projection'][2]), gp.gp_Dir(self.section_box['x_axis'][0], self.section_box['x_axis'][1], self.section_box['x_axis'][2])) section_box = BRepPrimAPI.BRepPrimAPI_MakeBox(axis, self.section_box['x'], self.section_box['y'], self.section_box['z']) self.section_box['shape'] = section_box.Shape() self.section_box['face'] = section_box.BottomFace() source = gp.gp_Ax3(axis) self.transformation_data = { 'top_left_corner': self.section_box['top_left_corner'], 'projection': self.section_box['projection'], 'x_axis': self.section_box['x_axis'] } destination = gp.gp_Ax3(gp.gp_Pnt(0, 0, 0), gp.gp_Dir(0, 0, -1), gp.gp_Dir(1, 0, 0)) self.transformation_dest = destination self.transformation = gp.gp_Trsf() self.transformation.SetDisplacement(source, destination)
def utilGetZRotatedShape(aShape, angle): aTransform = gp_Trsf() rotationAxis = gp_OZ() aTransform.SetRotation(rotationAxis, angle) rotatedShape = BRepBuilderAPI_Transform(aShape, aTransform).Shape() return rotatedShape
def move(orig_pypt, location_pypt, occtopology): """ This function moves an OCCtopology from the orig_pypt to the location_pypt. Parameters ---------- orig_pypt : tuple of floats The OCCtopology will move in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) location_pypt : tuple of floats The destination of where the OCCtopology will be moved in relation to the orig_pypt. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) occtopology : OCCtopology The OCCtopology to be moved. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex Returns ------- moved topology : OCCtopology (OCCshape) The moved OCCtopology. """ gp_ax31 = gp_Ax3(gp_Pnt(orig_pypt[0], orig_pypt[1], orig_pypt[2]), gp_DZ()) gp_ax32 = gp_Ax3( gp_Pnt(location_pypt[0], location_pypt[1], location_pypt[2]), gp_DZ()) aTrsf = gp_Trsf() aTrsf.SetTransformation(gp_ax32, gp_ax31) trsf_brep = BRepBuilderAPI_Transform(aTrsf) trsf_brep.Perform(occtopology, True) trsf_shp = trsf_brep.Shape() return trsf_shp
def scale(occtopology, scale_factor, ref_pypt): """ This function uniformly scales an OCCtopology based on the reference point and the scale factor. Parameters ---------- occtopology : OCCtopology The OCCtopology to be scaled. OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex scale_factor : float The scale factor. ref_pypt : tuple of floats The OCCtopology will scale in reference to this point. A pypt is a tuple that documents the xyz coordinates of a pt e.g. (x,y,z) Returns ------- scaled topology : OCCtopology (OCCshape) The scaled OCCtopology. """ xform = gp_Trsf() gp_pnt = construct.make_gppnt(ref_pypt) xform.SetScale(gp_pnt, scale_factor) brep = BRepBuilderAPI_Transform(xform) brep.Perform(occtopology, True) trsfshape = brep.Shape() return trsfshape
def Transform(ax0=gp_Ax3(), ax1=gp_Ax3(), shape=[]): trf = gp_Trsf() trf.SetTransformation(ax1, ax0) loc_face = TopLoc_Location(trf) for shp in shape: shp.Location(loc_face)
def _rotate(self, direction, angle): new = gp_Trsf() new.SetRotation(direction, angle) self.wrapped = self.wrapped * new
def __init__(self, shape): self.trsf = gp_Trsf() self.shape = shape self.shape_color = Noval self.display_mode = DISP_MODE_NONE self.style = "main" self.hidden = False
def mergeMove(aItemMove, aSuperMove): ret = Move() ret.aTrsf = gp_Trsf() ret.aTrsf *= aItemMove.aTrsf ret.aTrsf *= aSuperMove.aTrsf ret.aLayer = _getValue(aItemMove.aLayer, aSuperMove.aLayer) return ret
def translate(self, vector, elements=(), copy=False, make_groups=False, target_mesh=None): """ Translate the elements. :param vector_like vector: The translation vector. :param collection.Sequence(afem.smesh.entities.Element) elements: The elements to transform. If none are provided then the whole mesh is used. :param bool copy: Option to copy elements. :param bool make_groups: Option to make groups. :param afem.smesh.entities.Mesh target_mesh: The target mesh to place elements. :return: List of element ID's. :rtype: list(int) """ vector = CheckGeom.to_vector(vector) trsf = gp_Trsf() trsf.SetTranslation(vector) return self.transform(trsf, elements, copy, make_groups, target_mesh)
def clone_tooth(base_shape): clone = gp_Trsf() grouped_shape = base_shape # Find a divisor, between 1 and 8, for the number_of teeth multiplier = 1 max_multiplier = 1 for i in range(0, 8): if num_teeth % multiplier == 0: max_multiplier = i + 1 multiplier = max_multiplier for i in range(1, multiplier): clone.SetRotation(gp_OZ(), -i * tooth_angle) rotated_shape = BRepBuilderAPI_Transform(base_shape, clone, True).Shape() grouped_shape = BRepAlgoAPI_Fuse(grouped_shape, rotated_shape).Shape() # Rotate the basic tooth and fuse together aggregated_shape = grouped_shape for i in range(1, int(num_teeth / multiplier)): clone.SetRotation(gp_OZ(), - i * multiplier * tooth_angle) rotated_shape = BRepBuilderAPI_Transform(grouped_shape, clone, True).Shape() aggregated_shape = BRepAlgoAPI_Fuse(aggregated_shape, rotated_shape).Shape() cylinder = BRepPrimAPI_MakeCylinder(gp_XOY(), top_radius - roller_diameter, thickness) aggregated_shape = BRepAlgoAPI_Fuse(aggregated_shape, cylinder.Shape()).Shape() return aggregated_shape
def face_rotate(self, face=TopoDS_Face(), axs=gp_Ax1()): plan = self.pln_on_face(face) plan_axs = plan.Position() pln_angle = self.tmp_axis.Angle(plan_axs) ref_angle = self.tmp_axis.Direction().AngleWithRef( plan_axs.Direction(), axs.Direction()) print(np.rad2deg(pln_angle), np.rad2deg(ref_angle)) trf = gp_Trsf() if np.abs(ref_angle) >= np.pi / 2: trf.SetRotation(axs, -ref_angle) elif 0 < ref_angle < np.pi / 2: trf.SetRotation(axs, np.pi - ref_angle) elif -np.pi / 2 < ref_angle < 0: trf.SetRotation(axs, -ref_angle - np.pi) else: trf.SetRotation(axs, -ref_angle) #trf.SetTransformation(axs3.Rotated(axs, angle), axs3) loc_face = TopLoc_Location(trf) new_face = face.Located(loc_face) # self.sol_builder.Add(new_face) self.face_lst.Append(new_face) # face.Location(loc_face) if self.show == True: self.display.DisplayShape(new_face) return new_face
def face_tranfer(self, face=TopoDS_Face(), axs=gp_Ax1()): axs_3 = gp_Ax3(axs.Location(), axs.Direction()) trf = gp_Trsf() trf.SetTransformation(axs_3, self.tmp_axs3) loc_face = TopLoc_Location(trf) face.Location(loc_face) return face
def generate_tool_targets(self): ba = BRepAdaptor_Curve(self.helix_edge) u_min = ba.FirstParameter() u_max = ba.LastParameter() u_step = 0.1 u_now = u_min while u_now <= u_max: v_contact = gp_Vec(ba.Value(u_now).XYZ()) if self.inside: # cut inside v_contact_to_ball_center = -gp_Vec(v_contact.X(),v_contact.Y(),0).Normalized()*self.ball_radius else: # cut outside v_contact_to_ball_center = gp_Vec(v_contact.X(),v_contact.Y(),0).Normalized()*self.ball_radius trsf = gp_Trsf() trsf.SetRotation(gp_Ax1(gp_Pnt(0,0,0),gp_Dir(0,0,1)),pi/2) v_rotation_axis = v_contact_to_ball_center.Transformed(trsf) trsf.SetRotation(gp_Ax1(gp_Pnt(0,0,0),gp_Dir(v_rotation_axis.XYZ())),radians(self.cutting_angle)) v_ball_center_to_tool_tip = gp_Vec(0,0,-self.ball_radius) v_ball_center_to_tool_tip.Transform(trsf) v_tool_tip = v_contact+v_contact_to_ball_center+v_ball_center_to_tool_tip v_tool_orientation = - v_ball_center_to_tool_tip.Normalized() * (0.500+1e-8) if self.create_target_vis_edges: me = BRepBuilderAPI_MakeEdge(gp_Pnt(v_tool_tip.XYZ()),gp_Pnt((v_tool_tip+v_tool_orientation).XYZ())) self.target_edges.append(me.Edge()) I = v_tool_tip.X() / 1000 J = v_tool_tip.Y() / 1000 K = v_tool_tip.Z() / 1000 U = v_tool_orientation.X() V = v_tool_orientation.Y() W = v_tool_orientation.Z() x,y,z,a,b = self.ikSolver.solve((I,J,K,U,V,W),1e-6,False) x += self.output_offset[0] y += self.output_offset[1] z += self.output_offset[2] a += self.output_offset[3] b += self.output_offset[4] if self.v_previous_contact_point: cut_distance = (v_contact - self.v_previous_contact_point).Magnitude() f = self.feedrate / cut_distance self.gcode += "G01 X{:.6f} Y{:.6f} Z{:.6f} A{:.6f} B{:.6f} F{:.6f}\n".format(x,y,z,a,b,f) else: f = 0 self.gcode += "G0 X{:.6f} Y{:.6f} Z{:.6f} A{:.6f} B{:.6f}\n".format(x,y,z,a,b) self.v_previous_contact_point = v_contact print(x,y,z,a,b) if u_now == u_max: break u_next = u_now + u_step if u_next > u_max: u_next = u_max u_now = u_next
def setRotate(self, pntAxFrom, pntAxTo, angle): trsf = gp_Trsf() ax1 = gp_Ax1(pntAxFrom, gp_Dir(gp_Vec(pntAxFrom, pntAxTo))) trsf.SetRotation(ax1, angle) self.aTrsf *= trsf return self
def __GetTransform(self, X: float, Y: float, Z: float, RX: float, RY: float, RZ: float) -> gp_Trsf: trsf_T = gp_Trsf() trsf_RX = gp_Trsf() trsf_RY = gp_Trsf() trsf_RZ = gp_Trsf() center = gp_Pnt(X, Y, Z) ax1_X = gp_Ax1(center, gp_Dir(1., 0., 0.)) ax1_Y = gp_Ax1(center, gp_Dir(0., 1., 0.)) ax1_Z = gp_Ax1(center, gp_Dir(0., 0., 1.)) trsf_T.SetTranslation(gp_Vec(X, Y, Z)) trsf_RX.SetRotation(ax1_X, RX * math.pi / 180) trsf_RY.SetRotation(ax1_Y, RY * math.pi / 180) trsf_RZ.SetRotation(ax1_Z, RZ * math.pi / 180) return trsf_RZ * trsf_RY * trsf_RX * trsf_T
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 rotateAP(): ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(1., 0., 0.)) aRotTrsf = gp_Trsf() angle = math.pi / 18 # 10 degrees aRotTrsf.SetRotation(ax1, angle) aTopLoc = TopLoc_Location(aRotTrsf) win.activePart.Move(aTopLoc) win.redraw()
def rotate(axis, angle=None): if angle is None: angle = np.linalg.norm(axis) axis = axis / angle trsf = gp_Trsf() trsf.SetRotation(gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir( gp_Vec(axis[0], axis[1], axis[2]))), angle) return Transformation(trsf)
def rotating_cube_2_axis(event=None): display.EraseAll() ais_boxshp = build_shape() ax1 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 0., 1.)) ax2 = gp_Ax1(gp_Pnt(0., 0., 0.), gp_Dir(0., 1., 0.)) a_cube_trsf = gp_Trsf() a_cube_trsf2 = gp_Trsf() angle = 0.0 tA = time.time() n_rotations = 200 for i in range(n_rotations): a_cube_trsf.SetRotation(ax1, angle) a_cube_trsf2.SetRotation(ax2, angle) aCubeToploc = TopLoc_Location(a_cube_trsf * a_cube_trsf2) 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 __setstate__(self, dct): scl = dct["scale"] rot = dct["rotate"] tra = dct["transl"] _trsf = gp_Trsf() _trsf.SetRotation(*rot) _trsf.SetTranslation(*tra) _trsf.SetScale(scl)
def renderLabel(self, geometry, transforms, styleName, layerName): pnt, text, size = geometry color, transparency, materialName = self.getStyle(styleName) r, g, b = color trsf = gp_Trsf() for tr in transforms: trsf *= tr.getTrsf() pntTrans = pnt.Transformed(trsf) self.display.DisplayMessage(pntTrans, text, size, (r/256, g/256, b/256), False)
def rotate(self,shape) : from OCC.Core.gp import gp_Trsf from OCC.BRepBuilderAPI import BRepBuilderAPI_Transform trns = gp_Trsf() trns.SetRotation(self.RevAxis,self.getStart()) brep_trns = BRepBuilderAPI_Transform(shape, trns, False) brep_trns.Build() shape = brep_trns.Shape() return shape
def show_box(self, axs=gp_Ax3(), lxyz=[100, 100, 100]): box = make_box(*lxyz) ax1 = gp_Ax3(gp_Pnt(-lxyz[0] / 2, -lxyz[1] / 2, -lxyz[2] / 2), gp_Dir(0, 0, 1)) trf = gp_Trsf() trf.SetTransformation(axs, gp_Ax3()) trf.SetTransformation(ax1, gp_Ax3()) box.Location(TopLoc_Location(trf)) self.display.DisplayShape(axs.Location()) self.show_axs_pln(axs, scale=lxyz[0]) self.display.DisplayShape(box, transparency=0.7)
def rotate_shp_3_axis(shape, rx, ry, rz, unity="deg"): """ Rotate a shape around (O,x), (O,y) and (O,z). @param rx_degree : rotation around (O,x) @param ry_degree : rotation around (O,y) @param rz_degree : rotation around (O,z) @return : the rotated shape. """ if unity == "deg": # convert angle to radians rx = radians(rx) ry = radians(ry) rz = radians(rz) alpha = gp_Trsf() alpha.SetRotation(gp_OX(), rx) beta = gp_Trsf() beta.SetRotation(gp_OY(), ry) gamma = gp_Trsf() gamma.SetRotation(gp_OZ(), rz) brep_trns = BRepBuilderAPI_Transform(shape, alpha*beta*gamma, False) shp = brep_trns.Shape() return shp
def translate_shp(shp, vec, copy=False): trns = gp_Trsf() trns.SetTranslation(vec) brep_trns = BRepBuilderAPI_Transform(shp, trns, copy) brep_trns.Build() return brep_trns.Shape()