-
Notifications
You must be signed in to change notification settings - Fork 84
/
link.py
3862 lines (3335 loc) · 152 KB
/
link.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
import bpy #, bpy_extras
#import bpy_extras.view3d_utils as v3d
import atexit
from enum import IntEnum
import os, socket, time, select, struct, json, copy
#import subprocess
from mathutils import Vector, Quaternion, Matrix
from . import (importer, exporter, bones, geom, colorspace,
world, rigging, rigutils, drivers, modifiers,
jsonutils, utils, vars)
import textwrap
BLENDER_PORT = 9334
UNITY_PORT = 9335
RL_PORT = 9333
HANDSHAKE_TIMEOUT_S = 60
KEEPALIVE_TIMEOUT_S = 300
PING_INTERVAL_S = 120
TIMER_INTERVAL = 1/30
MAX_CHUNK_SIZE = 32768
SERVER_ONLY = False
CLIENT_ONLY = True
CHARACTER_TEMPLATE: list = None
MAX_RECEIVE = 30
USE_PING = False
USE_KEEPALIVE = False
SOCKET_TIMEOUT = 5.0
class OpCodes(IntEnum):
NONE = 0
HELLO = 1
PING = 2
STOP = 10
DISCONNECT = 11
DEBUG = 15
NOTIFY = 50
SAVE = 60
MORPH = 90
MORPH_UPDATE = 91
REPLACE_MESH = 95
MATERIALS = 96
CHARACTER = 100
CHARACTER_UPDATE = 101
PROP = 102
PROP_UPDATE = 103
UPDATE_REPLACE = 108
RIGIFY = 110
TEMPLATE = 200
POSE = 210
POSE_FRAME = 211
SEQUENCE = 220
SEQUENCE_FRAME = 221
SEQUENCE_END = 222
SEQUENCE_ACK = 223
LIGHTS = 230
CAMERA_SYNC = 231
FRAME_SYNC = 232
MOTION = 240
VISEME_NAME_MAP = {
"None": "None",
"Open": "V_Open",
"Explosive": "V_Explosive",
"Upper Dental": "V_Dental_Lip",
"Tight O": "V_Tight_O",
"Pucker": "V_Tight",
"Wide": "V_Wide",
"Affricate": "V_Affricate",
"Lips Parted": "V_Lip_Open",
"Tongue Up": "V_Tongue_up",
"Tongue Raised": "V_Tongue_Raise",
"Tongue Out": "V_Tongue_Out",
"Tongue Narrow": "V_Tongue_Narrow",
"Tongue Lower": "V_Tongue_Lower",
"Tongue Curl-U": "V_Tongue_Curl_U",
"Tongue Curl-D": "V_Tongue_Curl_D",
"EE": "EE",
"Er": "Er",
"Ih": "IH",
"Ah": "Ah",
"Oh": "Oh",
"W.OO": "W_OO",
"S.Z": "S_Z",
"Ch.J": "Ch_J",
"F.V": "F_V",
"Th": "TH",
"T.L.D": "T_L_D_N",
"B.M.P": "B_M_P",
"K.G": "K_G_H_NG",
"N.NG": "AE",
"R": "R",
}
class LinkActor():
name: str = "Name"
chr_cache = None
bones: list = None
skin_meshes: dict = None
meshes: list = None
rig_bones: list = None
expressions: list = None
visemes: list = None
morphs: list = None
cache: dict = None
alias: list = None
shape_keys: dict = None
ik_store: dict = None
def __init__(self, chr_cache):
self.chr_cache = chr_cache
self.name = chr_cache.character_name
self.bones = []
self.skin_meshes = {}
self.meshes = []
self.rig_bones = []
self.expressions = []
self.visemes = []
self.morphs = []
self.cache = None
self.alias = []
self.shape_keys = {}
return
def get_chr_cache(self):
return self.chr_cache
def get_link_id(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.get_link_id()
return None
def get_armature(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.get_armature()
return None
def select(self):
chr_cache = self.get_chr_cache()
if chr_cache:
chr_cache.select_all()
def get_type(self):
"""AVATAR|PROP|NONE"""
chr_cache = self.get_chr_cache()
return self.chr_cache_type(chr_cache)
def add_alias(self, link_id):
chr_cache = self.get_chr_cache()
if chr_cache:
actor_link_id = chr_cache.link_id
if not actor_link_id:
utils.log_info(f"Assigning actor link_id: {chr_cache.character_name}: {link_id}")
chr_cache.link_id = link_id
return
if link_id not in self.alias and actor_link_id != link_id:
utils.log_info(f"Assigning actor alias: {chr_cache.character_name}: {link_id}")
self.alias.append(link_id)
return
@staticmethod
def find_actor(link_id, search_name=None, search_type=None, context_chr_cache=None):
props = vars.props()
prefs = vars.prefs()
link_data = get_link_data()
utils.log_detail(f"Looking for LinkActor: {search_name} {link_id} {search_type}")
actor: LinkActor = None
chr_cache = props.find_character_by_link_id(link_id)
if chr_cache:
if not search_type or LinkActor.chr_cache_type(chr_cache) == search_type:
actor = LinkActor(chr_cache)
utils.log_detail(f"Chr found by link_id: {actor.name} / {link_id}")
return actor
utils.log_detail(f"Chr not found by link_id")
# try to find the character by name if the link id finds nothing
# character id's change after every reload in iClone/CC4 so these can change.
if search_name:
chr_cache = props.find_character_by_name(search_name)
if chr_cache:
if not search_type or LinkActor.chr_cache_type(chr_cache) == search_type:
utils.log_detail(f"Chr found by name: {chr_cache.character_name} / {chr_cache.link_id} -> {link_id}")
actor = LinkActor(chr_cache)
actor.add_alias(link_id)
return actor
utils.log_detail(f"Chr not found by name")
# finally if matching to any avatar, trying to find an avatar and there is only
# one avatar in the scene, use that one avatar, otherwise use the selected avatar
if False and link_data and link_data.is_cc() and prefs.datalink_match_any_avatar and search_type == "AVATAR":
chr_cache = None
if len(props.get_avatars()) == 1:
chr_cache = props.get_first_avatar()
else:
if not context_chr_cache:
context_chr_cache = props.get_context_character_cache()
if context_chr_cache and context_chr_cache.is_avatar():
chr_cache = context_chr_cache
if chr_cache:
utils.log_detail(f"Falling back to first Chr Avatar: {chr_cache.character_name} / {chr_cache.link_id} -> {link_id}")
actor = LinkActor(chr_cache)
actor.add_alias(link_id)
return actor
utils.log_info(f"LinkActor not found: {search_name} {link_id} {search_type}")
return actor
@staticmethod
def chr_cache_type(chr_cache):
if chr_cache:
return chr_cache.cache_type()
return "NONE"
def get_mesh_objects(self):
objects = None
chr_cache = self.get_chr_cache()
if chr_cache:
objects = chr_cache.get_all_objects(include_armature=False,
include_children=True,
of_type="MESH")
return objects
def object_has_sequence_shape_keys(self, obj):
if obj.data.shape_keys and obj.data.shape_keys.key_blocks:
for expression_name in self.expressions:
if expression_name in obj.data.shape_keys.key_blocks:
return True
for viseme_name in self.visemes:
if viseme_name in obj.data.shape_keys.key_blocks:
return True
return False
def collect_shape_keys(self):
self.shape_keys = {}
objects: list = self.get_mesh_objects()
# sort objects by reverse shape_key count (this should put the body mesh first)
objects.sort(key=utils.key_count, reverse=True)
# collect dictionary of shape keys and their primary key block
for obj in objects:
if obj.data.shape_keys and obj.data.shape_keys.key_blocks:
for key in obj.data.shape_keys.key_blocks:
if key.name not in self.shape_keys:
self.shape_keys[key.name] = key
def get_sequence_objects(self):
objects = []
non_sequence_objects = []
chr_cache = self.get_chr_cache()
if chr_cache:
all_objects = chr_cache.get_all_objects(include_armature=False,
include_children=True,
of_type="MESH")
for obj in all_objects:
if self.object_has_sequence_shape_keys(obj):
objects.append(obj)
else:
non_sequence_objects.append(obj)
return objects, non_sequence_objects
def set_template(self, bones, meshes, expressions, visemes, morphs):
self.bones = bones
self.meshes = meshes
self.expressions = expressions
self.visemes = self.remap_visemes(visemes)
self.morphs = morphs
rig = self.get_armature()
skin_meshes = {}
# rename pivot bones
for i, bone_name in enumerate(self.bones):
if bone_name == "_Object_Pivot_Node_":
self.bones[i] = "CC_Base_Pivot"
#for i, mesh_name in enumerate(meshes):
# if mesh_name in names:
# count = names[mesh_name]
# names[mesh_name] += 1
# meshes[i] = f"{mesh_name}.{count:03d}"
# else:
# names[mesh_name] == 1
names = {}
for i, mesh_name in enumerate(meshes):
obj = None
for child in rig.children:
child_source_name = utils.strip_name(child.name)
if child.type == "MESH" and child_source_name == mesh_name:
# determine the duplication suffix offset
if child_source_name in names:
count = names[child_source_name]
names[child_source_name] += 1
mesh_name = f"{child_source_name}.{count:03d}"
meshes[i] = mesh_name
else:
count = utils.get_duplication_suffix(child.name)
names[child_source_name] = count + 1
mesh_name = child.name
meshes[i] = mesh_name
obj = child
rot_mode = obj.rotation_mode
obj.rotation_mode = "QUATERNION"
skin_meshes[mesh_name] = [obj, obj.location.copy(), obj.rotation_quaternion.copy(), obj.scale.copy()]
obj.rotation_mode = rot_mode
self.skin_meshes = skin_meshes
def remap_visemes(self, visemes):
exported_visemes = []
for viseme_name in visemes:
if viseme_name in VISEME_NAME_MAP:
exported_visemes.append(VISEME_NAME_MAP[viseme_name])
return exported_visemes
def clear_template(self):
self.bones = None
def set_cache(self, cache):
self.cache = cache
def clear_cache(self):
self.cache = None
def update_name(self, new_name):
self.name = new_name
chr_cache = self.get_chr_cache()
if chr_cache:
chr_cache.character_name = new_name
def update_link_id(self, new_link_id):
chr_cache = self.get_chr_cache()
if chr_cache:
utils.log_info(f"Assigning new link_id: {chr_cache.character_name}: {new_link_id}")
chr_cache.link_id = new_link_id
def ready(self):
if self.cache and self.get_chr_cache() and self.get_armature():
return True
else:
return False
def is_rigified(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.rigified
return False
def has_key(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.get_import_has_key()
return False
def can_go_cc(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.can_go_cc()
return False
def can_go_ic(self):
chr_cache = self.get_chr_cache()
if chr_cache:
return chr_cache.can_go_ic()
return False
class LinkData():
link_host: str = "localhost"
link_host_ip: str = "127.0.0.1"
link_target: str = "BLENDER"
link_port: int = 9333
actors: list = []
# Sequence/Pose Props
sequence_current_frame: int = 0
sequence_start_frame: int = 0
sequence_end_frame: int = 0
sequence_actors: list = None
sequence_type: str = None
#
preview_shape_keys: bool = True
preview_skip_frames: bool = False
# remote props
remote_app: str = None
remote_version: str = None
remote_path: str = None
remote_exe: str = None
#
ack_rate: float = 0.0
ack_time: float = 0.0
#
motion_prefix: str = ""
use_fake_user: bool = False
def __init__(self):
return
def reset(self):
self.actors = []
self.sequence_actors = None
self.sequence_type = None
def is_cc(self):
if self.remote_app == "Character Creator":
return True
else:
return False
def find_sequence_actor(self, link_id) -> LinkActor:
for actor in self.sequence_actors:
if actor.get_link_id() == link_id:
return actor
for actor in self.sequence_actors:
if link_id in actor.alias:
return actor
return None
def set_action_settings(self, prefix: str, fake_user):
self.motion_prefix = prefix.strip()
self.use_fake_user = fake_user
LINK_DATA = LinkData()
def get_link_data():
global LINK_DATA
return LINK_DATA
def encode_from_json(json_data) -> bytearray:
json_string = json.dumps(json_data)
json_bytes = bytearray(json_string, "utf-8")
return json_bytes
def decode_to_json(data) -> dict:
text = data.decode("utf-8")
json_data = json.loads(text)
return json_data
def pack_string(s) -> bytearray:
buffer = bytearray()
buffer += struct.pack("!I", len(s))
buffer += bytes(s, encoding="utf-8")
return buffer
def unpack_string(buffer, offset=0):
length = struct.unpack_from("!I", buffer, offset)[0]
offset += 4
string: bytearray = buffer[offset:offset+length]
offset += length
return offset, string.decode(encoding="utf-8")
def get_local_data_path():
local_path = utils.local_path()
blend_file_name = utils.blend_file_name()
data_path = ""
if local_path and blend_file_name:
data_path = local_path
return data_path
def find_rig_pivot_bone(rig, parent):
bone: bpy.types.PoseBone
for bone in rig.pose.bones:
if bone.name.startswith("CC_Base_Pivot"):
if bones.is_target_bone_name(bone.parent.name, parent):
return bone.name
return None
def BFA(f):
"""Blender Frame Adjust:
Convert Blender frame index (starting at frame 1)
to CC/iC frame index (starting at frame 0)
"""
return max(0, f - 1)
def RLFA(f):
"""Reallusion Frame Adjust:
Convert Reallusion frame index (starting at frame 0)
to Blender frame index (starting at frame 1)
"""
return f + 1
def make_datalink_import_rig(actor: LinkActor):
"""Creates or re-uses and existing datalink pose rig for the character.
This uses a pre-generated character template (list of bones in the character)
sent from CC/iC to avoid encoding the bone names into the pose data stream."""
if not actor:
utils.log_error("make_datalink_import_rig - Invalid Actor:")
return None
if not actor.get_chr_cache():
utils.log_error(f"make_datalink_import_rig - Invalid Actor cache: {actor.name}")
return None
# get character armature
chr_rig = actor.get_armature()
if not chr_rig:
utils.log_error(f"make_datalink_import_rig - Invalid Actor armature: {actor.name}")
return None
utils.unhide(chr_rig)
chr_cache = actor.get_chr_cache()
is_prop = actor.get_type() == "PROP"
if utils.object_exists_is_armature(chr_cache.rig_datalink_rig):
actor.rig_bones = actor.bones.copy()
utils.unhide(chr_cache.rig_datalink_rig)
#utils.log_info(f"Using existing datalink transfer rig: {chr_cache.rig_datalink_rig.name}")
return chr_cache.rig_datalink_rig
no_constraints = True if chr_cache.rigified else False
rig_name = f"{chr_cache.character_name}_Link_Rig"
utils.log_info(f"Creating datalink transfer rig: {rig_name}")
# create pose armature
datalink_rig = utils.get_armature(rig_name)
if not datalink_rig:
datalink_rig = utils.create_reuse_armature(rig_name)
edit_bone: bpy.types.EditBone
arm: bpy.types.Armature = datalink_rig.data
if utils.edit_mode_to(datalink_rig):
while len(datalink_rig.data.edit_bones) > 0:
datalink_rig.data.edit_bones.remove(datalink_rig.data.edit_bones[0])
actor.rig_bones = actor.bones.copy()
for i, sk_bone_name in enumerate(actor.bones):
edit_bone = arm.edit_bones.new(sk_bone_name)
actor.rig_bones[i] = edit_bone.name
edit_bone.head = Vector((0,0,0))
edit_bone.tail = Vector((0,1,0))
edit_bone.align_roll(Vector((0,0,1)))
edit_bone.length = 0.1
utils.object_mode_to(datalink_rig)
# constraint character armature
l = len(actor.bones)
if not no_constraints:
for i, rig_bone_name in enumerate(actor.rig_bones):
sk_bone_name = actor.bones[i]
chr_bone_name = bones.find_target_bone_name(chr_rig, rig_bone_name)
if chr_bone_name:
bones.add_copy_location_constraint(datalink_rig, chr_rig, rig_bone_name, chr_bone_name)
bones.add_copy_rotation_constraint(datalink_rig, chr_rig, rig_bone_name, chr_bone_name)
else:
utils.log_warn(f"Could not find bone: {rig_bone_name} in character rig!")
utils.safe_set_action(datalink_rig, None)
utils.object_mode_to(datalink_rig)
utils.hide(datalink_rig)
chr_cache.rig_datalink_rig = datalink_rig
if chr_cache.rigified:
# a rigified character must retarget the link rig, but...
# the link rig doesn't have a valid bind pose, so the retargeting rig
# can't use it as a source rig for the roll axes on the ORG bones,
# so we use the original ones for the character type (option to_original_rig)
# (data on the original bones is added the ORG bones during rigify process)
rigging.adv_retarget_remove_pair(None, chr_cache)
if not chr_cache.rig_retarget_rig:
rigging.adv_retarget_pair_rigs(None, chr_cache,
rig_override=datalink_rig,
to_original_rig=True)
return datalink_rig
def remove_datalink_import_rig(actor: LinkActor):
if actor:
chr_cache = actor.get_chr_cache()
chr_rig = actor.get_armature()
if utils.object_exists_is_armature(chr_cache.rig_datalink_rig):
if chr_cache.rigified:
rigging.adv_retarget_remove_pair(None, chr_cache)
if actor.ik_store:
rigutils.restore_ik_stretch(actor.ik_store)
else:
# remove all contraints on the character rig
if utils.object_exists(chr_rig):
utils.unhide(chr_rig)
if utils.object_mode_to(chr_rig):
for pose_bone in chr_rig.pose.bones:
bones.clear_constraints(chr_rig, pose_bone.name)
utils.delete_armature_object(chr_cache.rig_datalink_rig)
chr_cache.rig_datalink_rig = None
#rigging.reset_shape_keys(chr_cache)
utils.object_mode_to(chr_rig)
def set_actor_expression_weight(objects, expression_name, weight):
global LINK_DATA
if objects and LINK_DATA.preview_shape_keys:
obj: bpy.types.Object
for obj in objects:
if expression_name in obj.data.shape_keys.key_blocks:
if obj.data.shape_keys.key_blocks[expression_name].value != weight:
obj.data.shape_keys.key_blocks[expression_name].value = weight
def set_actor_viseme_weight(objects, viseme_name, weight):
global LINK_DATA
if objects and LINK_DATA.preview_shape_keys:
for obj in objects:
if obj.data.shape_keys and obj.data.shape_keys.key_blocks:
if viseme_name in obj.data.shape_keys.key_blocks:
if obj.data.shape_keys.key_blocks[viseme_name].value != weight:
obj.data.shape_keys.key_blocks[viseme_name].value = weight
def ensure_current_frame(current_frame):
if bpy.context.scene.frame_current != current_frame:
bpy.context.scene.frame_current = current_frame
return current_frame
def next_frame(current_frame=None):
if current_frame is None:
current_frame = bpy.context.scene.frame_current
fps = bpy.context.scene.render.fps
end_frame = bpy.context.scene.frame_end
current_frame = min(end_frame, current_frame + 1)
bpy.context.scene.frame_current = current_frame
return current_frame
def prev_frame(current_frame=None):
if current_frame is None:
current_frame = bpy.context.scene.frame_current
fps = bpy.context.scene.render.fps
start_frame = bpy.context.scene.frame_start
current_frame = max(start_frame, current_frame - 1)
bpy.context.scene.frame_current = current_frame
return current_frame
def reset_action(chr_cache):
if chr_cache:
rig = chr_cache.get_armature()
if rig:
action = utils.safe_get_action(rig)
utils.clear_prop_collection(action.fcurves)
def create_fcurves_cache(count, indices, defaults):
curves = []
cache = {
"count": count,
"indices": indices,
"curves": curves,
}
for i in range(0, indices):
d = defaults[i]
cache_data = [d]*(count*2)
curves.append(cache_data)
return cache
def get_datalink_rig_action(rig, motion_id=None):
if not motion_id:
motion_id = "DataLink"
rig_id = rigutils.get_rig_id(rig)
action_name = rigutils.make_armature_action_name(rig_id, motion_id, LINK_DATA.motion_prefix)
if action_name in bpy.data.actions:
action = bpy.data.actions[action_name]
else:
action = bpy.data.actions.new(action_name)
utils.safe_set_action(rig, action)
action.use_fake_user = LINK_DATA.use_fake_user
return action
def prep_rig(actor: LinkActor, start_frame, end_frame):
"""Prepares the character rig for keyframing poses from the pose data stream."""
if actor and actor.get_chr_cache():
chr_cache = actor.get_chr_cache()
rig = actor.get_armature()
if not rig:
utils.log_error(f"Actor: {actor.name} invalid rig!")
return
objects, none_objects = actor.get_sequence_objects()
if rig:
rig_id = rigutils.get_rig_id(rig)
rl_arm_id = utils.get_rl_object_id(rig)
utils.log_info(f"Preparing Character Rig: {actor.name} {rig_id} / {len(actor.bones)} bones")
# set data
if LINK_DATA.sequence_type == "POSE":
motion_id = "Pose"
else:
motion_id = "Sequence"
set_id, set_generation = rigutils.generate_motion_set(rig, motion_id, LINK_DATA.motion_prefix)
# rig action
action = get_datalink_rig_action(rig, motion_id)
rigutils.add_motion_set_data(action, set_id, set_generation, rl_arm_id=rl_arm_id)
utils.log_info(f"Preparing rig action: {action.name}")
utils.clear_prop_collection(action.fcurves)
# shape key actions
num_expressions = len(actor.expressions)
num_visemes = len(actor.visemes)
if objects:
for obj in objects:
obj_id = rigutils.get_action_obj_id(obj)
action_name = rigutils.make_key_action_name(rig_id, motion_id, obj_id, LINK_DATA.motion_prefix)
utils.log_info(f"Preparing shape key action: {action_name} / {num_expressions}+{num_visemes} shape keys")
if action_name in bpy.data.actions:
action = bpy.data.actions[action_name]
else:
action = bpy.data.actions.new(action_name)
rigutils.add_motion_set_data(action, set_id, set_generation, obj_id=obj_id)
utils.clear_prop_collection(action.fcurves)
utils.safe_set_action(obj.data.shape_keys, action)
action.use_fake_user = LINK_DATA.use_fake_user
# remove actions from non sequence objects
for obj in none_objects:
utils.safe_set_action(obj.data.shape_keys, None)
if chr_cache.rigified:
# disable IK stretch
actor.ik_store = rigutils.disable_ik_stretch(rig)
BAKE_BONE_GROUPS = ["FK", "IK", "Special", "Root"] #not Tweak and Extra
BAKE_BONE_COLLECTIONS = ["Face", #"Face (Primary)", "Face (Secondary)",
"Torso", "Torso (Tweak)",
"Fingers", "Fingers (Detail)",
"Arm.L (IK)", "Arm.L (FK)", "Arm.L (Tweak)",
"Leg.L (IK)", "Leg.L (FK)", "Leg.L (Tweak)",
"Arm.R (IK)", "Arm.R (FK)", "Arm.R (Tweak)",
"Leg.R (IK)", "Leg.R (FK)", "Leg.R (Tweak)",
"Root"]
# TODO These bones may need to have their pose reset as they are damped tracked in the rig
BAKE_BONE_EXCLUSIONS = [
"thigh_ik.L", "thigh_ik.R", "thigh_parent.L", "thigh_parent.R",
"upper_arm_ik.L", "upper_arm_ik.R", "upper_arm_parent.L", "upper_arm_parent.R"
]
BAKE_BONE_LAYERS = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,28]
if utils.object_mode_to(rig):
bone: bpy.types.Bone
pose_bone: bpy.types.PoseBone
bones.make_bones_visible(rig, collections=BAKE_BONE_COLLECTIONS, layers=BAKE_BONE_LAYERS)
for pose_bone in rig.pose.bones:
bone = pose_bone.bone
bone.select = False
if bones.is_bone_in_collections(rig, bone, BAKE_BONE_COLLECTIONS,
BAKE_BONE_GROUPS):
if bone.name not in BAKE_BONE_EXCLUSIONS:
bone.hide = False
bone.hide_select = False
bone.select = True
pose_bone.rotation_mode = "QUATERNION"
else:
if utils.object_mode_to(rig):
bone: bpy.types.Bone
pose_bone: bpy.types.PoseBone
for pose_bone in rig.pose.bones:
bone = pose_bone.bone
bone.hide = False
bone.hide_select = False
bone.select = True
#pose_bone.rotation_mode = "QUATERNION"
# create keyframe cache for animation sequences
count = end_frame - start_frame + 1
bone_cache = {}
expression_cache = {}
viseme_cache = {}
morph_cache = {}
actor_cache = {
"rig": rig,
"bones": bone_cache,
"expressions": expression_cache,
"visemes": viseme_cache,
"morphs": morph_cache,
"start": start_frame,
"end": end_frame,
}
for pose_bone in rig.pose.bones:
bone_name = pose_bone.name
bone = rig.data.bones[bone_name]
if bone.select:
loc_cache = create_fcurves_cache(count, 3, [0,0,0])
sca_cache = create_fcurves_cache(count, 3, [1,1,1])
rot_cache = create_fcurves_cache(count, 4, [1,0,0,0])
bone_cache[bone_name] = {
"loc": loc_cache,
"sca": sca_cache,
"rot": rot_cache,
}
for expression_name in actor.expressions:
expression_cache[expression_name] = create_fcurves_cache(count, 1, [0])
for viseme_name in actor.visemes:
viseme_cache[viseme_name] = create_fcurves_cache(count, 1, [0])
for morph_name in actor.morphs:
pass
actor.set_cache(actor_cache)
def set_frame_range(start, end):
bpy.data.scenes["Scene"].frame_start = start
bpy.data.scenes["Scene"].frame_end = end
def set_frame(frame):
bpy.data.scenes["Scene"].frame_current = frame
bpy.context.view_layer.update()
def key_frame_pose_visual():
area = [a for a in bpy.context.screen.areas if a.type=="VIEW_3D"][0]
with bpy.context.temp_override(area=area):
bpy.ops.anim.keyframe_insert_menu(type='BUILTIN_KSI_VisualLocRot')
def store_bone_cache_keyframes(actor: LinkActor, frame):
"""Needs to be called after all constraints have been set and all bones in the pose positioned"""
if not actor.cache:
utils.log_error(f"No actor cache: {actor.name}")
return
rig = actor.get_armature()
start_frame = actor.cache["start"]
cache_index = (frame - start_frame) * 2
bone_cache = actor.cache["bones"]
for bone_name in bone_cache:
loc_cache = bone_cache[bone_name]["loc"]
sca_cache = bone_cache[bone_name]["sca"]
rot_cache = bone_cache[bone_name]["rot"]
pose_bone: bpy.types.PoseBone = rig.pose.bones[bone_name]
L: Matrix # local space matrix we want
NL: Matrix # non-local space matrix we want (if not using local location or inherit rotation)
M: Matrix = pose_bone.matrix # object space matrix of the pose bone after contraints and drivers
R: Matrix = pose_bone.bone.matrix_local # bone rest pose matrix
RI: Matrix = R.inverted() # bone rest pose matrix inverted
if pose_bone.parent:
PI: Matrix = pose_bone.parent.matrix.inverted() # parent object space matrix inverted (after contraints and drivers)
PR: Matrix = pose_bone.parent.bone.matrix_local # parent rest pose matrix
L = RI @ (PR @ (PI @ M))
NL = PI @ M
else:
L = RI @ M
NL = M
if not pose_bone.bone.use_local_location:
loc = NL.to_translation()
else:
loc = L.to_translation()
sca = L.to_scale()
if not pose_bone.bone.use_inherit_rotation:
rot = NL.to_quaternion()
else:
rot = L.to_quaternion()
for i in range(0, 3):
curve = loc_cache["curves"][i]
curve[cache_index] = frame
curve[cache_index + 1] = loc[i]
for i in range(0, 3):
curve = sca_cache["curves"][i]
curve[cache_index] = frame
curve[cache_index + 1] = sca[i]
for i in range(0, 4):
curve = rot_cache["curves"][i]
curve[cache_index] = frame
curve[cache_index + 1] = rot[i]
def store_shape_key_cache_keyframes(actor: LinkActor, frame, expression_weights, viseme_weights, morph_weights):
if not actor.cache:
utils.log_error(f"No actor cache: {actor.name}")
return
start_frame = actor.cache["start"]
cache_index = (frame - start_frame) * 2
expression_cache = actor.cache["expressions"]
for i, expression_name in enumerate(expression_cache):
curve = expression_cache[expression_name]["curves"][0]
curve[cache_index] = frame
curve[cache_index + 1] = expression_weights[i]
viseme_cache = actor.cache["visemes"]
for i, viseme_name in enumerate(viseme_cache):
curve = viseme_cache[viseme_name]["curves"][0]
curve[cache_index] = frame
curve[cache_index + 1] = viseme_weights[i]
def write_sequence_actions(actor: LinkActor, num_frames):
if actor.cache:
rig = actor.cache["rig"]
rig_action = utils.safe_get_action(rig)
objects, none_objects = actor.get_sequence_objects()
set_count = num_frames * 2
if rig_action:
utils.clear_prop_collection(rig_action.fcurves)
bone_cache = actor.cache["bones"]
for bone_name in bone_cache:
pose_bone: bpy.types.PoseBone = rig.pose.bones[bone_name]
loc_cache = bone_cache[bone_name]["loc"]
sca_cache = bone_cache[bone_name]["sca"]
rot_cache = bone_cache[bone_name]["rot"]
fcurve: bpy.types.FCurve
for i in range(0, 3):
data_path = pose_bone.path_from_id("location")
fcurve = rig_action.fcurves.new(data_path, index=i, action_group="Location")
fcurve.keyframe_points.add(num_frames)
fcurve.keyframe_points.foreach_set('co', loc_cache["curves"][i][:set_count])
for i in range(0, 3):
data_path = pose_bone.path_from_id("scale")
fcurve = rig_action.fcurves.new(data_path, index=i, action_group="Scale")
fcurve.keyframe_points.add(num_frames)
fcurve.keyframe_points.foreach_set('co', sca_cache["curves"][i][:set_count])
for i in range(0, 4):
data_path = pose_bone.path_from_id("rotation_quaternion")
fcurve = rig_action.fcurves.new(data_path, index=i, action_group="Rotation Quaternion")
fcurve.keyframe_points.add(num_frames)
fcurve.keyframe_points.foreach_set('co', rot_cache["curves"][i][:set_count])
expression_cache = actor.cache["expressions"]
viseme_cache = actor.cache["visemes"]
for obj in objects:
obj_action = utils.safe_get_action(obj.data.shape_keys)
if obj_action:
utils.clear_prop_collection(obj_action.fcurves)
for expression_name in expression_cache:
if expression_name in obj.data.shape_keys.key_blocks:
key_cache = expression_cache[expression_name]
key = obj.data.shape_keys.key_blocks[expression_name]
data_path = key.path_from_id("value")
fcurve = obj_action.fcurves.new(data_path, action_group="Expression")
fcurve.keyframe_points.add(num_frames)
fcurve.keyframe_points.foreach_set('co', key_cache["curves"][0][:set_count])
for viseme_name in viseme_cache:
if viseme_name in obj.data.shape_keys.key_blocks:
key_cache = viseme_cache[viseme_name]
key = obj.data.shape_keys.key_blocks[viseme_name]
data_path = key.path_from_id("value")
fcurve = obj_action.fcurves.new(data_path, action_group="Viseme")
fcurve.keyframe_points.add(num_frames)
fcurve.keyframe_points.foreach_set('co', key_cache["curves"][0][:set_count])
# remove actions from non sequence objects
for obj in none_objects:
utils.safe_set_action(obj.data.shape_keys, None)
actor.clear_cache()
class Signal():
callbacks: list = None
def __init__(self):
self.callbacks = []
def connect(self, func):
self.callbacks.append(func)
def disconnect(self, func=None):
if func:
self.callbacks.remove(func)
else:
self.callbacks.clear()
def emit(self, *args):
for func in self.callbacks:
func(*args)
class LinkService():
timer = None
server_sock: socket.socket = None
client_sock: socket.socket = None
server_sockets = []
client_sockets = []
empty_sockets = []
client_ip: str = "127.0.0.1"
client_port: int = BLENDER_PORT
is_listening: bool = False
is_connected: bool = False
is_connecting: bool = False
ping_timer: float = 0