Sorting the mesh vertices in Blender

735 views Asked by At

I'm creating an application that requires the vertices array of the mesh to be sorted in a particular way, to access them more easily: from left to right then downwards to upwards (in the xy plane) like this: [indexes][1]

My code successfully does that, but the resulting mesh is all glitched out: [resulting mesh][2] I think it's likely that the new edges are causing the problem, but haven't found a way to fix them. Here's the mesh sorting code I wrote:

# This example assumes we have a mesh object selected
import bpy
import bmesh

#Weights for order. Left>>Right Down>>Up
def order(vector):
    return vector[0]+200*vector[1]

# Get the active mesh
me = bpy.context.object.data
verts=[]

# Get a BMesh representation
bm = bmesh.new()   # create an empty BMesh
bm.from_mesh(me)   # fill it in from a Mesh

#Convert current verts to tuple list (x,y,z)
i=0
for v in bm.verts:
    verts.append((v.co.x,v.co.y,v.co.z))

# Sort the verts.
verts.sort(key=order)

#Assign the sorted vertices to the mesh
i=0
for v in bm.verts:
    v.co.x,v.co.y,v.co.z = verts[i]
    i+=1

#Debugging edges (possible problem?)
for v in bm.edges:
    if i<10:
        print(v)        
    i+=1

# Finish up, write the bmesh back to the mesh
bm.verts.index_update()
bm.to_mesh(me)

#bmesh.update_edit_mesh(me)
bm.free()  # free and prevent further access

Is there any way to rearrange the edges? Or any post processing trick I can do on the mesh, anything helps. Thanks in advance. [1]: https://i.stack.imgur.com/iuoBc.png [2]: https://i.stack.imgur.com/atxvF.png

0

There are 0 answers