forked from soupday/cc_blender_tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrigging.py
3133 lines (2563 loc) · 125 KB
/
rigging.py
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2021 Victor Soupday
# This file is part of CC/iC Blender Tools <https://github.com/soupday/cc_blender_tools>
#
# CC/iC Blender Tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# CC/iC Blender Tools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with CC/iC Blender Tools. If not, see <https://www.gnu.org/licenses/>.
from random import random
import bpy
import mathutils
import addon_utils
import math
import re
from . import utils, vars
from . import geom
from . import meshutils
from . import properties
from . import modifiers
from . import physics
from . import bones
from . import rigify_mapping_data
class BoundingBox:
box_min = [ float('inf'), float('inf'), float('inf')]
box_max = [-float('inf'),-float('inf'),-float('inf')]
def __init__(self):
for i in range(0,3):
self.box_min[i] = float('inf')
self.box_max[i] = -float('inf')
def add(self, coord):
for i in range(0,3):
if coord[i] < self.box_min[i]:
self.box_min[i] = coord[i]
if coord[i] > self.box_max[i]:
self.box_max[i] = coord[i]
def pad(self, padding):
for i in range(0,3):
self.box_min[i] -= padding
self.box_max[i] += padding
def relative(self, coord):
r = [0,0,0]
for i in range(0,3):
r[i] = (coord[i] - self.box_min[i]) / (self.box_max[i] - self.box_min[i])
return r
def coord(self, relative):
c = [0,0,0]
for i in range(0,3):
c[i] = relative[i] * (self.box_max[i] - self.box_min[i]) + self.box_min[i]
return c
def debug(self):
utils.log_always("BOX:")
utils.log_always("Min:", self.box_min)
utils.log_always("Max:", self.box_max)
def edit_rig(rig):
if rig and utils.edit_mode_to(rig):
return True
utils.log_error(f"Unable to edit rig: {rig}!")
return False
def select_rig(rig):
if rig and utils.object_mode_to(rig):
return True
utils.log_error(f"Unable to select rig: {rig}!")
return False
def prune_meta_rig(meta_rig):
"""Removes some meta rig bones that have no corresponding match in the CC3 rig.
(And are safe to remove)
"""
if edit_rig(meta_rig):
pelvis_r = bones.get_edit_bone(meta_rig, "pelvis.R")
pelvis_l = bones.get_edit_bone(meta_rig, "pelvis.L")
if pelvis_r and pelvis_l:
meta_rig.data.edit_bones.remove(pelvis_r)
pelvis_l.name = "pelvis"
def add_def_bones(chr_cache, cc3_rig, rigify_rig):
"""Adds and parents twist deformation bones to the rigify deformation bones.
Twist bones are parented to their corresponding limb bones.
The main limb bones are not vertex weighted in the meshes but the twist bones are,
so it's important the twist bones move (and stretch) with the parent limb.
Also adds some missing toe bones and finger bones.
(See: ADD_DEF_BONES array)
"""
utils.log_info("Adding addition control bones to Rigify Control Rig:")
utils.log_indent()
for def_copy in rigify_mapping_data.ADD_DEF_BONES:
src_bone_name = def_copy[0]
dst_bone_name = def_copy[1]
dst_bone_parent_name = def_copy[2]
relation_flags = def_copy[3]
layer = def_copy[4]
deform = dst_bone_name[:3] == "DEF"
scale = 1
ref = None
arg = None
if len(def_copy) > 5:
scale = def_copy[5]
if len(def_copy) > 6:
ref = def_copy[6]
if len(def_copy) > 7:
arg = def_copy[7]
utils.log_info(f"Adding/Processing: {dst_bone_name}")
# reparent an existing deformation bone
if src_bone_name == "-":
reparented_bone = bones.reparent_edit_bone(rigify_rig, dst_bone_name, dst_bone_parent_name)
if reparented_bone:
bones.set_edit_bone_flags(reparented_bone, relation_flags, deform)
bones.set_bone_layer(rigify_rig, dst_bone_name, layer)
# add a custom DEF or ORG bone
elif src_bone_name[:3] == "DEF" or src_bone_name[:3] == "ORG":
def_bone = bones.copy_edit_bone(rigify_rig, src_bone_name, dst_bone_name, dst_bone_parent_name, scale)
if def_bone:
bones.set_edit_bone_flags(def_bone, relation_flags, deform)
bones.set_bone_layer(rigify_rig, dst_bone_name, layer)
# partial rotation copy for share bones
if "_share" in dst_bone_name and ref:
bones.add_copy_rotation_constraint(rigify_rig, rigify_rig, ref, dst_bone_name, arg)
# or make a copy of a bone from the original character rig
else:
def_bone = bones.copy_rl_edit_bone(cc3_rig, rigify_rig, src_bone_name, dst_bone_name, dst_bone_parent_name, scale)
if def_bone:
bones.set_edit_bone_flags(def_bone, relation_flags, deform)
bones.set_bone_layer(rigify_rig, dst_bone_name, layer)
utils.log_recess()
def add_accessory_bones(chr_cache, cc3_rig, rigify_rig, bone_mappings):
# find all the accessories in the armature
accessory_bone_names = bones.find_accessory_bones(bone_mappings, cc3_rig)
# copy the accessory bone trees into the rigify rig
for bone_name in accessory_bone_names:
bone = cc3_rig.data.bones[bone_name]
if bone:
utils.log_info(f"Processing accessory root bone: {bone_name}")
cc3_parent_name = None
rigify_parent_name = None
if bone.parent:
cc3_parent_name = bone.parent.name
for bone_map in bone_mappings:
if bone_map[1] == cc3_parent_name:
# try to find the parent in the ORG bones
rigify_parent_name = f"ORG-{bone_map[0]}"
if rigify_parent_name not in rigify_rig.data.bones:
# then try the DEF bones
rigify_parent_name = f"DEF-{bone_map[0]}"
if rigify_parent_name not in rigify_rig.data.bones:
rigify_parent_name = None
if not (rigify_parent_name and rigify_parent_name in rigify_rig.data.bones):
utils.log_error(f"Unable to find matching accessory bone tree parent: {cc3_parent_name} in rigify bones!")
utils.log_info(f"Copying accessory bone tree into rigify rig: {bone.name} parent: {rigify_parent_name}")
bones.copy_rl_edit_bone_subtree(cc3_rig, rigify_rig, bone.name, bone.name, rigify_parent_name, 23)
def rl_vertex_group(obj, group):
"""Find the vertex group in the object, either with a prefixed CC_Base_ or without."""
if group in obj.vertex_groups:
return group
# remove "CC_Base_" from name and try again.
if len(group) > 8:
group = group[8:]
if group in obj.vertex_groups:
return group
return None
def rename_vertex_groups(cc3_rig, rigify_rig, vertex_groups):
"""Rename the CC3 rig vertex weight groups to the Rigify deformation bone names,
removes matching existing vertex groups created by parent with automatic weights.
Thus leaving just the automatic face rig weights.
"""
utils.log_info("Remapping original Deformation vertex groups to the new Rigify bones:")
utils.log_indent()
obj : bpy.types.Object
for obj in rigify_rig.children:
utils.log_info(f"Remapping groups for: {obj.name}")
for vgrn in vertex_groups:
vg_to = vgrn[0]
vg_from = rl_vertex_group(obj, vgrn[1])
if vg_from:
try:
if vg_to in obj.vertex_groups:
obj.vertex_groups.remove(obj.vertex_groups[vg_to])
except:
pass
try:
if vg_from in obj.vertex_groups:
obj.vertex_groups[vg_from].name = vg_to
except:
pass
for mod in obj.modifiers:
if mod.type == "ARMATURE":
mod.object = rigify_rig
mod.use_deform_preserve_volume = False
utils.log_recess()
def store_relative_mappings(meta_rig, coords):
"""Store bone positions relative to a bounding box of control bones.
"""
if edit_rig(meta_rig):
for mapping in rigify_mapping_data.RELATIVE_MAPPINGS:
bone_name = mapping[0]
bone = bones.get_edit_bone(meta_rig, bone_name)
if bone:
bone_head_pos = meta_rig.matrix_world @ bone.head
bone_tail_pos = meta_rig.matrix_world @ bone.tail
box = BoundingBox()
for i in range(2, len(mapping)):
rel_name = mapping[i]
rel_bone = bones.get_edit_bone(meta_rig, rel_name)
if rel_bone:
head_pos = meta_rig.matrix_world @ rel_bone.head
tail_pos = meta_rig.matrix_world @ rel_bone.tail
box.add(head_pos)
#box.add(tail_pos)
box.pad(rigify_mapping_data.BOX_PADDING)
coords[bone_name] = [box.relative(bone_head_pos), box.relative(bone_tail_pos)]
def restore_relative_mappings(meta_rig, coords):
"""Restore bone positions relative to a bounding box of control bones.
"""
if edit_rig(meta_rig):
for mapping in rigify_mapping_data.RELATIVE_MAPPINGS:
bone_name = mapping[0]
bone = bones.get_edit_bone(meta_rig, bone_name)
if bone:
box = BoundingBox()
for i in range(2, len(mapping)):
rel_name = mapping[i]
rel_bone = bones.get_edit_bone(meta_rig, rel_name)
if rel_bone:
head_pos = meta_rig.matrix_world @ rel_bone.head
tail_pos = meta_rig.matrix_world @ rel_bone.tail
box.add(head_pos)
#box.add(tail_pos)
box.pad(rigify_mapping_data.BOX_PADDING)
rc = coords[bone_name]
if (mapping[1] == "HEAD" or mapping[1] == "BOTH"):
bone.head = box.coord(rc[0])
if (mapping[1] == "TAIL" or mapping[1] == "BOTH"):
bone.tail = box.coord(rc[1])
def store_bone_roll(meta_rig, roll_store):
"""Store the bone roll and roll axis (z_axis) for each bone in the meta rig.
"""
if edit_rig(meta_rig):
for bone in meta_rig.data.edit_bones:
roll_store[bone.name] = [bone.roll, bone.z_axis]
def restore_bone_roll(meta_rig, roll_store):
"""Restore the bone roll for each bone in the meta rig, after the positions have matched
to the CC3 rig.
"""
if edit_rig(meta_rig):
for bone in meta_rig.data.edit_bones:
if bone.name in roll_store:
bone_roll = roll_store[bone.name][0]
bone_z_axis = roll_store[bone.name][1]
bone.align_roll(bone_z_axis)
for correction in rigify_mapping_data.ROLL_CORRECTION:
if correction[0] == bone.name:
axis = correction[1]
if axis == "X":
bone.align_roll(mathutils.Vector((1,0,0)))
if axis == "Y":
bone.align_roll(mathutils.Vector((0,1,0)))
if axis == "Z":
bone.align_roll(mathutils.Vector((0,0,1)))
if axis == "-X":
bone.align_roll(mathutils.Vector((-1,0,0)))
if axis == "-Y":
bone.align_roll(mathutils.Vector((0,-1,0)))
if axis == "-Z":
bone.align_roll(mathutils.Vector((0,0,-1)))
def set_rigify_params(meta_rig):
"""Apply custom Rigify parameters to bones in the meta rig.
"""
if select_rig(meta_rig):
for params in rigify_mapping_data.RIGIFY_PARAMS:
bone_name = params[0]
bone_param = params[1]
bone_value = params[2]
pose_bone = bones.get_pose_bone(meta_rig, bone_name)
if pose_bone:
try:
exec(f"pose_bone.rigify_parameters.{bone_param} = bone_value", None, locals())
except:
pass
def map_face_bones(cc3_rig, meta_rig, cc3_head_bone):
"""Map positions of special face bones.
"""
obj : bpy.types.Object = None
for child in cc3_rig.children:
if child.name.lower().endswith("base_eye"):
obj = child
length = 0.375
if edit_rig(meta_rig):
# left and right eyes
left_eye = bones.get_edit_bone(meta_rig, "eye.L")
left_eye_source = bones.get_rl_bone(cc3_rig, "CC_Base_L_Eye")
right_eye = bones.get_edit_bone(meta_rig, "eye.R")
right_eye_source = bones.get_rl_bone(cc3_rig, "CC_Base_R_Eye")
if left_eye and left_eye_source:
head_position = cc3_rig.matrix_world @ left_eye_source.head_local
tail_position = cc3_rig.matrix_world @ left_eye_source.tail_local
dir : mathutils.Vector = tail_position - head_position
left_eye.tail = head_position - (dir * length)
if right_eye and right_eye_source:
head_position = cc3_rig.matrix_world @ right_eye_source.head_local
tail_position = cc3_rig.matrix_world @ right_eye_source.tail_local
dir : mathutils.Vector = tail_position - head_position
right_eye.tail = head_position - (dir * length)
# head bone
spine6 = bones.get_edit_bone(meta_rig, "spine.006")
head_bone_source = bones.get_rl_bone(cc3_rig, cc3_head_bone)
if spine6 and head_bone_source:
head_position = cc3_rig.matrix_world @ head_bone_source.head_local
length = 0
n = 0
if left_eye_source:
left_eye_position = cc3_rig.matrix_world @ left_eye_source.head_local
length += left_eye_position.z - head_position.z
n += 1
if right_eye_source:
right_eye_position = cc3_rig.matrix_world @ right_eye_source.head_local
length += right_eye_position.z - head_position.z
n += 1
if n > 0:
length *= 2.65 / n
else:
length = 0.25
tail_position = head_position + mathutils.Vector((0,0,1)) * length
spine6.tail = tail_position
# teeth bones
face_bone = bones.get_edit_bone(meta_rig, "face")
teeth_t_bone = bones.get_edit_bone(meta_rig, "teeth.T")
teeth_t_source_bone = bones.get_rl_bone(cc3_rig, "CC_Base_Teeth01")
teeth_b_bone = bones.get_edit_bone(meta_rig, "teeth.B")
teeth_b_source_bone = bones.get_rl_bone(cc3_rig, "CC_Base_Teeth02")
if face_bone and teeth_t_bone and teeth_t_source_bone:
face_dir = face_bone.tail - face_bone.head
teeth_t_bone.head = (cc3_rig.matrix_world @ teeth_t_source_bone.head_local) + face_dir * 0.5
teeth_t_bone.tail = (cc3_rig.matrix_world @ teeth_t_source_bone.head_local)
if face_bone and teeth_b_bone and teeth_b_source_bone:
face_dir = face_bone.tail - face_bone.head
teeth_b_bone.head = (cc3_rig.matrix_world @ teeth_b_source_bone.head_local) + face_dir * 0.5
teeth_b_bone.tail = (cc3_rig.matrix_world @ teeth_b_source_bone.head_local)
def fix_jaw_pivot(cc3_rig, meta_rig):
"""Set the exact jaw bone position by setting the YZ coordinates of the jaw left and right bones.
"""
if edit_rig(meta_rig):
jaw_l_bone = bones.get_edit_bone(meta_rig, "jaw.L")
jaw_r_bone = bones.get_edit_bone(meta_rig, "jaw.R")
jaw_source_bone = bones.get_rl_bone(cc3_rig, "CC_Base_JawRoot")
if jaw_source_bone:
jaw_xyz = cc3_rig.matrix_world @ jaw_source_bone.head_local
if jaw_l_bone:
jaw_l_bone.head.z = jaw_xyz.z
jaw_l_bone.head.y = jaw_xyz.y
if jaw_r_bone:
jaw_r_bone.head.z = jaw_xyz.z
jaw_r_bone.head.y = jaw_xyz.y
def report_uv_face_targets(obj, meta_rig):
"""For reprting the UV coords of the face bones in the meta rig.
"""
if edit_rig(meta_rig):
mat_slot = get_head_material_slot(obj)
mesh = obj.data
t_mesh = geom.get_triangulated_bmesh(mesh)
bone : bpy.types.EditBone
for bone in meta_rig.data.edit_bones:
if bone.layers[0] and bone.name != "face":
head_world = bone.head
tail_world = bone.tail
head_uv = geom.get_uv_from_world(obj, t_mesh, mat_slot, head_world)
tail_uv = geom.get_uv_from_world(obj, t_mesh, mat_slot, tail_world)
utils.log_always(f"{bone.name} - uv: {head_uv} -> {tail_uv}")
def map_uv_targets(chr_cache, cc3_rig, meta_rig):
"""Fetch spacial coordinates for bone positions from UV coordinates.
"""
obj = chr_cache.get_body()
if obj is None:
utils.log_error("Cannot find BODY mesh for uv targets!")
return
if not edit_rig(meta_rig):
return
mat_slot = get_head_material_slot(obj)
mesh = obj.data
t_mesh = geom.get_triangulated_bmesh(mesh)
TARGETS = None
if chr_cache.generation == "G3Plus":
TARGETS = rigify_mapping_data.UV_TARGETS_G3PLUS
elif chr_cache.generation == "G3":
TARGETS = rigify_mapping_data.UV_TARGETS_G3
else:
return
for uvt in TARGETS:
name = uvt[0]
type = uvt[1]
num_targets = len(uvt) - 2
bone = bones.get_edit_bone(meta_rig, name)
if bone:
last = None
m_bone = None
m_last = None
if name.endswith(".R"):
m_name = name[:-2] + ".L"
m_bone = bones.get_edit_bone(meta_rig, m_name)
if type == "CONNECTED":
for index in range(0, num_targets):
uv_target = uvt[index + 2]
uv_target.append(0)
world = geom.get_world_from_uv(obj, t_mesh, mat_slot, uv_target, rigify_mapping_data.UV_THRESHOLD)
if m_bone or m_last:
m_uv_target = mirror_uv_target(uv_target)
m_world = geom.get_world_from_uv(obj, t_mesh, mat_slot, m_uv_target, rigify_mapping_data.UV_THRESHOLD)
if world:
if last:
last.tail = world
if m_last:
m_last.tail = m_world
if bone:
bone.head = world
if m_bone:
m_bone.head = m_world
if bone is None:
break
index += 1
last = bone
m_last = m_bone
# follow the connected chain of bones
if len(bone.children) > 0 and bone.children[0].use_connect:
bone = bone.children[0]
if m_bone:
m_bone = m_bone.children[0]
else:
bone = None
m_bone = None
elif type == "DISCONNECTED":
for index in range(0, num_targets):
target_uvs = uvt[index + 2]
uv_head = target_uvs[0]
uv_tail = target_uvs[1]
uv_head.append(0)
uv_tail.append(0)
world_head = geom.get_world_from_uv(obj, t_mesh, mat_slot, uv_head, rigify_mapping_data.UV_THRESHOLD)
world_tail = geom.get_world_from_uv(obj, t_mesh, mat_slot, uv_tail, rigify_mapping_data.UV_THRESHOLD)
if m_bone:
muv_head = mirror_uv_target(uv_head)
muv_tail = mirror_uv_target(uv_tail)
mworld_head = geom.get_world_from_uv(obj, t_mesh, mat_slot, muv_head, rigify_mapping_data.UV_THRESHOLD)
mworld_tail = geom.get_world_from_uv(obj, t_mesh, mat_slot, muv_tail, rigify_mapping_data.UV_THRESHOLD)
if bone and world_head:
bone.head = world_head
if m_bone:
m_bone.head = mworld_head
if bone and world_tail:
bone.tail = world_tail
if m_bone:
m_bone.tail = mworld_tail
index += 1
# follow the chain of bones
if len(bone.children) > 0:
bone = bone.children[0]
if m_bone:
m_bone = m_bone.children[0]
else:
break
elif type == "HEAD":
uv_target = uvt[2]
uv_target.append(0)
world = geom.get_world_from_uv(obj, t_mesh, mat_slot, uv_target, rigify_mapping_data.UV_THRESHOLD)
if world:
bone.head = world
elif type == "TAIL":
uv_target = uvt[2]
uv_target.append(0)
world = geom.get_world_from_uv(obj, t_mesh, mat_slot, uv_target, rigify_mapping_data.UV_THRESHOLD)
if world:
bone.tail = world
def mirror_uv_target(uv):
muv = uv.copy()
x = muv[0]
muv[0] = 1 - x
return muv
def get_head_material_slot(obj):
for i in range(0, len(obj.material_slots)):
slot = obj.material_slots[i]
if slot.material is not None:
if "Std_Skin_Head" in slot.material.name:
return i
return -1
def map_bone(cc3_rig, meta_rig, mapping):
"""Maps the head and tail of a bone in the destination
rig, to the positions of the head and tail of bones in
the source rig.
Must be in edit mode with the destination rig active.
"""
if not edit_rig(meta_rig):
return
if not mapping[0]:
return
dst_bone_name = mapping[0]
src_bone_head_name = mapping[1]
src_bone_tail_name = mapping[2]
utils.log_info(f"Mapping: {dst_bone_name} from: {src_bone_head_name}/{src_bone_tail_name}")
dst_bone : bpy.types.EditBone
dst_bone = bones.get_edit_bone(meta_rig, dst_bone_name)
src_bone = None
if dst_bone:
head_position = dst_bone.head
tail_position = dst_bone.tail
# fetch the target start point
if src_bone_head_name != "":
reverse = False
if src_bone_head_name[0] == "-":
src_bone_head_name = src_bone_head_name[1:]
reverse = True
src_bone = bones.get_rl_bone(cc3_rig, src_bone_head_name)
if not src_bone and len(mapping) >= 6:
for alt_name in mapping[5]:
src_bone = bones.get_rl_bone(cc3_rig, alt_name)
if src_bone:
break
if src_bone:
if reverse:
head_position = cc3_rig.matrix_world @ src_bone.tail_local
else:
head_position = cc3_rig.matrix_world @ src_bone.head_local
else:
utils.log_error(f"source head bone: {src_bone_head_name} not found!")
# fetch the target end point
if src_bone_tail_name != "":
reverse = False
if src_bone_tail_name[0] == "-":
src_bone_tail_name = src_bone_tail_name[1:]
reverse = True
src_bone = bones.get_rl_bone(cc3_rig, src_bone_tail_name)
if not src_bone and len(mapping) >= 6:
for alt_name in mapping[5]:
src_bone = bones.get_rl_bone(cc3_rig, alt_name)
if src_bone:
break
if src_bone:
if reverse:
tail_position = cc3_rig.matrix_world @ src_bone.head_local
else:
tail_position = cc3_rig.matrix_world @ src_bone.tail_local
else:
utils.log_error(f"source tail bone: {src_bone_tail_name} not found!")
# lerp the start and end positions if supplied
if src_bone:
if (len(mapping) >= 5 and
mapping[3] is not None and
mapping[4] is not None and
src_bone_head_name != "" and
src_bone_tail_name != ""):
start = mapping[3]
end = mapping[4]
vec = tail_position - head_position
org = head_position
head_position = org + vec * start
tail_position = org + vec * end
# set the head position
if src_bone_head_name != "":
dst_bone.head = head_position
# set the tail position
if src_bone_tail_name != "":
dst_bone.tail = tail_position
else:
utils.log_error(f"destination bone: {dst_bone_name} not found!")
def match_meta_rig(chr_cache, cc3_rig, meta_rig, rigify_data):
"""Map the bones of the meta rig to match the CC3 rig.
"""
relative_coords = {}
roll_store = {}
if edit_rig(cc3_rig):
# store all the meta-rig bone roll axes
store_bone_roll(meta_rig, roll_store)
#
if edit_rig(meta_rig):
# remove unnecessary bones
prune_meta_rig(meta_rig)
# store the relative positions of certain bones (face & heel)
store_relative_mappings(meta_rig, relative_coords)
# map all CC3 bones to Meta-rig bones
for mapping in rigify_data.bone_mapping:
map_bone(cc3_rig, meta_rig, mapping)
# determine positions of face bones (eyes, head and teeth)
map_face_bones(cc3_rig, meta_rig, rigify_data.head_bone)
# restore and apply the relative positions of certain bones (face & heel)
restore_relative_mappings(meta_rig, relative_coords)
# fix the jaw pivot
fix_jaw_pivot(cc3_rig, meta_rig)
# map the face rig bones by UV map if possible
if chr_cache.rig_full_face():
if chr_cache.can_rig_full_face():
map_uv_targets(chr_cache, cc3_rig, meta_rig)
else: # or hide them
hide_face_bones(meta_rig)
# restore meta-rig bone roll axes
restore_bone_roll(meta_rig, roll_store)
# set rigify rig params
set_rigify_params(meta_rig)
def fix_bend(meta_rig, bone_one_name, bone_two_name, dir : mathutils.Vector):
"""Determine if the bend between two bones is sufficient to generate an accurate pole in the rig,
by calculating where the middle joint lies on the line between the start and end points and
determining if the distance to that line is large enough and in the right direction.
Recalculating the joint position if not.
"""
dir.normalize()
if edit_rig(meta_rig):
one : bpy.types.EditBone = utils.find_edit_bone_in_armature(meta_rig, bone_one_name)
two : bpy.types.EditBone = utils.find_edit_bone_in_armature(meta_rig, bone_two_name)
if one and two:
start : mathutils.Vector = one.head
mid : mathutils.Vector = one.tail
end : mathutils.Vector = two.tail
u : mathutils.Vector = end - start
v : mathutils.Vector = mid - start
u.normalize()
l = u.dot(v)
line_mid : mathutils.Vector = u * l + start
disp : mathutils.Vector = mid - line_mid
d = disp.length
if dir.dot(disp) < 0 or d < 0.001:
utils.log_info(f"Bend between {bone_one_name} and {bone_two_name} is too shallow or negative, fixing.")
new_mid_dir : mathutils.Vector = dir - u.dot(dir) * u
new_mid_dir.normalize()
new_mid = line_mid + new_mid_dir * 0.001
utils.log_info(f"New joint position: {new_mid}")
one.tail = new_mid
two.head = new_mid
def hide_face_bones(meta_rig):
"""Move all the non basic face rig bones into a hidden layer.
"""
if edit_rig(meta_rig):
for b in rigify_mapping_data.NON_BASIC_FACE_BONES:
bone = bones.get_edit_bone(meta_rig, b)
if bone:
bone.layers[0] = False
bone.layers[31] = True
if select_rig(meta_rig):
for b in rigify_mapping_data.NON_BASIC_FACE_BONES:
bone = bones.get_bone(meta_rig, b)
if bone:
bone.layers[0] = False
bone.layers[31] = True
def convert_to_basic_face_rig(rigify_rig):
if edit_rig(rigify_rig):
for b in rigify_mapping_data.NON_BASIC_FACE_BONES:
bone_names = [b, f"DEF-{b}", f"ORG-{b}", f"MCH-{b}"]
for bone_name in bone_names:
bone = bones.get_edit_bone(rigify_rig, bone_name)
if bone:
rigify_rig.data.edit_bones.remove(bone)
select_rig(rigify_rig)
def add_shape_key_drivers(chr_cache, rig):
for obj in rig.children:
if obj.type == "MESH" and obj.parent == rig:
obj_cache = chr_cache.get_object_cache(obj)
if is_face_object(obj_cache, obj):
for skd_def in rigify_mapping_data.SHAPE_KEY_DRIVERS:
flags = skd_def[0]
if "Bfr" in flags and chr_cache.rigified_full_face_rig:
continue
shape_key_name = skd_def[1]
driver_def = skd_def[2]
var_def = skd_def[3]
add_shape_key_driver(rig, obj, shape_key_name, driver_def, var_def)
if utils.is_blender_version("3.1.0", "GTE"):
left_data_path = bones.get_data_rigify_limb_property("LEFT_LEG", "IK_Stretch")
right_data_path = bones.get_data_rigify_limb_property("RIGHT_LEG", "IK_Stretch")
expression = "pow(ik_stretch, 3)"
bones.add_constraint_scripted_influence_driver(rig, "DEF-foot.L", left_data_path, "ik_stretch", "STRETCH_TO", expression)
bones.add_constraint_scripted_influence_driver(rig, "DEF-foot.R", right_data_path, "ik_stretch", "STRETCH_TO", expression)
def add_shape_key_driver(rig, obj, shape_key_name, driver_def, var_def):
if utils.set_mode("OBJECT"):
shape_key = meshutils.find_shape_key(obj, shape_key_name)
if shape_key:
fcurve : bpy.types.FCurve
fcurve = shape_key.driver_add("value")
driver : bpy.types.Driver = fcurve.driver
driver.type = driver_def[0]
if driver.type == "SCRIPTED":
driver.expression = driver_def[1]
var : bpy.types.DriverVariable = driver.variables.new()
var.name = var_def[0]
var.type = var_def[1]
if var_def[1] == "TRANSFORMS":
#var.targets[0].id_type = "OBJECT"
var.targets[0].id = rig.id_data
var.targets[0].bone_target = var_def[2]
var.targets[0].rotation_mode = "AUTO"
var.targets[0].transform_type = var_def[3]
var.targets[0].transform_space = var_def[4]
def correct_meta_rig(meta_rig):
"""Add a slight displacement (if needed) to the knee and elbow to ensure the poles are the right way.
"""
utils.log_info("Correcting Meta-Rig, Knee and Elbow bends.")
utils.log_indent()
fix_bend(meta_rig, "thigh.L", "shin.L", mathutils.Vector((0,-1,0)))
fix_bend(meta_rig, "thigh.R", "shin.R", mathutils.Vector((0,-1,0)))
fix_bend(meta_rig, "upper_arm.L", "forearm.L", mathutils.Vector((0,1,0)))
fix_bend(meta_rig, "upper_arm.R", "forearm.R", mathutils.Vector((0,1,0)))
utils.set_mode("OBJECT")
utils.log_recess()
def modify_rigify_rig(cc3_rig, rigify_rig, rigify_data):
"""Resize and reposition Rigify control bones to make them easier to find.
Note: scale, location, rotation modifiers for custom control shapes is Blender 3.0.0+ only
"""
# turn off deformation for palm bones
if edit_rig(rigify_rig):
for edit_bone in rigify_rig.data.edit_bones:
if edit_bone.name.startswith("DEF-palm"):
edit_bone.use_deform = False
if utils.is_blender_version("3.0.0"):
if select_rig(rigify_rig):
utils.log_info("Resizing and Repositioning rig controls:")
utils.log_indent()
for mod in rigify_mapping_data.CONTROL_MODIFY:
bone_name = mod[0]
scale = mod[1]
translation = mod[2]
rotation = mod[3]
bone = bones.get_pose_bone(rigify_rig, bone_name)
if bone:
utils.log_info(f"Altering: {bone.name}")
bone.custom_shape_scale_xyz = scale
bone.custom_shape_translation = translation
bone.custom_shape_rotation_euler = rotation
utils.log_recess()
# hide control rig bones if RL chain parent bones missing from CC3 rig
if rigify_data.hide_chains and select_rig(rigify_rig):
bone_list = []
for chain_def in rigify_data.hide_chains:
rl_bone_name = chain_def[0]
rigify_regex_list = chain_def[1]
metarig_regex_list = chain_def[2]
# if the chain parent is missing from the cc3 rig, hide the control rig in rigify
if not bones.get_rl_bone(cc3_rig, rl_bone_name):
utils.log_info(f"Chain Parent missing from CC3 Rig: {rl_bone_name}")
utils.log_indent()
for regex in rigify_regex_list:
for bone in rigify_rig.data.bones:
if re.match(regex, bone.name):
utils.log_info(f"Hiding control rig bone: {bone.name}")
bones.set_pose_bone_layer(rigify_rig, bone.name, 22)
bone_list.append(bone.name)
utils.log_recess()
if bone_list and edit_rig(rigify_rig):
for bone_name in bone_list:
bones.set_edit_bone_layer(rigify_rig, bone_name, 22)
select_rig(rigify_rig)
def reparent_to_rigify(self, chr_cache, cc3_rig, rigify_rig):
"""Unparent (with transform) from the original CC3 rig and reparent to the new rigify rig (with automatic weights for the body),
setting the armature modifiers to the new rig.
The automatic weights will generate vertex weights for the additional face bones in the new rig.
(But only for the Body mesh)
"""
utils.log_info("Reparenting character objects to new Rigify Control Rig:")
utils.log_indent()
props = bpy.context.scene.CC3ImportProps
result = 1
if utils.set_mode("OBJECT"):
for obj in cc3_rig.children:
if obj.type == "MESH" and obj.parent == cc3_rig:
hidden = not obj.visible_get()
if hidden:
obj.hide_set(False)
obj_cache = chr_cache.get_object_cache(obj)
if utils.try_select_object(obj, True) and utils.set_active_object(obj):
bpy.ops.object.parent_clear(type = "CLEAR_KEEP_TRANSFORM")
# only the body and face objects will generate the automatic weights for the face rig.
if (chr_cache.rigified_full_face_rig and
utils.object_exists_is_mesh(obj) and
len(obj.data.vertices) >= 2 and
is_face_object(obj_cache, obj)):
obj_result = try_parent_auto(chr_cache, rigify_rig, obj)
if obj_result < result:
result = obj_result
else:
if utils.try_select_object(rigify_rig) and utils.set_active_object(rigify_rig):
bpy.ops.object.parent_set(type = "OBJECT", keep_transform = True)
arm_mod : bpy.types.ArmatureModifier = modifiers.add_armature_modifier(obj, True)
if arm_mod:
arm_mod.object = rigify_rig
if hidden:
obj.hide_set(True)
utils.log_recess()
return result
def clean_up(chr_cache, cc3_rig, rigify_rig, meta_rig):
"""Rename the rigs, hide the original CC3 Armature and remove the meta rig.
Set the new rig into pose mode.
"""
utils.log_info("Cleaning Up...")
rig_name = cc3_rig.name
cc3_rig.hide_set(True)
utils.delete_armature_object(meta_rig)
rigify_rig.name = rig_name + "_Rigify"
rigify_rig.data.name = rig_name + "_Rigify"
if utils.set_mode("OBJECT"):
# delesect all bones (including the hidden ones)
# Rigimap will bake and clear constraints on the ORG bones if we don't do this...
for bone in rigify_rig.data.bones:
bone.select = False
utils.clear_selected_objects()
if utils.try_select_object(rigify_rig, True):
utils.set_active_object(rigify_rig)
chr_cache.set_rigify_armature(rigify_rig)
# Skinning face rigs
#
#
def is_face_object(obj_cache, obj):
if obj and obj.type == "MESH":
if obj_cache and obj_cache.object_type in rigify_mapping_data.BODY_TYPES:
return True
if obj.data.shape_keys and obj.data.shape_keys.key_blocks:
for shape_key in obj.data.shape_keys.key_blocks:
if shape_key.name in rigify_mapping_data.FACE_TEST_SHAPEKEYS:
return True
return False
def is_face_def_bone(bvg):