File size: 10,089 Bytes
e9eca74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e6cdcd
 
 
 
 
 
 
 
e9eca74
 
 
 
 
 
 
 
 
 
 
 
 
 
0e6cdcd
 
 
 
 
 
 
 
 
e9eca74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e6cdcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b14d5c1
 
 
 
 
 
 
e9eca74
 
 
 
 
 
 
b14d5c1
 
 
 
 
 
 
 
 
 
 
8080e63
 
b14d5c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import math
import os
import sys

import bpy
import numpy as np
from bpy.types import Action, Armature, Mesh, Object

# isort: split
import bmesh
import mathutils


class HiddenPrints:
    def __init__(self, enable=True, suppress_err=False):
        self.enable = enable
        self.suppress_err = suppress_err

    def __enter__(self):
        if not self.enable:
            return
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, "w")
        if self.suppress_err:
            self._original_stderr = sys.stderr
            sys.stderr = open(os.devnull, "w")

    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self.enable:
            return
        sys.stdout.close()
        sys.stdout = self._original_stdout
        if self.suppress_err:
            sys.stderr.close()
            sys.stderr = self._original_stderr


USE_WORLD_COORDINATES = False


class Mode:
    def __init__(self, mode_name="EDIT", active_obj: Object = None):
        self.mode = mode_name
        self.active = active_obj
        self.pre_active = None
        self.pre_mode = "OBJECT"

    def __enter__(self):
        self.pre_active = bpy.context.view_layer.objects.active
        if self.pre_active is not None:
            self.pre_mode = bpy.context.object.mode
        bpy.context.view_layer.objects.active = self.active
        bpy.ops.object.mode_set(mode=self.mode)
        return self.active

    def __exit__(self, exc_type, exc_val, exc_tb):
        bpy.ops.object.mode_set(mode=self.pre_mode)
        bpy.context.view_layer.objects.active = self.pre_active


def reset():
    bpy.ops.wm.read_factory_settings(use_empty=True)


def update():
    bpy.context.view_layer.update()
    bpy.context.scene.update_tag()
    for obj in bpy.context.scene.objects:
        # obj.hide_render = obj.hide_render
        obj.update_tag()


def remove_all(delete_actions=True):
    for obj in bpy.data.objects.values():
        bpy.data.objects.remove(obj, do_unlink=True)
    bpy.ops.outliner.orphans_purge(do_recursive=True)
    if delete_actions:
        for action in bpy.data.actions:
            bpy.data.actions.remove(action, do_unlink=True)


def remove_empty():
    childless_empties = [e for e in bpy.data.objects if e.type.startswith("EMPTY") and not e.children]
    bpy.data.batch_remove(childless_empties)


def remove_collection(coll_name: str):
    if coll_name not in bpy.data.collections:
        return
    coll = bpy.data.collections[coll_name]
    for c in coll.children:
        remove_collection(c)
    bpy.data.collections.remove(coll, do_unlink=True)


def load_file(filepath: str, *args, **kwargs) -> "list[Object]":
    old_objs = set(bpy.context.scene.objects)
    if filepath.endswith(".glb"):
        bpy.ops.import_scene.gltf(filepath=filepath, *args, **kwargs)
    elif filepath.endswith(".fbx"):
        bpy.ops.import_scene.fbx(filepath=filepath, *args, **kwargs)
    elif filepath.endswith(".obj"):
        bpy.ops.wm.obj_import(filepath=filepath, *args, **kwargs)
    elif filepath.endswith(".ply"):
        bpy.ops.wm.ply_import(filepath=filepath, *args, **kwargs)
    else:
        raise RuntimeError(f"Invalid input file: {filepath}")
    imported_objs = set(bpy.context.scene.objects) - old_objs
    imported_objs = sorted(imported_objs, key=lambda x: x.name)
    print("Imported:", imported_objs)
    return imported_objs


def select_all():
    bpy.ops.object.select_all(action="SELECT")


def deselect():
    bpy.ops.object.select_all(action="DESELECT")


def select_objs(obj_list: "list[Object]" = None, deselect_first=False):
    if not obj_list:
        obj_list = bpy.context.scene.objects
    if deselect_first:
        deselect()
    for obj in obj_list:
        obj.select_set(True)


def select_mesh(obj_list: "list[Object]" = None, all=True, deselect_first=False):
    if not obj_list:
        obj_list = bpy.context.scene.objects
    if deselect_first:
        deselect()
    for obj in obj_list:
        if obj.type == "MESH":
            if all:
                obj.select_set(True)
            else:
                break


class Select:
    """
    Deselecting before and after selecting the specified objects.
    """

    def __init__(self, objs: "Object | list[Object]" = None):
        self.objs = (objs,) if isinstance(objs, Object) else objs
        self.objs: "tuple[Object]" = tuple(self.objs)

    def __enter__(self):
        select_objs(self.objs, deselect_first=True)
        return self.objs

    def __exit__(self, exc_type, exc_val, exc_tb):
        deselect()


def get_type_objs(obj_list: "list[Object]" = None, type="MESH", sort=True) -> "list[Object]":
    if not obj_list:
        obj_list = bpy.context.scene.objects
    type_obj_list = [obj for obj in obj_list if obj.type == type]
    if sort:
        type_obj_list = sorted(type_obj_list, key=lambda x: x.name)
    return type_obj_list


def get_all_mesh_obj(obj_list: "list[Object]" = None):
    return get_type_objs(obj_list, "MESH")


def get_all_armature_obj(obj_list: "list[Object]" = None):
    return get_type_objs(obj_list, "ARMATURE")


def get_armature_obj(obj_list: "list[Object]" = None) -> Object:
    if not obj_list:
        obj_list = bpy.context.scene.objects
    for obj in obj_list:
        if obj.type == "ARMATURE":
            return obj


def get_rest_bones(armature_obj: Object):
    if armature_obj is None:
        return None, None, None
    rest_bones = []
    rest_bones_tail = []
    bones_idx_dict: "dict[str, int]" = {}
    armature_data: Armature = armature_obj.data
    for i, bone in enumerate(armature_data.bones):
        pos = bone.head_local
        pos_tail = bone.tail_local
        if USE_WORLD_COORDINATES:
            pos = armature_obj.matrix_world @ pos
            pos_tail = armature_obj.matrix_world @ pos_tail
        rest_bones.append(pos)
        rest_bones_tail.append(pos_tail)
        bones_idx_dict[bone.name] = i
    rest_bones = np.stack(rest_bones, axis=0)
    rest_bones_tail = np.stack(rest_bones_tail, axis=0)
    return rest_bones, rest_bones_tail, bones_idx_dict


def transfer_weights(source_bone_name: str, target_bone_name: str, mesh_obj_list: "list[Object]"):
    if isinstance(mesh_obj_list, Object):
        mesh_obj_list = [mesh_obj_list]
    for obj in mesh_obj_list:
        source_group = obj.vertex_groups.get(source_bone_name)
        if source_group is None:
            return
        source_i = source_group.index
        target_group = obj.vertex_groups.get(target_bone_name)
        if target_group is None:
            target_group = obj.vertex_groups.new(name=target_bone_name)

        for v in obj.data.vertices:
            for g in v.groups:
                if g.group == source_i:
                    target_group.add((v.index,), g.weight, "ADD")
        obj.vertex_groups.remove(source_group)


def remove_empty_vgroups(mesh_obj_list: "list[Object]"):
    if isinstance(mesh_obj_list, Object):
        mesh_obj_list = [mesh_obj_list]
    for obj in mesh_obj_list:
        vertex_groups = obj.vertex_groups
        groups = {r: None for r in range(len(vertex_groups))}

        for vert in obj.data.vertices:
            for vg in vert.groups:
                i = vg.group
                if i in groups:
                    del groups[i]

        lis = list(groups)
        lis.sort(reverse=True)
        for i in lis:
            vertex_groups.remove(vertex_groups[i])


def set_action(armature_obj: Object, action: Action):
    if not armature_obj.animation_data:
        armature_obj.animation_data_create()
    armature_obj.animation_data.action = action
    return armature_obj


def mesh_quads2tris(obj_list: "list[Object]" = None):
    if not obj_list:
        obj_list = bpy.context.scene.objects
    for obj in obj_list:
        if obj.type == "MESH":
            with Mode("EDIT", obj):
                bpy.ops.mesh.quads_convert_to_tris(quad_method="BEAUTY", ngon_method="BEAUTY")


def get_enabled_addons() -> "list[str]":
    return [x.module for x in bpy.context.preferences.addons]


def enable_arp(armature_obj: Object, addon_path=os.path.join(os.path.dirname(__file__), "auto_rig_pro")):
    import sys

    assert os.path.isfile(os.path.join(addon_path, "__init__.py")), "Auto-Rig Pro not found"
    dirname, addon_name = os.path.split(addon_path)
    # if addon_name in get_enabled_addons():
    #     return
    sys.path.insert(0, dirname)
    with Mode("POSE", armature_obj):
        # import addon_utils
        # addon_utils.enable(addon_name)
        bpy.ops.preferences.addon_enable(module=addon_name)


def retarget(source_armature: Object, target_armature: Object, inplace=False):
    enable_arp(target_armature)
    scn = bpy.context.scene
    scn.source_rig = source_armature.name
    if inplace:
        scn.arp_retarget_in_place = True
    scn.target_rig = target_armature.name
    bpy.ops.arp.auto_scale()
    bpy.ops.arp.build_bones_list()
    hips = scn.bones_map_v2["mixamorig:Hips"]
    scn.bones_map_index = list(scn.bones_map_v2).index(hips)
    hips.set_as_root = True
    bpy.ops.arp.retarget()
    return target_armature


def load_mixamo_anim(char_file: str, anim_file: str, do_retarget=False, inplace=False, to_tris=False):
    char_objs = load_file(char_file) if isinstance(char_file, str) else char_file
    char_armature = get_armature_obj(char_objs)

    anim_objs = load_file(anim_file)
    anim_armature = get_armature_obj(anim_objs)
    print(anim_armature)
    print(anim_armature.animation_data)
    assert anim_armature.animation_data is not None and len(bpy.data.actions) > 0, f"Animation not found in {anim_file}"

    set_action(char_armature, anim_armature.animation_data.action)
    if do_retarget:
        retarget(anim_armature, char_armature, inplace=inplace)
        for action in bpy.data.actions:
            if action is not char_armature.animation_data.action:
                bpy.data.actions.remove(action, do_unlink=True)
    for obj in anim_objs:
        bpy.data.objects.remove(obj, do_unlink=True)

    if to_tris:
        mesh_quads2tris(char_objs)
    return char_objs