forked from chrisevans3d/uExport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuExport.py
1825 lines (1510 loc) · 73 KB
/
uExport.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
'''
uExport
Christopher Evans, Version 0.1, Feb 2014
@author = Chris Evans
version = 0.85
Add this to a shelf:
import uExport as ue
uExportToolWindow = ue.show()
'''
import os
import re
import time
import stat
import types
from cStringIO import StringIO
import xml.etree.ElementTree as xml
import json
import functools
import maya.cmds as cmds
import maya.OpenMayaUI as openMayaUI
import maya.mel as mel
# legacy support
from Qtpy.Qt import QtWidgets, QtCore, QtGui
mayaApi = cmds.about(api=True)
if mayaApi >= 201700:
import shiboken2 as shiboken
import pyside2uic as pysideuic
else:
import shiboken
import pysideuic
def show():
global uExportToolWindow
try:
uExportToolWindow.close()
except:
pass
uExportToolWindow = uExportTool()
uExportToolWindow.show()
return uExportToolWindow
def loadUiType(uiFile):
"""
Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first
and then execute it in a special frame to retrieve the form_class.
http://tech-artists.org/forum/showthread.php?3035-PySide-in-Maya-2013 (ChrisE)
"""
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uiFile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
#Fetch the base_class and form class based on their type in the xml from designer
form_class = frame['Ui_%s'%form_class]
base_class = eval('QtWidgets.%s'%widget_class)
return form_class, base_class
def getMayaWindow():
ptr = openMayaUI.MQtUtil.mainWindow()
if ptr is not None:
return shiboken.wrapInstance(long(ptr), QtWidgets.QWidget)
try:
selfDirectory = os.path.dirname(__file__)
uiFile = selfDirectory + '/uExport.ui'
except:
uiFile = 'D:\\Build\\usr\\jeremy_ernst\\MayaTools\\General\\Scripts\\epic\\rigging\\uExport\\uExport.ui'
form_class, base_class = loadUiType(uiFile)
if os.path.isfile(uiFile):
form_class, base_class = loadUiType(uiFile)
else:
cmds.error('Cannot find UI file: ' + uiFile)
#these are used by both classes below, this method is usually in the utils lib at Epic
def attrExists(attr):
if '.' in attr:
node, att = attr.split('.')
return cmds.attributeQuery(att, node=node, ex=1)
else:
cmds.warning('attrExists: No attr passed in: ' + attr)
return False
def msgConnect(attribFrom, attribTo, debug=0):
# TODO needs a mode to dump all current connections (overwrite/force)
objFrom, attFrom = attribFrom.split('.')
objTo, attTo = attribTo.split('.')
if debug: print 'msgConnect>>> Locals:', locals()
if not attrExists(attribFrom):
cmds.addAttr(objFrom, longName=attFrom, attributeType='message')
if not attrExists(attribTo):
cmds.addAttr(objTo, longName=attTo, attributeType='message')
# check that both atts, if existing are msg atts
for a in (attribTo, attribFrom):
if cmds.getAttr(a, type=1) != 'message':
cmds.warning('msgConnect: Attr, ' + a + ' is not a message attribute. CONNECTION ABORTED.')
return False
try:
return cmds.connectAttr(attribFrom, attribTo, f=True)
except Exception as e:
print e
return False
def findRelatedSkinCluster(skinObject):
'''Python implementation of MEL command: http://takkun.nyamuuuu.net/blog/archives/592'''
skinShape = None
skinShapeWithPath = None
hiddenShape = None
hiddenShapeWithPath = None
cpTest = cmds.ls( skinObject, typ="controlPoint" )
if len( cpTest ):
skinShape = skinObject
else:
rels = cmds.listRelatives( skinObject )
if rels == None: return False
for r in rels :
cpTest = cmds.ls( "%s|%s" % ( skinObject, r ), typ="controlPoint" )
if len( cpTest ) == 0:
continue
io = cmds.getAttr( "%s|%s.io" % ( skinObject, r ) )
if io:
continue
visible = cmds.getAttr( "%s|%s.v" % ( skinObject, r ) )
if not visible:
hiddenShape = r
hiddenShapeWithPath = "%s|%s" % ( skinObject, r )
continue
skinShape = r
skinShapeWithPath = "%s|%s" % ( skinObject, r )
break
if skinShape:
if len( skinShape ) == 0:
if len( hiddenShape ) == 0:
return None
else:
skinShape = hiddenShape
skinShapeWithPath = hiddenShapeWithPath
clusters = cmds.ls( typ="skinCluster" )
for c in clusters:
geom = cmds.skinCluster( c, q=True, g=True )
for g in geom:
if g == skinShape or g == skinShapeWithPath:
return c
return None
def getParents(item):
parents = []
current_item = item
current_parent = current_item.parent()
# Walk up the tree and collect all parent items of this item
while not current_parent is None:
parents.append(current_parent)
current_item = current_parent
current_parent = current_item.parent()
return parents
########################################################################
## UEXPORT CLASS
########################################################################
class uExport(object):
'''
Just a little basket to store things.
TODO: Add properties to get/set values
TODO: add logic to check that meshes exist across LODs
'''
def __init__(self, node):
#update for new LOD attrs instead of just rendermeshes
if not attrExists(node + '.rendermeshes_LOD0'):
if attrExists(node + '.rendermesh'):
if cmds.listConnections(node + '.rendermesh'):
lod0meshes = cmds.listConnections(node + '.rendermesh')
for mesh in lod0meshes:
msgConnect(node + '.rendermeshes_LOD0', mesh + '.uExport')
cmds.deleteAttr(node, at='rendermesh')
else:
cmds.addAttr(node, longName='rendermeshes_LOD0', attributeType='message')
else:
cmds.addAttr(node, longName='rendermeshes_LOD0', attributeType='message')
#add the other lod attrs
cmds.addAttr(node, longName='rendermeshes_LOD1', attributeType='message')
cmds.addAttr(node, longName='rendermeshes_LOD2', attributeType='message')
cmds.addAttr(node, longName='rendermeshes_LOD3', attributeType='message')
cmds.addAttr(node, longName='rendermeshes_LOD4', attributeType='message')
#TODO: don't assume 4 LODs
if not attrExists(node + '.export_script_LOD0'):
cmds.addAttr(node, longName='export_script_LOD0', dt='string')
cmds.addAttr(node, longName='export_script_LOD1', dt='string')
cmds.addAttr(node, longName='export_script_LOD2', dt='string')
cmds.addAttr(node, longName='export_script_LOD3', dt='string')
cmds.addAttr(node, longName='export_script_LOD4', dt='string')
if not attrExists(node + '.fbx_name_LOD0'):
cmds.addAttr(node, longName='fbx_name_LOD0', dt='string')
cmds.addAttr(node, longName='fbx_name_LOD1', dt='string')
cmds.addAttr(node, longName='fbx_name_LOD2', dt='string')
cmds.addAttr(node, longName='fbx_name_LOD3', dt='string')
cmds.addAttr(node, longName='fbx_name_LOD4', dt='string')
self.export_root = cmds.listConnections(node + '.export_root')
self.version = cmds.getAttr(node + '.uexport_ver')
self.node = node
self.name = node.split('|')[-1]
self.asset_name = node
self.folder_path = None
self.fbxPropertiesDict = None
if attrExists(node + '.asset_name'):
self.asset_name = cmds.getAttr(node + '.asset_name')
if attrExists(node + '.fbx_name'):
self.fbx_name = cmds.getAttr(node + '.fbx_name')
if attrExists(node + '.folder_path'):
self.folder_path = cmds.getAttr(node + '.folder_path')
#ART MetaData
#TO DO: Move to properties
if attrExists(node + '.joint_mover_template'):
self.joint_mover_template = cmds.getAttr(node + '.joint_mover_template')
if attrExists(node + '.skeleton_template'):
self.skeleton_template = cmds.getAttr(node + '.skeleton_template')
if attrExists(node + '.pre_script'):
self.pre_script = cmds.getAttr(node + '.pre_script')
if attrExists(node + '.post_script'):
self.post_script = cmds.getAttr(node + '.post_script')
if attrExists(node + '.export_file'):
self.export_file = cmds.getAttr(node + '.export_file')
if attrExists(node + '.anim_file'):
self.anim_file = cmds.getAttr(node + '.anim_file')
if attrExists(node + '.skeleton_uasset'):
self.skeleton_uasset = cmds.getAttr(node + '.skeleton_uasset')
if attrExists(node + '.skelmesh_uasset'):
self.skelmesh_uasset = cmds.getAttr(node + '.skelmesh_uasset')
if attrExists(node + '.physics_uasset'):
self.physics_uasset = cmds.getAttr(node + '.physics_uasset')
if attrExists(node + '.thumbnail_large'):
self.thumbnail_large = cmds.getAttr(node + '.thumbnail_large')
if attrExists(node + '.thumbnail_small'):
self.thumbnail_small = cmds.getAttr(node + '.thumbnail_small')
## Built in methods
########################################################################
def getLodDicts(self):
lodDicts = {}
lodDicts[0] = {'meshes':self.rendermeshes_LOD0, 'export_script':self.export_script_LOD0, 'fbx_name':self.fbx_name_LOD0}
lodDicts[1] = {'meshes':self.rendermeshes_LOD1, 'export_script':self.export_script_LOD1, 'fbx_name':self.fbx_name_LOD1}
lodDicts[2] = {'meshes':self.rendermeshes_LOD2, 'export_script':self.export_script_LOD2, 'fbx_name':self.fbx_name_LOD2}
lodDicts[3] = {'meshes':self.rendermeshes_LOD3, 'export_script':self.export_script_LOD3, 'fbx_name':self.fbx_name_LOD3}
lodDicts[4] = {'meshes':self.rendermeshes_LOD4, 'export_script':self.export_script_LOD4, 'fbx_name':self.fbx_name_LOD4}
return lodDicts
def getShaderDict(self):
shaderDict = {}
for mesh in self.rendermeshes_ALL:
for shader in self.getAssocShaders(mesh):
if shader not in shaderDict.keys():
shaderDict[shader] = [mesh]
else:
shaderDict[shader].append(mesh)
if shaderDict:
return shaderDict
else:
return False
def getAssocShaders(self, mesh):
shapes = cmds.listRelatives(mesh, shapes=1, f=True)
shadingGrps = cmds.listConnections(shapes,type='shadingEngine')
shaders = cmds.ls(cmds.listConnections(shadingGrps),materials=1)
return shaders
def connectRenderMeshes(self, renderMeshes, LOD=0):
try:
cmds.undoInfo(openChunk=True)
lodAttr = None
if LOD >=0 or LOD <=4:
lodAttr = self.node + '.rendermeshes_LOD' + str(LOD)
conns = cmds.listConnections(lodAttr, plugs=1, destination=1)
if conns:
for conn in cmds.listConnections(lodAttr, plugs=1, destination=1):
cmds.disconnectAttr(lodAttr, conn)
if lodAttr:
for mesh in renderMeshes:
msgConnect(lodAttr, mesh + '.uExport')
else:
cmds.error('connectRenderMeshes>>> please specify a LOD integer (0-4) for your meshes')
except Exception as e:
print e
finally:
cmds.undoInfo(closeChunk=True)
def getFbxExportPropertiesDict(self):
if not attrExists(self.node + '.fbxPropertiesDict'):
cmds.addAttr(self.node, longName='fbxPropertiesDict', dt='string')
self.fbxPropertiesDict = {'animInterpolation':'quaternion', 'upAxis':'default', 'triangulation':False}
cmds.setAttr(self.node + '.fbxPropertiesDict', json.dumps(self.fbxPropertiesDict), type='string')
return self.fbxPropertiesDict
else:
self.fbxPropertiesDict = json.loads(cmds.getAttr(self.node + '.fbxPropertiesDict'))
return self.fbxPropertiesDict
## Properties
########################################################################
#return and set the rendermeshes per LOD
@property
def rendermeshes_LOD0(self):
conns = cmds.listConnections(self.node + '.rendermeshes_LOD0')
if conns:
return conns
else: return []
@rendermeshes_LOD0.setter
def rendermeshes_LOD0(self, meshes):
self.connectRenderMeshes(meshes, LOD=0)
@property
def rendermeshes_LOD1(self):
conns = cmds.listConnections(self.node + '.rendermeshes_LOD1')
if conns:
return conns
else: return []
@rendermeshes_LOD1.setter
def rendermeshes_LOD1(self, meshes):
self.connectRenderMeshes(meshes, LOD=1)
@property
def rendermeshes_LOD2(self):
conns = cmds.listConnections(self.node + '.rendermeshes_LOD2')
if conns:
return conns
else: return []
@rendermeshes_LOD2.setter
def rendermeshes_LOD2(self, meshes):
self.connectRenderMeshes(meshes, LOD=2)
@property
def rendermeshes_LOD3(self):
conns = cmds.listConnections(self.node + '.rendermeshes_LOD3')
if conns:
return conns
else: return []
@rendermeshes_LOD3.setter
def rendermeshes_LOD3(self, meshes):
self.connectRenderMeshes(meshes, LOD=3)
@property
def rendermeshes_LOD4(self):
conns = cmds.listConnections(self.node + '.rendermeshes_LOD4')
if conns:
return conns
else: return []
@rendermeshes_LOD4.setter
def rendermeshes_LOD4(self, meshes):
self.connectRenderMeshes(meshes, LOD=4)
#number of lods
@property
def lodNum(self):
att = self.node + '.lodNum'
if attrExists(att):
return cmds.getAttr(att)
else:
cmds.addAttr(self.node, ln='lodNum', at='byte')
cmds.setAttr(att, 4)
return cmds.getAttr(att)
@lodNum.setter
def lodNum(self, meshes):
att = self.node + '.lodNum'
if attrExists(att):
return cmds.setAttr(att)
else:
cmds.addAttr(self.node, ln='lodNum', at='byte')
cmds.setAttr(att, 4)
return cmds.setAttr(att)
#return ALL lod geometry
@property
def rendermeshes_ALL(self):
meshes = []
meshes.extend(self.rendermeshes_LOD0)
meshes.extend(self.rendermeshes_LOD1)
meshes.extend(self.rendermeshes_LOD2)
meshes.extend(self.rendermeshes_LOD3)
meshes.extend(self.rendermeshes_LOD4)
return meshes
#return and set export script paths
@property
def export_script_LOD0(self):
return cmds.getAttr(self.node + '.export_script_LOD0')
@export_script_LOD0.setter
def export_script_LOD0(self, path):
cmds.setAttr(self.node + '.export_script_LOD0', path, type='string')
@property
def export_script_LOD1(self):
return cmds.getAttr(self.node + '.export_script_LOD1')
@export_script_LOD1.setter
def export_script_LOD1(self, path):
cmds.setAttr(self.node + '.export_script_LOD1', path, type='string')
@property
def export_script_LOD2(self):
return cmds.getAttr(self.node + '.export_script_LOD2')
@export_script_LOD2.setter
def export_script_LOD2(self, path):
cmds.setAttr(self.node + '.export_script_LOD2', path, type='string')
@property
def export_script_LOD3(self):
return cmds.getAttr(self.node + '.export_script_LOD3')
@export_script_LOD3.setter
def export_script_LOD3(self, path):
cmds.setAttr(self.node + '.export_script_LOD3', path, type='string')
@property
def export_script_LOD4(self):
return cmds.getAttr(self.node + '.export_script_LOD4')
@export_script_LOD4.setter
def export_script_LOD4(self, path):
cmds.setAttr(self.node + '.export_script_LOD4', path, type='string')
#return and set fbx export names
@property
def fbx_name_LOD0(self):
return cmds.getAttr(self.node + '.fbx_name_LOD0')
@fbx_name_LOD0.setter
def fbx_name_LOD0(self, name):
cmds.setAttr(self.node + '.fbx_name_LOD0', name, type='string')
@property
def fbx_name_LOD1(self):
return cmds.getAttr(self.node + '.fbx_name_LOD1')
@fbx_name_LOD1.setter
def fbx_name_LOD1(self, name):
cmds.setAttr(self.node + '.fbx_name_LOD1', name, type='string')
@property
def fbx_name_LOD2(self):
return cmds.getAttr(self.node + '.fbx_name_LOD2')
@fbx_name_LOD2.setter
def fbx_name_LOD2(self, name):
cmds.setAttr(self.node + '.fbx_name_LOD2', name, type='string')
@property
def fbx_name_LOD3(self):
return cmds.getAttr(self.node + '.fbx_name_LOD3')
@fbx_name_LOD3.setter
def fbx_name_LOD3(self, name):
cmds.setAttr(self.node + '.fbx_name_LOD3', name, type='string')
@property
def fbx_name_LOD4(self):
return cmds.getAttr(self.node + '.fbx_name_LOD4')
@fbx_name_LOD4.setter
def fbx_name_LOD4(self, path):
cmds.setAttr(self.node + '.fbx_name_LOD4', path, type='string')
#return joints
@property
def joints(self):
if self.export_root:
returnMe = []
children = cmds.listRelatives(self.export_root, type='joint',allDescendents=True)
if children:
returnMe.extend(children)
returnMe.append(self.export_root[0])
return returnMe
@joints.setter
def joints(self):
print 'Joints returned by walking hierarchy from the root, not directly settable.'
#return fbxExportDict
@property
def fbxExportProperties(self):
return self.getFbxExportPropertiesDict()
@fbxExportProperties.setter
def fbxExportProperties(self, dict):
self.fbxPropertiesDict = dict
cmds.setAttr(self.node + '.fbxPropertiesDict', json.dumps(self.fbxPropertiesDict), type='string')
########################################################################
## UEXPORT TOOL
########################################################################
class uExportTool(base_class, form_class):
title = 'uExportTool 0.8'
currentMesh = None
currentSkin = None
currentInf = None
currentVerts = None
currentNormalization = None
scriptJobNum = None
copyCache = None
jointLoc = None
iconLib = {}
iconPath = os.environ.get('MAYA_LOCATION', None) + '/icons/'
iconLib['joint'] = QtGui.QIcon(QtGui.QPixmap(iconPath + 'kinJoint.png'))
iconLib['ikHandle'] = QtGui.QIcon(QtGui.QPixmap(iconPath + 'kinHandle.png'))
iconLib['transform'] = QtGui.QIcon(QtGui.QPixmap(iconPath + 'orientJoint.png'))
def __init__(self, parent=getMayaWindow()):
self.closeExistingWindow()
super(uExportTool, self).__init__(parent)
self.setupUi(self)
self.setWindowTitle(self.title)
self.fbxVerLbl.setText('fbx plugin ' + str(self.fbxVersion()) + ' ')
wName = openMayaUI.MQtUtil.fullName(long(shiboken.getCppPointer(self)[0]))
## Connect UI
########################################################################
self.export_BTN.clicked.connect(self.export_FN)
self.createUexportNode_BTN.clicked.connect(self.createUexportNode_FN)
self.replaceUnknownNodes.clicked.connect(self.replaceUnknownNodes_FN)
self.refreshBTN.clicked.connect(self.refreshUI)
self.getTexturesP4BTN.clicked.connect(self.getTexturesP4_FN)
# TODO: Add save settings, setting p4 menu for now
self.p4CHK.setChecked(False)
self.workSpaceCMB.currentIndexChanged.connect(self.workspaceSelected)
#context menu
self.export_tree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.export_tree.customContextMenuRequested.connect(self.openMenu)
self.export_tree.itemClicked.connect(self.check_status)
self.export_tree.itemClicked.connect(self.itemClicked)
self.missingFilesTree.itemClicked.connect(self.itemClicked)
#check for p4 lib
yourP4Module = 'p4python.P4'
try:
__import__(yourP4Module)
except ImportError:
print 'Perforce lib not found.'
self.perforce = False
else:
self.perforce = True
print 'Perforce lib found.'
#Connect event filter to grab right/left click
self.export_tree.viewport().installEventFilter(self)
self.mousePress = None
self.snapRoot_CMB.setHidden(True)
self.refreshUI()
## GENERAL
########################################################################
#quick mesh check
def isMesh(self, node):
rels = cmds.listRelatives(node, children=True, s=True)
if rels:
for shp in rels:
if cmds.nodeType(shp)=='mesh':
return True
return False
def setOutlinerToShowAssetContents(self):
mel.eval('outlinerEditor -e -showContainerContents 1 outlinerPanel1; outlinerEditor -e \
-showContainedOnly 0 outlinerPanel1;')
def closeExistingWindow(self):
for qt in QtWidgets.qApp.topLevelWidgets():
try:
if qt.__class__.__name__ == self.__class__.__name__:
qt.deleteLater()
print 'uExport: Closed ' + str(qt.__class__.__name__)
except:
pass
def convertSkelSettingsToNN(delete=1):
orig = 'SkeletonSettings_Cache'
if cmds.objExists(orig):
if cmds.nodeType(orig) == 'unknown':
new = cmds.createNode('network')
for att in cmds.listAttr(orig):
if not cmds.attributeQuery(att, node=new, exists=1):
typ = cmds.attributeQuery(att, node=orig, at=1)
if typ == 'typed':
cmds.addAttr(new, longName=att, dt='string')
if cmds.getAttr(orig + '.' + att):
cmds.setAttr(new + '.' + att, cmds.getAttr(orig + '.' + att), type='string')
elif typ == 'enum':
cmds.addAttr(new, longName=att, at='enum', enumName=cmds.attributeQuery(att, node=orig, listEnum=1)[0])
cmds.delete(orig)
cmds.rename(new, 'SkeletonSettings_Cache')
def fbxVersion(self):
for plugin in cmds.pluginInfo(q=True, listPlugins=True):
if "fbxmaya" in plugin:
return cmds.pluginInfo(plugin, q=True, version=True)
def replaceUnknownNodes_FN(self):
self.convertSkelSettingsToNN()
def isBlendshape(self, mesh):
future = cmds.listHistory(mesh, future=1)
isShape = False
for node in future:
if cmds.nodeType(node) == 'blendShape':
return True
return False
def LOD_transferWeights(meshes, jointsToRemove, jointToTransferTo, debug=1, pruneWeights=0.001, *args):
'''
Original function by Charles Anderson @ Epic Games
'''
for mesh in meshes:
# Find the skin cluster for the current mesh
cluster = findCluster(mesh)
if debug:
print "MESH: ", mesh
print "CLUSTER: ", cluster
# Prune weights on the current mesh
if pruneWeights:
cmds.skinPercent(cluster, mesh, prw=pruneWeights)
# Find all of the current influences on the current skin cluster.
meshInfluences = cmds.skinCluster(cluster, q=True, inf=True)
#print "Current Influences: ", meshInfluences
for joint in jointsToRemove:
if joint in meshInfluences:
#print "Current Joint: ", joint
# If the jointToTransferTo is not already an influence on the current mesh then add it.
currentInfluences = cmds.skinCluster(cluster, q=True, inf=True)
if jointToTransferTo not in currentInfluences:
cmds.skinCluster(cluster, e=True, wt=0, ai=jointToTransferTo)
# Now transfer all of the influences we want to remove onto the jointToTransferTo.
for x in range(cmds.polyEvaluate(mesh, v=True)):
#print "TRANSFERRING DATA....."
value = cmds.skinPercent(cluster, (mesh+".vtx["+str(x)+"]"), t=joint, q=True)
if value > 0:
cmds.skinPercent(cluster, (mesh+".vtx["+str(x)+"]"), tmw=[joint, jointToTransferTo])
# Remove unused influences
currentInfluences = cmds.skinCluster(cluster, q=True, inf=True)
#print "Current Influences: ", currentInfluences
influencesToRemove = []
weightedInfs = cmds.skinCluster(cluster, q=True, weightedInfluence=True)
#print "Weighted Influences: ", weightedInfs
for inf in currentInfluences:
#print "Influence: ", inf
if inf not in weightedInfs:
#print "Update Influences to Remove List: ", inf
influencesToRemove.append(inf)
#print "ToRemove Influences: ", influencesToRemove
if influencesToRemove != []:
for inf in influencesToRemove:
cmds.skinCluster(cluster, e=True, ri=inf)
## UI RELATED
########################################################################
#event filter to grab and discern right/left click
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.MouseButtonPress and event.button() == QtCore.Qt.RightButton and source is self.export_tree.viewport()):
self.mousePress = 'right'
elif (event.type() == QtCore.QEvent.MouseButtonPress and event.button() == QtCore.Qt.LeftButton and source is self.export_tree.viewport()):
self.mousePress = 'left'
return super(uExportTool, self).eventFilter(source, event)
#contextual menus
def openMenu(self, position):
menu = QtWidgets.QMenu()
clickedWid = self.export_tree.itemAt(position)
if 'P4_FILE_LIST' in self.export_tree.itemAt(position).text(0):
checkOut = menu.addAction("Check out files")
pos = self.export_tree.mapToGlobal(position)
action = menu.exec_(pos)
if action:
print 'checkin gout files'
if 'LOD ' in clickedWid.text(0):
addMeshes = menu.addAction("Add selected meshes")
removeMeshes = menu.addAction("Remove selected meshes")
resetMeshes = menu.addAction("Set only selected meshes")
pos = self.export_tree.mapToGlobal(position)
action = menu.exec_(pos)
if action:
if action == addMeshes:
meshes = [mesh for mesh in cmds.ls(sl=1) if self.isMesh(mesh)]
uNode = clickedWid.uExport
lod = clickedWid.lod
existingMeshes = eval('uNode.rendermeshes_LOD' + str(lod))
existingMeshes.extend(meshes)
uNode.connectRenderMeshes(existingMeshes, LOD=clickedWid.lod)
self.refreshUI()
elif action == removeMeshes:
meshes = [mesh for mesh in cmds.ls(sl=1) if self.isMesh(mesh)]
uNode = clickedWid.uExport
lod = clickedWid.lod
existingMeshes = eval('uNode.rendermeshes_LOD' + str(lod))
newMeshes = [mesh for mesh in existingMeshes if mesh not in meshes]
uNode.connectRenderMeshes(newMeshes, LOD=lod)
self.refreshUI()
elif action == resetMeshes:
newMeshes = cmds.ls(sl=1)
uNode = clickedWid.uExport
lod = clickedWid.lod
uNode.connectRenderMeshes(newMeshes, LOD=lod)
self.refreshUI()
if not self.export_tree.itemAt(position).parent():
rootRewire = menu.addAction("Re-wire root joint attr to current selected joint")
meshSubmenu = menu.addMenu('EDIT RENDERMESHES >>')
addLOD0 = meshSubmenu.addAction("Add selected as LOD0 render meshes")
addLOD1 = meshSubmenu.addAction("Add selected as LOD1 render meshes")
addLOD2 = meshSubmenu.addAction("Add selected as LOD2 render meshes")
addLOD3 = meshSubmenu.addAction("Add selected as LOD3 render meshes")
addLOD4 = meshSubmenu.addAction("Add selected as LOD4 render meshes")
scriptSubmenu = menu.addMenu('ADD EXPORT SCRIPTS >>')
addScriptLOD0 = scriptSubmenu.addAction("Add LOD0 export script")
addScriptLOD1 = scriptSubmenu.addAction("Add LOD1 export script")
addScriptLOD2 = scriptSubmenu.addAction("Add LOD2 export script")
addScriptLOD3 = scriptSubmenu.addAction("Add LOD3 export script")
addScriptLOD4 = scriptSubmenu.addAction("Add LOD4 export script")
pos = self.export_tree.mapToGlobal(position)
action = menu.exec_(pos)
if action:
if action == rootRewire:
index = self.export_tree.selectedIndexes()[0]
uExportNode = self.export_tree.itemFromIndex(index).uExport.node
root = cmds.ls(sl=1)
if len(root) == 1:
self.connectRoot(uExportNode, root[0])
else:
cmds.error('Select a single joint, you == fail, bro. ' + str(root))
elif action in (addLOD0, addLOD1, addLOD2, addLOD3, addLOD4):
for index in self.export_tree.selectedIndexes():
uExportNode = self.export_tree.itemFromIndex(index).uExport
meshes = cmds.ls(sl=1)
#TODO: check if theyre actually meshes
if action == addLOD0: uExportNode.rendermeshes_LOD0 = meshes
if action == addLOD1: uExportNode.rendermeshes_LOD1 = meshes
if action == addLOD2: uExportNode.rendermeshes_LOD2 = meshes
if action == addLOD3: uExportNode.rendermeshes_LOD3 = meshes
if action == addLOD4: uExportNode.rendermeshes_LOD4 = meshes
elif action in (addScriptLOD0, addScriptLOD1, addScriptLOD2, addScriptLOD3, addScriptLOD4):
for index in self.export_tree.selectedIndexes():
uExportNode = self.export_tree.itemFromIndex(index).uExport
fileName,_ = QtWidgets.QFileDialog.getOpenFileName(self,
"Choose a Python Script", '',
"Python (*.py);;All Files (*)")
if fileName:
if action == addScriptLOD0: uExportNode.export_script_LOD0 = fileName
if action == addScriptLOD1: uExportNode.export_script_LOD1 = fileName
if action == addScriptLOD2: uExportNode.export_script_LOD2 = fileName
if action == addScriptLOD3: uExportNode.export_script_LOD3 = fileName
if action == addScriptLOD4: uExportNode.export_script_LOD4 = fileName
self.refreshUI()
def refreshUI(self):
start = time.time()
self.export_tree.clear()
self.missingFilesTree.clear()
self.uNodes = []
for node in self.getExportNodes():
self.uNodes.append(uExport(node))
self.buildExportTree(self.uNodes)
self.buildMissingFilesTree()
if self.p4CHK.isChecked():
if self.perforce:
self.getTexturesP4BTN.setEnabled(True)
self.getP4Workspaces()
# put export into the uExport class later
elapsed = (time.time() - start)
print 'uExport>>> Refreshed in %.2f seconds.' % elapsed
def buildExportTree(self, uNodes):
for uNode in uNodes:
red = QtGui.QColor(200, 75, 75, 255)
widRed = QtGui.QColor(200, 75, 75, 100)
blue = QtGui.QColor(50, 130, 210, 255)
widBlue = QtGui.QColor(50, 130, 210, 100)
#top level
wid1 = QtWidgets.QTreeWidgetItem()
font = wid1.font(0)
font.setPointSize(15)
wid1.setText(0,uNode.asset_name)
wid1.uExport = uNode
wid1.setText(1, uNode.version)
self.export_tree.addTopLevelItem(wid1)
wid1.setExpanded(True)
wid1.setFont(0,font)
font = wid1.font(0)
font.setPointSize(10)
wid1.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsSelectable)
wid1.setCheckState(0, QtCore.Qt.Checked)
wid1.setBackground(0, QtGui.QColor(widBlue))
#mesh branch
meshTop = QtWidgets.QTreeWidgetItem()
meshes = uNode.rendermeshes_LOD0
if meshes:
meshTop.setText(0, 'RENDER MESHES: (' + str(len(uNode.rendermeshes_ALL)) + ') LODS: (' + str(uNode.lodNum) + ')')
else:
meshTop.setText(0, 'RENDER MESHES: NONE')
meshTop.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable)
meshTop.setCheckState(0, QtCore.Qt.Checked)
wid1.addChild(meshTop)
meshTop.setExpanded(True)
allMeshRelated = []
#get mat info
start = time.time()
shaderDict = uNode.getShaderDict()
elapsed = (time.time() - start)
print 'uExport>>> Built shader dict for ' + uNode.asset_name + ' in %.2f seconds.' % elapsed
#meshes
lodDicts = uNode.getLodDicts()
if lodDicts:
for lodNum in lodDicts:
lodWid = QtWidgets.QTreeWidgetItem()
#get mesh info
meshes = lodDicts[lodNum]['meshes']
numMeshes = '0'
if meshes:
numMeshes = str(len(meshes))
else:
lodWid.setForeground(0,red)
continue
numShaders = 0
usedShaders = []
if shaderDict:
numShaders = len(shaderDict.keys())
for mat in shaderDict.keys():
for mesh in meshes:
if mesh in shaderDict[mat]:
usedShaders.append(mat)
else:
lodWid.setForeground(0,red)
wid1.setBackground(0, widRed)
usedShaders = set(usedShaders)
widText = 'LOD ' + str(lodNum) + ' (' + numMeshes + ' meshes) (' + str(len(usedShaders)) + ' materials)'
if lodDicts[lodNum]['export_script']:
widText += ' > Export Script: ' + lodDicts[lodNum]['export_script'].split('/')[-1]
lodWid.setText(0, widText)
#add metadata for later use
lodWid.lod = lodNum
lodWid.uExport = uNode
meshTop.addChild(lodWid)
#create mesh top widget
meshLodTop = QtWidgets.QTreeWidgetItem()
meshLodTop.setText(0, 'MESHES (' + numMeshes + ')')
lodWid.addChild(meshLodTop)
matLodTop = QtWidgets.QTreeWidgetItem()
if meshes:
for mesh in meshes:
meshWid = QtWidgets.QTreeWidgetItem()
meshWid.setText(0, mesh)
meshLodTop.addChild(meshWid)
if not findRelatedSkinCluster(mesh):
if self.isBlendshape(mesh):
meshWid.setForeground(0, blue)
meshWid.setText(0, mesh + ' (blendshape)')
else:
meshWid.setForeground(0, red)
wid1.setBackground(0, widRed)
meshWid.setText(0, mesh + ': NO SKINCLUSTER')
for item in getParents(meshWid):
item.setExpanded(True)
meshWid.selectMe = [mesh]
meshLodTop.selectMe = meshes
else:
meshWid = QtWidgets.QTreeWidgetItem()
meshWid.setText(0, 'NONE')
meshLodTop.addChild(meshWid)
#create mat top widget
matLodTop = QtWidgets.QTreeWidgetItem()
lodWid.addChild(matLodTop)
usedShaders = list(set(usedShaders))
for shader in usedShaders:
matWid = QtWidgets.QTreeWidgetItem()
matWid.setText(0, shader)
matWid.setText(1, str(shaderDict[shader]))
matLodTop.addChild(matWid)
matWid.selectMe = [shader]
self.export_tree.sortItems(0, QtCore.Qt.SortOrder(0))
matLodTop.setText(0, 'MATERIALS (' + str(len(usedShaders)) + ')')
matLodTop.selectMe = usedShaders
lodWid.selectMe = usedShaders + meshes
allMeshRelated.extend(lodWid.selectMe)
meshTop.selectMe = allMeshRelated
#anim branch
animTop = QtWidgets.QTreeWidgetItem()
animTop.selectMe = uNode.joints
if uNode.export_root: