Wie staple ich UV-Inseln mit Python in Blender?

Sep 18 2020

Ich suche nach einer Hilfe / Lösung für meine Frage "Wie man eine UV-Insel mit Python in Blender stapelt.

Ich bin noch nicht weit vom Anfang entfernt, aber das ist alles, was ich so weit gebracht habe:

import bpy

me = bpy.context.object.data
uv_layer = me.uv_layers.active.data

for poly in me.polygons:
    # Here I want to move the selected poly in the location of my 2D cursor
    # So eventually all my polygons are stacked into the same pile 

Dies ist eine sehr Anfängerfrage und alle Hilfe und Hinweise werden sehr geschätzt.

------------------BEARBEITEN---------------------

Hier ist eine Illustration, was ich mit dem Skript erreichen möchte:

  1. Wählen Sie UV-Insel

  2. Fang die UV-Insel am 2D-Cursor

  3. Wiederholen Sie die Phasen 1 und 2 für jede Fläche im Netz, damit schließlich alle Flächen übereinander gestapelt werden

Antworten

2 lemon Sep 18 2020 at 13:52

Hier brauchen wir drei Dinge:

  • Suchen Sie die 2D-Cursorposition
  • Überprüfen Sie den Modus, in dem wir uns befinden, bevor Sie die UV-Koordinaten verarbeiten
  • Verwenden Sie die UV-Schicht, um UV-Koordinaten zu finden

Wenn für jedes Gesicht UV-Koordinaten gefunden wurden, berechnen Sie deren Mittelpunkt und versetzen Sie die Koordinaten um die Differenz zum Cursor.

Beachten Sie, dass der Cursor nicht gefunden wird, wenn kein UV-Editor geöffnet ist, und nichts tut.

Kommentierter 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)