The goal of my script is to automate creation of hooks for cloth simulations. Everything works great except for on deformed meshes.
So at the beginning I would select the verts in edit mode, then use bpy.ops.view3d.snap_cursor_to_selected() to send the 3d cursor to the selection of vertices, and then an empty is created on top of the 3d cursor with bpy.ops.object.empty_add() .
But, if the mesh is deformed by an armature modifier, the 3d cursor snaps to world space and not where the deformed mesh is.
How do you snap the 3d cursor to the deformed selection of vertices?
Ok the below works, and also added in averaging the selected verts:
import bpy
import bmesh
import mathutils
context = bpy.context
obj = context.object
dg = context.evaluated_depsgraph_get() # Get the dependency graph
# Update selection of verts
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
# Access desgraph to get deformed data
bpy.ops.object.mode_set(mode='OBJECT')
object_eval = obj.evaluated_get(dg)
mesh_eval = object_eval.data
# Get the active mesh
objd = mesh_eval
# Get a BMesh representation
bm = bmesh.new() # Create an empty BMesh
bm.from_mesh(objd) # Fill it in from a Mesh
bpy.ops.object.mode_set(mode='EDIT')
# Get coordinates of selected verts and average them
x = y = z = i = 0
selectedVerts = [v for v in bm.verts if v.select]
for v in selectedVerts:
vec = mathutils.Vector(v.co)
# Witchcraft:
x += vec.x
y += vec.y
z += vec.z
i += 1
x = x/i
y = y/i
z = z/i
# Set cursor location
bpy.context.scene.cursor.location = (x,y,z)
bm.free() # Free and prevent further access