mathutils.kdtree.py 840 B

1234567891011121314151617181920212223242526272829303132333435
  1. import mathutils
  2. # create a kd-tree from a mesh
  3. from bpy import context
  4. obj = context.object
  5. mesh = obj.data
  6. size = len(mesh.vertices)
  7. kd = mathutils.kdtree.KDTree(size)
  8. for i, v in enumerate(mesh.vertices):
  9. kd.insert(v.co, i)
  10. kd.balance()
  11. # Find the closest point to the center
  12. co_find = (0.0, 0.0, 0.0)
  13. co, index, dist = kd.find(co_find)
  14. print("Close to center:", co, index, dist)
  15. # 3d cursor relative to the object data
  16. co_find = obj.matrix_world.inverted() @ context.scene.cursor.location
  17. # Find the closest 10 points to the 3d cursor
  18. print("Close 10 points")
  19. for (co, index, dist) in kd.find_n(co_find, 10):
  20. print(" ", co, index, dist)
  21. # Find points within a radius of the 3d cursor
  22. print("Close points within 0.5 distance")
  23. for (co, index, dist) in kd.find_range(co_find, 0.5):
  24. print(" ", co, index, dist)