Beispiel #1
0
 def SetCenter(self, theShape):
     props = GProp_GProps()
     brepgprop_SurfaceProperties(theShape, props)
     cog = props.CentreOfMass()
     cog_x, cog_y, cog_z = cog.Coord()
     self.myCenter = gp_Pnt(cog_x, cog_y, cog_z)
     print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z))
Beispiel #2
0
 def area(self):
     """
     :return: The area of all faces of the shape.
     :rtype: float
     """
     props = GProp_GProps()
     brepgprop_SurfaceProperties(self.object, props, True)
     return props.Mass()
Beispiel #3
0
 def system(self):
     self._system = GProp_GProps()
     # todo, type should be abstracted with TopoDS...
     _topo_type = self.instance.topo_type
     if _topo_type == 'face' or _topo_type == 'shell':
         brepgprop_SurfaceProperties(self.instance, self._system)
     elif _topo_type == 'edge':
         brepgprop_LinearProperties(self.instance, self._system)
     elif _topo_type == 'solid':
         brepgprop_VolumeProperties(self.instance, self._system)
     return self._system
Beispiel #4
0
    def __init__(self, size, face=None, faceU=None, ax3=None):
        # gp_Ax3 of XYZ coord system
        origin = gp_Pnt(0, 0, 0)
        wDir = gp_Dir(0, 0, 1)
        uDir = gp_Dir(1, 0, 0)
        vDir = gp_Dir(0, 1, 0)
        xyzAx3 = gp_Ax3(origin, wDir, uDir)
        if (not face and not ax3):  # create default wp (in XY plane at 0,0,0)
            axis3 = xyzAx3
            gpPlane = gp_Pln(xyzAx3)
            self.gpPlane = gpPlane  # type: gp_Pln
            self.plane = Geom_Plane(gpPlane)  # type: Geom_Plane
        elif face:  # create workplane on face, uDir defined by faceU
            wDir = face_normal(face)  # from OCCUtils.Construct module
            props = GProp_GProps()
            brepgprop_SurfaceProperties(face, props)
            origin = props.CentreOfMass()
            '''
            surface = BRep_Tool_Surface(face) # type: Handle_Geom_Surface
            plane = Handle_Geom_Plane.DownCast(surface).GetObject() # type: Geom_Plane
            gpPlane = plane.Pln() # type: gp_Pln
            origin = gpPlane.Location() # type: gp_Pnt
            '''
            uDir = face_normal(faceU)  # from OCCUtils.Construct module
            axis3 = gp_Ax3(origin, wDir, uDir)
            vDir = axis3.YDirection()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane
        elif ax3:
            axis3 = ax3
            uDir = axis3.XDirection()
            vDir = axis3.YDirection()
            wDir = axis3.Axis().Direction()
            origin = axis3.Location()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane

        self.Trsf = gp_Trsf()
        self.Trsf.SetTransformation(axis3)
        self.Trsf.Invert()
        self.origin = origin
        self.uDir = uDir
        self.vDir = vDir
        self.wDir = wDir
        self.face = face
        self.size = size
        self.border = self.makeWpBorder(self.size)
        self.clList = []  # List of 'native' construction lines
        self.clineList = []  # List of pyOCC construction lines
        self.ccircList = []  # List of pyOCC construction circles
        self.wireList = []  # List of pyOCC wires
        self.wire = None
        self.hvcl((0, 0))  # Make H-V clines through origin
        self.accuracy = 0.001  # min distance between two points
Beispiel #5
0
def shape_faces_surface():
    """ Compute the surface of each face of a shape
    """
    # first create the shape
    the_shape = BRepPrimAPI_MakeBox(50., 30., 10.).Shape()
    # then loop over faces
    t = TopologyExplorer(the_shape)
    props = GProp_GProps()
    shp_idx = 1
    for face in t.faces():
        brepgprop_SurfaceProperties(face, props)
        face_surf = props.Mass()
        print("Surface for face nbr %i : %f" % (shp_idx, face_surf))
        shp_idx += 1
Beispiel #6
0
    def __init__(self, size, face=None, faceU=None, ax3=None):
        # gp_Ax3 of XYZ coord system
        origin = gp_Pnt(0, 0, 0)
        wDir = gp_Dir(0, 0, 1)
        uDir = gp_Dir(1, 0, 0)
        vDir = gp_Dir(0, 1, 0)
        xyzAx3 = gp_Ax3(origin, wDir, uDir)
        if (not face and not ax3):  # create default wp (in XY plane at 0,0,0)
            axis3 = xyzAx3
            gpPlane = gp_Pln(xyzAx3)
            self.gpPlane = gpPlane  # type: gp_Pln
            self.plane = Geom_Plane(gpPlane)  # type: Geom_Plane
        elif face:  # create workplane on face, uDir defined by faceU
            wDir = face_normal(face)  # from OCCUtils.Construct module
            props = GProp_GProps()
            brepgprop_SurfaceProperties(face, props)
            origin = props.CentreOfMass()
            uDir = face_normal(faceU)  # from OCCUtils.Construct module
            axis3 = gp_Ax3(origin, wDir, uDir)
            vDir = axis3.YDirection()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane
        elif ax3:
            axis3 = ax3
            uDir = axis3.XDirection()
            vDir = axis3.YDirection()
            wDir = axis3.Axis().Direction()
            origin = axis3.Location()
            self.gpPlane = gp_Pln(axis3)
            self.plane = Geom_Plane(self.gpPlane)  # type: Geom_Plane

        self.Trsf = gp_Trsf()
        self.Trsf.SetTransformation(axis3)
        self.Trsf.Invert()
        self.origin = origin
        self.uDir = uDir
        self.vDir = vDir
        self.wDir = wDir
        self.wVec = gp_Vec(wDir)
        self.face = face
        self.size = size
        self.border = self.makeWpBorder(self.size)
        self.clines = set()  # set of c-lines with (a, b, c) coefficients
        self.ccircs = set()  # set of c-circs with (pc, r) coefficients
        self.edgeList = []  # List of profile lines type: <TopoDS_Edge>
        self.wire = None
        self.accuracy = 1e-6  # min distance between two points
        self.hvcl((0, 0))  # Make H-V clines through origin
def measure_shape_mass_center_of_gravity(shape):
    """Returns the shape center of gravity
    Returns a gp_Pnt if requested (set as_Pnt to True)
    or a list of 3 coordinates, by default."""
    inertia_props = GProp_GProps()
    if is_edge(shape):
        brepgprop_LinearProperties(shape, inertia_props)
        mass_property = "Length"
    elif is_face(shape):
        brepgprop_SurfaceProperties(shape, inertia_props)
        mass_property = "Area"
    else:
        brepgprop_VolumeProperties(shape, inertia_props)
        mass_property = "Volume"
    cog = inertia_props.CentreOfMass()
    mass = inertia_props.Mass()
    return cog, mass, mass_property
Beispiel #8
0
def calc_area(s):
    props = GProp_GProps()
    brepgprop_SurfaceProperties(s.geometry, props)
    return props.Mass()
Beispiel #9
0
 def surface(self):
     '''returns the area of a surface
     '''
     prop = GProp_GProps()
     brepgprop_SurfaceProperties(self.shape, prop, self.tolerance)
     return prop
Beispiel #10
0
    def max_counter(self, facesS_2):
        section_edges = list(Topo(facesS_2).edges())
        # print(len(section_edges))

        if len(section_edges) > 0:

            Wire_c = BRepBuilderAPI_MakeWire()
            prep_list = []
            Wire_c.Add(section_edges[0])
            prep_list.append(section_edges[0])
            ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

            # no need for a loop since we know for a fact that
            # the edge has only one start and one end
            c = ex.Current()
            cv = topods_Vertex(c)
            v0 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            v1 = BRep_Tool_Pnt(cv)
            section_edges.pop(0)
            flag = 0
            wires = []

            while len(section_edges) > 0:

                new_list = []

                for edges in section_edges:
                    # Wire_c.Add(edges)
                    ex = TopExp_Explorer(edges, TopAbs_VERTEX)
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    End_1 = BRep_Tool_Pnt(cv)
                    ex.Next()
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    End_2 = BRep_Tool_Pnt(cv)

                    if End_1.X() == v0.X() and End_1.Y() == v0.Y() and End_1.Z(
                    ) == v0.Z():
                        Wire_c.Add(edges)
                        v0 = End_2
                        flag = 0
                    elif End_1.X() == v1.X() and End_1.Y() == v1.Y(
                    ) and End_1.Z() == v1.Z():
                        Wire_c.Add(edges)
                        v1 = End_2
                        flag = 0
                    elif End_2.X() == v0.X() and End_2.Y() == v0.Y(
                    ) and End_2.Z() == v0.Z():
                        Wire_c.Add(edges)
                        v0 = End_1
                        flag = 0
                    elif End_2.X() == v1.X() and End_2.Y() == v1.Y(
                    ) and End_2.Z() == v1.Z():
                        Wire_c.Add(edges)
                        v1 = End_1
                        flag = 0
                    else:
                        new_list.append(edges)

                flag += 1
                section_edges = new_list

                if flag >= 5:
                    # print('number_ostalos', len(section_edges))
                    wires.append(Wire_c.Wire())
                    Wire_c = BRepBuilderAPI_MakeWire()

                    Wire_c.Add(section_edges[0])
                    ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

                    # no need for a loop since we know for a fact that
                    # the edge has only one start and one end
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    v0 = BRep_Tool_Pnt(cv)
                    ex.Next()
                    c = ex.Current()
                    cv = topods_Vertex(c)
                    v1 = BRep_Tool_Pnt(cv)
                    section_edges.pop(0)
                    flag = 0

            wires.append(Wire_c.Wire())

            areas = []
            props = GProp_GProps()

            for wire in wires:
                brown_face = BRepBuilderAPI_MakeFace(wire)
                brown_face = brown_face.Face()
                # props = GProp_GProps()
                brepgprop_SurfaceProperties(brown_face, props)
                areas.append(props.Mass())

            return max(areas)

        else:
            return 0
Beispiel #11
0
def glue_solids(event=None):
    display.EraseAll()
    display.Context.RemoveAll(True)
    # Without common edges
    S1 = BRepPrimAPI_MakeBox(gp_Pnt(500., 500., 0.), gp_Pnt(100., 250., 300.)).Shape()
    # S2 = BRepPrimAPI_MakeBox(gp_Pnt(300., 300., 300.), gp_Pnt(600., 600., 600.)).Shape()
    S2 = read_step_file(os.path.join('..', 'part_of_sattelate', 'pribore', 'Camara_WS16.STEP'))
    bbox = Bnd_Box()
    brepbndlib_Add(S2, bbox)
    xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
    print(bbox.Get())
    p0 = gp_Pnt(xmin + (xmax - xmin) / 2, ymin + (ymax - ymin) / 2, zmin+0.01)

    vnorm = gp_Dir(0, 0, 1)
    pln = gp_Pln(p0, vnorm)
    face = BRepBuilderAPI_MakeFace(pln, -(xmax - xmin) / 2 - 1, (xmax - xmin) / 2 + 1, -(ymax - ymin) / 2 - 1,
                                   (ymax - ymin) / 2 + 1).Face()
    # face = BRepBuilderAPI_MakeFace(pln, -10, 10, -10,10).Face()
    '''planeZ = BRepBuilderAPI_MakeFace(
        gp_Pln(gp_Pnt(xmin, ymin, zmin), gp_Pnt(xmax, ymax, zmin), gp_Pnt(xmin, ymax, zmin))).Face()'''
    facesS_2 = BRepAlgoAPI_Section(face, S2).Shape()
    # print(facesS_2)
    display.DisplayShape(face, update=True)
    display.DisplayShape(S2, update=True)
    display.DisplayShape(facesS_2, update=True)

    section_edges = list(Topo(facesS_2).edges())
    print(len(section_edges))

    '''toptool_seq_shape = TopTools_SequenceOfShape()
    for edge in section_edges:
        toptool_seq_shape.Append(edge)'''

    Wire_c = BRepBuilderAPI_MakeWire()
    prep_list = []
    Wire_c.Add(section_edges[0])
    prep_list.append(section_edges[0])
    ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

    # no need for a loop since we know for a fact that
    # the edge has only one start and one end
    c = ex.Current()
    cv = topods_Vertex(c)
    v0 = BRep_Tool_Pnt(cv)
    ex.Next()
    c = ex.Current()
    cv = topods_Vertex(c)
    v1 = BRep_Tool_Pnt(cv)
    section_edges.pop(0)
    flag = 0
    wires = []

    while len(section_edges) > 0:

        new_list = []

        for edges in section_edges:
            #Wire_c.Add(edges)
            ex = TopExp_Explorer(edges, TopAbs_VERTEX)
            c = ex.Current()
            cv = topods_Vertex(c)
            End_1 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            End_2 = BRep_Tool_Pnt(cv)

            if End_1.X() == v0.X() and End_1.Y() == v0.Y() and End_1.Z() == v0.Z():
                Wire_c.Add(edges)
                v0 = End_2
                flag = 0
            elif End_1.X() == v1.X() and End_1.Y() == v1.Y() and End_1.Z() == v1.Z():
                Wire_c.Add(edges)
                v1 = End_2
                flag = 0
            elif End_2.X() == v0.X() and End_2.Y() == v0.Y() and End_2.Z() == v0.Z():
                Wire_c.Add(edges)
                v0 = End_1
                flag = 0
            elif End_2.X() == v1.X() and End_2.Y() == v1.Y() and End_2.Z() == v1.Z():
                Wire_c.Add(edges)
                v1 = End_1
                flag = 0
            else:
                new_list.append(edges)

        flag += 1
        section_edges = new_list

        if flag >= 5:
            print('number_ostalos', len(section_edges))
            wires.append(Wire_c.Wire())
            #wir = Wire_c.Wire()
            print('ttttt')
            Wire_c = BRepBuilderAPI_MakeWire()

            Wire_c.Add(section_edges[0])
            ex = TopExp_Explorer(section_edges[0], TopAbs_VERTEX)

            # no need for a loop since we know for a fact that
            # the edge has only one start and one end
            c = ex.Current()
            cv = topods_Vertex(c)
            v0 = BRep_Tool_Pnt(cv)
            ex.Next()
            c = ex.Current()
            cv = topods_Vertex(c)
            v1 = BRep_Tool_Pnt(cv)
            section_edges.pop(0)
            flag = 0

    # wires.append(Wire_c.Wire())
    wires.append(bild_wire(Wire_c))
    props = GProp_GProps()

    yellow_wire = wires[0]
    brown_face = BRepBuilderAPI_MakeFace(yellow_wire)
    brown_face = brown_face.Face()
    brepgprop_SurfaceProperties(brown_face, props)
    face_surf = props.Mass()
    print(face_surf)
    #display.DisplayColoredShape(brown_face.Face(), 'BLUE')


    areas = []
    props = GProp_GProps()

    for wire in wires:
        brown_face = BRepBuilderAPI_MakeFace(wire)
        brown_face = brown_face.Face()
        #props = GProp_GProps()
        brepgprop_SurfaceProperties(brown_face, props)
        areas.append(props.Mass())


    print(areas)


    print(len(wires))
Beispiel #12
0
 def __init__(self, shape, tol=1.0e-7, skip_shared=False):
     super(SurfaceProps, self).__init__()
     brepgprop_SurfaceProperties(shape.object, self._props, tol,
                                 skip_shared)
Beispiel #13
0
 def cal_are(self, shp=TopoDS_Shape()):
     brepgprop_SurfaceProperties(shp, self.prop)
     return self.prop.Mass()
Beispiel #14
0
def mesh_model(model, max_size=1e-5, tolerance=1e-7, repair=False, terminal=1):
    # In/Output definitions
    fil = model.split("/")[-1][:-5]
    folder = "/".join(model.split("/")[:-1])
    scale_factor = 1000.0
    verts = []
    norms = []
    faces = []
    curvs = []
    vert_map = {}
    d1_feats = []
    d2_feats = []
    t_curves = []
    #norm_map = {}
    with fileinput.FileInput(model, inplace=True) as fi:
        for line in fi:
            print(line.replace(
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )",
                "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )"
            ),
                  end='')

    stats = {}

    # OCC definitions
    occ_steps = read_step_file(model)
    stats["#parts"] = len(occ_steps)
    stats["model"] = model
    print("Reading step %s with %i parts." % (model, len(occ_steps)))
    #tot = 0
    #for s in occ_steps:
    #    occ_topo = TopologyExplorer(s)
    #    print(s)
    #    print(len(list(occ_topo.edges())))
    #    tot += len(list(occ_topo.edges()))
    occ_cnt = 0
    bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=True)
    diag = np.sqrt(bbox[6]**2 + bbox[7]**2 + bbox[8]**2)
    max_length = diag * max_size  #, 9e-06
    tolerance = diag * tolerance
    #print(fil, diag, max_length, tolerance)
    stats["bbox"] = bbox
    stats["max_length"] = float(max_length)
    stats["tolerance"] = float(tolerance)
    stats["diag"] = float(diag)

    occ_topo = TopologyExplorer(occ_steps[occ_cnt])
    occ_top = Topo(occ_steps[occ_cnt])
    occ_props = GProp_GProps()
    occ_brt = BRep_Tool()

    # Gmsh definitions
    gmsh.initialize()
    gmsh.clear()
    gmsh.option.setNumber("General.Terminal", terminal)
    gmsh.option.setNumber("Geometry.Tolerance", tolerance)
    gmsh.option.setNumber("Geometry.OCCFixDegenerated", 0)
    gmsh.option.setNumber("Geometry.OCCFixSmallEdges", 0)
    gmsh.option.setNumber("Geometry.OCCFixSmallFaces", 0)
    gmsh.option.setNumber("Geometry.OCCSewFaces", 0)
    gmsh.option.setNumber("Mesh.CharacteristicLengthMax", max_length)
    gmsh.open(model)

    # Gmsh meshing
    #gmsh.model.mesh.generate(1)
    #gmsh.model.mesh.refine()
    #gmsh.model.mesh.refine()
    gmsh.model.mesh.generate(2)
    #gmsh.write("results/" + file + ".stl")
    gmsh_edges = gmsh.model.getEntities(1)
    gmsh_surfs = gmsh.model.getEntities(2)
    #print("O", tot, "G", len(gmsh_edges))
    #continue
    gmsh_entities = gmsh.model.getEntities()
    #gmsh.model.occ.synchronize()
    #print(dir(gmsh.model.occ))
    total_edges = 0
    total_surfs = 0
    for l in range(len(occ_steps)):
        topo = TopologyExplorer(occ_steps[l])
        total_edges += len(list(topo.edges()))
        total_surfs += len(list(topo.faces()))

        vol = brepgprop_VolumeProperties(occ_steps[l], occ_props, tolerance)
        #print(dir(occ_props), dir(occ_props.PrincipalProperties()), dir(occ_props.volume()), occ_props.Mass())
        sur = brepgprop_SurfaceProperties(occ_steps[l], occ_props, tolerance)
        #print(vol, "Test", sur)

    stats["#edges"] = total_edges
    stats["#surfs"] = total_surfs
    stats["volume"] = vol
    stats["surface"] = sur
    stats["curves"] = []
    stats["surfs"] = []
    stats["#points"] = 0
    print("Number of surfaces: %i, Number of curves: %i" %
          (total_surfs, total_edges))
    #print(total_edges, total_surfs, len(gmsh_edges), len(gmsh_surfs))
    if not total_edges == len(gmsh_edges):
        print("Skipping due to wrong EDGES", model)
        return
    if not total_surfs == len(gmsh_surfs):
        print("Skipping due to wrong SURFS", model)
        return

    #print("Reading curvature")
    v_cnt = 1
    v_nodes = []
    occ_offset = 0
    invalid_model = False
    c_cnt = 0

    #v_cont_cnt = 0
    #print(len(list(occ_topo.edges())), len(list(occ_topo.solids())), len(list(occ_topo.faces())), len(list(occ_topo.vertices())))
    for e in gmsh_entities[:]:
        #print(e)
        nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes(
            e[0], e[1], True)
        elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements(
            e[0], e[1])
        n_id = e[1] - occ_offset
        #print(e, occ_offset, n_id)
        #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags)
        if e[0] == 0:  # Process points
            #print(e[1], nodeCoords)
            vert_map[e[1]] = v_cnt
            verts.append([
                nodeCoords[0] * 1000.0, nodeCoords[1] * 1000.0,
                nodeCoords[2] * 1000.0
            ])
            v_cnt += 1
            stats["#points"] += 1

            #pass
        if e[0] == 1:  # Process contours
            if n_id - 1 == len(list(occ_topo.edges())):
                #print("CNT", occ_cnt)
                occ_cnt += 1
                occ_offset = e[1] - 1
                n_id = 1
                occ_topo = TopologyExplorer(occ_steps[occ_cnt])
                occ_top = Topo(occ_steps[occ_cnt])
                #print("Defunct curve", n_id, len(list(occ_topo.edges())))
                #continue
            #print(n_id)
            curve = BRepAdaptor_Curve(list(occ_topo.edges())[n_id - 1])
            # Add type and parametric nodes/indices
            #print("type", edge_map[curve.GetType()])
            if gmsh.model.getType(e[0], e[1]) == "Unknown":
                #print("Skipping OtherCurve", nodeTags)
                continue

            for i, n in enumerate(nodeTags):
                if n >= v_cnt:
                    vert_map[n] = v_cnt
                    verts.append([
                        nodeCoords[i * 3] * 1000.0,
                        nodeCoords[i * 3 + 1] * 1000.0,
                        nodeCoords[i * 3 + 2] * 1000.0
                    ])
                    v_cnt += 1
                else:
                    print(n, v_cnt)

            #print(v_ind, type(v_ind), v_par, type(v_par))
            stats["curves"].append(edge_map[curve.GetType()])
            #print(n_id, edge_map[curve.GetType()], gmsh.model.getType(e[0], e[1]))
            #print(list(occ_topo.edges()), n_id-1)
            c_type = edge_map[curve.GetType()]  #gmsh.model.getType(e[0], e[1])
            if not gmsh.model.getType(e[0], e[1]) == edge_map[curve.GetType()]:
                print("Skipped due to non matching edges ", model,
                      gmsh.model.getType(e[0], e[1]),
                      edge_map[curve.GetType()])
                #invalid_model = True
                #break

            d1_feat = convert_curve(curve)

            edg = list(occ_topo.edges())[n_id - 1]

            for f in occ_top.faces_from_edge(edg):
                #ee = (e)
                #print(dir(ee))
                #d1_feat = {}
                su = BRepAdaptor_Surface(f)
                c = BRepAdaptor_Curve2d(edg, f)
                t_curve = {
                    "surface": f,
                    "3dcurve": c_cnt,
                    "2dcurve": convert_2dcurve(c)
                }
                #print(edge_map[c.GetType()], surf_map[su.GetType()], edge_map[curve.GetType()])
                #d1f = convert_2dcurve(c)
                #print(d1f)
                #ccnt += 1
                #print(d1_feat)
                t_curves.append(t_curve)

            if len(elemNodeTags) > 0:
                #v_ind = [int(elemNodeTags[0][0]) - 1] # first vertex
                v_ind = [int(nodeTags[-2]) - 1]
                for no in nodeTags[:-2]:
                    v_ind.append(int(no) - 1)  # interior vertices
                v_ind.append(int(nodeTags[-1]) - 1)
                #v_ind.append(int(elemNodeTags[0][-1]) - 1) # last vertex
                d1_feat["vert_indices"] = v_ind
                #v_par = [float(curve.FirstParameter())] # first param
                v_par = [float(nodeParams[-2] * scale_factor)]
                for no in nodeParams[:-2]:
                    v_par.append(float(no * scale_factor))  # interior params
                v_par.append(float(nodeParams[-1] * scale_factor))
                #v_par.append(float(curve.LastParameter())) # last param
                d1_feat["vert_parameters"] = v_par
            else:
                print("No nodetags", edge_map[curve.GetType()], elemNodeTags)

            #print("VERTS", len(d1_feat["vert_indices"]), len(d1_feat["vert_parameters"]))
            d1_feats.append(d1_feat)
            c_cnt += 1
            #t_curve = curve.Trim(curve.FirstParameter(), curve.LastParameter(), 0.0001).GetObject()
            #print(curve.FirstParameter(), curve.LastParameter())

    #print("Processing surfaces")
    gmsh_entities = gmsh.model.getEntities(2)
    n_cnt = 1
    occ_offset = 0
    occ_cnt = 0
    occ_topo = TopologyExplorer(occ_steps[occ_cnt])
    occ_top = Topo(occ_steps[occ_cnt])
    f_cnt = 0
    f_sum = 0
    first_face = True
    mean_curv = 0.0
    curv_cnt = 0
    gaus_curv = 0.0
    s_cnt = 0

    for e in gmsh_entities[:]:
        #print(e)
        nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes(
            e[0], e[1], True)
        elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements(
            e[0], e[1])
        n_id = e[1] - occ_offset
        #print(e, occ_offset, n_id)
        #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags)
        if e[0] == 2:
            #print(e, gmsh.model.getType(e[0], e[1]), elemTypes)
            if n_id - 1 == len(list(occ_topo.faces())):
                #print("CNT", occ_cnt)
                occ_cnt += 1
                occ_offset = e[1] - 1
                n_id = 1
                occ_topo = TopologyExplorer(occ_steps[occ_cnt])
                occ_top = Topo(occ_steps[occ_cnt])
            if "getNormals" in dir(gmsh.model):
                nls = gmsh.model.getNormals(e[1], nodeParams)
            else:
                nls = gmsh.model.getNormal(e[1], nodeParams)
            curvMax, curvMin, dirMax, dirMin = gmsh.model.getPrincipalCurvatures(
                e[1], nodeParams)
            #surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id-1])
            norm_map = {}
            for i, n in enumerate(nodeTags):
                norms.append([nls[i * 3], nls[i * 3 + 1], nls[i * 3 + 2]])
                curvs.append([
                    curvMin[i], curvMax[i], dirMin[i * 3], dirMin[i * 3 + 1],
                    dirMin[i * 3 + 2], dirMax[i * 3], dirMax[i * 3 + 1],
                    dirMax[i * 3 + 2]
                ])
                curv_cnt += 1
                mean_curv += (curvMin[i] + curvMax[i]) / 2.0
                gaus_curv += (curvMin[i] * curvMax[i])
                norm_map[n] = n_cnt
                n_cnt += 1
                if n in vert_map.keys():
                    v = verts[vert_map[n] - 1]
                    #print("Vert contained", n)
                    #v_cont_cnt += 1
                    #                    assert(v[0] == nodeCoords[i*3] * 1000.0 and v[1] == nodeCoords[i*3+1] * 1000.0 and v[2] == nodeCoords[i*3+2] * 1000.0)
                    continue
                else:
                    vert_map[n] = v_cnt
                #occ_node = surf.Value(nodeParams[i], nodeParams[i+1])
                #vertices.append([occ_node.X(), occ_node.Y(), occ_node.Z()])
                verts.append([
                    nodeCoords[i * 3] * 1000.0, nodeCoords[i * 3 + 1] * 1000.0,
                    nodeCoords[i * 3 + 2] * 1000.0
                ])
                #print("S", occ_node.Coord(), [nodeCoords[i*3]*1000, nodeCoords[i*3+1]*1000, nodeCoords[i*3+2]*1000])
                #print(occ_node.Coord(), nodeCoords[i*3:(i+1)*3])
                v_cnt += 1

            d2_faces = []
            for i, t in enumerate(elemTypes):
                for j in range(len(elemTags[i])):
                    faces.append([
                        vert_map[elemNodeTags[i][j * 3]],
                        vert_map[elemNodeTags[i][j * 3 + 1]],
                        vert_map[elemNodeTags[i][j * 3 + 2]],
                        norm_map[elemNodeTags[i][j * 3]],
                        norm_map[elemNodeTags[i][j * 3 + 1]],
                        norm_map[elemNodeTags[i][j * 3 + 2]]
                    ])
                    d2_faces.append(f_cnt)
                    f_cnt += 1
            #print(len(list(occ_topo.faces())), n_id-1)
            surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id - 1])
            #print("type", edge_map[curve.GetType()])
            #if gmsh.model.getType(e[0], e[1]) == "Unknown":
            #    print("Skipping OtherCurve", nodeTags)
            #    continue
            #print(surf)
            g_type = gmsh_map[gmsh.model.getType(e[0], e[1])]
            if g_type != "Other" and not g_type == surf_map[surf.GetType()]:
                print("Skipped due to non matching surfaces ", model, g_type,
                      surf_map[surf.GetType()])
                #invalid_model = True
                #break

            stats["surfs"].append(surf_map[surf.GetType()])

            d2_feat = convert_surface(surf)
            d2_feat["face_indices"] = d2_faces

            for tc in t_curves:
                if tc["surface"] == list(occ_topo.faces())[n_id - 1]:
                    tc["surface"] = s_cnt

            if len(elemNodeTags) > 0:
                #print(len(elemNodeTags[0]), len(nodeTags), len(nodeParams))
                v_ind = []  #int(elemNodeTags[0][0])] # first vertex
                for no in nodeTags:
                    v_ind.append(int(no) - 1)  # interior vertices
                #v_ind.append(int(elemNodeTags[0][-1])) # last vertex
                d2_feat["vert_indices"] = v_ind
                v_par = []  #float(surf.FirstParameter())] # first param
                for io in range(int(len(nodeParams) / 2)):
                    v_par.append([
                        float(nodeParams[io * 2] * scale_factor),
                        float(nodeParams[io * 2 + 1] * scale_factor)
                    ])  # interior params
                #v_par.append(float(surf.LastParameter())) # last param
                d2_feat["vert_parameters"] = v_par
            else:
                print("No nodetags", edge_map[curve.GetType()], elemNodeTags)

            f_sum += len(d2_feat["face_indices"])
            d2_feats.append(d2_feat)
            s_cnt += 1

    if invalid_model:
        return

    stats["#sharp"] = 0
    stats["gaus_curv"] = float(gaus_curv / curv_cnt)
    stats["mean_curv"] = float(mean_curv / curv_cnt)

    if not f_sum == len(faces):
        print("Skipping due to wrong FACES", model)
        return
    if True:
        vert2norm = {}
        for f in faces:
            #print(f)
            for fii in range(3):
                if f[fii] in vert2norm:
                    vert2norm[f[fii]].append(f[fii + 3])
                else:
                    vert2norm[f[fii]] = [f[fii + 3]]
        for d1f in d1_feats:
            sharp = True
            for vi in d1f["vert_indices"][1:-1]:
                #print(vi, vert2norm.keys())
                nos = list(set(vert2norm[vi + 1]))
                if len(nos) == 2:
                    n0 = np.array(norms[nos[0]])
                    n1 = np.array(norms[nos[1]])
                    #print(np.linalg.norm(n0), np.linalg.norm(n1))
                    if np.abs(n0.dot(n1)) > 0.95:
                        sharp = False
                        #break
                else:
                    sharp = False
            if sharp:
                stats["#sharp"] += 1
            d1f["sharp"] = sharp

    stats["#verts"] = len(verts)
    stats["#faces"] = len(faces)
    stats["#norms"] = len(norms)

    #with open("results/" + file + ".json", "w") as fil:
    #    json.dump(d1_feats, fil, sort_keys=True, indent=2)
    #with open("results/" + file + "_faces.json", "w") as fil:
    #   json.dump(d2_feats, fil, sort_keys=True, indent=2)

    features = {"curves": d1_feats, "surfaces": d2_feats, "trim": t_curves}
    if True:
        res_path = folder.replace("/step/", "/feat/")
        fip = fil.replace("_step_", "_features_")
        print("%s/%s.yml" % (res_path, fip))
        with open("%s/%s.yml" % (res_path, fip), "w") as fili:
            yaml.dump(features, fili, indent=2)

        res_path = folder.replace("/step/", "/stat/")
        fip = fil.replace("_step_", "_stats_")
        with open("%s/%s.yml" % (res_path, fip), "w") as fili:
            yaml.dump(stats, fili, indent=2)

        print("Generated model with %i vertices and %i faces." %
              (len(verts), len(faces)))
        res_path = folder.replace("/step/", "/obj/")
        fip = fil.replace("_step_", "_trimesh_")
        with open("%s/%s.obj" % (res_path, fip), "w") as fili:
            for v in verts:
                fili.write("v %f %f %f\n" % (v[0], v[1], v[2]))
            for vn in norms:
                #print(np.linalg.norm(vn))
                fili.write("vn %f %f %f\n" % (vn[0], vn[1], vn[2]))
            for vn in curvs:
                fili.write(
                    "vc %f %f %f %f %f %f %f %f\n" %
                    (vn[0], vn[1], vn[2], vn[3], vn[4], vn[5], vn[6], vn[7]))
            for f in faces:
                fili.write("f %i//%i %i//%i %i//%i\n" %
                           (f[0], f[3], f[1], f[4], f[2], f[5]))

        faces = np.array(faces)
        face_indices = faces[:, :3] - 1
        norm_indices = faces[:, 3:] - 1
    gmsh.clear()
    gmsh.finalize()
    #print(curvs)
    return {
        "statistics": stats,
        "features": features,
        "vertices": np.array(verts),
        "normals": np.array(norms),
        "curvatures": np.array(curvs),
        "face_indices": face_indices,
        "normal_indices": norm_indices,
        "trim": t_curves
    }