Skip to content

Instantly share code, notes, and snippets.

@Petethegoat
Created September 29, 2018 13:59
Show Gist options
  • Save Petethegoat/91b3f7b188b9dcd84a2a4aeab20ddd48 to your computer and use it in GitHub Desktop.
Save Petethegoat/91b3f7b188b9dcd84a2a4aeab20ddd48 to your computer and use it in GitHub Desktop.
bl_info = {
"name": "Convert Face Textures to Material Textures",
"author": "Greatness7",
"location": "Object -> Search -> Convert Face Textures to Material Textures",
"description": "Convert Face Textures to Material Textures",
"category": "Object",
}
import bpy
from pathlib import Path
from collections import defaultdict
class ParentArmatureKeepPose(bpy.types.Operator):
bl_idname = 'object.face_tex_to_mat_tex'
bl_label = "Convert Face Textures to Material Textures"
bl_description = "Convert Face Textures to Material Textures"
bl_options = {'REGISTER', 'UNDO'}
@staticmethod
def create_textured_material(ob, image):
name = "%s" % Path(image.name).with_suffix("")
# use duplicates if possible, else make new
tex = bpy.data.textures.get(name,
bpy.data.textures.new(name, type='IMAGE'))
mat = bpy.data.materials.get(name,
bpy.data.materials.new(name))
# create the material
ob.data.materials.append(mat)
# create texture slot
tex.image = image
if not mat.texture_slots[0]:
mat.texture_slots.add().texture = tex
def execute(self, context):
for ob in bpy.context.selected_objects:
images_face_map = defaultdict(list)
uv_data = ob.data.uv_textures.active.data
for i, face in enumerate(ob.data.polygons):
try:
images_face_map[uv_data[i].image].append(face)
except (AttributeError, IndexError):
pass
materials = {}
for i, slot in enumerate(ob.material_slots):
try:
image = slot.material.texture_slots[0].texture.image
materials[image] = i
except (AttributeError, IndexError):
pass
for image, faces in images_face_map.items():
try:
i = materials[image]
except KeyError:
self.create_textured_material(ob, image)
i = next(i for i, slot in enumerate(ob.material_slots)
if slot.material == ob.data.materials[-1])
for face in faces:
face.material_index = i
return {'FINISHED'}
def register():
bpy.utils.register_module(__name__)
def unregister():
bpy.utils.unregister_module(__name__)
if __name__ == "__main__":
register()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment