Merge branch 'main' into viseme-dev

This commit is contained in:
Yusarina
2024-07-25 00:57:08 +01:00
committed by GitHub
18 changed files with 712 additions and 200 deletions
+27 -23
View File
@@ -1,8 +1,8 @@
import bpy
import re
from typing import List, Tuple, Optional
from typing import List, Tuple, Optional, Set
from bpy.types import Material, Operator, Context, Object
from ..core.common import clean_material_names
from ..core.common import clean_material_names, get_selected_armature, is_valid_armature, get_all_meshes
from ..core.register import register_wrap
from ..functions.translations import t
@@ -65,49 +65,54 @@ class CombineMaterials(Operator):
@classmethod
def poll(cls, context: Context) -> bool:
return context.active_object is not None
armature = get_selected_armature(context)
return armature is not None and is_valid_armature(armature)
def execute(self, context: Context) -> set:
bpy.ops.object.mode_set(mode='OBJECT')
armature: Optional[Object] = next((obj for obj in bpy.data.objects if obj.type == 'ARMATURE'), None)
def execute(self, context: Context) -> Set[str]:
armature = get_selected_armature(context)
if not armature:
self.report({'WARNING'}, "No armature selected")
return {'CANCELLED'}
meshes: List[Object] = [obj for obj in bpy.data.objects if obj.type == 'MESH' and 'Armature' in obj.modifiers and obj.modifiers['Armature'].object == armature]
if not meshes:
return {'CANCELLED'}
context.view_layer.objects.active = armature
bpy.ops.object.mode_set(mode='OBJECT')
meshes = get_all_meshes(context)
if not meshes:
self.report({'WARNING'}, "No meshes found for the selected armature")
return {'CANCELLED'}
self.consolidate_materials(meshes)
self.remove_unused_materials()
self.cleanmatslots()
self.clean_material_names()
bpy.ops.object.mode_set(mode='OBJECT')
bpy.context.view_layer.objects.active = armature
return {'FINISHED'}
def consolidate_materials(self, objects: List[Object]) -> None:
mat_mapping: dict = {}
def consolidate_materials(self, meshes: List[Object]) -> None:
mat_mapping: Dict[str, Material] = {}
num_combined: int = 0
for ob in objects:
for slot in ob.material_slots:
for mesh in meshes:
for slot in mesh.material_slots:
mat: Optional[Material] = slot.material
if mat:
base_name: str = get_base_name(mat.name)
if base_name in mat_mapping:
base_mat: Material = mat_mapping[base_name]
if materials_match(base_mat, mat):
consolidate_textures(base_mat, mat)
num_combined += 1
slot.material = base_mat
try:
if materials_match(base_mat, mat):
consolidate_textures(base_mat, mat)
num_combined += 1
slot.material = base_mat
except AttributeError:
# Skip this material if there's an attribute mismatch
continue
else:
mat_mapping[base_name] = mat
report_consolidated(self, num_combined)
def remove_unused_materials(self) -> None:
for mat in bpy.data.materials:
if not any(obj for obj in bpy.data.objects if obj.material_slots and mat.name in obj.material_slots):
@@ -125,4 +130,3 @@ class CombineMaterials(Operator):
for obj in bpy.data.objects:
if obj.type == 'MESH':
clean_material_names(obj)
+117
View File
@@ -0,0 +1,117 @@
import bpy
from ..core import common
from ..core import register_wrap
from .translations import t
import re
@register_wrap
class CreateDigitigradeLegs(bpy.types.Operator):
bl_idname = "avatar_toolkit.createdigitigradelegs"
bl_label = t('Tools.create_digitigrade_legs.label')
bl_description = t('Tools.create_digitigrade_legs.desc')
@classmethod
def poll(cls, context):
if(context.active_object is None):
return False
if(context.selected_editable_bones is not None):
if(len(context.selected_editable_bones) == 2):
return True
return False
def execute(self, context):
for digi0 in context.selected_editable_bones:
digi1: bpy.types.EditBone = None
digi2: bpy.types.EditBone = None
digi3: bpy.types.EditBone = None
try:
digi1 = digi0.children[0]
digi2 = digi1.children[0]
digi3 = digi2.children[0]
except:
print("bone format incorrect! Please select a chain of 4 continious bones!") #TODO: Show this to user. this is an error.
return {'CANCELLED'}
digi4 = None
try:
digi4 = digi3.children[0]
except:
print("no toe bone. Continuing.")
digi0.select = True
digi1.select = True
digi2.select = True
digi3.select = True
if(digi4):
digi4.select = True
bpy.ops.armature.roll_clear()
bpy.ops.armature.select_all(action='DESELECT')
#creating transform for upper leg
digi0.select = True
bpy.ops.transform.create_orientation(name="Toolkit_digi0", overwrite=True)
bpy.ops.armature.select_all(action='DESELECT')
#duplicate digi0 and assign it to thigh
thigh = common.duplicatebone(digi0)
bpy.ops.armature.select_all(action='DESELECT')
#make digi2 parrallel to digi1
digi2.align_orientation(digi0)
#extrude thigh
thigh.select_tail = True
bpy.ops.armature.extrude_move(ARMATURE_OT_extrude={"forked":False},TRANSFORM_OT_translate=None)
#set new bone to calf varible
bpy.ops.armature.select_more()
calf = context.selected_bones[0]
bpy.ops.armature.select_all(action='DESELECT')
#set calf end to digi2 end
calf.tail = digi2.tail
#make copy of calf, flip it, and then align bone so that it's head is moved to match in align phase
flipedcalf = common.duplicatebone(calf)
bpy.ops.armature.select_all(action='DESELECT')
flipedcalf.select = True
bpy.ops.armature.switch_direction()
bpy.ops.armature.select_all(action='DESELECT')
flippeddigi1 = common.duplicatebone(digi1)
bpy.ops.armature.select_all(action='DESELECT')
flippeddigi1.select = True
bpy.ops.armature.switch_direction()
bpy.ops.armature.select_all(action='DESELECT')
#align flipped calf to flipped middle leg to move the head
flipedcalf.align_orientation(flippeddigi1)
flipedcalf.length = flippeddigi1.length
#assign calf tail to flipped calf head so it moves calf's tail to be out at the perfect parallelagram
calf.head = flipedcalf.tail
#delete helper bones
bpy.ops.armature.select_all(action='DESELECT')
flippeddigi1.select = True
bpy.ops.armature.delete()
bpy.ops.armature.select_all(action='DESELECT')
flipedcalf.select = True
bpy.ops.armature.delete()
bpy.ops.armature.select_all(action='DESELECT')
#reparent the foot to the new calf so it will be part of the new foot IK chain
digi3.parent = calf
#Tada! It's done! now to rename the old 3 segments that make up the old part to noik so resonite doesn't try to select them
digi0.name = re.compile(re.escape("<noik>"), re.IGNORECASE).sub("",digi0.name)+"<noik>"
digi1.name = re.compile(re.escape("<noik>"), re.IGNORECASE).sub("",digi1.name)+"<noik>"
digi2.name = re.compile(re.escape("<noik>"), re.IGNORECASE).sub("",digi2.name)+"<noik>"
#finally fully done!
return {'FINISHED'}
+186
View File
@@ -0,0 +1,186 @@
import bpy
from bpy.types import Operator
from bpy_extras.io_utils import ImportHelper
from ..core.register import register_wrap
from ..core.importer import imports, import_types
from ..functions.translations import t
import pathlib
import os
from ..core import common
@register_wrap
class ImportAnyModel(Operator, ImportHelper):
bl_idname = 'avatar_toolkit.import_any_model'
bl_label = t('Tools.import_any_model.label')
bl_description = t('Tools.import_any_model.desc')
bl_options = {'REGISTER', 'UNDO'}
files: bpy.props.CollectionProperty(type=bpy.types.OperatorFileListElement, options={'HIDDEN', 'SKIP_SAVE'})
filter_glob: bpy.props.StringProperty(default = imports, options={'HIDDEN','SKIP_SAVE'})
directory: bpy.props.StringProperty(maxlen=1024, subtype='FILE_PATH', options={'HIDDEN', 'SKIP_SAVE'})
#since I wrote this myself, a bit more efficent than cats. mostly - @989onan
def execute(self, context: bpy.types.Context):
file_grouping_dict: dict[str, list[dict[str,str]]] = dict()#group our files so our importers can import them together. in the case of OBJ+MTL and others that need grouped files, this is extremely important.
#check if we are importing multiple files
is_multi = False
try:
for file in self.files:
pass
is_multi = True
except Exception as e:
is_multi = False
print(e)
#put the files together into lists of same importers
if(is_multi):
for file in self.files:
fullpath = os.path.join(self.directory,os.path.basename(file.name))
name = pathlib.Path(fullpath).suffix.replace(".","")
#this makes sure our imports that should be grouped stay together.
#basically the method checks for if the first value has a lambda with the same bytecode as another lambda, then it will use that value's key (ex:"obj"<->"mtl" or "fbx"), keeping same importers together
try:
name2 = next(key for key,value in import_types.items() if value.__code__.co_code == import_types[name].__code__.co_code)
print(name +" is the same importer as "+name2+", grouping.")
name = name2
except Exception as e:
print("error when trying to find a value of the same value in the kinds of importers. May just be an import type that's a singlet:")
print(e)
if name not in file_grouping_dict: file_grouping_dict[name] = []
file_grouping_dict[name].append({"name": os.path.basename(file.name)}) #emulate passing a list of files.
else:
fullpath: str = os.path.join(os.path.dirname(self.filepath),os.path.basename(self.filepath))
name = pathlib.Path(fullpath).suffix.replace(".","")
if name not in file_grouping_dict: file_grouping_dict[name] = []
file_grouping_dict[name].append({"name": fullpath}) #emulate passing a list of files.
#import the files together to make sure things like obj import together. This is important
for file_group_name,files in file_grouping_dict.items():
try:
if(self.directory):
print(files)
import_types[file_group_name](self.directory,files,self.filepath)
else:
import_types[file_group_name]("",files,self.filepath) #give an empty directory, works just fine for 90%
except AttributeError as e:
print("Warning, you may not have the required importer!")
common.open_web_after_delay_multi_threaded(delay=12, url=t('Importing.importer_search_term').format(extension = file_group_name))
self.report({'ERROR'},t('Importing.need_importer').format(extension = file_group_name))
print("importer error was:")
print(e)
return {'FINISHED'}
#This needs to be done with our own MMD importer:
"""
#stolen from cats. Oh wait I made this code riiiiiiight - @989onan
@register_wrap
class ImportMMDAnimation(bpy.types.Operator, ImportHelper):
bl_idname = 'avatar_toolkit.import_mmd_animation'
bl_label = t('Importer.mmd_anim_importer.label')
bl_description = t('Importer.mmd_anim_importer.desc')
bl_options = {'INTERNAL', 'UNDO'}
filter_glob: bpy.props.StringProperty(
default="*.vmd",
options={'HIDDEN'}
)
files: bpy.props.CollectionProperty(type=bpy.types.OperatorFileListElement, options={'HIDDEN', 'SKIP_SAVE'})
directory: bpy.props.StringProperty(maxlen=1024, subtype='FILE_PATH', options={'HIDDEN', 'SKIP_SAVE'})
filepath: bpy.props.StringProperty()
@classmethod
def poll(cls, context):
if common.get_armature(context) is None:
return False
return True
def execute(self, context):
# Make sure that the first layer is visible
if hasattr(context.scene, 'layers'):
context.scene.layers[0] = True
filename, extension = os.path.splitext(self.filepath)
if(extension == ".vmd"):
#A dictionary to change the current model to MMD importer compatable temporarily
bonedict = {
"chest":"UpperBody",
"neck":"Neck",
"head":"Head",
"hips":"Center",
"spine":"LowerBody",
"right_wrist":"Wrist_R",
"right_elbow":"Elbow_R",
"right_arm":"Arm_R",
"right_shoulder":"Shoulder_R",
"right_leg":"Leg_R",
"right_knee":"Knee_R",
"right_ankle":"Ankle_R",
"right_toe":"Toe_R",
"left_wrist":"Wrist_L",
"left_elbow":"Elbow_L",
"left_arm":"Arm_L",
"left_shoulder":"Shoulder_L",
"left_leg":"Leg_L",
"left_knee":"Knee_L",
"left_ankle":"Ankle_L",
"left_toe":"Toe_L"
}
armature = common.get_armature(context)
common.unselect_all()
common.Set_Mode(context, 'OBJECT')
common.unselect_all()
common.set_active(armature)
orig_names = dict()
reverse_bone_lookup = dict()
for (preferred_name, name_list) in bone_names.items():
for name in name_list:
reverse_bone_lookup[name] = preferred_name
for bone in armature.data.bones:
if common.simplify_bonename(bone.name) in reverse_bone_lookup and reverse_bone_lookup[common.simplify_bonename(bone.name)] in bonedict:
orig_names[bonedict[reverse_bone_lookup[common.simplify_bonename(bone.name)]]] = bone.name
bone.name = bonedict[reverse_bone_lookup[common.simplify_bonename(bone.name)]]
try:
bpy.ops.mmd_tools.import_vmd(filepath=self.filepath,bone_mapper='RENAMED_BONES',use_underscore=True, dictionary='INTERNAL')
except AttributeError as e:
print("importer error was:")
print(e)
print(t('Importing.importer_search_term'))
common.open_web_after_delay_multi_threaded(delay=12, url=t('Importing.importer_search_term').format(extension = "MMD"))
self.report({'ERROR'},t('Importing.need_importer').format(extension = "MMD"))
return {'CANCELLED'}
#iterate through bones and put them back, therefore blender API will change the animation to be correct.
#this is because renaming bones fixes the animation targets in the data model.
for bone in armature.data.bones:
if common.simplify_bonename(bone.name) in orig_names:
bone.name = orig_names[common.simplify_bonename(bone.name)]
common.unselect_all()
common.Set_Mode(context, 'OBJECT')
common.unselect_all()
common.set_active(armature)
return {'FINISHED'} """
+15 -11
View File
@@ -1,8 +1,8 @@
import bpy
from typing import List, Optional
from typing import List, Optional, Set
from bpy.types import Operator, Context, Object
from ..core.register import register_wrap
from ..core.common import fix_uv_coordinates
from ..core.common import fix_uv_coordinates, get_selected_armature, is_valid_armature, select_current_armature, get_all_meshes
from ..functions.translations import t
@register_wrap
@@ -14,21 +14,23 @@ class JoinAllMeshes(Operator):
@classmethod
def poll(cls, context: Context) -> bool:
return context.mode == 'OBJECT'
armature = get_selected_armature(context)
return armature is not None and is_valid_armature(armature)
def execute(self, context: Context) -> set:
def execute(self, context: Context) -> Set[str]:
self.join_all_meshes(context)
return {'FINISHED'}
def join_all_meshes(self, context: Context) -> None:
if not bpy.data.objects:
self.report({'INFO'}, "No objects in the scene")
if not select_current_armature(context):
self.report({'WARNING'}, "No armature selected")
return
armature = get_selected_armature(context)
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
meshes: List[Object] = [obj for obj in bpy.data.objects if obj.type == 'MESH']
meshes: List[Object] = get_all_meshes(context)
for mesh in meshes:
mesh.select_set(True)
@@ -43,6 +45,8 @@ class JoinAllMeshes(Operator):
else:
self.report({'WARNING'}, "No mesh objects selected")
context.view_layer.objects.active = armature
@register_wrap
class JoinSelectedMeshes(Operator):
bl_idname = "avatar_toolkit.join_selected_meshes"
@@ -52,17 +56,17 @@ class JoinSelectedMeshes(Operator):
@classmethod
def poll(cls, context: Context) -> bool:
return context.mode == 'OBJECT'
return context.mode == 'OBJECT' and len([obj for obj in context.selected_objects if obj.type == 'MESH']) > 1
def execute(self, context: Context) -> set:
def execute(self, context: Context) -> Set[str]:
self.join_selected_meshes(context)
return {'FINISHED'}
def join_selected_meshes(self, context: Context) -> None:
selected_objects: List[Object] = [obj for obj in bpy.context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'WARNING'}, "No mesh objects selected")
if len(selected_objects) < 2:
self.report({'WARNING'}, "Please select at least two mesh objects")
return
bpy.ops.object.mode_set(mode='OBJECT')
+122
View File
@@ -0,0 +1,122 @@
from ast import Dict
from itertools import count
import bpy
import re
from typing import List, Tuple, Optional, TypedDict
from bpy.types import Material, Operator, Context, Object
from ..core.register import register_wrap
from ..core.common import get_selected_armature, is_valid_armature, select_current_armature, get_all_meshes
class meshEntry(TypedDict):
mesh: bpy.types.Object
shapekeys: list[str]
@register_wrap
class RemoveDoublesSafely(Operator):
bl_idname = "avatar_toolkit.remove_doubles_safely"
bl_label = "Remove Doubles Safely"
bl_description = "Remove Doubles on all meshes, making sure to not fuse things like mouths together."
bl_options = {'REGISTER', 'UNDO'}
objects_to_do: list[meshEntry] = []
merge_distance: bpy.props.FloatProperty(default=0.0001)
@classmethod
def poll(cls, context: Context) -> bool:
armature = get_selected_armature(context)
return armature is not None and is_valid_armature(armature)
def execute(self, context: Context) -> set:
if not select_current_armature(context):
self.report({'WARNING'}, "No armature selected")
return {'CANCELLED'}
armature = get_selected_armature(context)
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
objects: List[Object] = get_all_meshes(context)
for mesh in objects:
if mesh.data.name not in [stored_object["mesh"].data.name for stored_object in self.objects_to_do]:
mesh_shapekeys = {"mesh":mesh,"shapekeys":[]}
mesh_data: bpy.types.Mesh = mesh.data
shape: bpy.types.ShapeKey = None
if mesh_data.shape_keys:
for shape in mesh_data.shape_keys.key_blocks:
mesh_shapekeys["shapekeys"].append(shape.name)
self.objects_to_do.append(mesh_shapekeys)
return {'FINISHED'}
def invoke(self, context: Context, event: bpy.types.Event) -> set:
self.execute(context)
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def modify_mesh(self, context: Context, mesh: meshEntry):
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
context.view_layer.objects.active = mesh["mesh"]
mesh_data: bpy.types.Mesh = mesh["mesh"].data
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
for index, point in enumerate(mesh["mesh"].active_shape_key.points):
if point.co.xyz != mesh_data.shape_keys.key_blocks[0].points[index].co.xyz:
mesh_data.vertices[index].select = True
print("shapekey has a moved vertex at index \""+str(index)+"\", excluding from double merging!")
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
def modal(self, context: Context, event: bpy.types.Event) -> set:
if len(self.objects_to_do) > 0:
mesh = self.objects_to_do[0]
mesh_data: bpy.types.Mesh = mesh["mesh"].data
if len(mesh['shapekeys']) > 0:
shapekeyname: str = mesh['shapekeys'].pop(0)
target_shapekey: int = mesh_data.shape_keys.key_blocks.find(shapekeyname)
mesh["mesh"].active_shape_key_index = target_shapekey
print("doing shapekey \""+shapekeyname+"\" on mesh \""+mesh['mesh'].name+"\".")
self.modify_mesh(context, mesh)
elif not (mesh_data.shape_keys):
print("doing mesh with no shapekeys named \""+mesh['mesh'].name+"\".")
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
bpy.ops.object.mode_set(mode='EDIT')
mesh_data.vertices.foreach_set("select",[False]*len(mesh_data.vertices))
bpy.ops.mesh.select_all(action="INVERT")
bpy.ops.mesh.remove_doubles(threshold=self.merge_distance,use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
self.objects_to_do.pop(0)
else:
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action="INVERT")
bpy.ops.mesh.remove_doubles(threshold=self.merge_distance,use_unselected=False)
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
self.objects_to_do.pop(0)
if len(self.objects_to_do) > 0:
mesh = self.objects_to_do[0]
mesh["mesh"].select_set(True)
context.view_layer.objects.active = mesh["mesh"]
bpy.ops.object.mode_set(mode='EDIT')
mesh_data.vertices.foreach_set("select",[False]*len(mesh_data.vertices))
bpy.ops.object.mode_set(mode='OBJECT')
mesh["mesh"].select_set(False)
else:
return {'FINISHED'}
return {'RUNNING_MODAL'}
+8 -9
View File
@@ -4,7 +4,7 @@ from typing import List, Optional
import re
from bpy.types import Operator, Context, Object
from ..core.dictionaries import bone_names
from ..core.common import get_armature, simplify_bonename
from ..core.common import get_selected_armature, simplify_bonename, is_valid_armature
from ..functions.translations import t
@register_wrap
@@ -16,12 +16,14 @@ class ConvertToResonite(Operator):
@classmethod
def poll(cls, context: Context) -> bool:
if not get_armature(context):
return False
return True
armature = get_selected_armature(context)
return armature is not None and is_valid_armature(armature)
def execute(self, context: Context) -> set:
armature = get_armature(context)
armature = get_selected_armature(context)
if not armature:
self.report({'WARNING'}, "No armature selected")
return {'CANCELLED'}
translate_bone_fails = 0
untranslated_bones = set()
@@ -89,8 +91,6 @@ class ConvertToResonite(Operator):
'thumb_3_r': "thumb3.R"
}
context.view_layer.objects.active = armature
bpy.ops.object.mode_set(mode='EDIT')
@@ -111,5 +111,4 @@ class ConvertToResonite(Operator):
else:
self.report({'INFO'}, "Successfully translated all bones to humanoid names")
return {'FINISHED'}
return {'FINISHED'}