-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimPin.py
1546 lines (1350 loc) · 89.5 KB
/
animPin.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
# Animation Pin Tool
# -------------------------------------------------------------------- #
__author__ = "Daniel Klug"
__version__ = "1.35"
__date__ = "04-02-2023"
__email__ = "[email protected]"
# -------------------------------------------------------------------- #
'''
Installation:
Place both files in your maya/scripts folder, then restart Maya
Usage:
To launch the UI, use this python command:
import animPin as animPin; animPin.show()
By command line from within the script editor:
import animPin as animPin; animPin.create_pins() # To create pins
import animPin as animPin; animPin.bake_pins() # To bake selected pin groups
'''
# Imports ============================================================ #
import maya.cmds as cmds
import maya.mel as mel
import maya.api.OpenMaya as api
import maya.api.OpenMayaAnim as anim
import maya.OpenMayaUI as mui
# Qt is a project by Marcus Ottosson-> https://github.com/mottosso/Qt.py
from Qt import QtGui, QtCore, QtCompat, QtWidgets, __binding__
# from Qt.QtGui import QPen, QColor, QBrush, QLinearGradient
if "PyQt" == __binding__:
import sip
elif "PySide" == __binding__:
import shiboken as shiboken # Do Pyside
elif "PySide2" == __binding__:
import shiboken2 as shiboken # You're on Maya 2018, aren't you?
import base64
import itertools
from collections import OrderedDict
from functools import wraps
import re # I'm so sorry
# Globals ============================================================ #
WIDTH = 180
HEIGHT = 462
_view = None
ap_suffix= '_pin'
pin_group = 'pin_group#'
master_group = 'animPins_group'
locator_scale = 10 # Season to taste - depends on your rig size
pin_data = OrderedDict([
('control' , {'dataType' : "string"}),
('constraint' , {'dataType' : "string"}),
('start_frame' , {'attributeType': "float"}),
('end_frame' , {'attributeType': "float"}),
# ('translates_enabled' , {'attributeType': "bool"}), # We can use the locked channels
# ('rotates_enabled' , {'attributeType': "bool"}),
('translate_keys' , {'dataType' : "string"}),
('rotate_keys' , {'dataType' : "string"}),
('translate_locked' , {'attributeType': "bool"}),
('rotate_locked' , {'attributeType': "bool"}),
('preserve_blendParent' , {'dataType' : "string"}) # Was there a blendparent node there to begin with?
])
# Get the timeline object
aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
tuple_rex = re.compile("([0-9]+\.[0-9]+\, [0-9]+\.[0-9]+)")
# Decorators ========================================================= #
def viewportOff(func):
"""
Decorator - turn off Maya display while func is running.
if func will fail, the error will be raised after.
"""
@wraps(func)
def wrap( *args, **kwargs ):
# Turn $gMainPane Off:
mel.eval("paneLayout -e -manage false $gMainPane")
cmds.refresh(suspend=True)
# Decorator will try/except running the function.
# But it will always turn on the viewport at the end.
# In case the function failed, it will prevent leaving maya viewport off.
try:
return func( *args, **kwargs )
except Exception:
raise # will raise original error
finally:
mel.eval("paneLayout -e -manage true $gMainPane")
cmds.refresh(suspend=False)
cmds.refresh()
return wrap
def undo(func):
'''
Decorator - open/close undo chunk
'''
@wraps(func)
def wrap(*args, **kwargs):
cmds.undoInfo(openChunk = True)
try:
return func(*args, **kwargs)
except Exception:
raise # will raise original error
finally:
cmds.undoInfo(closeChunk = True)
# cmds.undo()
return wrap
def noUndo(func):
'''
Decorator - open/close undo chunk
'''
@wraps(func)
def wrap(*args, **kwargs):
cmds.undoInfo(stateWithoutFlush = False)
try:
return func(*args, **kwargs)
except Exception:
raise # will raise original error
finally:
cmds.undoInfo(stateWithoutFlush = True)
# cmds.undo()
return wrap
# Public methods ===================================================== #
@undo
def create_pins(selection = None, start_frame = None, end_frame = None, group_override = None):
'''
selection: could be a string, list of strings, or MSelectionList
start_frame: float
end_frame: float
group_override = None
'''
# Validate input ------------------------------------------------- #
sel_list = _get_selectionList(selection)
controls = _validate_selection(sel_list)
if controls.isEmpty():
api.MGlobal.displayError(\
"Could not find any valid nodes to pin.")
return None
start_frame, end_frame = _validate_framerange(start_frame, end_frame)
if start_frame == None or end_frame == None:
api.MGlobal.displayError(\
"Could not validate frame range from %s to %s." % \
(start_frame, end_frame))
return None
new_pin_group = _create_new_pin_group()
if not new_pin_group:
api.MGlobal.displayError(\
"Could not create a valid group to add pins.")
return None
# Begin alpha setup ---------------------------------------------- #
locators = []
constraints = []
for i in range(controls.length()):
# This is the part that makes this tool special
control = controls.getDependNode(i)
control_name = api.MFnDependencyNode(control).name()
control_data = _read_control_data(control, start_frame, end_frame)
locator = _create_locator_pin(control_data, new_pin_group)
locators.append(locator)
constraint_node = cmds.parentConstraint(control_name, locator)[0]
constraints.append(constraint_node)
cmds.setKeyframe(locator)
cmds.setAttr(locator + '.blendParent1', 1)
# Do magic ------------------------------------------------------- #
results = _do_bake(locators, start_frame, end_frame)
if not results:
raise ValueError("Bake failed.")
cmds.delete(constraints)
# Begin omega setup ---------------------------------------------- #
pins = _get_pins(new_pin_group)
for pin in pins:
control = cmds.getAttr(pin + '.control')
MSel = api.MGlobal.getSelectionListByName(control)
controlFN = api.MFnDependencyNode(MSel.getDependNode(0))
if _is_locked_or_not_keyable(controlFN, 'translate'):
skip_translate = ['x', 'y', 'z']
else:
skip_translate = 'none'
if _is_locked_or_not_keyable(controlFN, 'rotate'):
skip_rotate = ['x', 'y', 'z']
else:
skip_rotate = 'none'
constraint_node = cmds.parentConstraint( \
pin, \
control, \
skipTranslate = skip_translate, \
skipRotate = skip_rotate)[0] # Reversed
cmds.setAttr(pin + '.constraint', \
constraint_node, \
type = 'string')
try:
cmds.setKeyframe(control, \
attribute="blendParent1", \
time=[start_frame, end_frame], \
value=1)
cmds.setKeyframe(control, \
attribute="blendParent1", \
time=[start_frame-1, end_frame+1], \
value=0)
except:
api.MGlobal.displayWarning(\
"Could not key the blendParent. " \
"Be careful outside the buffer range!")
# Lock the attributes of the locator that were locked on the control
t_lock = cmds.getAttr(pin + '.translate_locked')
r_lock = cmds.getAttr(pin + '.rotate_locked')
cmds.setAttr(locator + '.t', lock=t_lock, keyable=(not t_lock))
cmds.setAttr(locator + '.r', lock=r_lock, keyable=(not r_lock))
print("Successfully created new pin group, '%s'!" % new_pin_group)
return new_pin_group
@undo
def bake_pins(pin_groups = None, bake_option = 1, start_frame = None, end_frame = None):
'''
Bake options
'''
if not pin_groups:
# check selection
selection = cmds.ls(sl=True)
pin_groups = _get_pin_groups()
pin_group_list = set(selection).intersection(pin_groups)
pins_to_bake = _get_pins(pin_group_list)
if not pins_to_bake:
api.MGlobal.displayWarning(\
"No pins could be found to bake.")
return None
constraints = []
controls_to_bake = []
blendParents_to_restore = {}
pin_groups_to_delete = set()
for pin in pins_to_bake:
pin_constraint = cmds.getAttr(pin + '.constraint')
constraints.append(pin_constraint)
control = cmds.getAttr(pin + '.control')
if not cmds.objExists(control):
# Last ditch effort to find the control. Was it renamed?
control = cmds.listConnections(\
pin_constraint + '.constraintParentInverseMatrix')[0] or []
if control: # fix the data
cmds.setAttr(pin + '.control', control, type = 'string')
controls_to_bake.append(control)
pin_parent = cmds.listRelatives(pin, parent=True)[0]
pin_groups_to_delete.add(pin_parent)
bp_keys = cmds.getAttr(pin + '.preserve_blendParent')
blendParents_to_restore[control] = bp_keys
start_frame, end_frame = _validate_bakerange(\
pins_to_bake, \
start_frame, \
end_frame)
if start_frame == None or end_frame == None:
api.MGlobal.displayError(\
"Could not validate frame range from %s to %s." % \
(start_frame, end_frame))
return None
if bake_option == 0:
sample = 1
print("Matching keys...")
else:
sample = bake_option
print("Baking on %ds" % sample)
# Do magic ------------------------------------------------------- #
success = _do_bake(\
controls_to_bake, \
start_frame, \
end_frame, \
sample)
if not success:
raise ValueError("Bake failed.")
# cmds.refresh() # Check it out
for control, bp_keys in blendParents_to_restore.items():
for match in tuple_rex.finditer(bp_keys):
cmds.setKeyframe(\
control, \
at='blendParent1', \
time = float(match.group(0).split(', ')[0]), \
value = float(match.group(0).split(', ')[1]) \
)
if bake_option == 0: # Proceed with the Match Keys procedure
success = _match_keys_procedure(\
pins_to_bake, \
start_frame, \
end_frame)
if not success:
raise ValueError("match_keys_procedure failed.")
cmds.delete(constraints)
cmds.delete(list(pin_groups_to_delete))
# Final check to see if the master_group is empty. If so, delete it.
global master_group
pins_exist = _get_pins()
if not pins_exist:
cmds.delete(master_group)
print("Successfully baked these pin groups:")
for pin_group in list(pin_groups_to_delete):
print(pin_group)
return pin_groups_to_delete # We're done here!
# Private methods ==================================================== #
def _to_ranges(iterable):
# https://stackoverflow.com/questions/4628333/converting-a-list-of-integers-into-range-in-python/43091576#43091576
iterable = sorted(set(iterable))
for key, group in itertools.groupby(enumerate(iterable), lambda t: t[1] - t[0]):
group = list(group)
yield group[0][1], group[-1][1]
def _validate_bakerange(pins_to_bake, start_frame, end_frame):
all_pins_start_frame = set()
all_pins_end_frame = set()
for pin in pins_to_bake:
pin_start = cmds.getAttr(pin + '.start_frame')
pin_end = cmds.getAttr(pin + '.end_frame')
all_pins_start_frame.add(pin_start)
all_pins_end_frame.add(pin_end)
all_pins_start_frame = list(all_pins_start_frame)[0]
all_pins_end_frame = list(all_pins_end_frame)[0]
selected_range = str(cmds.timeControl(
aPlayBackSliderPython,
q=True,
range=True)
)
selected_range = [float(x) for x in selected_range.strip('"').split(':')]
if not selected_range[1] - 1 == selected_range[0]:
start_frame, end_frame = selected_range
start_frame, end_frame = _validate_framerange(start_frame, end_frame)
if start_frame < all_pins_start_frame:
start_frame = all_pins_start_frame
# api.MGlobal.displayError(\
# "Start frame is before pin start frame. Aborting!")
# return None
if end_frame > all_pins_end_frame:
end_frame = all_pins_end_frame
# api.MGlobal.displayError(\
# "End frame is before pin end frame. Aborting!")
# return None
return start_frame, end_frame
def _is_locked_or_not_keyable(controlFN, attribute):
plug = controlFN.findPlug(attribute, False)
if any(plug.child(p).isLocked \
for p in range(plug.numChildren())):
return True
if not any(plug.child(p).isKeyable \
for p in range(plug.numChildren())):
return True
for p in range(plug.numChildren()):
plug_array = plug.child(p).connectedTo(True, False)
if plug_array:
if plug_array[0].isChild:
return True # Assume it is constrained
# Check to see if it is constrained
# return plug_array[0].parent().node().hasFn(api.MFn.kParentConstraint):
return False
def _validate_selection(sel_list):
current_pins = _get_pins()
validated_sel_list = api.MSelectionList()
for i in range(sel_list.length()):
try:
dag = sel_list.getDagPath(i)
except TypeError:
continue # Quietly skip non-dag nodes
control_dep = sel_list.getDependNode(i)
controlFN = api.MFnDependencyNode(control_dep)
control_name = controlFN.name()
pinned_control = control_name + ap_suffix
if pinned_control in current_pins:
api.MGlobal.displayError(\
"Node '%s' is already pinned! " \
"Skipping..." % control_name)
continue
if control_name in current_pins:
api.MGlobal.displayError(\
"Node '%s' is a pin! " \
"Skipping..." % control_name)
continue
if 'animation' in controlFN.classification(controlFN.typeName):
continue # Quietly ignore animation curves
if not controlFN.typeName in ['transform', 'joint', 'ikHandle']:
api.MGlobal.displayError(\
"Node '%s' is not a valid transform node. " \
"Skipping..." % control_name)
continue
if _is_locked_or_not_keyable(controlFN, 'translate') and _is_locked_or_not_keyable(controlFN, 'rotate'):
api.MGlobal.displayError(\
"Node '%s' has no available transform channels. " \
"Skipping..." % control_name)
continue
validated_sel_list.add(sel_list.getDependNode(i))
return validated_sel_list
def _get_pin_groups():
global master_group
found_pin_groups = []
if cmds.objExists(master_group):
master_group_children = cmds.listRelatives(\
master_group, \
type = 'transform') or []
for found_pin_group in master_group_children:
found_pin_groups.append(found_pin_group)
return found_pin_groups # Returns list
def _get_pins(pin_groups = None):
# search for group
# ask about override if cant find it
# If not supplied with a pin group, it gets all pins
# pin_groups is a string or list of strings
if isinstance(pin_groups, (str, unicode)): pin_groups = [pin_groups]
found_pins = []
if not pin_groups:
pin_groups = _get_pin_groups()
for group in pin_groups:
pins = cmds.listRelatives(group, type = 'transform') or []
for pin in pins:
found_pins.append(pin)
return found_pins
def _validate_framerange(start_frame, end_frame):
if start_frame == None:
api.MGlobal.displayWarning(\
"No start_frame supplied. Defaulting to timeline...")
start_frame = cmds.playbackOptions(\
query = True, \
animationStartTime = True)
if end_frame == None:
api.MGlobal.displayWarning(\
"No end_frame supplied. Defaulting to timeline...")
end_frame = cmds.playbackOptions(\
query = True, \
animationEndTime = True)
if start_frame > end_frame:
api.MGlobal.displayError(\
"Start frame needs to be before end frame!")
return None
return start_frame, end_frame
def _read_control_data(control, start_frame, end_frame):
'''
control: MObject
start_frame: float
end_frame: float
'''
# global pin_data # Do we need this
control_data = OrderedDict()
controlFN = api.MFnDependencyNode(control)
control_name = str(controlFN.name())
t_keys = _get_keys_from_obj_attribute(controlFN, 'translate')
r_keys = _get_keys_from_obj_attribute(controlFN, 'rotate')
t_lock = _is_locked_or_not_keyable(controlFN, 'translate')
r_lock = _is_locked_or_not_keyable(controlFN, 'rotate')
# Goddammit, I shouldn't be assuming blendparent1
# Instead, I SHOULD be just tracking which one
# I created and store the rest. But I'm lazy.
bp_keys = []
if 'blendParent1' in cmds.listAttr(control_name):
bp_key_times = _get_keys_from_obj_attribute(\
controlFN, \
'blendParent1')
if bp_key_times:
key_values = []
for time in bp_key_times:
key_value = cmds.getAttr(\
control_name + '.blendParent1', \
time = time)
key_values.append(key_value)
bp_keys = list(zip(bp_key_times, key_values))
else:
bp_keys = [cmds.getAttr(control_name + '.blendParent1')]
control_data['control'] = control_name
control_data['start_frame'] = start_frame
control_data['end_frame'] = end_frame
control_data['translate_keys'] = t_keys
control_data['rotate_keys'] = r_keys
control_data['translate_locked'] = t_lock
control_data['rotate_locked'] = r_lock
control_data['preserve_blendParent'] = bp_keys # ugh
return control_data
def _get_keys_from_obj_attribute(controlFN, attribute):
keys = set()
attribute_plug = controlFN.findPlug(attribute, False) # Networked?
if attribute_plug.isCompound:
for c in range(attribute_plug.numChildren()):
plug = attribute_plug.child(c)
if anim.MAnimUtil.isAnimated(plug):
keys.update(_get_keys_from_curve(plug))
else:
if anim.MAnimUtil.isAnimated(attribute_plug):
keys.update(_get_keys_from_curve(attribute_plug))
return list(keys)
def _get_keys_from_curve(plug):
curve = anim.MFnAnimCurve(plug)
return [curve.input(k).value for k in range(curve.numKeys)]
def _get_master_group(group_override = None):
global master_group
if isinstance(group_override, str):
master_group = group_override
if not cmds.objExists(master_group):
master_group = cmds.createNode('transform',
name = master_group,
skipSelect = True)
return master_group
def _create_new_pin_group():
master_group = _get_master_group()
new_pin_group = cmds.createNode('transform',
name = pin_group,
parent = master_group,
skipSelect = True)
return new_pin_group
def _get_selectionList(selection):
if not selection:
return api.MGlobal.getActiveSelectionList()
elif isinstance(selection, str):
return api.MGlobal.getSelectionListByName(selection)
elif isinstance(selection, list):
nodes = api.MSelectionList() # Prime the list
for sel in selection:
try:
node = api.MGlobal.getSelectionListByName(sel)
nodes.merge(node)
except:
api.MGlobal.displayError(
"Could not fetch selection. " \
"Try submitting an MSelectionList " \
"or a list of string names."
)
return nodes
else: # You know what you're doing
return selection
def _create_locator_pin(control_data, pin_group):
# global pin_data # Do we need this?
control_name = control_data['control']
locator = cmds.spaceLocator(name = control_name + ap_suffix)[0]
cmds.setAttr(locator + ".scale", *[locator_scale]*3) # Unpack * 3
cmds.parent(locator, pin_group)
for attr in ['x', 'y', 'z']:
cmds.setAttr(\
locator + '.s' + attr, \
keyable = False, \
channelBox = True)
for key, value in pin_data.iteritems():
cmds.addAttr(\
locator, \
longName = key, \
**value) # kwargs ftw
for key, value in control_data.items():
if isinstance(value, (str, list)):
if isinstance(value, list):
value = ' '.join(map(str,value))
cmds.setAttr(locator + '.' + key, value, type = 'string')
else:
cmds.setAttr(locator + '.' + key, value)
return locator
def _get_maya_window():
ptr = mui.MQtUtil.mainWindow()
return QtCompat.wrapInstance(int(ptr), QtWidgets.QMainWindow) # use this when we have QtCompat
# return _wrap_instance(long(ptr), QtWidgets.QMainWindow)
def _wrap_instance(ptr, base=None):
"""
Utility to convert a pointer to a Qt class instance (PySide/PyQt compatible)
:param ptr: Pointer to QObject in memory
:type ptr: long or Swig instance
:param base: (Optional) Base class to wrap with (Defaults to QObject, which should handle anything)
:type base: QtGui.QWidget
:return: QWidget or subclass instance
:rtype: QtGui.QWidget
"""
if ptr is None:
return None
ptr = long(ptr) #Ensure type
if globals().has_key('shiboken') and "PySide" in __binding__:
if base is None:
qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)
metaObj = qObj.metaObject()
cls = metaObj.className()
superCls = metaObj.superClass().className()
if hasattr(QtGui, cls):
base = getattr(QtGui, cls)
elif hasattr(QtGui, superCls):
base = getattr(QtGui, superCls)
else:
base = QtGui.QWidget
return shiboken.wrapInstance(long(ptr), base)
elif globals().has_key('sip') and "PyQt" in __binding__:
base = QtCore.QObject
return sip.wrapinstance(long(ptr), base)
else:
# return None
ptr = mui.MQtUtil.mainWindow()
return QtCompat.wrapInstance(long(ptr), QtWidgets.QMainWindow)
# Decorated methods ================================================== #
# @undo # Nevermind, the entire bake procedure is contained.
def _match_keys_procedure(pins_to_bake, start_frame, end_frame, composite = True):
for pin in pins_to_bake:
control = cmds.getAttr(pin + '.control')
# Snipe translate keys
translate_keys = cmds.getAttr(pin + '.translate_keys') or []
translate_keys_baked = set(cmds.keyframe(
control,
attribute = 't',
time = (start_frame, end_frame),
query = True) or [])
if translate_keys:
translate_keys = [float(x) for x in translate_keys.split(' ')]
float_translate_keys = translate_keys[:]
for key in float_translate_keys:
if not key.is_integer():
translate_keys.remove(key)
translate_keys.append(int(round(key)))
translate_keys_to_remove = list(set(translate_keys_baked - \
set(translate_keys)))
# Snipe rotate keys
rotate_keys = cmds.getAttr(pin + '.rotate_keys') or []
rotate_keys_baked = set(cmds.keyframe(
control,
attribute = 'r',
time = (start_frame, end_frame),
query = True) or [])
if rotate_keys:
rotate_keys = [float(x) for x in rotate_keys.split(' ')]
float_rotate_keys = rotate_keys[:]
for key in float_rotate_keys:
if not key.is_integer():
rotate_keys.remove(key)
rotate_keys.append(int(round(key)))
rotate_keys_to_remove = list(set(rotate_keys_baked - \
set(rotate_keys)))
keys_baked = list(translate_keys_baked | rotate_keys_baked) # Join 2 sets
if composite == True:
composited_keys = list(set(translate_keys + rotate_keys))
keys_to_remove = list(set(keys_baked) - set(composited_keys))
# for key in _to_ranges(keys_to_remove): # Had to remove to make room for floats for now
for key in keys_to_remove:
cmds.cutKey(control, \
t = (key, ), attribute = ('t', 'r'), clear = True)
else:
for key in _to_ranges(translate_keys_to_remove):
cmds.cutKey(control, \
t = key, attribute = 't', clear = True)
for key in _to_ranges(rotate_keys_to_remove):
cmds.cutKey(control, \
t = key, attribute = 'r', clear = True)
keys_baked.insert(0, keys_baked[0]-1)
keys_baked.append(keys_baked[-1]+1)
keys = []
bp_keys = cmds.getAttr(pin + '.preserve_blendParent')
for match in tuple_rex.finditer(bp_keys):
keys.append(float(match.group(0).split(', ')[0]))
# values = float(match.group(0).split(', ')[1])
bp_keys_to_remove = list(set(keys_baked) - set(keys))
for key in _to_ranges(bp_keys_to_remove):
cmds.cutKey(\
control, \
time = key, \
attribute = ('blendParent1'), \
clear = True)
return True
@viewportOff
def _do_bake(nodes_to_bake, start_frame, end_frame, sample = 1):
'''
nodes: list
start_frame: int
end_frame: int
'''
try:
cmds.bakeResults(
nodes_to_bake,
simulation = True,
time = (start_frame, end_frame),
sampleBy = sample,
oversamplingRate = 1,
disableImplicitControl = True,
preserveOutsideKeys = True,
at = ("tx", "ty", "tz", "rx", "ry", "rz", "blendParent1"),
sparseAnimCurveBake = False,
removeBakedAttributeFromLayer = False,
removeBakedAnimFromLayer = False,
bakeOnOverrideLayer = False,
minimizeRotation = True,
controlPoints = False,
shape = True
)
return True
except:
return False
# Classes ============================================================ #
class View(QtWidgets.QDialog):
"""docstring for View"""
def __init__(self, parent = None): #_get_maya_window()):
super(View, self).__init__(parent)
self.parent = _get_maya_window()
self.setParent(self.parent)
self.setWindowFlags(
QtCore.Qt.Dialog |
QtCore.Qt.WindowCloseButtonHint #| # Remove the ? button
# QtCore.Qt.WindowStaysOnTopHint
)
self.setObjectName('AnimPin')
self.setWindowTitle('Animation Pin Tool')
self.setProperty("saveWindowPref", True)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
# Class globals
self.pressPos = None
self.isMoving = False
self._callbacks = {}
self.width = WIDTH
self.height = HEIGHT
self.mini_state = False
# Organizing the startup sequence
self.build_UI()
self.init_connections()
self.init_frame_range()
self._init_pin_group_list()
# Event methods -------------------------------------------------- #
def init_connections(self):
# Connections ------------------------------------------------ #
self.BTN_create_pins.clicked.connect(self.on_create_pins)
self.BTN_bake_pins.clicked.connect(self.on_bake_pins)
self.destroyed.connect(self.closeEvent)
# Listbox connections
self.LST_pin_groups.itemSelectionChanged.connect(self._pass_selection_to_maya)
self.LST_pin_groups.itemChanged.connect(self._ui_pin_name_changed)
def init_frame_range(self):
spin_start = cmds.playbackOptions(\
query = True, \
animationStartTime = True)
spin_end = cmds.playbackOptions(\
query = True, \
animationEndTime = True)
self.SPN_start_frame.setValue(spin_start)
self.SPN_end_frame.setValue(spin_end)
# Build UI ------------------------------------------------------- #
def build_UI(self):
# Start with the stylesheet ---------------------------------- #
self.setStyleSheet("\
QWidget{\
background-color: rgb(70, 70, 70); \
color: rgb(140, 140, 140);\
font: 10pt Arial, Sans-serif;\
outline: 0;\
}\
QGroupBox {\
background-color: rgb(65, 65, 65);\
border: 1px solid;\
border-color: rgb(80, 80, 80); \
border-radius: 5px;\
margin-top: 2.5ex; \
}\
QGroupBox::title {\
color:rgb(120,120,120);\
subcontrol-origin: margin;\
subcontrol-position: top center; \
margin: 0px 4px;\
padding: 0px;\
}\
QLabel#headerLabel{\
background-color: rgb(59, 82, 125);\
}\
Line {\
margin: 0px;\
padding: 0px;\
}\
QSpinBox {\
padding: 0px 8px 0px 5px;\
background-color: rgb(50, 50, 50);\
border-width: 0px;\
border-radius: 8px;\
color: rgb(150, 150, 150);\
font: bold 14pt Sans-serif ;\
}\
QSpinBox:focus {\
background-color: rgb(55, 55, 55);\
}\
QSpinBox:hover {\
background-color: rgb(60, 60, 60);\
}\
QSpinBox:pressed {\
background-color: rgb(74, 105, 129);\
}\
QRadioButton {\
background-color: rgb(65, 65, 65);\
color: rgb(180, 180, 180);\
border-radius:8px;\
padding: 4px;\
}\
QRadioButton:checked{\
background-color: rgb(80, 80, 80); \
\
}\
QRadioButton:focus {\
background-color: rgb(85, 85, 85);\
}\
QRadioButton:hover{\
background-color: rgb(90, 90, 90);\
}\
QRadioButton:pressed{\
background-color: rgb(74, 105, 129);\
}\
QRadioButton::indicator {\
width: 8px;\
height: 8px;\
border-radius: 6px;\
}\
QRadioButton::indicator:checked {\
background-color: #05B8CC;\
border: 2px solid grey;\
border-color: rgb(180, 180, 180);\
}\
QRadioButton::indicator:unchecked {\
background-color: rgb(60, 60, 60);\
border: 2px solid grey;\
border-color: rgb(140, 140, 140);\
}\
QPushButton {\
background-color: rgb(80, 80, 80);\
border-style: solid;\
border-width:0px;\
border-color: rgb(160, 70, 60);\
border-radius:8px;\
color: rgb(186, 186, 186);\
min-height: 50px;\
}\
QPushButton:checked {\
background-color: rgb(157, 102, 71);\
}\
QPushButton:focus {\
background-color: rgb(85, 85, 85);\
}\
QPushButton:hover{\
background-color: rgb(90, 90, 90);\
}\
QPushButton:pressed{\
background-color: rgb(74, 105, 129);\
}\
QPushButton[state='active']{\
background-color: rgb(96, 117, 79);\
}\
QPushButton[state='set']{\
background-color: rgb(70, 99, 91);\
}\
QPushButton[state='clear']{\
background-color: rgb(80, 80, 80);\
}\
QProgressBar {\
border: 1px solid;\
border-color:rgb(90,90,90);\
border-radius: 5px;\
}\
QProgressBar::chunk {\
background-color: #05B8CC;\
width: 20px;\
}\
QListWidget {\
show-decoration-selected: 1; \
background: rgb(65, 65, 65); \
border: 1px solid grey;\
border-radius: 10px;\
padding: 6px 6px;\
border-color: rgb(80, 80, 80); \
margin-bottom: 0px;\
padding-right: 6px;\
alternate-background-color: rgb(65, 65, 65); \
}\
QListWidget:focus {\
background-color: rgb(60, 60, 60);\
}\
QListWidget::item {\
background: rgb(65, 65, 65); \
margin-bottom: 2px;\
border: 0px solid #000000;\
border-radius: 4px; \
padding-left: 4px;\
margin-right: 4px;\
height:24px;\
}\
QListWidget::item:alternate {\
border: 0px solid #3c3c3c;\
background: rgb(62, 62, 62);\
}\
QListWidget::item:selected {\
background-color: #4a6981;\
}\
QListWidget::item:selected:!active {\
background-color: #4f718c; \
color: #fff;\
}\
QListWidget::item:hover {\
background: rgb(80, 80, 80);\
}\
QListWidget::item:selected:hover {\
background-color: #4f7089;\
}\
QListWidget::item::selected:pressed {\
background-color: #648eaf;\