forked from janberger/aniMeta
-
Notifications
You must be signed in to change notification settings - Fork 1
/
aniMeta.py
16688 lines (13029 loc) · 666 KB
/
aniMeta.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
# -*- coding: UTF-8 -*-
'''
Copyright (c) 2018-2021 Prof. Jan Berger, Hochschule fuer Technik und Wirtschaft Berlin, Germany
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Autodesk® Maya® is a registered trademark of Autodesk Inc.
All other brand names, product names or trademarks belong to their respective holders.
Supported Maya Versions:
2020-2022
Supported OS:
Any OS supported by Maya
'''
import sys
import json
import os
import math
import inspect
import shutil
import ast
import copy
from six import string_types
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
import maya.cmds as mc
import maya.mel as mm
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
from maya import OpenMayaUI as omui
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from PySide2 import QtCore
from shiboken2 import wrapInstance
from functools import partial
px = omui.MQtUtil.dpiScale
kPluginName = 'aniMeta'
kPluginVersion = '01.00.128'
kLeft, kRight, kCenter, kAll, kSelection = range( 5 )
kHandle, kIKHandle, kJoint, kMain, kBodyGuide, kBipedRoot, kQuadrupedRoot, kCustomHandle, kBodyGuideLock, kBipedRootUE = range(10)
kBiped, kBipedUE, kQuadruped, kCustom = range(4)
kRigTypeString = ['Biped', 'BipedUE', 'Quadruped', 'Custom' ]
kLocal, kWorld, kParent = range(3)
kBasic, kSymmetricTranslation, kSymmetricRotation, kAuto = range( 4 )
kTorso, kArm, kHand, kLeg, kHead, kFace = range(6)
kPairBlend, kPairBlendTranslate, kPairBlendRotate = range(3)
kRigStateBind, kRigStateGuide, kRigStateControl = range(3)
kXYZ, kYZX, kZXY, kXZY, kYXZ, kZYX = range(6)
kFK, kIK = range(2)
curveType = [ 'animCurveTA', 'animCurveTL', 'animCurveTT', 'animCurveTU',
'animCurveUA', 'animCurveUL', 'animCurveUT', 'animCurveUU' ]
floatDataTypes = [ 'double', 'doubleLinear' ]
angleDataTypes = ['doubleAngle']
static, animCurve = range( 2 )
attrInput = [ 'static', 'animCurve' ]
floatPrec = 5
py_version = float( sys.version[0:3] )
def maya_useNewAPI():
"""
We need this for Maya Python API 2.0
"""
pass
class AniMeta( object ):
aniMetaDataAttrName = 'aniMetaData'
hik_side = [ 'Center', 'Left', 'Right', 'None' ]
hik_type = [ 'None', 'Root', 'Hip', 'Knee', 'Foot',
'Toe', 'Spine', 'Neck', 'Head', 'Collar',
'Shoulder', 'Elbow', 'Hand', 'Finger', 'Thumb',
'PropA', 'PropB', 'PropC', 'Other', 'Index Finger',
'Middle Finger', 'Ring Finger', 'Pinky Finger', 'Extra Finger', 'Big Toe',
'Index Toe', 'Middle Toe', 'Ring Toe', 'Pinky Toe', 'Extra Toe']
attrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'ro', 'jox', 'joy', 'joz', 'side', 'type', 'radius' ]
defaults = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0, 0.0, 0.0, 0.0, 0, 0, 1 ]
kBasic, kSymmetricTranslation, kSymmetricRotation = range( 3 )
kParent, kOrient, kPoint, kAim = range(4)
kCube, kSphere, kPipe = range(3)
ui = None
def __init__( self ):
self.workspace = mc.workspace( query=True, fn=True )
self.folder_aniMeta = 'aniMeta'
self.folder_pose = os.path.join( self.workspace, self.folder_aniMeta, 'Pose' )
self.folder_anim = os.path.join( self.workspace, self.folder_aniMeta, 'Anim' )
self.folder_rig = os.path.join( self.workspace, self.folder_aniMeta, 'Rig' )
self.check_folder( self.folder_pose )
self.check_folder( self.folder_anim )
self.check_folder( self.folder_rig )
# Required plug-in that may or may not already be loaded
mc.loadPlugin("mayaHIK", quiet=True)
def check_folder (self, folder):
if not os.path.isdir( folder ):
try:
os.makedirs( folder )
except:
mc.warning('aniMeta: There was a problem creating folder', folder)
def create_ui( self, *args ):
self.ui = AniMetaUI()
self.update_ui()
def find_node( self, root, nodeName ):
'''
Finds a DAG node within the specified character node, useful when multiple rigs are present.
:param root: The character`s name.
:param nodeName: The DAG node to look for
:return: A string with the long DAG path to the node or None if the node is not found.
'''
if nodeName is None:
return None
if root is None:
return None
nodeNameShort = self.short_name(nodeName)
if not root:
mc.warning( 'aniMeta: Character is not specified, please select it from the Character Editor.')
# Remove colons in case rig is referenced
if ':' in nodeNameShort:
buff = nodeNameShort.split(':')
nodeNameShort = buff[len(buff) - 1]
nodes = mc.listRelatives( root, ad=True, c=True, f=True) or []
for node in nodes:
currentNode = self.short_name(node)
# Remove colons in case rig is referenced
if ':' in currentNode:
buff = currentNode.split(':')
currentNode = buff[len(buff) - 1]
if currentNode == nodeNameShort:
return node
return None
def get_active_char( self ):
'''
Gets the selected character from the character list.
:return: the selected character
'''
list = self.get_char_list()
if list is not None:
count = list.count()
if count > 0:
char = list.currentText()
if mc.objExists( char ):
return char
else:
return None
else:
return None
def get_char_list( self ):
ptr = None
try:
ptr = omui.MQtUtil.findControl( 'aniMetaUI' )
except:
#mc.warning( 'aniMeta find char: Can not find UI.' )
return None
widget = None
try:
if py_version < 3:
widget = wrapInstance( long( ptr ), QWidget )
else:
# Python 3 doesn`t featrue the long data type anymore, so we can simply use int
widget = wrapInstance( int( ptr ), QWidget )
except:
mc.warning( 'aniMeta find char: please select a character in the character editor' )
return None
list = None
try:
list = widget.findChild( QComboBox, 'aniMetaCharList' )
except:
#mc.warning( 'aniMeta find char: Can not find character list.' )
return None
return list
def get_metaData( self, node, attr = aniMetaDataAttrName ):
data = { }
try:
if mc.attributeQuery( attr, exists = True, node = node ):
data = eval( mc.getAttr( node + '.' + attr ) )
except:
pass
return data
def get_nodes( self, root, dict = None, attr = aniMetaDataAttrName, hierarchy = True ):
if dict is None:
dict = { }
if root is not None:
if hierarchy:
if not mc.objExists( root ):
mc.warning( root + ' does not exist.' )
return False
else:
if len( root ) > 0:
for r in root:
if not mc.objExists( r ):
mc.warning( 'Object ' + r + ' does not exist.' )
if len( dict ) == 0:
mc.warning( 'Please specify which metaData to look for.' )
return False
keys = sorted( dict.keys() )
keyCount = len( dict.keys() )
nodes = [ ]
if hierarchy:
nodes = mc.listRelatives( root, children = True, ad = True, pa = True ) or [ ]
nodes.append( root )
else:
nodes = root
if root is None:
nodes = mc.ls()
matches = [ ]
for node in nodes:
if self.match_metaData( node, dict ):
# The IK nodes have pipes and we dont want those here
if '|' in node:
node = node.split('|')
node = node[ len( node ) - 1 ]
matches.append( node )
matches = sorted( matches )
return matches
def get_mobject( self, node ):
if isinstance( node, om.MDagPath ):
return node.node()
try:
list = om.MSelectionList()
list.add( node )
obj = list.getDependNode( 0 )
return obj
except:
print ( 'Can not get an MObject from ', node )
return None
def get_path ( self, nodeName, showWarnings=True ):
'''
Returns the MDagPath of a given maya node`s string name, the verbose flag enables/disables warnings
:rtype:
'''
if isinstance( nodeName, om.MDagPath ):
return nodeName
if nodeName is not None:
obj = self.get_mobject( nodeName )
if obj is not None:
dagPath = om.MDagPath()
if obj != om.MObject().kNullObj :
dagPath = om.MDagPath.getAPathTo( obj )
else:
if showWarnings:
print( 'get_path: can not get a valid MDagPath:', nodeName)
return None
return dagPath
return None
def get_scene_info( self ):
dict = { }
dict[ 'time' ] = mc.currentUnit( query = True, time = True )
dict[ 'angle' ] = mc.currentUnit( query = True, angle = True )
dict[ 'linear' ] = mc.currentUnit( query = True, linear = True )
dict[ 'fileName' ] = mc.file( q = True, sceneName = True )
dict[ 'maya' ] = mc.about( version = True )
dict[ 'aniMeta' ] = kPluginVersion
return dict
def match_metaData( self, node = 'myNode', dict = None ):
'''
Returns True if the given node`s metaData attr dict matches the Keys and Values of the dict argument
:param node: the node to check
:param dict: the dictionary with the matching criteria
:return: True if it matches ALL keys and values, otherwise returns False
'''
if dict is None:
dict = { }
metaData = self.get_metaData( node )
if len( metaData ) > 0:
keys = sorted( dict.keys() )
keyCount = len( dict.keys() )
matches = [ ]
if len( metaData ) > 0:
keyMatch = 0
for key in keys:
if key in metaData:
if dict[ key ] == metaData[ key ]:
keyMatch += 1
# if we want both sides ...
# before it was just if, keeping an eye on it
elif key == 'Side' and dict[ 'Side' ] == kAll:
keyMatch += 1
if keyMatch == keyCount:
return True
return False
def set_attr( self, node, attr, value, setKeyframe = False ):
if isinstance( node, om.MDagPath ):
node = node.fullPathName()
if mc.objExists( node ):
if mc.objExists( node + '.' + attr ):
if mc.getAttr( node + '.' + attr, se = True ):
if setKeyframe is False:
mc.setAttr( node + '.' + attr, value )
else:
mc.setKeyframe( node, attribute = attr, value = value )
def set_metaData( self, node, data = None, attr = aniMetaDataAttrName ):
if data is None:
data = { }
node_path = self.get_path( node )
if node_path is not None:
if not mc.attributeQuery( attr, exists = True, node = node_path.fullPathName() ):
mc.addAttr( node_path.fullPathName(), ln = attr, dt = "string" )
mc.setAttr( node_path.fullPathName() + '.' + attr, str( data ), typ = 'string' )
def short_name( self, node ):
if node is not None:
if isinstance( node, string_types ) :
buff = node.split('|')
return buff[len(buff)-1]
elif isinstance( node, om.MDagPath ):
buff = node.fullPathName().split('|')
return buff[len(buff)-1]
else:
print('aniMeta.short_name: unknown node type ', node , node.__class__.__name__ )
else:
return None
def update_ui( self, *args, **kwargs ):
ptr = omui.MQtUtil.findControl( 'aniMetaUI' )
if ptr is not None:
ui = AniMetaUI( create = False )
ui.char_list_refresh()
if 'picker' in kwargs:
ui = AniMetaUI( create = True )
ui.char_list_refresh()
class Menu(AniMeta):
menuName = 'aniMeta'
mainWindow = 'MayaWindow'
menu = None
def create( self ):
char = Char()
self.delete()
self.menu = mc.menu( self.menuName, parent = self.mainWindow )
######################################################################################
#
# Menu
mc.menuItem( label = 'Character Editor', c= self.create_ui )
##################################################################################
#
# Character
mc.menuItem( label = 'Character', sm = True, to = True, parent = self.menu )
mc.menuItem( label = 'Create', divider=True )
mc.menuItem( label = 'Biped', c = partial( char.create, name='Adam', type=kBiped ) )
mc.menuItem( label = 'Biped UE', c = partial( char.create, name='Adam', type=kBipedUE ) )
# Character
#
##################################################################################
##################################################################################
#
# Rigging
riggingMenu = mc.menuItem( label = 'Rig', sm = True, to = True, parent = self.menu )
rig = Rig()
mc.setParent( riggingMenu, menu = True )
mc.menuItem( d = True, dl = 'Control Handles' )
mc.menuItem( label = 'Create Custom Control', c = rig.create_custom_control )
mc.menuItem( label = 'Delete Custom Control', c = rig.delete_custom_control )
mc.menuItem( d = True, dl = 'Grouping' )
mc.menuItem( label = 'Create Null', c = rig.create_nul )
mc.menuItem( d = True, dl = 'Hierarchy I/O' )
mc.menuItem( label = 'Export Hierarchy ...', c = rig.export_joints_ui )
mc.menuItem( label = 'Import Hierarchy ...', c = rig.import_joints_ui )
mc.menuItem( d = True, dl = 'Driven Keys I/O' )
mc.menuItem( label = 'Export Driven Keys ...', c = rig.export_drivenKeys_ui )
mc.menuItem( label = 'Import Driven Keys ...', c = rig.import_drivenKeys_ui )
# Rigging
#
##################################################################################
##################################################################################
#
# Skinning
riggingMenu = mc.menuItem( label = 'Skinning', sm = True, to = True, parent = self.menu )
skin = Skin()
mc.menuItem( d = True, dl = 'Skinning' )
mc.menuItem( label = 'Bind Skin', c = skin.bind )
mc.menuItem( label = 'Smooth Weights', c = skin.smooth )
mc.menuItem( label = 'Smooth Weights Tool', c = skin.smooth_tool )
mc.menuItem( label = 'Reset Skin Influences', c = skin.reset )
mc.menuItem( label = 'Transfer Skinning', c = skin.transfer )
mc.menuItem( label = 'Mirror Skin Weights', c = skin.mirror )
mc.menuItem( d = True, dl = 'Skinning I/O ' )
mc.menuItem( label = 'Export Skinning ...', c = skin.export_ui )
mc.menuItem( label = 'Import Skinning ...', c = skin.import_ui )
# Skinning
#
##################################################################################
##################################################################################
#
# Transform
mc.menuItem( label = 'Transform', sm = True, to = True, parent = self.menu )
xform = Transform()
xform_mirror_ui = TransformMirrorUI()
mc.menuItem( label = 'Copy', c = xform.copy )
mc.menuItem( label = 'Paste', c = xform.paste )
mc.menuItem( label = 'Mirror', c = xform_mirror_ui.mirror )
mc.menuItem( optionBox = True, c = xform_mirror_ui.ui )
mc.menuItem( d = True, dl = 'Joints' )
mc.menuItem( label = 'Zero Out Joint Rotation', c = xform.zero_out_joint_orient )
mc.menuItem( label = 'Zero Out to Offset Parent', c = xform.zero_out_to_offsetParent )
# Transform
#
##################################################################################
##################################################################################
#
# Modeling
model = Model()
model_menu = mc.menuItem( label = 'Model', sm = True, to = True, parent = self.menu )
mc.menuItem( label = 'Mirror Geometry', c = model.mirror_geo, parent = model_menu )
mc.menuItem( label = 'Split BlendShape', c = BlendShapeSplitter, parent = model_menu )
mc.menuItem( d = True, dl = 'Symmetry' )
mc.menuItem( label = 'Flip Points', c = model.flip_geo, parent = model_menu )
mc.menuItem( label = 'Mirror Points', c = model.mirror_geo, parent = model_menu )
mc.menuItem( label = 'Export Symmetry...', c = model.export_symmetry_ui, parent = model_menu )
mc.menuItem( label = 'Specify Symmetry File ...', c = model.specify_symmetry_file, parent = model_menu )
# Modeling
#
##################################################################################
##################################################################################
#
# Misc
mc.setParent( self.menu, menu = True )
mc.menuItem( divider = True )
mc.menuItem( label = 'Options...', c=AniMetaOptionsUI)
#mc.menuItem( label = 'Documentation...',
# c = 'import maya.cmds as cmds\ncmds.launch(web="https://htw3d.readthedocs.io/en/latest/")' )
#mc.menuItem( label = 'About ...',
# c = 'import maya.OpenMaya\nmaya.OpenMaya.MGlobal.displayInfo("' + kPluginName + ' version ' + kPluginVersion + ', written by Jan Berger")' )
# Misc
#
##################################################################################
# Menu
#
######################################################################################
def delete( self ):
if mc.menu( self.menuName, exists = True ):
mc.deleteUI( self.menuName )
######################################################################################
#
# Transform
class Transform(AniMeta):
xforms = {}
def __init__(self):
super( Transform, self ).__init__()
def copy( self, *args, **kwargs ):
sel = mc.ls( sl = True )
xDict = { }
if sel is not None:
for s in sel:
xDict[ self.short_name( s ) ] = self.get_matrix( node = s, space = kWorld )
self.xforms = xDict
def create_matrix( self, translate = om.MVector( 0, 0, 0 ), rotate = om.MEulerRotation( 0, 0, 0, 0 ),
scale = ( 1, 1, 1 ) ):
tmat = om.MTransformationMatrix()
rmat = om.MTransformationMatrix( rotate.asMatrix() )
smat = om.MTransformationMatrix()
# Translate
tmat.setTranslation( translate, om.MSpace.kTransform )
# Scale
smat.setScale( scale, om.MSpace.kTransform )
return smat.asMatrix() * rmat.asMatrix() * tmat.asMatrix()
def get_translate( self, matrix ):
'''Returns the translate component of a given matrix'''
matrixT = om.MTransformationMatrix( matrix )
return matrixT.translation( om.MSpace.kTransform )
def get_matrix( self, node, space=kWorld):
'''Returns the transformation of certain DAG nodes in local or world space as MMatrix object.'''
obj1 = self.get_mobject(node)
if obj1 is None:
return None
if ( obj1.apiType() == om.MFn.kTransform or obj1.apiType() == om.MFn.kJoint or obj1.apiType() == om.MFn.kIkHandle):
dagFn1 = om.MFnDagNode(obj1)
dagPath1 = dagFn1.getPath()
if space == kLocal:
transFn = om.MFnTransform(dagPath1)
t = transFn.translation(om.MSpace.kTransform)
translate = om.MTransformationMatrix()
translate.setTranslation(t, om.MSpace.kTransform)
rotate = transFn.rotation(om.MSpace.kTransform)
s = om.MVector(transFn.scale())
scale = om.MTransformationMatrix()
scale.setScale(s, om.MSpace.kTransform)
return scale.asMatrix() * rotate.asMatrix() * translate.asMatrix()
elif space == kWorld:
return dagPath1.inclusiveMatrix()
elif space == kParent:
return dagPath1.exclusiveMatrix()
else:
print ('Invalid input, please specify 1 transform nodes by DAG path name, these were received: ', node)
return []
else:
#print ('get: invalid node type specfified: ', node, mc.nodeType(node))
return None
def invert_matrix(self, matrix ):
tmat = om.MTransformationMatrix( matrix )
return tmat.asMatrixInverse()
def print_matrix(self, matrix, text=''):
t = self.get_translate(matrix)
r = self.get_rotate(matrix)
s = self.get_scale(matrix)
print( text )
print( 'Translate:', round( t[0], 5 ), round( t[1], 5 ), round( t[2], 5 ) )
print( 'Rotate: ', round( math.degrees(r[0]), 5 ), round( math.degrees(r[1]), 5 ), round( math.degrees(r[2]), 5 ) )
print( 'Scale: ', round( s[0], 5 ), round( s[1], 5 ), round( s[2], 5 ) )
def get_rotate( self, matrix ):
'''Returns the rotate component of a given matrix'''
matrixT = om.MTransformationMatrix( matrix )
return matrixT.rotation()
def get_polevector_position(self, dagPath_1, dagPath_2, dagPath_3, preferredAngle=(0.0, 0.0, 0.0)):
'''
Calulates the Position for the Pole Vector
:param dagPath_1: Start IK node ( ie Upper Leg )
:param dagPath_2: Effector IK node ( ie Knee )
:param dagPath_3: Handle IK node ( ie Foot )
:param preferredAngle: The preferred angle of the IK Solver.
:return: MVector with the world position
'''
# Preferred Angle
pa = om.MVector(45.0, 0.0, 0.0)
pa.x = math.radians(preferredAngle[0])
pa.y = math.radians(preferredAngle[1])
pa.z = math.radians(preferredAngle[2])
dag1WorldTMat = self.get_matrix( dagPath_1, kWorld )
dag2WorldTMat = self.get_matrix( dagPath_2, kWorld )
dag3WorldTMat = self.get_matrix( dagPath_3, kWorld )
#dag4WorldTMat = self.get_matrix( dagPath_4, kWorld )
# Redundant? Should be just identity ...
m1 = dag1WorldTMat
m2 = dag2WorldTMat * self.invert_matrix( dag1WorldTMat )
m3 = dag3WorldTMat * self.invert_matrix( dag1WorldTMat )
L1 = self.get_translate( m1 )
L2 = self.get_translate( m2 )
L3 = self.get_translate( m3 )
V1 = self.get_translate( m2 ) #- L1
V2 = L3 - L2
V3 = self.get_translate( m3 ) #L1 - L3
angle = V1.angle(V2)
multi = 1.0
angle = round( angle, 4 )
worldTrans = om.MVector()
if abs(angle) > 0.001:
# there is an angle
a = V1.length()
b = V2.length()
c = V3.length()
V3.normalize()
# Half the distance
V3 = V3 * ( c * 0.5 )
# Get the Vector to the knee
V4 = V1 - V3
V4.normalize()
# Scale the Vector to have it clearly in front of the knee
V4 *= ( a+b ) * 0.75
pole_pos_mat = self.create_matrix(translate=V3+V4)
return pole_pos_mat * dag1WorldTMat
else:
# there is no angle
pa.normalize()
L4 = L2 + pa
V4 = L4 - L2
'''
print ''
print 'pa',pa
print 'L2', L2
print 'L4', L4
print 'V4', V4
'''
cross = om.MVector()
cross.x = V2.y * V4.z - V4.y * V2.z
cross.y = V4.x * V2.z - V2.x * V4.z
cross.z = V2.x * V4.y - V2.y * V4.x
#print 'cross', cross
poleOffset = om.MTransformationMatrix()
poleOffset.setTranslation(cross, om.MSpace.kWorld)
outMat = poleOffset.asMatrix() * dag2WorldTMat
worldTrans = self.get_translate( outMat )
#self.print_matrix( poleOffset.asMatrix(), 'Pole Offset' )
#self.print_matrix( dag2WorldTMat, 'dag2WorldTMat' )
#self.print_matrix( outMat, 'outMat' )
''', 'PoleOffset
pa.normalize()
L4 = L2 + pa
V4 = L4 - L2
cross = om.MVector()
cross.x = V2.y * V4.z - V4.y * V2.z
cross.y = V4.x * V2.z - V2.x * V4.z
cross.z = V2.x * V4.y - V2.y * V4.x
# Hack
cross.x = 50 * pa.x
cross.y = 50 * pa.y
cross.z = 50 * pa.z
poleOffset = om.MTransformationMatrix()
poleOffset.setTranslation(cross, om.MSpace.kWorld)
outMat = poleOffset.asMatrix() * dag2WorldTMat
worldTrans = self.get_translate( outMat )
'''
return self.create_matrix(translate=worldTrans)
def get_rotation_order( self, order ):
if order == 0:
return om.MEulerRotation.kXYZ
elif order == 1:
return om.MEulerRotation.kYZX
elif order == 2:
return om.MEulerRotation.kZXY
elif order == 3:
return om.MEulerRotation.kXZY
elif order == 4:
return om.MEulerRotation.kYXZ
elif order == 5:
return om.MEulerRotation.kZYX
else:
return om.MEulerRotation.kXYZ
def get_scale( self, matrix ):
'''Returns the scale component of a given matrix'''
matrixT = om.MTransformationMatrix( matrix )
return matrixT.scale( om.MSpace.kTransform )
def list_to_matrix( self, matrix_list ):
''' Creates an MMatrix instance from a list with 16 float values.'''
if len( matrix_list ) == 16:
matrix = om.MMatrix()
no = 0
for i in range( 4 ):
for j in range( 4 ):
matrix.setElement( i, j, matrix_list[ no ] )
no += 1
return matrix
else:
return None
def matrix_to_list( self, matrix ):
''' Creates a list with 16 float values from a MMatrix instance.'''
m_list = [ ]
for i in range( 4 ):
for j in range( 4 ):
m_list.append( round( matrix.getElement( i, j ), 6 ) )
return m_list
def mirror_matrix( self, matrix, mode = kSymmetricRotation, space = kLocal, refObect = '' ):
t = self.get_translate( matrix )
r = self.get_rotate( matrix )
s = self.get_scale( matrix )
t.x *= -1
r.y *= -1
r.z *= -1
if mode == kSymmetricTranslation:
s[ 0 ] *= -1
elif mode == kSymmetricRotation:
if space == kWorld:
offset = om.MEulerRotation( math.radians( 180 ), 0, 0 )
mirror_rotation = offset.asMatrix() * r.asMatrix()
r = self.get_rotate( mirror_rotation )
if space == kLocal:
t = self.get_translate( matrix )
t.x *= -1
t.y *= -1
t.z *= -1
r = self.get_rotate( matrix )
elif mode == kBasic:
doNothing = 1
else:
print('mirrorMatrix: invalid mode')
return self.create_matrix( translate = t, rotate = r, scale = s )
def paste( self, *args, **kwargs ):
sel = mc.ls( sl = True )
xDict = self.xforms
if sel is not None and xDict is not None:
keys = xDict.keys()
# if there is only one transform in the dict, apply to all elected objects
if len( keys ) == 1:
for s in sel:
self.set_matrix( node = s, matrix = xDict[ keys[ 0 ] ], space = kWorld )
# otherwise match the transformation one by one
else:
for s in sel:
if s in xDict:
self.set_matrix( node = s, matrix = xDict[ s ], space = kWorld )
def match_transform(self, node, target, space = kWorld ):
m = None
if mc.objExists( target ):
m = self.get_matrix( target, space )
if mc.objExists( node ) and m:
self.set_matrix( node, m, space )
return True
def set_matrix( self, node, matrix, space = kWorld, setKeyframe = False, setTranslate=True, setRotate=True, setScale=True ):
if not isinstance( node, om.MDagPath ):
path = self.get_path( node )
if path is None:
mc.warning('aniMeta: Couldn`t get a path to' + node )
else:
node = path
if not isinstance( matrix, om.MMatrix ):
mc.warning( 'aniMeta: Invalid matrix object for node ' + node.partialPathName())
return False
if space == kLocal:
t = self.get_translate( matrix )
r = self.get_rotate( matrix )
s = self.get_scale( matrix )
# Translate
if setTranslate:
self.set_attr( node, "tx", t.x, setKeyframe )
self.set_attr( node, "ty", t.y, setKeyframe )
self.set_attr( node, "tz", t.z, setKeyframe )
# Rotate
if setRotate:
rotOrder = mc.getAttr( node.fullPathName() + '.rotateOrder' )
if rotOrder != 0:
r.reorderIt( self.get_rotation_order( rotOrder ) )
self.set_attr( node, "rx", math.degrees( r.x ), setKeyframe )
self.set_attr( node, "ry", math.degrees( r.y ), setKeyframe )
self.set_attr( node, "rz", math.degrees( r.z ), setKeyframe )
# Scale
if setScale:
self.set_attr( node, "sx", s[ 0 ], setKeyframe )
self.set_attr( node, "sy", s[ 1 ], setKeyframe )
self.set_attr( node, "sz", s[ 2 ], setKeyframe )
elif space == kWorld:
obj1 = self.get_mobject( node )
if (obj1.apiType() == om.MFn.kTransform or obj1.apiType() == om.MFn.kJoint):
# get stuff
dagFn1 = om.MFnDagNode( obj1 )
#dagPath1 = om.MDagPath()
dagPath1 = dagFn1.getPath()
parentMat = om.MTransformationMatrix( dagPath1.exclusiveMatrix() )
out_matrix = matrix * parentMat.asMatrixInverse()
if obj1.apiType() is om.MFn.kJoint:
joPlug = dagFn1.findPlug( 'jointOrient', False )
joPlugX = joPlug.child( 0 )
joPlugY = joPlug.child( 1 )
joPlugZ = joPlug.child( 2 )
jo_matrix = om.MTransformationMatrix(
om.MEulerRotation( joPlugX.asDouble(), joPlugY.asDouble(), joPlugZ.asDouble() ).asMatrix() )
t = self.get_translate( out_matrix )
r = self.get_rotate( out_matrix )
s = self.get_scale( out_matrix )
r_matrix = r.asMatrix() * jo_matrix.asMatrixInverse()
r = self.get_rotate( r_matrix )
out_matrix = self.create_matrix( t, r, s )