forked from ExpiredPopsicle/SnekStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MediaPipeController.gd
1399 lines (1068 loc) · 48.5 KB
/
MediaPipeController.gd
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
extends Mod_Base
# Tracker process state and UDP connection info.
var udp_server = null
@export var udp_port_base : int = 7098
var _udp_port = udp_port_base # This will change dynamically based on port availability.
# NEW tracker stuff.
var tracker_python_process : KiriPythonWrapperInstance = null
# Current tracking state.
var last_parsed_data = {}
var hand_landmarks_left = []
var hand_landmarks_right = []
var hand_time_since_last_update = [0.0, 0.0]
var hand_time_since_last_missing = [0.0, 0.0]
var mirrored_last_frame = true
var blend_shape_last_values = {}
var head_tracker : Node3D
var hand_trackers = {}
var hand_rest_trackers = {}
var _init_complete = false
var frames_missing_before_spine_reset = 6.0
var blend_to_rest_speed = 4.5
var head_vertical_offset : float = 0.0
var hips_vertical_blend_speed : float = 6.0
# FIXME: Make this a dictionary (spine, left hand, right hand, etc)
var _ikchains = []
# Settings stuff
@export var mirror_mode : bool = true
@export var arm_rest_angle : float = 70
@export var arm_reset_time : float = 0.5
@export var arm_reset_speed : float = 0.1
@export var use_external_tracker = false
@export var hand_tracking_enabed : bool = true
var use_vrm_basic_shapes = false
var use_mediapipe_shapes = true
var frame_rate_limit = 60
var video_device = Array() # It's an array that we only ever put one thing in.
var blendshape_calibration = {}
var debug_visible_hand_trackers = false
# TODO: Add settings for these
var do_ik_curve = true
var do_yaw_global = true
var do_point_tracker = true
var do_pole_targets = true
var do_rotate_to_match_tracker = true
var do_hands = true
# Temp variables for settings.
var _devices_by_list_entry = {}
var _devices_list = []
var functions_blendshapes = preload("MediaPipeController_BlendShapes.gd")
# FIXME: Make key for this configurable.
var tracking_pause = false
var hand_confidence_time_threshold = 1.0
var hand_count_change_time_threshold = 1.0
var hand_rotation_smoothing : float = 1.0
var hand_position_smoothing : float = 1.0
var chest_yaw_scale : float = 0.25
var lean_scale : float = 1.0
var hip_adjustment_speed : float = 1.0
var blendshape_scale : float = 1.2
func _ready():
var script_path : String = self.get_script().get_path()
var script_dirname : String = script_path.get_base_dir()
tracker_python_process = KiriPythonWrapperInstance.new( \
script_dirname.path_join("/_tracker/Project/new_tracker.py"))
print("Setting up Python...")
if not tracker_python_process.setup_python(false):
OS.alert("Something went wrong when setting up tracker dependencies!")
add_tracked_setting("hand_tracking_enabed", "Hand tracking enabled")
add_tracked_setting("use_vrm_basic_shapes", "Use basic VRM shapes")
add_tracked_setting("use_mediapipe_shapes", "Use MediaPipe shapes")
add_tracked_setting("mirror_mode", "Mirror mode")
add_tracked_setting("frame_rate_limit", "Frame rate limit", { "min" : 1.0, "max" : 240.0 })
add_tracked_setting("arm_rest_angle", "Arm rest angle", { "min" : 0.0, "max" : 180.0 })
add_tracked_setting("use_external_tracker", "Disable internal tracker")
add_tracked_setting("hand_confidence_time_threshold", "Hand confidence time", { "min" : 0.0, "max" : 20.0 })
add_tracked_setting("hand_count_change_time_threshold", "Hand count change time", { "min" : 0.0, "max" : 20.0 })
add_tracked_setting("frames_missing_before_spine_reset", "Untracked frames before reset", { "min" : -1.0, "max" : 120.0, "step" : 1.0 })
add_tracked_setting("blend_to_rest_speed", "Blend back to rest pose speed", { "min" : 0.0, "max" : 10.0, "step" : 0.1 })
add_tracked_setting("head_vertical_offset", "Head vertical offset", { "min" : -1.0, "max" : 1.0 })
add_tracked_setting("hips_vertical_blend_speed", "Hips vertical blend speed", { "min" : 0.0, "max" : 20.0 })
add_tracked_setting("hand_position_smoothing", "Hand Position Smoothing", { "min" : 1.0, "max" : 5.0 })
add_tracked_setting("hand_rotation_smoothing", "Hand Rotation Smoothing", { "min" : 1.0, "max" : 5.0 })
add_tracked_setting("chest_yaw_scale", "Chest Yaw Rotation Scale", { "min" : -2.0, "max" : 2.0 })
add_tracked_setting("lean_scale", "Lean Scale", { "min" : -4.0, "max" : 4.0 })
add_tracked_setting("hip_adjustment_speed", "Hip Adjustment Speed", { "min" : 0.0, "max" : 10.0 })
add_tracked_setting("blendshape_scale", "Blend Shape Scale", { "min" : 0.0, "max" : 10.0 })
# Star the Python tracker process just long enough to scan for video
# devices. We won't be starting "for real" until we get to scene_init.
tracker_python_process.start_process(false)
_scan_video_devices()
add_tracked_setting(
"video_device", "Video Device",
{"values" : _devices_list,
"combobox" : true})
tracker_python_process.stop_process()
add_tracked_setting("debug_visible_hand_trackers", "Debug: Visible hand trackers")
add_tracked_setting("tracking_pause", "Pause tracking")
head_tracker = $Head
hand_trackers["Left"] = $Hand_Left
hand_trackers["Right"] = $Hand_Right
hand_rest_trackers["Left"] = $LeftHandRestReference
hand_rest_trackers["Right"] = $RightHandRestReference
set_status("Waiting to start")
update_settings_ui()
var calibration_button : Button = Button.new()
calibration_button.text = "Calibrate Face"
get_settings_window().add_child(calibration_button)
calibration_button.pressed.connect(_calibrate_face)
var clear_calibration_button : Button = Button.new()
clear_calibration_button.text = "Clear Calibration"
get_settings_window().add_child(clear_calibration_button)
clear_calibration_button.pressed.connect(func() : blendshape_calibration = {})
_update_for_new_model_if_needed()
func save_before(_settings_current: Dictionary):
_settings_current["blendshape_calibration"] = blendshape_calibration
func _send_settings_to_tracker():
# Don't send these if the tracker process isn't running. We'll send them
# after it starts, instead (called in _start_process).
if tracker_python_process.get_status() != KiriPythonWrapperInstance.KiriPythonWrapperStatus.STATUS_RUNNING:
return
# Clear out video device setting if it doesn't exist in the list of video
# devices.
if len(video_device):
if not video_device[0] in _devices_by_list_entry.keys():
video_device.clear()
# Set the video device.
if len(video_device):
var actual_device_data = _devices_by_list_entry[video_device[0]]
tracker_python_process.call_rpc_sync(
"set_video_device_number", [actual_device_data["index"]])
else:
# If no camera selected, then select device -1.
tracker_python_process.call_rpc_sync(
"set_video_device_number", [-1])
tracker_python_process.call_rpc_async(
"set_hand_confidence_time_threshold", [hand_confidence_time_threshold])
tracker_python_process.call_rpc_async(
"set_hand_count_change_time_threshold", [hand_count_change_time_threshold])
func load_after(_settings_old : Dictionary, _settings_new : Dictionary):
super.load_after(_settings_old, _settings_new)
_update_arm_rest_positions()
if _settings_new["chest_yaw_scale"] != _settings_old["chest_yaw_scale"]:
_setup_ik_chains()
_send_settings_to_tracker()
var reset_blend_shapes = false
if _settings_old["use_vrm_basic_shapes"] != _settings_new["use_vrm_basic_shapes"]:
reset_blend_shapes = true
if _settings_old["use_mediapipe_shapes"] != _settings_new["use_mediapipe_shapes"]:
reset_blend_shapes = true
if reset_blend_shapes:
for k in blend_shape_last_values.keys():
blend_shape_last_values[k] = 0.0
if _settings_old["blendshape_calibration"] != _settings_new["blendshape_calibration"]:
blendshape_calibration = _settings_new["blendshape_calibration"]
func scene_init():
_start_process()
# Find a port number that's open to use. Must be done before start_tracker.
# OR call the set port number RPC after changing it.
assert(!udp_server)
udp_server = PacketPeerUDP.new()
var udp_error = 1
_udp_port = udp_port_base
while udp_error != OK:
udp_error = udp_server.bind(_udp_port, "127.0.0.1")
if udp_error != OK:
_udp_port += 1
start_tracker()
blend_shape_last_values = {}
last_parsed_data = {}
# Move trackers into the scene.
var root = get_skeleton().get_parent()
head_tracker.reparent(root)
hand_trackers["Left"].reparent(root)
hand_trackers["Right"].reparent(root)
hand_rest_trackers["Left"].reparent(root)
hand_rest_trackers["Right"].reparent(root)
# Set the head tracker to match the model's head position.
var head_bone_index = get_skeleton().find_bone("Head")
head_tracker.transform = get_skeleton().get_bone_global_rest(head_bone_index)
_setup_ik_chains()
_update_arm_rest_positions()
_init_complete = true
func scene_shutdown():
stop_tracker()
_stop_process()
udp_server.close()
udp_server = null
head_tracker.reparent(self)
hand_trackers["Left"].reparent(self)
hand_trackers["Right"].reparent(self)
hand_rest_trackers["Left"].reparent(self)
hand_rest_trackers["Right"].reparent(self)
_ikchains = []
_init_complete = false
# -----------------------------------------------------------------------------
# Post-load model setup.
func _update_arm_rest_positions():
var skel : Skeleton3D = get_skeleton()
if skel:
for side in [ "Left", "Right" ]:
var rotation_axis : Vector3 = Vector3(0.0, 0.0, 1.0)
if side == "Left":
rotation_axis *= -1
# Rotate the shoulder down so the arm is resting at a specific angle
# on the Z axis.
var shoulder_index = skel.find_bone(side + "Shoulder")
var hand_index = skel.find_bone(side + "Hand")
var shoulder_origin : Vector3 = skel.get_bone_global_rest(shoulder_index).origin
var hand_origin : Vector3 = skel.get_bone_global_rest(hand_index).origin
var rotation_basis = Basis(rotation_axis, deg_to_rad(arm_rest_angle))
var new_offset : Vector3 = (hand_origin - shoulder_origin).rotated(
rotation_axis, deg_to_rad(arm_rest_angle))
hand_rest_trackers[side].transform.origin = shoulder_origin + new_offset
hand_rest_trackers[side].transform.basis = rotation_basis
func _setup_ik_chains():
# ORDER MATTERS ON THE CHAIN ARRAY. SPINE BEFORE ARMS BEFORE FINGERS.
_ikchains = []
var chain_spine : MediaPipeController_IKChain = MediaPipeController_IKChain.new()
chain_spine.skeleton = get_skeleton()
chain_spine.base_bone = "Hips"
chain_spine.tip_bone = "Head"
chain_spine.rotation_low = 0.0 * PI
chain_spine.rotation_high = 2.0 * PI
chain_spine.do_yaw = true
chain_spine.main_axis_of_rotation = Vector3(1.0, 0.0, 0.0)
chain_spine.secondary_axis_of_rotation = Vector3(0.0, 1.0, 0.0)
chain_spine.pole_direction_target = Vector3(0.0, 0.0, 0.0) # No pole target
chain_spine.tracker_object = head_tracker
chain_spine.yaw_scale = chest_yaw_scale
#chain_spine.do_rotate_to_match_tracker = false
#chain_spine.do_point_tracker = false
#chain_spine.do_pole_targets = false
# FIXME: Add yaw scale as an option.
_ikchains.append(chain_spine)
var x_pole_dist = 10.0
var z_pole_dist = 10.0
var y_pole_dist = 5.0
var arm_rotation_axis = Vector3(0.0, 1.0, 0.0).normalized()
var finger_rotation_axis = Vector3(0.0, 0.0, 1.0).normalized()
var hand_tracker_left : Node3D = hand_trackers["Left"]
var hand_tracker_right : Node3D = hand_trackers["Right"]
# FIXME: UGHHHGGHfgjkdnjvhndfvdfnvjkdfnjksdfn
# FIXME: MIRROR MESS
hand_tracker_left = hand_trackers["Right"]
hand_tracker_right = hand_trackers["Left"]
# Make sure finger landmarks exist already.
_reset_hand_landmarks()
for side in [ "Left", "Right" ]:
var chain_hand = MediaPipeController_IKChain.new()
chain_hand.skeleton = get_skeleton()
chain_hand.base_bone = side + "UpperArm"
chain_hand.tip_bone = side + "Hand"
#chain_hand.tip_bone = side + "IndexProximal"
chain_hand.rotation_low = 0.05 * PI
chain_hand.rotation_high = 2.0 * 0.99 * PI
chain_hand.do_yaw = false
chain_hand.do_bone_roll = true
chain_hand.secondary_axis_of_rotation = Vector3(0.0, 1.0, 0.0)
if side == "Left":
chain_hand.main_axis_of_rotation = -arm_rotation_axis
chain_hand.pole_direction_target = Vector3(
x_pole_dist, -y_pole_dist, -z_pole_dist)
chain_hand.tracker_object = hand_tracker_left
else:
chain_hand.main_axis_of_rotation = arm_rotation_axis
chain_hand.pole_direction_target = Vector3(
-x_pole_dist, -y_pole_dist, -z_pole_dist)
chain_hand.tracker_object = hand_tracker_right
_ikchains.append(chain_hand)
return
# See here for where these numbers come from:
# https://ai.google.dev/edge/mediapipe/solutions/vision/hand_landmarker
var fingertip_tracking_mappings = {
"Index" : 8,
"Middle" : 12,
"Ring" : 16,
"Little" : 20,
"Thumb" : 4
}
for side in [ "Left", "Right" ]:
var hand_tracker_object = hand_tracker_left
if side == "Right":
hand_tracker_object = hand_tracker_right
for finger in [ "Index", "Middle", "Ring", "Little" ]:
var chain_finger : MediaPipeController_IKChain = \
MediaPipeController_IKChain.new()
chain_finger.skeleton = get_skeleton()
# Attempt to find finger root bone.
chain_finger.base_bone = side + finger + "Proximal"
if chain_finger.skeleton.find_bone(chain_finger.base_bone) == -1:
# Finger missing entirely? Bail out.
continue
# Attempt to find finger most-distal bone.
chain_finger.tip_bone = side + finger + "Distal"
if chain_finger.skeleton.find_bone(chain_finger.tip_bone) == -1:
chain_finger.tip_bone = side + finger + "Intermediate"
if chain_finger.skeleton.find_bone(chain_finger.tip_bone) == -1:
# Can't find needed bones. Bail.
continue
# Keep looking and see if we can find something beyond the most
# distant bone.
var search_past_finger_tips_for_bones : bool = true
while true:
var child_bones : PackedInt32Array = chain_finger.skeleton.get_bone_children(
chain_finger.skeleton.find_bone(chain_finger.tip_bone))
if child_bones.size() == 1:
chain_finger.tip_bone = chain_finger.skeleton.get_bone_name(child_bones[0])
else:
break
chain_finger.tracker_object = hand_tracker_object.get_child(
fingertip_tracking_mappings[finger])
if side == "Left":
chain_finger.main_axis_of_rotation = -finger_rotation_axis
chain_finger.secondary_axis_of_rotation = Vector3(0.0, 1.0, 0.0)
else:
chain_finger.main_axis_of_rotation = finger_rotation_axis
chain_finger.secondary_axis_of_rotation = Vector3(0.0, 1.0, 0.0)
chain_finger.rotation_low = 0.05 * PI
chain_finger.rotation_high = 1.0 * 0.99 * PI
chain_finger.do_yaw = false
chain_finger.do_bone_roll = false
chain_finger.do_rotate_to_match_tracker = false
chain_finger.do_point_tracker = false
chain_finger.do_pole_targets = false
#chain_finger.pole_direction_target = Vector3(0.0, 10.0, 0.0)
#chain_finger.pole_direction_rotation_object = hand_tracker_object
_ikchains.append(chain_finger)
var chain_thumb : MediaPipeController_IKChain = \
MediaPipeController_IKChain.new()
chain_thumb.skeleton = get_skeleton()
# Attempt to find finger root bone.
chain_thumb.base_bone = side + "ThumbMetacarpal"
#chain_thumb.base_bone = side + "ThumbProximal"
if chain_thumb.skeleton.find_bone(chain_thumb.base_bone) == -1:
# Finger missing entirely? Bail out.
continue
print(chain_thumb.skeleton.get_concatenated_bone_names())
# Attempt to find finger most-distal bone.
chain_thumb.tip_bone = side + "ThumbDistal"
if chain_thumb.skeleton.find_bone(chain_thumb.tip_bone) == -1:
chain_thumb.tip_bone = side + "ThumbIntermediate"
if chain_thumb.skeleton.find_bone(chain_thumb.tip_bone) == -1:
chain_thumb.tip_bone = side + "ThumbProximal"
if chain_thumb.skeleton.find_bone(chain_thumb.tip_bone) == -1:
# Can't find needed bones. Bail.
continue
chain_thumb.tracker_object = hand_tracker_object.get_child(
fingertip_tracking_mappings["Thumb"])
if side == "Left":
chain_thumb.main_axis_of_rotation = -finger_rotation_axis
else:
chain_thumb.main_axis_of_rotation = finger_rotation_axis
chain_thumb.rotation_low = 0.05 * PI
chain_thumb.rotation_high = 0.5 * 0.99 * PI
chain_thumb.do_yaw = false
chain_thumb.do_bone_roll = false
chain_thumb.do_rotate_to_match_tracker = false
chain_thumb.do_pole_targets = false
_ikchains.append(chain_thumb)
func _update_for_new_model_if_needed():
_setup_ik_chains()
_update_arm_rest_positions()
func _calibrate_face():
var data = {}
var start = Time.get_ticks_msec()
blendshape_calibration = {}
for key in blend_shape_last_values.keys():
data[key] = []
# Calibrate for 200 ms
while Time.get_ticks_msec() < start + 200:
for key in blend_shape_last_values:
if blend_shape_last_values[key] > 0 && key.countn("eye") == 0:
data[key].append(blend_shape_last_values[key])
await get_tree().process_frame
# Average data gathered
for blendshape in data.keys():
blendshape_calibration[blendshape] = (data[blendshape].reduce(func(accum, number): return accum + number, 0)) / 2.0
# -----------------------------------------------------------------------------
# Tracker process interop.
func _scan_video_devices():
var dl = tracker_python_process.call_rpc_sync(
"enumerate_camera_devices", [])
var device_list : Array = dl if dl is Array else []
print(device_list)
for device in device_list:
var device_generated_name = "{name} ({backend}:{index})".format(device)
print(device_generated_name)
_devices_list.append(device_generated_name)
_devices_by_list_entry[device_generated_name] = device
# Create a fake "None" entry.
_devices_list.insert(0, "None")
_devices_by_list_entry["None"] = { "index" : -1 }
func start_tracker():
tracker_python_process.call_rpc_sync(
"set_udp_port_number", [_udp_port])
tracker_python_process.call_rpc_sync(
"set_hand_confidence_time_threshold", [hand_confidence_time_threshold])
var video_device_index_to_use = 0
if len(video_device) > 0:
if video_device[0] in _devices_by_list_entry:
var actual_device_data = _devices_by_list_entry[video_device[0]]
video_device_index_to_use = int(actual_device_data["index"])
else:
video_device_index_to_use = -1
# FIXME: Replace this all with a single settings dict.
tracker_python_process.call_rpc_async(
"set_video_device_number", [video_device_index_to_use])
tracker_python_process.call_rpc_async(
"set_hand_count_change_time_threshold", [hand_count_change_time_threshold])
tracker_python_process.call_rpc_sync(
"start_tracker", [])
func stop_tracker():
tracker_python_process.call_rpc_sync(
"stop_tracker", [])
set_status("Stopped")
func mirror_parsed_data(parsed_data : Dictionary) -> Dictionary:
var new_parsed_data : Dictionary = parsed_data.duplicate(true)
# Flip head rotation.
new_parsed_data["head_quat"][1] *= -1
new_parsed_data["head_quat"][2] *= -1
# Flip head position
new_parsed_data["head_origin"][0] *= -1
# First, just swap the names.
for hand_name in [ "left", "right" ]:
var opposite_hand : String = "left"
if hand_name == "left":
opposite_hand = "right"
new_parsed_data["hand_" + hand_name + "_score"] = parsed_data["hand_" + opposite_hand + "_score"]
new_parsed_data["hand_" + hand_name + "_rotation"] = parsed_data["hand_" + opposite_hand + "_rotation"]
new_parsed_data["hand_" + hand_name + "_origin"] = parsed_data["hand_" + opposite_hand + "_origin"]
new_parsed_data["hand_landmarks_" + hand_name] = parsed_data["hand_landmarks_" + opposite_hand]
# Now, swap the values.
for hand_name in [ "left", "right" ]:
var hand_score_str = "hand_" + hand_name + "_score"
var hand_rotation_str = "hand_" + hand_name + "_rotation"
var hand_origin_str = "hand_" + hand_name + "_origin"
var hand_landmark_str = "hand_landmarks_" + hand_name
# Mirror origins.
new_parsed_data[hand_origin_str][0] *= -1
# Mirror the rotation by converting to a quaternion and flipping the
# same way we flipped the head. Then just convert back.
var rotation_basis_array = new_parsed_data[hand_rotation_str]
var rotation_basis = Basis(
Vector3(rotation_basis_array[0][0], rotation_basis_array[0][1], rotation_basis_array[0][2]),
Vector3(rotation_basis_array[1][0], rotation_basis_array[1][1], rotation_basis_array[1][2]),
Vector3(rotation_basis_array[2][0], rotation_basis_array[2][1], rotation_basis_array[2][2]))
var new_rotation : Basis = (rotation_basis * Basis()).orthonormalized()
var new_rot_quat = new_rotation.get_rotation_quaternion()
new_rot_quat.y *= -1.0
new_rot_quat.z *= -1.0
new_rotation = Basis(new_rot_quat)
new_parsed_data[hand_rotation_str] = [
[new_rotation.x.x, new_rotation.x.y, new_rotation.x.z],
[new_rotation.y.x, new_rotation.y.y, new_rotation.y.z],
[new_rotation.z.x, new_rotation.z.y, new_rotation.z.z]]
# Flip the landmark positions on both X and Z (horizontal and forward)
# axes.
for landmark_index in range(0, len(new_parsed_data[hand_landmark_str])):
new_parsed_data[hand_landmark_str][landmark_index][1] *= -1
new_parsed_data[hand_landmark_str][landmark_index][2] *= -1
# Mirror blend shapes.
if parsed_data.has("blendshapes"):
for shape_name : String in parsed_data["blendshapes"].keys():
var new_string = shape_name
if shape_name.contains("Left"):
new_string = shape_name.replace("Left", "Right")
elif shape_name.contains("Right"):
new_string = shape_name.replace("Right", "Left")
if new_string != shape_name:
new_parsed_data["blendshapes"][new_string] = parsed_data["blendshapes"][shape_name]
return new_parsed_data
func process_new_packets(model, delta):
var most_recent_packet = null
var dropped_packets = 0
while true:
var packet = udp_server.get_packet()
# FIXME: Disallow packets from remote systems, unless allowed
# explicitly.
var packet_string = packet.get_string_from_utf8()
var json = JSON.new()
json.parse(packet_string)
var parsed_data = json.data
if parsed_data:
if "status" in parsed_data:
set_status(parsed_data["status"])
continue
if "error" in parsed_data:
set_status("Error: " + parsed_data["error"])
continue
set_status("Receiving tracker data")
# -----------------
if mirror_mode:
parsed_data = mirror_parsed_data(parsed_data)
if parsed_data.has("blendshapes"):
functions_blendshapes.apply_blendshape_scale(parsed_data["blendshapes"], blendshape_scale)
last_parsed_data["head_quat"] = parsed_data["head_quat"]
last_parsed_data["head_origin"] = parsed_data["head_origin"]
last_parsed_data["head_missing_time"] = parsed_data["head_missing_time"]
for hand_name in [ "left", "right" ]:
var hand_score_str = "hand_" + hand_name + "_score"
var hand_rotation_str = "hand_" + hand_name + "_rotation"
var hand_origin_str = "hand_" + hand_name + "_origin"
var hand_landmark_str = "hand_landmarks_" + hand_name # FIXME: Make this consistent.
# FIXME: Put all the hand stuff under one dictionary entry.
if hand_score_str in parsed_data:
var override_val : bool = false
if not (hand_score_str in last_parsed_data):
override_val = true
elif last_parsed_data[hand_score_str] < parsed_data[hand_score_str]:
override_val = true
if override_val:
last_parsed_data[hand_score_str] = parsed_data[hand_score_str]
last_parsed_data[hand_rotation_str] = parsed_data[hand_rotation_str]
last_parsed_data[hand_origin_str] = parsed_data[hand_origin_str]
last_parsed_data[hand_landmark_str] = parsed_data[hand_landmark_str]
if "blendshapes" in parsed_data:
# Save the parsed data.
last_parsed_data["blendshapes"] = parsed_data["blendshapes"]
if blendshape_calibration != {}:
for blendshape in last_parsed_data["blendshapes"]:
if blendshape_calibration[blendshape]:
last_parsed_data["blendshapes"][blendshape] -= blendshape_calibration[blendshape]
#blend_shape_last_values.duplicate()
var shape_dict_new = {}
# Merge in MediaPipe or basic VRM blendshapes per options.
if use_vrm_basic_shapes:
shape_dict_new.merge(
functions_blendshapes.convert_mediapipe_shapes_to_vrm_standard(last_parsed_data["blendshapes"]),
true)
if use_mediapipe_shapes:
shape_dict_new.merge(
last_parsed_data["blendshapes"],
true)
# Apply smoothing.
# FIXME: Parameterize.
shape_dict_new = functions_blendshapes.apply_smoothing(
blend_shape_last_values, shape_dict_new,
delta)
# Eye fixups.
# FIXME: Make optional.
shape_dict_new = functions_blendshapes.fixup_eyes(shape_dict_new)
# Blend back to a rest position if we have lost tracking.
if frames_missing_before_spine_reset < last_parsed_data["head_missing_time"]:
shape_dict_new = functions_blendshapes.apply_rest_shapes(
blend_shape_last_values, delta, blend_to_rest_speed)
functions_blendshapes.apply_animations(
model, shape_dict_new)
blend_shape_last_values = shape_dict_new
if len(packet) > 0:
if most_recent_packet != null:
dropped_packets += 1
most_recent_packet = packet
else:
break
if dropped_packets > 0:
if dropped_packets <= 2:
print_log(["Dropped packets (within tolerance): ", dropped_packets])
else:
print_log(["Dropped packets (WARNING): ", dropped_packets])
# -----------------------------------------------------------------------------
# Actual update code.
func rotate_bone_in_global_space(
skel : Skeleton3D,
bone_index : int,
axis : Vector3,
angle : float,
relative : bool = false):
if axis.length() <= 0.0001:
return
var parent_bone_index = skel.get_bone_parent(bone_index)
var gs_rotation = Basis(axis.normalized(), angle).get_rotation_quaternion()
var gs_rotation_parent = skel.get_bone_global_rest(parent_bone_index).basis.get_rotation_quaternion()
var gs_rotation_rest = skel.get_bone_global_rest(bone_index).basis.get_rotation_quaternion()
var bs_rotation = gs_rotation_parent.inverse() * gs_rotation * gs_rotation_rest
if relative:
skel.set_bone_pose_rotation(
bone_index,
skel.get_bone_pose_rotation(bone_index) * bs_rotation)
else:
skel.set_bone_pose_rotation(
bone_index,
bs_rotation)
func handle_lean(skel : Skeleton3D, angle : float):
var current_bone : int = skel.find_bone("Head")
var hips_bone : int = skel.find_bone("Hips")
var bone_count : int = 0
while current_bone != hips_bone and current_bone != -1:
bone_count += 1
current_bone = skel.get_bone_parent(current_bone)
angle /= float(bone_count)
current_bone = skel.find_bone("Head")
while current_bone != hips_bone and current_bone != -1:
rotate_bone_in_global_space(skel, current_bone, Vector3(0.0, 0.0, 1.0), angle, true)
current_bone = skel.get_bone_parent(current_bone)
func _start_process():
tracker_python_process.start_process(false)
_send_settings_to_tracker()
func _stop_process():
tracker_python_process.stop_process()
func _process(delta):
var skel : Skeleton3D = get_app().get_skeleton()
if not _init_complete:
return
if not udp_server:
return
var model_root = get_model()
if not model_root:
return
# FIXME: Remove this. OffKai hack.
if tracking_pause:
return
# FIXME: Hack.
# This just moves the body based on the head position.
var head_pos = head_tracker.transform.origin
var model_pos = model_root.transform.origin
var head_rest_transform = skel.get_bone_global_rest(skel.find_bone("Head"))
if true:
model_root.transform.origin = model_pos.lerp(head_pos, delta * hip_adjustment_speed)
#model_root.transform.origin = head_pos
#model_root.transform.origin.y = model_y
#model_root.transform.origin.y = lerp(model_pos.y, head_pos.y - 1.9, 0.01)
# FIXME: Hard-coded fudge factor.
# FIXME: Why can't we just map this directly again? It looks like we're shrugging when the arms get set up wrong or something.
model_root.transform.origin.y = lerp(
model_pos.y, head_pos.y - head_rest_transform.origin.y + head_vertical_offset,
clamp(hips_vertical_blend_speed * delta, 0.0, 1.0))
process_new_packets(model_root, delta)
var delta_scale = delta * 60.0
if delta_scale > 1.0:
delta_scale = 1.0
if delta_scale < 0.01:
delta_scale = 0.01
if last_parsed_data:
var parsed_data = last_parsed_data
# FIXME: Make these adjustable.
# (copygirl) Assume that the tracking camera is placed 30cm directly in front
# of the user's head. For that, offset by head's rest transform.
var camera_origin_offset = Vector3(0.0, 0.0, 0.3) + head_rest_transform.origin
# (copygirl) For some reason the raw hand data does not appear to be properly
# relative to the camera? This 15cm offset might help with that.
var hand_origin_offset = Vector3(0.0, 0.15, 0.0)
var arbitrary_scale = 1.0
var score_exponent = 1.5
var score_threshold = 0.1
var head_rotation_scale = 2.0
# These are for transforming individual feature points from the
# mediapipe hand coordinate into skeleton coordinates.
var hand_origin_multiplier = Vector3(1.0, 1.0, 1.0)
var head_origin_multiplier = Vector3(1.0, 1.0, 1.0)
var head_quat_multiplier = [1.0, 1.0, 1.0, 1.0]
var tracker_left = hand_trackers["Left"]
var tracker_right = hand_trackers["Right"]
# FIXME: MIRROR MESS (CLEAN THIS UP)
hand_origin_multiplier = Vector3(-1.0, 1.0, 1.0)
head_origin_multiplier = Vector3(-1.0, 1.0, 1.0)
head_quat_multiplier = [1.0, -1.0, -1.0, 1.0]
tracker_left = hand_trackers["Right"]
tracker_right = hand_trackers["Left"]
# -----------------------------------------------------------------------------------------
# Hand packets
# Pick hand rest references based on mirroring.
var hand_rest_reference_left = hand_rest_trackers["Left"]
var hand_rest_reference_right = hand_rest_trackers["Right"]
# FIXME: Code smell. Replace with a function call.
var per_hand_data = [
{
"side" : "Left",
"tracker_object" : tracker_left,
"rest_reference_object" : hand_rest_reference_left,
"index" : 0
}, {
"side" : "Right",
"tracker_object" : tracker_right,
"rest_reference_object" : hand_rest_reference_right,
"index" : 1
}
]
for hand_data in per_hand_data:
var time_since_last_update = hand_time_since_last_update[hand_data["index"]]
var time_since_last_missing = hand_time_since_last_missing[hand_data["index"]]
var hand_str = hand_data["side"]
var hand_str_lower = hand_str.to_lower()
var tracker_ob = hand_data["tracker_object"]
var hand_score_str = "hand_" + hand_str_lower + "_score"
var hand_origin_str = "hand_" + hand_str_lower + "_origin"
var hand_rotation_str = "hand_" + hand_str_lower + "_rotation"
var hand_origin_array = parsed_data[hand_origin_str]
var hand_score = parsed_data[hand_score_str]
# Apply thresholds to the confidence score.
if parsed_data[hand_score_str] < score_threshold or not hand_tracking_enabed: # FIXME: Wrong place for the enabled check?
parsed_data[hand_score_str] = 0.0
# Track time since last visible or not.
if hand_score >= score_threshold:
time_since_last_update = 0.0
time_since_last_missing += delta
else:
time_since_last_update += delta
time_since_last_missing = 0.0
hand_time_since_last_update[hand_data["index"]] = time_since_last_update
hand_time_since_last_missing[hand_data["index"]] = time_since_last_missing
if time_since_last_update > arm_reset_time:
var reference_ob = hand_data["rest_reference_object"]
# Move hand to rest position.
tracker_ob.transform.origin = tracker_ob.transform.origin.lerp(
reference_ob.transform.origin, arm_reset_speed) # FIXME: Hardcoded value.
var rot_quat1 = tracker_ob.transform.basis.get_rotation_quaternion()
var rot_quat2 = reference_ob.transform.basis.get_rotation_quaternion()
tracker_ob.transform.basis = Basis(rot_quat1.slerp(rot_quat2, arm_reset_speed)) # FIXME: Hardcoded value
tracker_ob.transform.basis = tracker_ob.transform.basis.orthonormalized()
elif time_since_last_missing > 0.1: # FIXME: Hardcoded value.
# Stretch the last bit of the score out with an exponent.
parsed_data[hand_score_str] = pow(parsed_data[hand_score_str], score_exponent)
# TODO: Replace the tracker object with just a Transform3D.
var target_origin = camera_origin_offset + hand_origin_offset \
+ Vector3(hand_origin_array[0], hand_origin_array[1], hand_origin_array[2]) \
* hand_origin_multiplier * arbitrary_scale
# (copygirl) TODO: Can this be removed? What is its purpose?
# # Attempt to move hand in front of model. Reaching behind is
# # *usually* the results of bad data.
# #
# # FIXME: Ugly hack.
# # If we're going to do this, we need to make sure we do it in the model's forward
# # direction.
# #
# # FIXME: Hardcoded values all over this part.
# #
# var chest_transform_global_pose = skel.get_bone_global_pose(skel.find_bone("Chest"))
# var min_z = chest_transform_global_pose.origin
# if target_origin.z < min_z.z + 0.2:
# target_origin.z = min_z.z + 0.2
#
# # Move tracker forward if we're reaching across the chest to see
# # if we can fix some clipping-into-chest problems.
# #
# # FIXME: Hardcoded values all over this part.
# #
#
# # FIXME: THIS IS BAD CODE AND YOU (KIRI) SHOULD FEEL BAD ABOUT IT.
# var tracker_in_chest_space = chest_transform_global_pose.inverse() * target_origin
# # FIXME: Hack for mirror.
# var swap_tracker = tracker_right
# if tracker_ob == swap_tracker:
# tracker_in_chest_space.x *= -1
# # Just clamp the overall reach, first.
#
# # Clamp tracker reach.
# # FIXME: Hardcoded value.
# if tracker_in_chest_space.x < -0.2:
# tracker_in_chest_space.x = -0.2
#
# # Now move forward.
# if tracker_in_chest_space.x < 0.0:
# # FIXME: Hardcoded scaling value.
# tracker_in_chest_space.z += -(tracker_in_chest_space.x - 0.1) * 0.2
# # FIXME: Hack for mirror.
# if tracker_ob == swap_tracker:
# tracker_in_chest_space.x *= -1
#
# target_origin = chest_transform_global_pose * tracker_in_chest_space
var rotation_basis_array = parsed_data[hand_rotation_str]
var rotation_basis = Basis(
Vector3(rotation_basis_array[0][0], rotation_basis_array[0][1], rotation_basis_array[0][2]),
Vector3(rotation_basis_array[1][0], rotation_basis_array[1][1], rotation_basis_array[1][2]),