dxfezdxftrimesh

extracting vertices_list and faces_list with ezdxf


I am trying to correctly extract vertices and faces from POLYLINE(POLYFACE) DXF files. When I try to create a Trimesh after extraction nothing is showing up. Any idea?

import ezdxf
import trimesh


doc = ezdxf.readfile(r"C:\Users\Baldan\Downloads\simplified.dxf")
msp = doc.modelspace()

vertices = []
faces = []

for e in msp:
    for vertex in e.vertices:
        if vertex.is_face_record:
            # Extract face information
            indices = [vertex.get_dxf_attrib(name, 0) for name in ('vtx0', 'vtx1', 'vtx2', 'vtx3')]
            # Filter out 0 indices as they indicate the end of the face definition
            indices = [idx for idx in indices if idx != 0]
            faces.append(tuple(indices))
        # Assuming vertex is a DXFVertex with a .dxf.location attribute
        x, y, z = vertex.dxf.location
        vertices.append((x, y, z))

mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
mesh.export('test.ply', file_type='ply')

Solution

  • You have to separate the face and location VERTEX entities and for some unknown reason are the vertex indices 1-based:

    doc = ezdxf.readfile(r"C:\Users\Baldan\Downloads\simplified.dxf")
    msp = doc.modelspace()
    
    def trimesh_from_polyface(polyface):
        vertices = []
        faces = []
        for vertex in polyface.vertices:
            if vertex.is_face_record:
                # Extract face information
                indices = [vertex.get_dxf_attrib(name, 0) for name in ('vtx0', 'vtx1', 'vtx2', 'vtx3')]
                # Filter out 0 indices as they indicate the end of the face definition
                # Vertex indices are 1-based!
                indices = [idx-1 for idx in indices if idx != 0]
                faces.append(tuple(indices))
            elif vertex.is_poly_face_mesh_vertex:    
                x, y, z = vertex.dxf.location
                vertices.append((x, y, z))
        return trimesh.Trimesh(vertices=vertices, faces=faces)
    
        
    for e in msp.query("POLYLINE"):
        if e.is_poly_face_mesh:
            mesh = trimesh_from_polyface()
            mesh.export('test.ply', file_type='ply')