Sorting vertices indices

Hello,

I want to use a mesh that makes up some sort of 2D line path, and I need the vertices indices to start from the vertex closest to 0,0, move towards an edge that is in the Y-up direction, until the last vertex in the mesh…

Now the problem is, if the vertices were not created in this order, how can I store the vertex closest to 0,0 the first in a list, move up(Y axis-up), and continue storing the linked vertices in a list till the last one? :expressionless:

I hope I wasn’t confusing… >.<

I think I made it… I have never done anything too serious with python thought, so this code probably sucks.

I’m using it for a racing game driveline, maybe someone else will find it useful, and won’t have to go through all this stuff just to order a bunch of vertices…


def WriteLeftDriveLine(obj, filename):
  "Write the .drvl file"
  mesh = obj.getData()
  mesh.transform(obj.getMatrix())
  for f in mesh.faces:
    if len(f.v) != 2:
      print "Can't export Drive Line .drvl file: invalid mesh."
      print "The mesh must be made of linked line segments only."
      return

  filename = Blender.sys.splitext(filename)[0]
  filename += '.drvl'
  drvfile = file(filename, "w")
  print "Writing drive line file: %s" % filename
  verts = mesh.verts

  shortest_distance = 100000
  for v in verts:
	#find vertex closest to 0,0
    distance = sqrt(v[0]**2 + v[1]**2)
    if distance &lt;  shortest_distance:
      shortest_distance = distance
      first_vertex = v

  #Find the two vertex that are linked to the first vertex
  e_v = []
  edges = mesh.edges

  for e in edges:
    if first_vertex == e.v1:
      e_v.append(e.v2)
    elif first_vertex == e.v2:
      e_v.append(e.v1)
 
  second_vertex = first_vertex
  #Find the vertex which has the higher Y value
  for v in e_v:
    if v[1] &gt; second_vertex[1]:
      second_vertex = v
  
  if second_vertex == first_vertex:
    print "Can't export Drive Line .drvl file: invalid mesh."
    print "The mesh only has one point."
    return

  sorted_vertex = [first_vertex, second_vertex]

  prev_vertex = first_vertex
  curr_vertex = second_vertex

  count = 2
  #Find the edge that contains the second vertex but does not has first vertex
  while count != len(verts):
    for e in edges:
      if prev_vertex != e.v1 and prev_vertex != e.v2:
        #Find which vertex is the next_vertex
        if curr_vertex == e.v1:
          prev_vertex = curr_vertex
          curr_vertex = e.v2
          sorted_vertex.append(curr_vertex)
          count = count + 1
          break
        elif curr_vertex == e.v2:
          prev_vertex = curr_vertex
          curr_vertex = e.v1
          sorted_vertex.append(curr_vertex)
          count = count + 1
          break

  for v in sorted_vertex:
	drvfile.write('%f,%f
' % (v[0], v[1]))
  
  drvfile.close()

Theres a script in blenders CVS that converts a mesh into a polyline