Here we need three things:
- Find the 2d cursor position
- Check the mode we are in before processing the UV coordinates
- Use the UV layer to find UV coordinates
For each face, once UV coordinates are found, calculate their center and offset the coordinates by the difference from the cursor.
Note that if no UV editor opened, won't find the cursor and does nothing.
Commented code:
import bpy
from mathutils import Vector
def find_cursor_location():
# Look through area and find the first image editor
for area in bpy.context.screen.areas:
if area.type == 'IMAGE_EDITOR':
return area.spaces.active.cursor_location
return None
obj = bpy.context.object
cursor = find_cursor_location()
if cursor:
#Check the mode as we cant do it in edit mode
mode = obj.mode
if mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
me = obj.data #Need to get it here in case mode is changed
uv_layer = me.uv_layers.active
if uv_layer:
for poly in me.polygons:
# Get all Uv coordinates of the face
uvs = [uv_layer.data[loop_index].uv for loop_index in poly.loop_indices]
# Its center
center = sum(uvs, Vector((0,0))) / len(uvs)
# The needed offset
delta = center - cursor
# Shift UV coords
for uv_data in [uv_layer.data[loop_index] for loop_index in poly.loop_indices]:
uv_data.uv -= delta
#Back to the mode we were in
if mode != 'OBJECT':
bpy.ops.object.mode_set(mode=mode)