Finding nearest vertices

One of the most common tasks when working with mesh geometry using the Python API in Blender is finding the nearest neighboring vertices for a given point. We can find all the nearest vertices within a certain distance from a given vertex using the BMesh and KD-Tree tools.

Let’s write a simple script that will find and select all vertices within a specified distance from each selected vertex on the mesh. Start with the mesh in edit mode.

Create a BMesh object and copy the geometry of the currently active mesh into it.

Now create a KD-Tree. Fill it with data containing the coordinates of all mesh points. We’ll also perform a preliminary calculations to balance the tree.

For example we want to find all vertices within a distance of 0.7 from the selected ones. Set this distance.

Loop through all the selected vertices.

To find all the required vertices using KD-Tree, we can use the find_range() method, passing the coordinates of the selected point and the range within which to search. The method returns the coordinates, index, and distance to each found point. Let’s select it and print its data to the console.

After the loop completes, we return the geometry with the updated selection to the original mesh and clear the BMesh object, which we no longer need.

This way, we’ve selected all vertices that lie within the specified distance from each originally selected point.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments