Multisort Python

I am trying to write a custom exporter for Blender in Python. However, I'm having trouble figuring out how I can use my own Python sort implementation to sort my vertices the way I need.

Basically, I need to export the vertices so that they can form a grid like this, assuming V is double.

VVVVV VVVVV VVVVV VVVVV 

The "engine", which I write automatically, gets the X and Z coordinate values ​​based on where it is on the vertex map above. V represents the Y coordinate. Thus, this 5 by 5 vertex map would create 4 by 4 face grids.

However, in Blender, the vertices appear individually ordered for each face of the grid, but rather in a format such as my. Therefore, in order to export it, I need to first order the coordinates in depth (Y coordinate in Blender), and then in width (X coordinate in Blender). It should behave like an SQL query, where the specified first parameter takes precedence in order compared to the second.

This is what my code currently looks like

 #!BPY """ Name: 'VaV Export' Blender: 269 Group: 'Export' Tooltip: 'Export to VaV file format' """ import Blender import bpy class Coordinate: def __init__(self, posX, posY): self.posX = posX self.posY = posY def sortX(self, other): if posX < other.posX: return 1 def sortY(self, other): if posY < other.posY: return 1 def write(filename): out = open(filename, "w") terraindata = bpy.data.meshes["Terrain"] vertices = terraindata.vertices vertices = sorted(vertices, key = lambda x: x.co.y, reverse = True) vertices = sorted(vertices, key = lambda x: x.co.x, reverse = False) print(vertices) Blender.Window.FileSelector(write, "Export") 

The first call to sorted () successfully arranges it by depth (Y). However, the 2nd sort call messed up the order (as expected). How can I change this so that both species occur without a second occurrence of the first?

Thanks for your time in advance!

+6
source share
2 answers

Change

 vertices = sorted(vertices, key = lambda x: x.co.y, reverse = True) 

to

 vertices = sorted(vertices, key = lambda x: (x.co.y, x.co.x), reverse = True) 

... and that should do it.

+3
source

If I understand correctly, you want to arrange your vertices by decreasing the y coordinate, with coordinates with equal y values, ordered with increasing x coordinate. If this is correct, you can return the tuple (-x.co.y, x.co.x) from your key function to sorted , and Python will do all sorting at the same time.

An alternative would be to take the page out of the radix sort and first sort by the least significant coordinate (for example, x ), and then the more significant coordinate ( y ). This will work since Python sort stable .

+2
source

All Articles