def getColor(self, shape): # Get the part color #string_seq = self.layer_tool.GetObject().GetLayers(shape) color = Quantity_Color() self.color_tool.GetColor(shape, XCAFDoc_ColorSurf, color) logger.debug("color: %i, %i, %i", color.Red(), color.Green(), color.Blue()) return color
def __init__(self, name): self.data = [] self.rootNode: Node = None self.objectName = name self.objectCounter = 0 self.curCoordinateSystem = gp_Ax3(gp.XOY()) self.myType = Sketch_ObjectType.MainSketchType self.myColor = Quantity_Color(Quantity_NOC_YELLOW) self.myStyle = Aspect_TOL_SOLID self.myWidth = 1.0 self.myPrs3dAspect = Prs3d_LineAspect(self.myColor, self.myStyle, self.myWidth) self.myPolylineMode = False self.curPnt2d = gp.Origin2d() self.myFirstgp_Pnt2d = gp.Origin2d() self.mySecondgp_Pn2d = gp.Origin2d() self.myFirstPoint: Geom_CartesianPoint = Geom_CartesianPoint( gp.Origin()) self.mySecondPoint: Geom_CartesianPoint = Geom_CartesianPoint( gp.Origin()) self.myRubberLine = AIS_Line(self.myFirstPoint, self.mySecondPoint) self.myRubberLine.SetColor(Quantity_Color(Quantity_NOC_LIGHTPINK1))
def SetColor(self, theColor): if type(theColor) == tuple: self.myWireAspect.SetColor( Quantity_Color(theColor[0], theColor[1], theColor[2], theColor[3])) else: self.myWireAspect.SetColor(Quantity_Color(theColor)) self.myWireColor = theColor
def draw_simple_text(x, y, text_str): str_to_display = TCollection_AsciiString(text_str) height = 30 font_name = TCollection_AsciiString("Courier") display_type = Aspect_TODT_NORMAL text_color = Quantity_Color(Quantity_NOC_BLACK) subtitle_color = Quantity_Color(Quantity_NOC_BLACK) aTextItem = TextItem(str_to_display, x, y, height, font_name, text_color, subtitle_color, display_type, display.GetOverLayer()) display.register_overlay_item(aTextItem)
def make_axis_triedron(self): self.x_axis = AIS_Axis( Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(1, 0, 0))))) self.y_axis = AIS_Axis( Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(0, 1, 0))))) self.z_axis = AIS_Axis( Geom_Line(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(gp_XYZ(0, 0, 1))))) self.x_axis.SetColor(Quantity_Color(1, 0, 0, Quantity_TOC_RGB)) self.y_axis.SetColor(Quantity_Color(0, 1, 0, Quantity_TOC_RGB)) self.z_axis.SetColor(Quantity_Color(0, 0, 1, Quantity_TOC_RGB))
def show_grid(self, step=1., size=10. + 1e-6, color1=(.7, .7, .7), color2=(0, 0, 0)): viewer = self._get_viewer() viewer.ActivateGrid(Aspect_GT_Rectangular, Aspect_GDM_Lines) viewer.SetRectangularGridGraphicValues(size, size, 0) viewer.SetRectangularGridValues(0, 0, step, step, 0) grid = viewer.Grid() grid.SetColors(Quantity_Color(*color1, TOC_RGB), Quantity_Color(*color2, TOC_RGB))
def get_colour_from_step_file(face, colour_tool): """ This is to get the colour of an topo shape """ aColor = Quantity_Color() colour_tool.GetColor(face, XCAFDoc_ColorSurf, aColor) ### Time 255 since in the step the colour value is normizad betwen [0,1] # for x in aColor.Values(Quantity_TOC_RGB): # print (x) # print(str(255*x)) # print(str(round(255*x))) rgb = tuple(round(255 * x) for x in aColor.Values(Quantity_TOC_RGB)) # print(rgb) return rgb
def scl_init_display(self): self.display, self.start_display = init_display( periodic_callback=self.periodic, period=1) self.display.SetRenderingParams(Method=0, RaytracingDepth=3, IsShadowEnabled=False, IsReflectionEnabled=False, IsAntialiasingEnabled=False, IsTransparentShadowEnabled=False, StereoMode=0, AnaglyphFilter=1, ToReverseStereo=False) # self.add_menu('View') # self.add_function_to_menu('View', self.top) # self.add_function_to_menu('View', self.bottom) # self.add_function_to_menu('View', self.left) # self.add_function_to_menu('View', self.right) # self.add_function_to_menu('View', self.front) # self.add_function_to_menu('View', self.rear) # self.add_function_to_menu('View', self.isometric1) # self.add_function_to_menu('View', self.isometric2) # self.add_function_to_menu('View', self.isometric3) # self.add_function_to_menu('View', self.isometric4) # self.add_function_to_menu('View', self.isometric5) # self.add_function_to_menu('View', self.isometric6) # self.add_function_to_menu('View', self.isometric7) # self.add_function_to_menu('View', self.isometric8) # self.add_function_to_menu('View', self.perspective) # self.add_function_to_menu('View', self.orthographic) # self.add_function_to_menu('View', self.reset) # self.add_function_to_menu('View', self.rxp) # positive x rotation # self.add_function_to_menu('View', self.rxn) # negative x rotation # self.add_function_to_menu('View', self.ryp) # self.add_function_to_menu('View', self.ryn) # self.add_function_to_menu('View', self.rzp) # self.add_function_to_menu('View', self.rzn) p = gp_Pnt(0., 0., 0.) d = gp_Dir(0., 0., 1.) a = gp_Ax3(p, d) self.display.View.SetBgGradientColors( Quantity_Color(Quantity_NOC_ALICEBLUE), Quantity_Color(Quantity_NOC_ALICEBLUE), 2, True) self.axis() self.display.Repaint()
def line(): # create a line p1 = gp_Pnt(2., 3., 4.) d1 = gp_Dir(4., 5., 6.) line1 = Geom_Line(p1, d1) ais_line1 = AIS_Line(line1) # if we need to edit color, we can simply use SetColor # ais_line1.SetColor(Quantity_NOC_RED) # but actually we need to edit more, not just color. Line width and style as well # To do that, we need to do use AIS_Drawer and apply it to ais_line1 drawer = Prs3d_Drawer() ais_line1.SetAttributes(drawer) display.Context.Display(ais_line1, False) # we can apply the same rule for other lines by just doing a for loop for i in range(1, 5): p2 = gp_Pnt(i, 2., 5.) d2 = gp_Dir(4 * i, 6., 9.) line2 = Geom_Line(p2, d2) ais_line2 = AIS_Line(line2) width = float(i) drawer = ais_line2.Attributes() # asp : first parameter color, second type, last width asp = Prs3d_LineAspect(Quantity_Color(9 * i), i, width) drawer.SetLineAspect(asp) ais_line2.SetAttributes(drawer) display.Context.Display(ais_line2, False) start_display()
def _styleAis(self, ais, styleName, styleValue): if styleName == 'color': r, g, b = styleValue color = Quantity_Color(r, g, b, Quantity_TOC_RGB) ais.SetColor(color) if isinstance(ais, AIS_Trihedron): ais.SetArrowColor(color) ais.SetTextColor(color) elif styleName == 'tran': ais.SetTransparency(styleValue) elif styleName == 'material': aspect = Graphic3d_MaterialAspect(MATERIAL_TYPES.index(styleValue)) ais.SetMaterial(aspect) elif styleName == 'lineType': lineType = LINE_TYPES.index(styleValue) ais.Attributes().WireAspect().SetTypeOfLine(lineType) ais.Attributes().LineAspect().SetTypeOfLine(lineType) elif styleName == 'lineWidth': ais.Attributes().LineAspect().SetWidth(styleValue) ais.Attributes().WireAspect().SetWidth(styleValue) if isinstance(ais, AIS_Point): if styleName == 'pointType': ais.SetMarker(POINT_TYPES.index(styleValue)) if styleName == 'pointSize': ais.Attributes().PointAspect().SetScale(styleValue)
def __init__(self, filename, layer_name='layer-00'): logger.info("StepOcafExporter instantiated with " "filename : %s" % filename) check_exporter_filename(filename, step_extensions) check_overwrite(filename) self.filename = filename self.h_doc = h_doc = Handle_TDocStd_Document() # logger.info("Empty Doc?", h_doc.IsNull()) if h_doc.IsNull(): logger.info("Empty Doc?") # Create the application app = _XCAFApp.XCAFApp_Application_GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool().ShapeTool(doc.Main()) l_colors = XCAFDoc_DocumentTool().ColorTool(doc.Main()) l_layers = XCAFDoc_DocumentTool().LayerTool(doc.Main()) _ = TDF_LabelSequence() _ = TDF_LabelSequence() # TopoDS_Shape aShape; self.shape_tool = h_shape_tool.GetObject() self.top_label = self.shape_tool.NewShape() self.colors = l_colors.GetObject() self.layers = l_layers.GetObject() self.current_color = Quantity_Color(Quantity_NOC_RED) self.current_layer = self.layers.AddLayer( TCollection_ExtendedString(layer_name)) self.layer_names = {}
def test_write_step_file(self) -> None: """Exports a colored box into a STEP file""" ### initialisation doc = TDocStd_Document(TCollection_ExtendedString("pythonocc-doc")) self.assertTrue(doc is not None) # Get root assembly shape_tool = XCAFDoc_DocumentTool.ShapeTool(doc.Main()) colors = XCAFDoc_DocumentTool.ColorTool(doc.Main()) ### create the shape to export test_shape = BRepPrimAPI_MakeBox(100.0, 100.0, 100.0).Shape() ### add shape shp_label = shape_tool.AddShape(test_shape) ### set a color for this shape r = 1.0 g = b = 0.5 red_color = Quantity_Color(r, g, b, Quantity_TypeOfColor.Quantity_TOC_RGB) colors.SetColor(shp_label, red_color, XCAFDoc_ColorGen) # write file WS = XSControl_WorkSession() writer = STEPCAFControl_Writer(WS, False) writer.Transfer(doc, STEPControl_AsIs) status = writer.Write("./test_io/test_ocaf_generated.stp") self.assertTrue(status) self.assertTrue(os.path.isfile("./test_io/test_ocaf_generated.stp"))
def get_color_from_name(color_name): ''' from the string 'WHITE', returns Quantity_Color WHITE. color_name is the color name, case insensitive. ''' enum_name = 'Quantity_NOC_%s' % color_name.upper() if enum_name in globals(): color_num = globals()[enum_name] return Quantity_Color(color_num) elif enum_name + '1' in globals(): color_num = globals()[enum_name + '1'] print('Many colors for color name %s, using first.' % color_name) else: color_num = Quantity_NOC_WHITE print('Color name not defined. Use White by default') return Quantity_Color(color_num)
def test_write_step_file(self): ''' Exports a colored box into a STEP file ''' ### initialisation h_doc = Handle_TDocStd_Document() assert (h_doc.IsNull()) # Create the application app = XCAFApp_Application.GetApplication().GetObject() app.NewDocument(TCollection_ExtendedString("MDTV-CAF"), h_doc) # Get root assembly doc = h_doc.GetObject() h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main()) l_Colors = XCAFDoc_DocumentTool_ColorTool(doc.Main()) shape_tool = h_shape_tool.GetObject() colors = l_Colors.GetObject() ### create the shape to export test_shape = BRepPrimAPI_MakeBox(100., 100., 100.).Shape() ### add shape shp_label = shape_tool.AddShape(test_shape) ### set a color for this shape r = 1 g = b = 0.5 red_color = Quantity_Color(r, g, b, 0) colors.SetColor(shp_label, red_color, XCAFDoc_ColorGen) # write file WS = XSControl_WorkSession() writer = STEPCAFControl_Writer(WS.GetHandle(), False) writer.Transfer(h_doc, STEPControl_AsIs) status = writer.Write("./test_io/test_ocaf_generated.stp") assert status assert os.path.isfile("./test_io/test_ocaf_generated.stp")
def DisplayColoredShape( self, shapes, color='YELLOW', update=False, ): if isinstance(color, str): dict_color = { 'WHITE': Quantity_NOC_WHITE, 'BLUE': Quantity_NOC_BLUE1, 'RED': Quantity_NOC_RED, 'GREEN': Quantity_NOC_GREEN, 'YELLOW': Quantity_NOC_YELLOW, 'CYAN': Quantity_NOC_CYAN1, 'BLACK': Quantity_NOC_BLACK, 'ORANGE': Quantity_NOC_ORANGE } clr = Quantity_Color(dict_color[color]) elif isinstance(color, Quantity_Color): clr = color else: raise ValueError( 'color should either be a string ( "BLUE" ) or a Quantity_Color(0.1, 0.8, 0.1) got %s' % color) return self.DisplayShape(shapes, color=clr, update=update)
def add_scrolled_text(event=None): str_to_display = TCollection_AsciiString("Pythonocc Rocks!!") x1 = 1024 / 2 y1 = 768 / 2 height = 30 font_name = TCollection_AsciiString("Arial") display_type = Aspect_TODT_DEKALE text_color = Quantity_Color(Quantity_NOC_ORANGE) subtitle_color = Quantity_Color(Quantity_NOC_BLACK) aTextItem = TextItem(str_to_display, x1, y1, height, font_name, text_color, subtitle_color, display_type, display.GetOverLayer(), ScrollX=random.random()-0.5, ScrollY=random.random()-0.5) display.register_overlay_item(aTextItem) rotate_shp(ais_bottle)
def display_triedron(self): """Show a black triedron in lower right corner""" self.View.TriedronDisplay( Aspect_TOTP_RIGHT_LOWER, Quantity_Color(Quantity_NOC_BLACK), 0.1, V3d_ZBUFFER, )
def random_color(self): """ Set the color randomly. :return: None. """ r, g, b = rand(1, 3)[0] self._color = Quantity_Color(r, g, b, Quantity_TOC_RGB)
def ray_tracing_mode(self): # create one spotlight spot_light = V3d_SpotLight(gp_Pnt(-1000, -1000, 1000), V3d_XnegYnegZpos, Quantity_Color(Quantity_NOC_WHITE)) # display the spotlight in rasterized mode self.display.Viewer.AddLight(spot_light) self.display.View.SetLightOn() self.display.SetRaytracingMode(depth=8)
def draw_wp(self, uid): """Draw the workplane with uid.""" context = self.canvas._display.Context if uid: wp = self.wp_dict[uid] border = wp.border if uid == self.activeWpUID: borderColor = Quantity_Color(Quantity_NOC_DARKGREEN) else: borderColor = Quantity_Color(Quantity_NOC_GRAY) aisBorder = AIS_Shape(border) context.Display(aisBorder, True) context.SetColor(aisBorder, borderColor, True) transp = 0.8 # 0.0 <= transparency <= 1.0 context.SetTransparency(aisBorder, transp, True) drawer = aisBorder.DynamicHilightAttributes() context.HilightWithColor(aisBorder, drawer, True) clClr = Quantity_Color(Quantity_NOC_MAGENTA1) for cline in wp.clines: geomline = wp.geomLineBldr(cline) aisline = AIS_Line(geomline) aisline.SetOwner(geomline) drawer = aisline.Attributes() # asp parameters: (color, type, width) asp = Prs3d_LineAspect(clClr, 2, 1.0) drawer.SetLineAspect(asp) aisline.SetAttributes(drawer) context.Display(aisline, False) # (see comment below) # 'False' above enables 'context' mode display & selection pntlist = wp.intersectPts() # type <gp_Pnt> for point in pntlist: self.canvas._display.DisplayShape(point) for ccirc in wp.ccircs: aiscirc = AIS_Circle(wp.convert_circ_to_geomCirc(ccirc)) drawer = aisline.Attributes() # asp parameters: (color, type, width) asp = Prs3d_LineAspect(clClr, 2, 1.0) drawer.SetLineAspect(asp) aiscirc.SetAttributes(drawer) context.Display(aiscirc, False) # (see comment below) # 'False' above enables 'context' mode display & selection for edge in wp.edgeList: self.canvas._display.DisplayShape(edge, color="WHITE") self.canvas._display.Repaint()
def import_as_multiple_shapes(event=None): compound = read_step_file( os.path.join('..', 'assets', 'models', 'as1_pe_203.stp')) t = TopologyExplorer(compound) display.EraseAll() for solid in t.solids(): color = Quantity_Color(random.random(), random.random(), random.random(), Quantity_TOC_RGB) display.DisplayColoredShape(solid, color) display.FitAll()
def draw_lines(pnt_list, nr_of_points, display): """ rendering a large number of points through the usual way of: display.DisplayShape( make_vertex( gp_Pnt() ) ) is fine for TopoDS_Shapes but certainly not for large number of points. in comparison, drawing all the voxel samples takes 18sec using the approach above, but negigable when using this function its about 2 orders of Magnitude faster, so worth the extra hassle here we use a more close-to-the-metal approach of drawing directly in OpenGL see [1] for a more detailed / elegant way to perform this task [1] http://www.opencascade.org/org/forum/thread_21732/?forum=3 Parameters ---------- pnt_list: list of (x,y,z) tuples vertex list display: qtViewer3d """ a_presentation, group = create_ogl_group(display) black = Quantity_Color(Quantity_NOC_BLACK) asp = Graphic3d_AspectLine3d(black, Aspect_TOL_SOLID, 1) gg = Graphic3d_ArrayOfPolylines( nr_of_points * 2, nr_of_points * 2, 0, # maxEdges False, # hasVColors True) try: while 1: pnt = gp_Pnt(*next(pnt_list)) gg.AddVertex(pnt) pnt = gp_Pnt(*next(pnt_list)) gg.AddVertex(pnt) # create the line, with a random color gg.AddBound(2, random.random(), random.random(), random.random()) except StopIteration: pass group.SetPrimitivesAspect(asp) group.AddPrimitiveArray(gg) a_presentation.Display()
def runTests(self): # self.canva._display.Test() '''HR exercise 9/7/20 Want to convert line above with new code that is self-contained here C++ code to replicate (from 'Display3d.cpp') is below: BRepPrimAPI_MakeBox S(100,50,40); Handle(AIS_Shape) anAISShape = new AIS_Shape(S.Shape()); myAISContext->Display(anAISShape, Standard_False); myV3dView->ZFitAll(); myV3dView->FitAll(); ''' # S = BRepPrimAPI_MakeBox(100,100,100) # S_shape = AIS_Shape(S.Shape()) # self.canva._display.DisplayShape(S_shape, update=True) display = self.canva._display filename = 'Torch Assembly.STEP' # ## # ## # # From "core_load_step_ap203" # color = Quantity_Color(random.random(), # random.random(), # random.random(), # Quantity_TOC_RGB) # # compound = read_step_file(os.path.join('..', 'assets', 'models', 'as1_pe_203.stp')) # compound = read_step_file(filename) # t = TopologyExplorer(compound) # display.EraseAll() # for solid in t.solids(): # color = Quantity_Color(random.random(), # random.random(), # random.random(), # Quantity_TOC_RGB) # display.DisplayColoredShape(solid, color) ## ## # From "core_load_step_with_names_colors" shapes_labels_colors = read_step_file_with_names_colors(filename) for shpt_lbl_color in shapes_labels_colors: label, c = shapes_labels_colors[shpt_lbl_color] display.DisplayColoredShape(shpt_lbl_color, color=Quantity_Color( c.Red(), c.Green(), c.Blue(), Quantity_TOC_RGB)) display.View.FitAll() display.View.ZFitAll()
def import_filtered_output(event=None): outputFiles = glob.glob(os.path.join(OUTPUT_DIR, '*' + OUTPUT_EXTENSION)) if len(outputFiles) > 0: display.EraseAll() for outputFile in outputFiles: compound = read_step_file(outputFile) color = Quantity_Color(random.random(), random.random(), random.random(), Quantity_TOC_RGB) display.DisplayColoredShape(compound, color) display.FitAll() else: display.EraseAll() print("import_output_file() error - No output file(s) found")
def __init__(self, parent=None): fmt = QtOpenGL.QGLFormat() super().__init__(fmt, parent=parent) self._display = OCCViewer.Viewer3d() self._inited = False # enable Mouse Tracking self.setMouseTracking(True) # Strong focus self.setFocusPolicy(QtCore.Qt.WheelFocus) self.setAttribute(QtCore.Qt.WA_NativeWindow) self.setAttribute(QtCore.Qt.WA_PaintOnScreen) self.setAttribute(QtCore.Qt.WA_NoSystemBackground) self.setAutoFillBackground(False) color1 = Quantity_Color(.55, .55, .55, Quantity_TOC_RGB) color2 = Quantity_Color(.22, .22, .22, Quantity_TOC_RGB) self._display.View.SetBgGradientColors( color1, color2, Aspect_GFM_VER, True)
def to_occ_color(color) -> Quantity_Color: if not isinstance(color, QColor): if isinstance(color, tuple): if isinstance(color[0], int): color = QColor(*color) elif isinstance(color[0], float): color = QColor.fromRgbF(*color) else: raise ValueError('Unknown color format') else: color = QColor(color) return Quantity_Color(color.redF(), color.greenF(), color.blueF(), TOC_RGB)
def _renderShapeObj(self, aShape): shapeTr = BRepBuilderAPI_Transform(aShape, self.aMove.getTrsf()).Shape() ais = AIS_Shape(shapeTr) r, g, b = self.aStyle.getNormedColor() aisColor = Quantity_Color( r, g, b, Quantity_TypeOfColor(Quantity_TypeOfColor.Quantity_TOC_RGB)) ais.SetColor(aisColor) ais.SetTransparency(self.aStyle.getNormedTransparency()) aspect = Graphic3d_MaterialAspect( MATERIAL_CONSTS[self.aStyle.getMaterial()]) ais.SetMaterial(aspect) self.display.Context.Display(ais, False)
def exportFaces(self, topoDS_Assembly, topoDS_Compound, index): folder = self.folder + "/compound" + str(index) + "_faces" os.system("mkdir " + folder) # outFile = open(folder + "/faces.x3d", "w") self.dataStruct["compounds"].append("compound" + str(index) + "_faces") # self.printStart(outFile) for index, TopAbs_face in enumerate( topoDS_Assembly.faces_from_solids(topoDS_Compound)): color = Quantity_Color(random.random(), random.random(), random.random(), Quantity_TOC_RGB) tesselator = ShapeTesselator(TopAbs_face) tesselator.Compute(True) write_stl_file(TopAbs_face, folder + "/faces_" + str(index) + ".stl")
def renderShapeObj(self, shape, transforms, styleName): color, transparency, materialName = self.getStyle(styleName) trsf = gp_Trsf() for tr in transforms: trsf *= tr.getTrsf() shape = BRepBuilderAPI_Transform(shape, trsf).Shape() ais = AIS_Shape(shape) r,g,b = color aisColor = Quantity_Color(r/256, g/256, b/256, Quantity_TypeOfColor(Quantity_TypeOfColor.Quantity_TOC_RGB)) ais.SetColor(aisColor) ais.SetTransparency(transparency/100) aspect = Graphic3d_MaterialAspect(getMaterialNameConst(materialName)) ais.SetMaterial(aspect) self.display.Context.Display(ais, False)
def get_color_from_name(color_name): """from the string 'WHITE', returns Quantity_Color WHITE. color_name is the color name, case insensitive. """ enum_name = "Quantity_NOC_%s" % color_name.upper() if enum_name in globals(): color_num = globals()[enum_name] elif enum_name + "1" in globals(): color_num = globals()[enum_name + "1"] print("Many colors for color name %s, using first." % color_name) else: color_num = Quantity_NOC_WHITE print("Color name not defined. Use White by default") return Quantity_Color(color_num)