-
Notifications
You must be signed in to change notification settings - Fork 84
/
rigging.py
4055 lines (3344 loc) · 173 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 addon_utils
import math
import re
from . import utils, vars
from . import geom
from . import meshutils
from . import properties
from . import modifiers
from . import springbones, rigidbody
from . import physics
from . import drivers, bones
from . import rigutils
from . import rigify_mapping_data
from mathutils import Vector, Matrix, Quaternion
BONEMAP_METARIG_NAME = 0 # metarig bone name or rigify rig basename
BONEMAP_CC_HEAD = 1 # CC rig source bone and (head) postion of head bone
BONEMAP_CC_TAIL = 2 # CC rig bone (head) position of tail
BONEMAP_LERP_FROM = 3 # how far from cc_head to cc_tail to place the metarig bone head (optional)
BONEMAP_LERP_TO = 4 # how far from cc_head to cc_tail to place the metarig bone tail (optional)
BONEMAP_ALT_NAMES = 5 # index of alternative bones to map if CC_HEAD is missing from source (i.e. missing fingers) (optional)
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 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 rigutils.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 fix_rigify_bones(chr_cache, rigify_rig):
# align roll to +Z on
BONES = {
"ORG-eye.R": "+Z",
"MCH-eye.R": "+Z",
"ORG-eye.R": "+Z",
"MCH-eye.R": "+Z",
"ORG-eye.L": "+Z",
"MCH-eye.L": "+Z",
"ORG-eye.L": "+Z",
"MCH-eye.L": "+Z",
"jaw_master": "-Z",
"MCH-mouth_lockg": "-Z",
"MCH-jaw_master": "-Z",
"MCH-jaw_master.001": "-Z",
"MCH-jaw_master.002": "-Z",
"MCH-jaw_master.003": "-Z",
}
if rigutils.edit_rig(rigify_rig):
ZUP = Vector((0,0,1))
ZDOWN = Vector((0,0,-1))
for bone_name in BONES:
bone_dir = BONES[bone_name]
edit_bone = bones.get_edit_bone(rigify_rig, bone_name)
if edit_bone:
if bone_dir == "+Z":
edit_bone.align_roll(ZUP)
elif bone_dir == "-Z":
edit_bone.align_roll(ZDOWN)
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]
collection = def_copy[5]
deform = dst_bone_name[:3] == "DEF"
scale = 1
ref = None
arg = None
if len(def_copy) > 6:
scale = def_copy[6]
if len(def_copy) > 7:
ref = def_copy[7]
if len(def_copy) > 8:
arg = def_copy[8]
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 and relation_flags:
bones.set_edit_bone_flags(reparented_bone, relation_flags, deform)
bones.set_bone_collection(rigify_rig, reparented_bone, collection, None, layer)
# add a custom DEF, ORG or MCH bone
elif src_bone_name[:3] == "DEF" or src_bone_name[:3] == "ORG" or src_bone_name[:3] == "MCH":
new_bone = bones.copy_edit_bone(rigify_rig, src_bone_name, dst_bone_name, dst_bone_parent_name, scale)
if new_bone:
bones.set_edit_bone_flags(new_bone, relation_flags, deform)
bones.set_bone_collection(rigify_rig, new_bone, collection, None, layer)
# partial rotation copy for share bones
if ref and arg is not None:
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:
new_bone = bones.copy_rl_edit_bone(cc3_rig, rigify_rig, src_bone_name, dst_bone_name, dst_bone_parent_name, scale)
if new_bone:
bones.set_edit_bone_flags(new_bone, relation_flags, deform)
bones.set_bone_collection(rigify_rig, new_bone, collection, None, layer)
utils.log_recess()
def add_extension_bones(chr_cache, cc3_rig, rigify_rig, bone_mapping, vertex_group_map):
# find all the accessories in the armature
accessory_bone_names = bones.find_accessory_bones(bone_mapping, cc3_rig)
spring_rig_names = springbones.get_spring_rig_names(chr_cache, 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]
is_spring_rig = bone_name in spring_rig_names
# fix old spring rig bone name
if is_spring_rig and bone_name.startswith("RL_"):
bone.name = "RLS_" + bone_name[3:]
bone_name = bone.name
utils.log_info(f"Updating spring rig name to {bone_name}")
if is_spring_rig:
prefix = "RLS_"
else:
prefix = "RLA_"
if bone:
if is_spring_rig:
utils.log_info(f"Processing Spring Rig root bone: {bone_name}")
else:
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
rigify_parent_name = bones.get_rigify_meta_bone(rigify_rig, bone_mapping, cc3_parent_name)
if not (rigify_parent_name and rigify_parent_name in rigify_rig.data.bones):
utils.log_error(f"Unable to find matching accessory/spring bone tree parent: {cc3_parent_name} in rigify bones!")
if is_spring_rig:
utils.log_info(f"Copying Spring Rig bone tree into rigify rig: {bone.name} parent: {rigify_parent_name}")
else:
utils.log_info(f"Copying Accessory bone tree into rigify rig: {bone.name} parent: {rigify_parent_name}")
if bone.name.startswith(prefix):
dst_name = bone.name
else:
dst_name = f"{prefix}{bone.name}"
bones.copy_rl_edit_bone_subtree(cc3_rig, rigify_rig, bone.name,
dst_name, rigify_parent_name, "DEF-",
"DEF", vars.DEF_BONE_LAYER, vertex_group_map)
def lookup_bone_def_parent(bone_defs, def_bone):
if def_bone.parent:
def_bone_parent_name = def_bone.parent.name
for bone_def in bone_defs:
if bone_def[4] == def_bone_parent_name:
return bone_def
return None
def lookup_bone_def_child(bone_defs, def_bone):
if def_bone.children:
def_bone_child_name = def_bone.children[0].name
for bone_def in bone_defs:
if bone_def[4] == def_bone_child_name:
return bone_def
return None
def rigify_spring_chain(rig, spring_root, length, def_bone, bone_defs, ik_targets, mch_root = None):
length += 1
base_name = def_bone.name
if base_name.startswith("DEF-"):
base_name = base_name[4:]
if mch_root is None:
mch_root = bones.copy_edit_bone(rig, def_bone.name, f"MCH-{base_name}_parent", spring_root.name, 1.0)
bones.set_bone_collection(rig, mch_root, "MCH", None, vars.MCH_BONE_LAYER)
mch_root.parent = spring_root
parent_def = lookup_bone_def_parent(bone_defs, def_bone)
if not parent_def:
parent_def = [mch_root.name, mch_root.name, mch_root.name, "", "", spring_root.name, 0]
fk_bone = bones.copy_edit_bone(rig, def_bone.name, f"{base_name}_fk", parent_def[0], 1.0)
mch_bone = bones.copy_edit_bone(rig, def_bone.name, f"MCH-{base_name}_ik", parent_def[1], 1.0)
org_bone = bones.copy_edit_bone(rig, def_bone.name, f"ORG-{base_name}", parent_def[2], 1.0)
twk_bone = bones.copy_edit_bone(rig, def_bone.name, f"{base_name}_tweak", org_bone.name, 1.0)
sim_bone = bones.copy_edit_bone(rig, def_bone.name, f"SIM-{base_name}", parent_def[5], 1.0)
if not def_bone.name.startswith("DEF-"):
def_bone.name = f"DEF-{def_bone.name}"
bone_def = [fk_bone.name, mch_bone.name, org_bone.name, twk_bone.name, def_bone.name, sim_bone.name, length]
bones.set_bone_collection(rig, fk_bone, "Spring (FK)", None, vars.SPRING_FK_LAYER, color="FK")
bones.set_bone_collection(rig, mch_bone, "MCH", None, vars.MCH_BONE_LAYER)
bones.set_bone_collection(rig, org_bone, "ORG", None, vars.ORG_BONE_LAYER)
bones.set_bone_collection(rig, twk_bone, "Spring (Tweak)", None, vars.SPRING_TWEAK_LAYER, color="TWEAK")
bones.set_bone_collection(rig, def_bone, "DEF", None, vars.DEF_BONE_LAYER)
bones.set_bone_collection(rig, sim_bone, "Simulation", None, vars.SIM_BONE_LAYER, color="SIM")
fk_bone.use_connect = True if length > 1 else False
mch_bone.use_connect = True if length > 1 else False
bone_defs.append(bone_def)
for child_def_bone in def_bone.children:
rigify_spring_chain(rig, spring_root, length, child_def_bone, bone_defs, ik_targets, mch_root = mch_root)
if len(def_bone.children) == 0 and length > 0:
ik_target_name = mch_root.name[4:-7]
ik_target_bone = bones.new_edit_bone(rig, f"{ik_target_name}_target_ik", mch_bone.name)
ik_target_bone.head = def_bone.tail
ik_target_bone.tail = def_bone.tail + 0.5 * (def_bone.tail - def_bone.head)
ik_target_bone.roll = def_bone.roll
ik_target_bone.parent = mch_root
ik_targets.append([mch_bone.name, ik_target_bone.name, length])
return mch_root.name
def process_spring_groups(rig, spring_rig, ik_groups):
scale = 1.0
if rigutils.edit_rig(rig):
for group_name in ik_groups:
ik_names = ik_groups[group_name]["targets"]
if len(ik_names) > 1:
pos_head = Vector((0,0,0))
pos_tail = Vector((0,0,0))
for ik_bone_name in ik_names:
ik_bone = rig.data.edit_bones[ik_bone_name]
pos_head += ik_bone.head
pos_tail += ik_bone.tail
pos_head /= len(ik_names)
pos_tail /= len(ik_names)
radius = 0
for ik_bone_name in ik_names:
ik_bone = rig.data.edit_bones[ik_bone_name]
r = (ik_bone.head - pos_head).length
if r > radius:
radius = r
radius = max(0.05, r)
group_ik_bone = bones.new_edit_bone(rig, f"{group_name}_group_ik", spring_rig.name)
group_ik_bone.head = pos_head
bones.set_bone_collection(rig, group_ik_bone, "Spring (IK)", None, vars.SPRING_IK_LAYER, color="IK")
dir = pos_tail - pos_head
dir[0] = 0
group_ik_bone.tail = pos_head + dir
ik_groups[group_name]["control"] = { "bone_name": group_ik_bone.name, "radius": radius }
for ik_bone_name in ik_names:
ik_bone = rig.data.edit_bones[ik_bone_name]
ik_bone.parent = group_ik_bone
ik_bone.inherit_scale = 'NONE'
def set_spring_rig_constraints(rig, bone_defs, ik_groups, ik_targets, mch_roots):
fk_bone : bpy.types.PoseBone
twk_bone : bpy.types.PoseBone
rigidbody.add_simulation_bone_collection(rig)
shape_fk = bones.generate_spring_widget(rig, "SpringBoneFK", "FK", 0.5)
shape_ik = bones.generate_spring_widget(rig, "SpringBoneIK", "IK", 0.025)
shape_grp = bones.generate_spring_widget(rig, "SpringBoneGRP", "GRP", 0.025)
shape_twk = bones.generate_spring_widget(rig, "SpringBoneTWK", "TWK", 0.0125)
if rigutils.select_rig(rig):
for group_name in ik_groups:
if ik_groups[group_name]["control"]:
ik_group_bone_name = ik_groups[group_name]["control"]["bone_name"]
ik_group_bone_radius = ik_groups[group_name]["control"]["radius"]
ik_group_bone = rig.pose.bones[ik_group_bone_name]
ik_group_bone.custom_shape = shape_grp
ik_group_bone.use_custom_shape_bone_size = False
ik_group_bone.lock_scale[1] = True
scale = (ik_group_bone_radius + 0.05) / 0.025
rigutils.set_bone_shape_scale(ik_group_bone, scale)
bones.set_pose_bone_lock(ik_group_bone, lock_scale = [0,1,0])
bones.set_bone_collection(rig, ik_group_bone, "Spring (IK)", "IK", vars.SPRING_IK_LAYER, color="IK")
#drivers.add_custom_float_property(ik_group_bone, "IK_FK", 0.0, 0.0, 1.0, description="Group FK Influence")
#drivers.add_custom_float_property(ik_group_bone, "SIM", 0.0, 0.0, 1.0, description="Group Simulation Influence")
for chain_root_name in bone_defs:
# find the ik group the chain belongs and it's IK->FK data path
#group_ik_fk_data_path = None
#group_sim_data_path = None
#for group_name in ik_groups:
# for crn in ik_groups[group_name]["chain_root_names"]:
# if crn == chain_root_name:
# if ik_groups[group_name]["control"]:
# ik_group_bone_name = ik_groups[group_name]["control"]["bone_name"]
# group_ik_fk_data_path = bones.get_data_path_pose_bone_property(ik_group_bone_name, "IK_FK")
# group_sim_data_path = bones.get_data_path_pose_bone_property(ik_group_bone_name, "SIM")
chain_bone_defs = bone_defs[chain_root_name]
mch_root_name = mch_roots[chain_root_name]
mch_root = bones.get_pose_bone(rig, mch_root_name)
bones.set_bone_collection(rig, mch_root, "MCH", None, vars.MCH_BONE_LAYER)
drivers.add_custom_float_property(mch_root, "IK_FK", 0.0, 0.0, 1.0, description="FK Influence")
drivers.add_custom_float_property(mch_root, "SIM", 0.0, 0.0, 1.0, description="Simulation Influence")
ik_fk_data_path = bones.get_data_path_pose_bone_property(mch_root_name, "IK_FK")
sim_data_path = bones.get_data_path_pose_bone_property(mch_root_name, "SIM")
for bone_def in chain_bone_defs:
fk_bone_name = bone_def[0]
mch_bone_name = bone_def[1]
org_bone_name = bone_def[2]
twk_bone_name = bone_def[3]
def_bone_name = bone_def[4]
sim_bone_name = bone_def[5]
length = bone_def[6]
fk_bone = rig.pose.bones[fk_bone_name]
twk_bone = rig.pose.bones[twk_bone_name]
mch_bone = rig.pose.bones[mch_bone_name]
org_bone = rig.pose.bones[org_bone_name]
def_bone = rig.pose.bones[def_bone_name]
sim_bone = rig.pose.bones[sim_bone_name]
fk_bone.custom_shape = shape_fk
fk_bone.use_custom_shape_bone_size = True
twk_bone.custom_shape = shape_twk
twk_bone.use_custom_shape_bone_size = False
if length == 1:
bones.set_pose_bone_lock(fk_bone, lock_location=[1,1,1], lock_scale=[0,1,0])
else:
bones.set_pose_bone_lock(fk_bone, lock_scale=[0,1,0])
bones.set_pose_bone_lock(mch_bone, lock_location = [1,1,1], lock_rotation = [1,1,1,1], lock_scale=[1,1,1])
bones.set_pose_bone_lock(twk_bone, lock_rotation = [1,0,1,1], lock_scale = [0,1,0])
bones.set_bone_collection(rig, fk_bone, "Spring (FK)", "FK", vars.SPRING_FK_LAYER, color="FK")
bones.set_bone_collection(rig, twk_bone, "Spring (Tweak)", "Tweak", vars.SPRING_TWEAK_LAYER, color="TWEAK")
bones.set_bone_collection(rig, sim_bone, "Simulation", "Simulation", vars.SIM_BONE_LAYER, color="SIM")
bones.set_bone_collection(rig, mch_bone, "MCH", None, vars.MCH_BONE_LAYER)
bones.set_bone_collection(rig, org_bone, "ORG", None, vars.ORG_BONE_LAYER)
bones.set_bone_collection(rig, def_bone, "DEF", None, vars.DEF_BONE_LAYER)
# sim > fk (influence driver)
simc = bones.add_copy_transforms_constraint(rig, rig, sim_bone_name, fk_bone_name, 0.0)
simc_driver = drivers.make_driver(simc, "influence", "SCRIPTED", "sim")
drivers.make_driver_var(simc_driver, "SINGLE_PROP", "sim", rig, "OBJECT", sim_data_path)
# fk -> org
fkc = bones.add_copy_transforms_constraint(rig, rig, fk_bone_name, org_bone_name, 1.0)
# mch -> org (influence driver)
mchc = bones.add_copy_transforms_constraint(rig, rig, mch_bone_name, org_bone_name, 1.0)
expr = "(1.0 - ikfk)*(1.0 - sim)"
mchc_driver = drivers.make_driver(mchc, "influence", "SCRIPTED", expr)
drivers.make_driver_var(mchc_driver, "SINGLE_PROP", "ikfk", rig, "OBJECT", ik_fk_data_path)
drivers.make_driver_var(mchc_driver, "SINGLE_PROP", "sim", rig, "OBJECT", sim_data_path)
# twk (parented to mch) -> def
defc1 = bones.add_copy_transforms_constraint(rig, rig, twk_bone_name, def_bone_name, 1.0)
# finally: def > stretch_to def.child:twk
if len(def_bone.children) > 0:
child_def = lookup_bone_def_child(chain_bone_defs, def_bone)
if child_def:
twk_child_bone_name = child_def[3]
defc2 = bones.add_stretch_to_constraint(rig, rig, twk_child_bone_name, def_bone_name, 1.0)
for group_name in ik_groups:
ik_names = ik_groups[group_name]["targets"]
for chain_root_name in ik_targets:
ik_target_def = ik_targets[chain_root_name]
for mch_bone_name, ik_bone_name, length in ik_target_def:
if ik_bone_name in ik_names:
ik_bone = rig.pose.bones[ik_bone_name]
ik_bone.custom_shape = shape_ik
ik_bone.use_custom_shape_bone_size = False
ik_bone.lock_scale[1] = True
bones.set_bone_collection(rig, ik_bone, "Spring (IK)", "IK", vars.SPRING_IK_LAYER, color="IK")
bones.add_inverse_kinematic_constraint(rig, rig, ik_bone_name, mch_bone_name,
use_tail=True, use_stretch=True, influence=1.0,
use_location=True, use_rotation=True,
orient_weight=1.0, chain_count=length)
drivers.add_custom_string_property(ik_bone, "ik_root", str(mch_bone_name))
def rigify_spring_rig(chr_cache, rigify_rig, parent_mode):
pose_position = rigify_rig.data.pose_position
rigify_rig.data.pose_position = "REST"
if rigutils.edit_rig(rigify_rig):
spring_rig = springbones.get_spring_rig(chr_cache, rigify_rig, parent_mode, mode = "EDIT")
if not spring_rig:
return
spring_rig_name = spring_rig.name
bone_defs = {}
ik_targets = {}
ik_groups = {}
mch_roots = {}
for chain_root in spring_rig.children:
chain_bone_defs = []
chain_ik_targets = []
mch_root_name = rigify_spring_chain(rigify_rig, spring_rig, 0, chain_root, chain_bone_defs, chain_ik_targets)
bone_defs[chain_root.name] = chain_bone_defs
ik_targets[chain_root.name] = chain_ik_targets
mch_roots[chain_root.name] = mch_root_name
if chain_bone_defs and chain_ik_targets:
names = [ bone_def[4] for bone_def in chain_bone_defs ]
chain_name = utils.get_common_name(names)
if not chain_name:
chain_name = "NONE"
if chain_name.startswith("DEF-"):
chain_name = chain_name[4:]
if chain_name not in ik_groups:
ik_groups[chain_name] = { "targets": [],
"chain_root_names": [],
"control": None }
ik_groups[chain_name]["targets"].extend([ ik_target_def[1] for ik_target_def in chain_ik_targets ])
ik_groups[chain_name]["chain_root_names"].append(chain_root.name)
process_spring_groups(rigify_rig, spring_rig, ik_groups)
set_spring_rig_constraints(rigify_rig, bone_defs, ik_groups, ik_targets, mch_roots)
drivers.add_custom_float_property(rigify_rig.pose.bones[spring_rig_name], "rigified", 1.0)
bones.set_bone_collection_visibility(rigify_rig, "Spring (FK)", vars.SPRING_FK_LAYER, True)
bones.set_bone_collection_visibility(rigify_rig, "Spring (IK)", vars.SPRING_IK_LAYER, True)
bones.set_bone_collection_visibility(rigify_rig, "Spring (Tweak)", vars.SPRING_TWEAK_LAYER, True)
bones.set_bone_collection_visibility(rigify_rig, "Spring (Edit)", vars.SPRING_EDIT_LAYER, False)
bones.set_bone_collection_visibility(rigify_rig, "Simulation", vars.SIM_BONE_LAYER, False)
rigify_rig.data.pose_position = pose_position
def rigify_spring_rigs(chr_cache, cc3_rig, rigify_rig, bone_mapping):
props = vars.props()
rigutils.select_rig(rigify_rig)
pose_position = rigify_rig.data.pose_position
rigify_rig.data.pose_position = "REST"
spring_rigs = springbones.get_spring_rigs(chr_cache, rigify_rig, mode = "POSE")
if spring_rigs:
for parent_mode in spring_rigs:
rigify_spring_rig(chr_cache, rigify_rig, parent_mode)
props.section_rigify_spring = True
rigify_rig.data.pose_position = pose_position
def derigify_spring_rig(chr_cache, rigify_rig, parent_mode):
to_remove = []
to_layer = []
DRIVER_PROPS = [ "influence" ]
if rigutils.select_rig(rigify_rig):
spring_rig = springbones.get_spring_rig(chr_cache, rigify_rig, parent_mode, mode = "POSE")
child_bones = bones.get_bone_children(spring_rig, include_root=False)
for bone in child_bones:
# keep only the DEF bones (and the RL_ spring root):
if bone.name.startswith("DEF-"):
bone.name = bone.name[4:]
bones.set_bone_collection(rigify_rig, bone, "Spring (Edit)", None, vars.SPRING_EDIT_LAYER)
to_layer.append(bone.name)
else:
to_remove.append(bone.name)
# remove any drivers on the contraints
for c in bone.constraints:
for prop in DRIVER_PROPS:
c.driver_remove(prop)
# remove all constraints from the spring rig bones
while bone.constraints:
bone.constraints.remove(bone.constraints[0])
if rigutils.edit_rig(rigify_rig):
for bone_name in to_remove:
utils.log_info(f"Removing spring rigify bone: {bone_name}")
bone = rigify_rig.data.edit_bones[bone_name]
rigify_rig.data.edit_bones.remove(bone)
for bone_name in to_layer:
utils.log_info(f"Keeping spring rig bone: {bone_name}")
bones.set_bone_collection(rigify_rig, bone, "Spring (Edit)", None, vars.SPRING_EDIT_LAYER)
if "rigified" in spring_rig:
spring_rig["rigified"] = False
rigutils.select_rig(rigify_rig)
bones.set_bone_collection_visibility(rigify_rig, "Spring (Edit)", vars.SPRING_EDIT_LAYER, True)
def group_props_to_value(chr_cache, group_pose_bone, prop, value):
arm = None
if chr_cache:
arm = chr_cache.get_armature()
if group_pose_bone and arm:
for child_pose_bone in group_pose_bone.children:
if "ik_root" in child_pose_bone:
search_bone_name = child_pose_bone["ik_root"]
else:
search_bone_name = child_pose_bone.name
spring_rig_def, mch_root_name, parent_mode = springbones.get_spring_rig_from_child(chr_cache, arm, search_bone_name)
mch_root = arm.pose.bones[mch_root_name]
if prop in mch_root:
mch_root[prop] = value
# set a bone value to force an update:
l = group_pose_bone.location
group_pose_bone.location = l
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, acc_vertex_group_map):
"""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}")
# remove the destination vertex groups (these will have been created by the parenting operation)
# and rename the source vertex groups to the destination groups
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
# rename accessory vertex groups
for vg in obj.vertex_groups:
if vg.name in acc_vertex_group_map:
dst_vg_name = acc_vertex_group_map[vg.name]
vg.name = dst_vg_name
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 rigutils.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 rigutils.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(cc3_rig, meta_rig, roll_store, rigify_data: rigify_mapping_data.RigifyData):
"""Store the bone roll and roll axis (z_axis) for each bone in the meta rig.
"""
prefs = vars.prefs()
cc3_bone_store = {}
bone: bpy.types.EditBone
if rigutils.edit_rig(cc3_rig):
for bone in cc3_rig.data.edit_bones:
cc3_bone_store[bone.name] = (cc3_rig.matrix_world @ bone.z_axis)
if rigutils.edit_rig(meta_rig):
for bone in meta_rig.data.edit_bones:
source_name = rigify_data.get_source_bone(bone.name)
if prefs.rigify_align_bones == "CC" and source_name and source_name in cc3_bone_store:
z_axis: Vector = cc3_bone_store[source_name]
z_axis.normalize()
roll_store[bone.name] = [bone.roll, z_axis]
else:
z_axis: Vector = (meta_rig.matrix_world @ bone.z_axis)
z_axis.normalize()
roll_store[bone.name] = [bone.roll, 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.
"""
prefs = vars.prefs()
if rigutils.edit_rig(meta_rig):
steep_a_pose = False
world_x = Vector((1, 0, 0))
# test upper arm for a steep A-pose (arms at more than 45 degrees down)
arm_l = bones.get_edit_bone(meta_rig, "upper_arm.L")
y_axis = arm_l.y_axis.normalized()
if world_x.dot(y_axis) < 0.707:
steep_a_pose = True
# test lower arm for a steep A-pose (for good measure)
arm_l = bones.get_edit_bone(meta_rig, "forearm.L")
y_axis = arm_l.y_axis.normalized()
if world_x.dot(y_axis) < 0.707:
steep_a_pose = True
bone: bpy.types.EditBone
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)
if prefs.rigify_align_bones == "METARIG":
for correction in rigify_mapping_data.ROLL_CORRECTION:
if correction[0] == bone.name:
if steep_a_pose:
axis = correction[2]
else:
axis = correction[1]
bones.align_edit_bone_roll(bone, axis)
def set_rigify_params(meta_rig):
"""Apply custom Rigify parameters to bones in the meta rig.
"""
if rigutils.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 rigutils.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 : 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 : 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 + 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 rigutils.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 rigutils.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.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 = drivers.get_head_body_object(chr_cache)
if obj is None:
utils.log_error("Cannot find BODY mesh for uv targets!")
return
if not rigutils.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
if not TARGETS:
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