tpaviot / pythonocc-core

Python package for 3D geometry CAD/BIM/CAM
GNU Lesser General Public License v3.0
1.39k stars 380 forks source link

Gmsh compatibility #815

Open PhilippMetsch opened 4 years ago

PhilippMetsch commented 4 years ago

Hi,

I am really new to pythonocc and at the moment I am trying to prepare a - to some extent - automated mesh generation using the Gmsh-Python-API. For the visualization of my geometry, I am currently using pythonocc to read a "step" or "brep" file that I created with gmsh and visualize it using init_display from SimpleGui. Now, something strange happens: whenever I initialize the display with the init_display method, the behavior of Gmsh changes. After the initialization, I am not able to create the mesh anymore (some kind of binary error) and - what I think is really weird - to write a mesh that I generated before to a binary file. Somehow, Gmsh mixes up "," and "." in its file writing process, so that the written file is useless.

Are you aware of any changes to the environemt due to the initialization of the display with pythonocc? Maybe because both, Gmsh and pythonocc use the system occ libraries?

tpaviot commented 4 years ago

@Flifff pythonocc and gmsh both relies on opencascade technology. The OCCViewer module might sets the CASROOT environmenet variable see https://github.com/tpaviot/pythonocc-core/blob/master/src/Display/OCCViewer.py#L85

I use to work with both gmsh and pythonocc together, I nevers faced any issue. Hard to say what happens on your machine without any information about your platform, environment, the script you're running etc.

PhilippMetsch commented 4 years ago

Sorry, I knew something was missing: I am running Gmsh 4.5.5 compiled with OpenCascade 7.4.0 from source and the latest conda built of pythonocc-core on a 64bit Debian bullseye. The part of the code I am talking about looks like this:

`
############################

Load required libraries:

    ############################
    # Standard Python libraries
    import numpy as np                                                              # numpy for fast array computations
    import tempfile as tf                                                           # tempfile for temporary files and folders
    # import pdb                                                                      # pdb for debugging

    # additional program libraries
    try:
        from OCC.Display.SimpleGui import init_display as initRenderer              # rendering window initialization
        from OCC.Core.BRep import BRep_Builder as brepBuilder                       # ".brep" object handling
        from OCC.Core.BRepTools import breptools_Read as brepReader                 # ".brep"-file reader
        from OCC.Extend.DataExchange import read_step_file as stepReader
        from OCC.Core.TopoDS import TopoDS_Shape as topoShape                       # creation of OCC shapes
        from OCC.Extend.TopologyUtils import TopologyExplorer as topoExplorer       # topology exploring (needed to cycle through the objects of the compund)
        from OCC.Core.Quantity import Quantity_Color as color                       # color methods
        from OCC.Core.Quantity import Quantity_TOC_RGB as typeRGB                   # RGB color type
        from OCC.Core.Aspect import Aspect_TOTP_LEFT_LOWER                          # property to place axes widget into the lower left corner
        from OCC.Core.V3d import V3d_ZBUFFER                                        # property to place axes widget into the lower left corner
        PYTHONOCCAVAILABLE=True
    except ImportError:
        PYTHONOCCAVAILABLE=False

    # self defined class definition
    class GeometryVisualization():
        """Class for Gmsh model geometry visualization

        This class visualizes the geometry of a given GmshModel using the PYTHONOCC
        library. It provides a simple method to visualize the model geometry by
        storing the geometric model information into a temporary ".brep"-file which
        is read by PYTHONOCC.

        Attributes:
        -----------
        model: GmshModel object instance
            model instance for which the geometry has to be displayed

        renderer: renderer object instance
            instance of a rendering class

        groupColors: list of PYTHONOCC Quantity_Colors
            colors used for the visualization of the individual physical model groups

        lineColor: PYTHONOCC Quantity_Color
            color used for the cisualization of lines (especially in wireframe mode)
        """
        #########################
        # Initialization method #
        #########################
        def __init__(self,model=None):
            """Initilaization method for the GeometryVisualization class

            This method initializes a new instance of the GeometryVisualization
            class and visualizes the geometry of the passed GmshModel instance.
            Within the method, basic visualization settings as well as additional
            key press events for the rendering window are defined, before the
            visualization method is called.

            Parameters:
            model: GmshModel object instance
                model for which the geometry has to be visualized
            """
            if PYTHONOCCAVAILABLE:
                # plausibility checks for input arguments
                if model is None:
                    raise ValueError("No model instance to visualize passed. For the visualization of the model geometry, that model has to be known. Check your input data.")
                self.model=model

                # set renderer and place axes widget in the lower left corner
                self.renderer, self.startRenderer = initRenderer(display_triedron=False,background_gradient_color1=[82, 87, 110],background_gradient_color2=[82, 87, 110])[0:2]
                self.renderer.View.TriedronDisplay(Aspect_TOTP_LEFT_LOWER, color(1,1,1,typeRGB), 0.1, V3d_ZBUFFER)

                # set window title
                self.renderer.get_parent().parent().setWindowTitle("GmshModel Geometry Visualization")

                # set additional key events
                backendOpts=self.renderer.get_parent()                                  # get options of the rendering backend
                backendOpts._key_map.update({ord("X"): self.setViewX})                  # x-key pressed -> set view to y-z plane
                backendOpts._key_map.update({ord("Y"): self.setViewY})                  # y-key pressed -> set view to x-z plane
                backendOpts._key_map.update({ord("Z"): self.setViewZ})                  # z-key pressed -> set view to x-y plane
                backendOpts._key_map.update({ord("R"): self.resetView})                 # r-key pressed -> set reset view
                backendOpts._key_map.update({ord("Q"): self.close})                     # q-key pressed -> close window

                # set colors for the individual model groups
                self.groupColors=[]
                shapeColors=[color(0,0,0.7,typeRGB),                  # (dark) blue
                             color(0.7,0,0,typeRGB),                  # (dark) red
                             color(0,0.7,0,typeRGB),                  # (dark) green
                             color(0.7,0,1,typeRGB),                  # purple
                             color(1,0.57,0,typeRGB),                 # orange
                             color(0,0.7,0.7,typeRGB),                # cyan
                             color(0.7,0.7,0.7,typeRGB),              # (dark) grey
                ]
                self.lineColor=color(1,1,1,typeRGB)                   # white
                for iEnt in model.gmshAPI.getEntities(model.dimension):                 # loop over all gmsh entities of the highest model dimension
                    entGrp=model.gmshAPI.getPhysicalGroupsForEntity(*iEnt)              # get the physical group of the entity
                    self.groupColors.append(shapeColors[entGrp[0]-1])                   # assign color assuming that order of shapes in brep file is the same as in Gmsh model

                # visualize the model geometry
                print(PYTHONOCCAVAILABLE)
                self.visualizeGeometry()

            else:
                print("The geometry visualization class depends on the pythonocc library. It seems like you have not installed it. The geometry visualization is therefore unavailable for you.")`

If I try to generate the mesh or save an existing one using the Gmsh-Python-API before the initialization method is called, everything works. After the method call, something is messed up. I hope this helps understanding my problem. I will have a look to your hint about the CASROOT environment variable.

Thanks for your quick help

weiweiisok commented 3 years ago

May I ask you a question? How to make the mesh displayable in pythonocc after meshed by gmsh API ?