simplex-solver 3.0.18__37-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. pysimplex.pyd +0 -0
  2. simplex_solver-3.0.18.dist-info/METADATA +87 -0
  3. simplex_solver-3.0.18.dist-info/RECORD +81 -0
  4. simplex_solver-3.0.18.dist-info/WHEEL +5 -0
  5. simplex_solver-3.0.18.dist-info/licenses/LICENSE +165 -0
  6. simplexui/__init__.py +54 -0
  7. simplexui/channelBox.py +862 -0
  8. simplexui/comboCheckDialog.py +335 -0
  9. simplexui/commands/__init__.py +16 -0
  10. simplexui/commands/alembicCommon.py +1045 -0
  11. simplexui/commands/applyCorrectives.py +455 -0
  12. simplexui/commands/buildIceXML.py +443 -0
  13. simplexui/commands/correctiveInterface.py +271 -0
  14. simplexui/commands/expandedExport.py +435 -0
  15. simplexui/commands/hdf5Convert.py +62 -0
  16. simplexui/commands/mayaCorrectiveInterface.py +164 -0
  17. simplexui/commands/mesh.py +1086 -0
  18. simplexui/commands/reorderSimplexPoints.py +103 -0
  19. simplexui/commands/rigidAlign.py +103 -0
  20. simplexui/commands/setDelta.xsicompound +60 -0
  21. simplexui/commands/smpxBlend.py +634 -0
  22. simplexui/commands/unsubdivide.py +1232 -0
  23. simplexui/commands/uvTransfer.py +986 -0
  24. simplexui/commands/xsiCorrectiveInterface.py +136 -0
  25. simplexui/dragFilter.py +299 -0
  26. simplexui/falloffDialog.py +476 -0
  27. simplexui/img/ChefHead.png +0 -0
  28. simplexui/img/frozen.png +0 -0
  29. simplexui/interface/__init__.py +30 -0
  30. simplexui/interface/dummyInterface.py +1564 -0
  31. simplexui/interface/mayaInterface.py +3197 -0
  32. simplexui/interface/xsiInterface.py +2944 -0
  33. simplexui/interfaceModel.py +1040 -0
  34. simplexui/interfaceModelTrees.py +439 -0
  35. simplexui/interfaceModel_Test.py +259 -0
  36. simplexui/items/__init__.py +26 -0
  37. simplexui/items/accessor.py +217 -0
  38. simplexui/items/combo.py +855 -0
  39. simplexui/items/falloff.py +780 -0
  40. simplexui/items/group.py +295 -0
  41. simplexui/items/progression.py +745 -0
  42. simplexui/items/shape.py +444 -0
  43. simplexui/items/simplex.py +1747 -0
  44. simplexui/items/slider.py +741 -0
  45. simplexui/items/stack.py +156 -0
  46. simplexui/items/traversal.py +969 -0
  47. simplexui/main.pyw +22 -0
  48. simplexui/menu/__init__.py +73 -0
  49. simplexui/menu/dummyPlugins/__init__.py +16 -0
  50. simplexui/menu/genericPlugins/__init__.py +16 -0
  51. simplexui/menu/genericPlugins/_builtins.py +260 -0
  52. simplexui/menu/genericPlugins/checkPossibleCombos.py +47 -0
  53. simplexui/menu/genericPlugins/exportSplit.py +61 -0
  54. simplexui/menu/genericPlugins/showFalloffs.py +24 -0
  55. simplexui/menu/genericPlugins/showTraversals.py +24 -0
  56. simplexui/menu/genericPlugins/simplexUvTransfer.py +109 -0
  57. simplexui/menu/genericPlugins/unsubdivide.py +71 -0
  58. simplexui/menu/mayaPlugins/__init__.py +16 -0
  59. simplexui/menu/mayaPlugins/exportOther.py +45 -0
  60. simplexui/menu/mayaPlugins/extractProgressives.py +67 -0
  61. simplexui/menu/mayaPlugins/freezeCombo.py +251 -0
  62. simplexui/menu/mayaPlugins/generateShapeIncrementals.py +100 -0
  63. simplexui/menu/mayaPlugins/importObjs.py +196 -0
  64. simplexui/menu/mayaPlugins/linearizeTraversal.py +49 -0
  65. simplexui/menu/mayaPlugins/makeShelfBtn.py +69 -0
  66. simplexui/menu/mayaPlugins/relaxToSelection.py +77 -0
  67. simplexui/menu/mayaPlugins/reloadDefinition.py +34 -0
  68. simplexui/menu/mayaPlugins/snapToNeutral.py +74 -0
  69. simplexui/menu/mayaPlugins/softSelectToCluster.py +204 -0
  70. simplexui/menu/mayaPlugins/tweakMix.py +138 -0
  71. simplexui/menu/mayaPlugins/updateRestShape.py +107 -0
  72. simplexui/menu/xsiPlugins/__init__.py +16 -0
  73. simplexui/simplexDialog.py +1391 -0
  74. simplexui/travCheckDialog.py +393 -0
  75. simplexui/traversalDialog.py +277 -0
  76. simplexui/ui/comboCheckDialog.ui +475 -0
  77. simplexui/ui/falloffDialog.ui +243 -0
  78. simplexui/ui/simplexDialog.ui +1458 -0
  79. simplexui/ui/travCheckDialog.ui +488 -0
  80. simplexui/ui/traversalDialog.ui +532 -0
  81. simplexui/utils.py +320 -0
@@ -0,0 +1,3197 @@
1
+ # Copyright 2016, Blur Studio
2
+ #
3
+ # This file is part of Simplex.
4
+ #
5
+ # Simplex is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU Lesser General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # Simplex is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU Lesser General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU Lesser General Public License
16
+ # along with Simplex. If not, see <http://www.gnu.org/licenses/>.
17
+
18
+ # pylint: disable=invalid-name
19
+ from __future__ import absolute_import
20
+
21
+ import json
22
+ import re
23
+ from contextlib import contextmanager
24
+ from ctypes import c_double, c_float
25
+ from functools import wraps
26
+
27
+ import maya.cmds as cmds
28
+ import maya.OpenMaya as om
29
+ import six
30
+ from alembic.AbcGeom import GeometryScope, OPolyMeshSchemaSample, OV2fGeomParamSample
31
+ from imath import IntArray, UnsignedIntArray, V2fArray, V3fArray
32
+ from six.moves import map, range, zip
33
+
34
+ from ..commands.alembicCommon import mkSampleVertexPoints
35
+ from Qt import QtCore
36
+ from Qt.QtCore import Signal
37
+ from Qt.QtWidgets import (
38
+ QApplication,
39
+ QDialog,
40
+ QMainWindow,
41
+ QMessageBox,
42
+ QSplashScreen,
43
+ )
44
+
45
+ try:
46
+ import numpy as np
47
+ except ImportError:
48
+ np = None
49
+
50
+ try:
51
+ import imathnumpy
52
+ except ImportError:
53
+ imathnumpy = None
54
+
55
+
56
+ # UNDO STACK INTEGRATION
57
+ @contextmanager
58
+ def undoContext(inst=None):
59
+ """
60
+
61
+ Parameters
62
+ ----------
63
+ inst :
64
+ (Default value = None)
65
+
66
+ Returns
67
+ -------
68
+
69
+ """
70
+ if inst is None:
71
+ DCC.staticUndoOpen()
72
+ else:
73
+ inst.undoOpen()
74
+ try:
75
+ yield
76
+ finally:
77
+ if inst is None:
78
+ DCC.staticUndoClose()
79
+ else:
80
+ inst.undoClose()
81
+
82
+
83
+ def undoable(f):
84
+ """
85
+
86
+ Parameters
87
+ ----------
88
+ f :
89
+
90
+
91
+ Returns
92
+ -------
93
+
94
+ """
95
+
96
+ @wraps(f)
97
+ def stacker(*args, **kwargs):
98
+ """
99
+
100
+ Parameters
101
+ ----------
102
+ *args :
103
+
104
+ **kwargs :
105
+
106
+
107
+ Returns
108
+ -------
109
+
110
+ """
111
+ inst = None
112
+ if args and isinstance(args[0], DCC):
113
+ inst = args[0]
114
+ with undoContext(inst):
115
+ return f(*args, **kwargs)
116
+
117
+ return stacker
118
+
119
+
120
+ # temporarily disconnect inputs from a list of nodes and plugs
121
+ def doDisconnect(targets, testCnxType=("double", "float")):
122
+ """
123
+
124
+ Parameters
125
+ ----------
126
+ targets :
127
+
128
+ testCnxType :
129
+ (Default value = ("double")
130
+ "float") :
131
+
132
+
133
+ Returns
134
+ -------
135
+
136
+ """
137
+ if not isinstance(targets, (list, tuple)):
138
+ targets = [targets]
139
+ targets = list(set(targets))
140
+ cnxs = {}
141
+ for target in targets:
142
+ tcnx = {}
143
+ cnxs[target] = tcnx
144
+
145
+ cnx = cmds.listConnections(
146
+ target, plugs=True, destination=False, source=True, connections=True
147
+ )
148
+ if cnx is None:
149
+ cnx = []
150
+
151
+ for i in range(0, len(cnx), 2):
152
+ cnxType = cmds.getAttr(cnx[i], type=True)
153
+ if cnxType not in testCnxType:
154
+ continue
155
+ tcnx[cnx[i + 1]] = cnx[i]
156
+ cmds.disconnectAttr(cnx[i + 1], cnx[i])
157
+ return cnxs
158
+
159
+
160
+ def doReconnect(cnxs):
161
+ """
162
+
163
+ Parameters
164
+ ----------
165
+ cnxs :
166
+
167
+
168
+ Returns
169
+ -------
170
+
171
+ """
172
+ for tdict in six.itervalues(cnxs):
173
+ for s, d in six.iteritems(tdict):
174
+ if not cmds.isConnected(s, d):
175
+ cmds.connectAttr(s, d, force=True)
176
+
177
+
178
+ @contextmanager
179
+ def disconnected(targets, testCnxType=("double", "float")):
180
+ """
181
+
182
+ Parameters
183
+ ----------
184
+ targets :
185
+
186
+ testCnxType :
187
+ (Default value = ("double")
188
+ "float") :
189
+
190
+
191
+ Returns
192
+ -------
193
+
194
+ """
195
+ cnxs = doDisconnect(targets, testCnxType=testCnxType)
196
+ try:
197
+ yield cnxs
198
+ finally:
199
+ doReconnect(cnxs)
200
+
201
+
202
+ class DCC(object):
203
+ """ """
204
+
205
+ program = "maya"
206
+
207
+ def __init__(self, simplex, stack=None):
208
+ if not cmds.pluginInfo("simplex_maya", query=True, loaded=True):
209
+ cmds.loadPlugin("simplex_maya")
210
+ self.undoDepth = 0
211
+ self.name = None # the name of the system
212
+ self.mesh = None # the mesh object with the system
213
+ self.ctrl = None # the object that has all the controllers on it
214
+ self.shapeNode = None # the deformer object
215
+ self.op = None # the simplex object
216
+ self.simplex = simplex # the abstract representation of the setup
217
+ self._live = True
218
+ self.sliderMul = self.simplex.sliderMul
219
+
220
+ # def __deepcopy__(self, memo):
221
+ # '''
222
+ # I don't actually need to define this here because I know that
223
+ # all of the maya "objects" store here are just strings
224
+ # But if they *weren't* (like in XSI) I would need to skip
225
+ # the maya objects when deepcopying, otherwise I might access
226
+ # a deleted scene node and crash everything
227
+ # And if we did skip things, I would also need to store a
228
+ # persistent accessor to use in case we get back to here
229
+ # through an undo
230
+ # '''
231
+ # pass
232
+
233
+ def _checkAllShapeValidity(self, shapeNames):
234
+ """Check shapes to see if they exist, and either gather the missing files, or
235
+ Load the proper data onto the shapes
236
+
237
+ Parameters
238
+ ----------
239
+ shapeNames :
240
+
241
+
242
+ Returns
243
+ -------
244
+
245
+ """
246
+ # Keep the set ordered, but make a set for quick checking
247
+ missingNameSet = set()
248
+ missingNames = []
249
+ seen = set()
250
+
251
+ # Get the blendshape weight names
252
+ try:
253
+ # GOOD GOD. This is because in maya 2016.5, if you delete a multi-instance
254
+ # then listAttr, *it lists the deleted ones, and skips the ones at the end*
255
+ # So I have to use aliasAttr and filter for the weights
256
+ aliases = cmds.aliasAttr(self.shapeNode, query=True) or []
257
+ attrs = [
258
+ aliases[i]
259
+ for i in range(0, len(aliases), 2)
260
+ if aliases[i + 1].startswith("weight[")
261
+ ]
262
+ attrs = set(attrs)
263
+
264
+ except ValueError:
265
+ attrs = set()
266
+
267
+ for shapeName in shapeNames:
268
+ if shapeName in seen:
269
+ continue
270
+ seen.add(shapeName)
271
+ if shapeName not in attrs:
272
+ if shapeName not in missingNameSet:
273
+ missingNameSet.add(shapeName)
274
+ missingNames.append(shapeName)
275
+ return missingNames, len(attrs)
276
+
277
+
278
+ @classmethod
279
+ def _removeExtraShapeNodes(cls, tfm):
280
+ shapeNodes = cmds.listRelatives(tfm, shapes=True, noIntermediate=True)
281
+ if len(shapeNodes) > 1:
282
+ keeper = None
283
+ todel = []
284
+ for sn in shapeNodes:
285
+ tfmChk = ''.join(sn.rsplit('Shape', 1))
286
+ if tfmChk == tfm:
287
+ keeper = sn
288
+ else:
289
+ todel.append(sn)
290
+ if keeper is not None:
291
+ cmds.delete(todel)
292
+
293
+
294
+ def preLoad(self, simp, simpDict, create=True, pBar=None):
295
+ """
296
+
297
+ Parameters
298
+ ----------
299
+ simp :
300
+
301
+ simpDict :
302
+
303
+ create :
304
+ (Default value = True)
305
+ pBar :
306
+ (Default value = None)
307
+
308
+ Returns
309
+ -------
310
+
311
+ """
312
+ cmds.undoInfo(state=False)
313
+ try:
314
+ if pBar is not None:
315
+ pBar.setLabelText("Loading Connections")
316
+ QApplication.processEvents()
317
+ ev = simpDict["encodingVersion"]
318
+
319
+ shapeNames = simpDict.get("shapes")
320
+ if not shapeNames:
321
+ return
322
+
323
+ if ev > 1:
324
+ shapeNames = [i["name"] for i in shapeNames]
325
+
326
+ toMake, nextIndex = self._checkAllShapeValidity(shapeNames)
327
+
328
+ if not toMake:
329
+ return
330
+
331
+ if not create:
332
+ if pBar is not None:
333
+ msg = "\n".join(
334
+ [
335
+ "Some shapes are Missing:",
336
+ ", ".join(toMake),
337
+ "",
338
+ "Create them?",
339
+ ]
340
+ )
341
+ btns = QMessageBox.Yes | QMessageBox.Cancel
342
+ bret = QMessageBox.question(pBar, "Missing Shapes", msg, btns)
343
+ if not bret & QMessageBox.Yes:
344
+ raise RuntimeError("Missing Shapes: {}".format(toMake))
345
+ else:
346
+ raise RuntimeError("Missing Shapes: {}".format(toMake))
347
+
348
+ if pBar is not None:
349
+ spacer = "_" * max(list(map(len, toMake)))
350
+ pBar.setMaximum(len(toMake))
351
+ pBar.setLabelText("Creating Empty Shape:\n{0}".format(spacer))
352
+ pBar.setValue(0)
353
+ QApplication.processEvents()
354
+
355
+ baseShape = cmds.duplicate(self.mesh)[0]
356
+ cmds.delete(baseShape, constructionHistory=True)
357
+ self._removeExtraShapeNodes(baseShape)
358
+
359
+ for i, shapeName in enumerate(toMake):
360
+ if pBar is not None:
361
+ pBar.setLabelText("Creating Empty Shape:\n{0}".format(shapeName))
362
+ pBar.setValue(i)
363
+ QApplication.processEvents()
364
+
365
+ baseShape = cmds.rename(baseShape, shapeName)
366
+
367
+ index = self._firstAvailableIndex()
368
+ cmds.blendShape(
369
+ self.shapeNode, edit=True, target=(self.mesh, index, baseShape, 1.0)
370
+ )
371
+ weightAttr = "{0}.weight[{1}]".format(self.shapeNode, index)
372
+ thing = cmds.ls(weightAttr)[0]
373
+
374
+ cmds.connectAttr("{0}.weights[{1}]".format(self.op, nextIndex), thing)
375
+ nextIndex += 1
376
+
377
+ cmds.delete(baseShape)
378
+ except Exception:
379
+ cmds.undoInfo(state=True)
380
+ raise
381
+
382
+
383
+ def postLoad(self, simp, preRet):
384
+ """
385
+
386
+ Parameters
387
+ ----------
388
+ simp :
389
+
390
+ preRet :
391
+
392
+ Returns
393
+ -------
394
+
395
+ """
396
+ cmds.undoInfo(state=True)
397
+
398
+ def checkForErrors(self, window):
399
+ """ Check for any DCC specific errors
400
+
401
+ Parameters
402
+ ----------
403
+ window : QMainWindow
404
+ The simplex window
405
+ """
406
+ shapeNodes = cmds.listRelatives(self.mesh, shapes=True, noIntermediate=True)
407
+ if len(shapeNodes) > 1:
408
+ msg = (
409
+ "The current mesh has multiple shape nodes.",
410
+ "The UI will still mostly work, but extracting/connecting shapes"
411
+ "may fail in unexpected ways."
412
+ )
413
+ QMessageBox.warning(window, "Multiple Shape Nodes", '\n'.join(msg))
414
+
415
+ # System IO
416
+ @undoable
417
+ def loadNodes(self, simp, thing, create=True, pBar=None):
418
+ """Create a new system based on the simplex tree
419
+ Build any DCC objects that are missing if create=True
420
+ Raises a runtime error if missing objects are found and
421
+ create=False
422
+
423
+ Parameters
424
+ ----------
425
+ simp :
426
+
427
+ thing :
428
+
429
+ create :
430
+ (Default value = True)
431
+ pBar :
432
+ (Default value = None)
433
+
434
+ Returns
435
+ -------
436
+
437
+ """
438
+ self.name = simp.name
439
+ self.mesh = thing
440
+
441
+ # Find all blendshapes in the history
442
+ rawShapeNodes = [
443
+ h for h in cmds.listHistory(thing) if cmds.nodeType(h) == "blendShape"
444
+ ]
445
+
446
+ # Find any simplex ops connected to the history
447
+ # that have the given name
448
+ ops = []
449
+ for sn in rawShapeNodes:
450
+ op = cmds.listConnections(
451
+ "{0}.{1}".format(sn, "message"),
452
+ source=False,
453
+ destination=True,
454
+ type="simplex_maya",
455
+ )
456
+ if not op:
457
+ continue
458
+ op = op[0]
459
+ js = cmds.getAttr(op + ".definition") or ""
460
+ sn = json.loads(js).get("systemName")
461
+ if sn == self.name:
462
+ ops.append(op)
463
+
464
+ if len(ops) > 1:
465
+ raise RuntimeError(
466
+ "Found too many Simplex systems with the same name on the same object"
467
+ )
468
+
469
+ # Back-select the shape nodes connected to those ops
470
+ shapeNodes = []
471
+ for op in ops:
472
+ sn = cmds.listConnections(
473
+ "{0}.{1}".format(op, "shapeMsg"),
474
+ source=True,
475
+ destination=False,
476
+ type="blendShape",
477
+ )
478
+ if sn:
479
+ shapeNodes.append(sn[0])
480
+
481
+ # Find the msg connected control object
482
+ ctrlCnx = []
483
+ for op in ops:
484
+ ccnx = cmds.listConnections(
485
+ "{0}.{1}".format(op, "ctrlMsg"),
486
+ source=True,
487
+ destination=False,
488
+ )
489
+ if ccnx:
490
+ ctrlCnx.append(ccnx[0])
491
+
492
+ if not shapeNodes:
493
+ if not create:
494
+ raise RuntimeError(
495
+ "Blendshape operator not found with creation turned off"
496
+ )
497
+ # Unlock the normals on the rest head because blendshapes don't work with locked normals
498
+ # and you can't really do this after the blendshape has been created
499
+ intermediates = [
500
+ shp
501
+ for shp in cmds.listRelatives(self.mesh, shapes=True, path=True)
502
+ if cmds.getAttr(shp + ".intermediateObject")
503
+ ]
504
+ meshToFreeze = self.mesh if not intermediates else intermediates[0]
505
+ isIntermediate = cmds.getAttr(meshToFreeze + ".intermediateObject")
506
+ cmds.polyNormalPerVertex(meshToFreeze, ufn=True)
507
+ cmds.polySoftEdge(meshToFreeze, a=180, ch=1)
508
+ cmds.setAttr(meshToFreeze + ".intermediateObject", 0)
509
+ cmds.delete(meshToFreeze, constructionHistory=True)
510
+ cmds.setAttr(meshToFreeze + ".intermediateObject", isIntermediate)
511
+
512
+ self.shapeNode = cmds.blendShape(
513
+ self.mesh, name="{0}_BS".format(self.name), frontOfChain=True
514
+ )[0]
515
+ else:
516
+ self.shapeNode = shapeNodes[0]
517
+
518
+ # find/build the operator
519
+ # GODDAMMIT, why does maya return None instead of an empty list?????
520
+ if not ops:
521
+ if not create:
522
+ raise RuntimeError(
523
+ "Simplex operator not found with creation turned off"
524
+ )
525
+ self.op = cmds.createNode("simplex_maya", name=self.name)
526
+ cmds.addAttr(self.op, longName="revision", attributeType="long")
527
+ cmds.addAttr(self.op, longName="shapeMsg", attributeType="message")
528
+ cmds.addAttr(self.op, longName="ctrlMsg", attributeType="message")
529
+ cmds.connectAttr(
530
+ "{0}.{1}".format(self.shapeNode, "message"),
531
+ "{0}.{1}".format(self.op, "shapeMsg"),
532
+ )
533
+ else:
534
+ self.op = ops[0]
535
+
536
+ # find/build the ctrl object
537
+ if not ctrlCnx:
538
+ if not create:
539
+ raise RuntimeError("Control object not found with creation turned off")
540
+ self.ctrl = cmds.group(empty=True, name="{0}_CTRL".format(self.name))
541
+ for attr in [
542
+ ".tx",
543
+ ".ty",
544
+ ".tz",
545
+ ".rx",
546
+ ".ry",
547
+ ".rz",
548
+ ".sx",
549
+ ".sy",
550
+ ".sz",
551
+ ".v",
552
+ ]:
553
+ cmds.setAttr(self.ctrl + attr, keyable=False, channelBox=False)
554
+ cmds.addAttr(self.ctrl, longName="solver", attributeType="message")
555
+ cmds.connectAttr(
556
+ "{0}.{1}".format(self.ctrl, "solver"),
557
+ "{0}.{1}".format(self.op, "ctrlMsg"),
558
+ )
559
+ else:
560
+ self.ctrl = ctrlCnx[0]
561
+
562
+ def getShapeThing(self, shapeName):
563
+ """
564
+
565
+ Parameters
566
+ ----------
567
+ shapeName :
568
+
569
+
570
+ Returns
571
+ -------
572
+
573
+ """
574
+ s = cmds.ls("{0}.{1}".format(self.shapeNode, shapeName))
575
+ if not s:
576
+ return None
577
+ return s[0]
578
+
579
+ def getSliderThing(self, sliderName):
580
+ """
581
+
582
+ Parameters
583
+ ----------
584
+ sliderName :
585
+
586
+
587
+ Returns
588
+ -------
589
+
590
+ """
591
+ things = cmds.ls("{0}.{1}".format(self.ctrl, sliderName))
592
+ if not things:
593
+ return None
594
+ return things[0]
595
+
596
+ @staticmethod
597
+ @undoable
598
+ def buildRestAbc(abcMesh, name):
599
+ """
600
+
601
+ Parameters
602
+ ----------
603
+ abcMesh :
604
+
605
+ name :
606
+
607
+
608
+ Returns
609
+ -------
610
+
611
+ """
612
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
613
+ cmds.loadPlugin("AbcImport")
614
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
615
+ raise RuntimeError("Unable to load the AbcImport plugin")
616
+
617
+ abcPath = str(abcMesh.getArchive())
618
+
619
+ abcNode = cmds.createNode("AlembicNode")
620
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
621
+ cmds.setAttr(abcNode + ".speed", 24) # Is this needed anymore?
622
+ cmds.setAttr(abcNode + ".time", 0)
623
+
624
+ importHead = cmds.polySphere(
625
+ name="{0}_SIMPLEX".format(name), constructionHistory=False
626
+ )[0]
627
+ importHeadShape = [i for i in cmds.listRelatives(importHead, shapes=True)][0]
628
+
629
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
630
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
631
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
632
+ cmds.sets(importHead, e=True, forceElement="initialShadingGroup")
633
+ cmds.delete(abcNode)
634
+ return importHead
635
+
636
+ @staticmethod
637
+ def vertCount(mesh):
638
+ return cmds.polyEvaluate(mesh, vertex=True)
639
+
640
+ @undoable
641
+ def loadAbc(self, abcMesh, js, pBar=None):
642
+ """
643
+
644
+ Parameters
645
+ ----------
646
+ abcMesh :
647
+
648
+ js :
649
+
650
+ pBar :
651
+ (Default value = None)
652
+
653
+ Returns
654
+ -------
655
+
656
+ """
657
+ # UGH, I *REALLY* hate that this is faster
658
+ # But if I want to be "pure" about it, I should just bite the bullet
659
+ # and do the direct alembic manipulation in C++
660
+
661
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
662
+ cmds.loadPlugin("AbcImport")
663
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
664
+ raise RuntimeError("Unable to load the AbcImport plugin")
665
+
666
+ abcPath = str(abcMesh.getArchive())
667
+
668
+ abcNode = cmds.createNode("AlembicNode")
669
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
670
+
671
+ timeUnits = {
672
+ "game": 15,
673
+ "film": 24,
674
+ "pal": 25,
675
+ "ntsc": 30,
676
+ "show": 48,
677
+ "palf": 50,
678
+ "ntscf": 60,
679
+ }
680
+
681
+ fps = cmds.currentUnit(time=True, query=True)
682
+ if isinstance(fps, six.string_types):
683
+ if fps.endswith("fps"):
684
+ fps = fps[:-3]
685
+ if fps in timeUnits:
686
+ fps = timeUnits[fps]
687
+ fps = float(fps)
688
+
689
+ cmds.setAttr(abcNode + ".speed", fps)
690
+
691
+ shapes = js["shapes"]
692
+ shapeDict = {i.name: i for i in self.simplex.shapes}
693
+
694
+ if js["encodingVersion"] > 1:
695
+ shapes = [i["name"] for i in shapes]
696
+
697
+ importHead = cmds.polySphere(name="importHead", constructionHistory=False)[0]
698
+ importHeadShape = [i for i in cmds.listRelatives(importHead, shapes=True)][0]
699
+
700
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
701
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
702
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
703
+
704
+ importRest = cmds.duplicate(self.mesh, name="importRest")[0]
705
+ cmds.delete(importRest, constructionHistory=True)
706
+ self._removeExtraShapeNodes(importRest)
707
+
708
+ importBS = cmds.blendShape(importRest, importHead)[0]
709
+ cmds.blendShape(importBS, edit=True, weight=[(0, 1.0)])
710
+ # Maybe get shapeNode from self.mesh??
711
+ importOrig = [
712
+ i for i in cmds.listRelatives(importHead, shapes=True) if i.endswith("Orig")
713
+ ][0]
714
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importOrig + ".inMesh")
715
+ cmds.delete(importRest)
716
+
717
+ if pBar is not None:
718
+ pBar.show()
719
+ pBar.setMaximum(len(shapes))
720
+ longName = max(shapes, key=len)
721
+ pBar.setValue(1)
722
+ pBar.setLabelText("Loading:\n{0}".format("_" * len(longName)))
723
+
724
+ for i, shapeName in enumerate(shapes):
725
+ if pBar is not None:
726
+ pBar.setValue(i)
727
+ pBar.setLabelText("Loading:\n{0}".format(shapeName))
728
+ QApplication.processEvents()
729
+ if pBar.wasCanceled():
730
+ return
731
+ index = self.getShapeIndex(shapeDict[shapeName])
732
+ cmds.setAttr(abcNode + ".time", i)
733
+
734
+ outAttr = "{0}.worldMesh[0]".format(importHead)
735
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(
736
+ self.shapeNode, index
737
+ )
738
+ inAttr = "{0}.inputTargetItem[6000].inputGeomTarget".format(tgn)
739
+
740
+ cmds.connectAttr(outAttr, inAttr, force=True)
741
+ cmds.disconnectAttr(outAttr, inAttr)
742
+ cmds.delete(abcNode)
743
+ cmds.delete(importHead)
744
+
745
+ def getAllShapeVertices(self, shapes, pBar=None):
746
+ """
747
+
748
+ Parameters
749
+ ----------
750
+ shapes :
751
+
752
+ pBar :
753
+ (Default value = None)
754
+
755
+ Returns
756
+ -------
757
+
758
+ """
759
+ sl = om.MSelectionList()
760
+ sl.add(self.mesh)
761
+ thing = om.MDagPath()
762
+ sl.getDagPath(0, thing)
763
+ meshFn = om.MFnMesh(thing)
764
+ ptCount = meshFn.numVertices()
765
+ with disconnected(self.shapeNode) as cnx:
766
+ shapeCnx = cnx[self.shapeNode]
767
+ for v in six.itervalues(shapeCnx):
768
+ cmds.setAttr(v, 0.0)
769
+
770
+ if pBar is not None:
771
+ # find the longest name for displaying stuff
772
+ sns = "_" * max(list(map(len, [s.name for s in shapes])))
773
+ pBar.setLabelText("Getting Shape:\n{0}".format(sns))
774
+ pBar.setMaximum(len(shapes))
775
+ QApplication.processEvents()
776
+
777
+ for i, shape in enumerate(shapes):
778
+ if pBar is not None:
779
+ pBar.setLabelText("Getting Shape:\n{0}".format(shape.name))
780
+ pBar.setValue(i)
781
+ QApplication.processEvents()
782
+
783
+ cmds.setAttr(shape.thing, 1.0)
784
+
785
+ if np is not None:
786
+ rawPts = meshFn.getRawPoints()
787
+ cta = (c_float * ptCount * 3).from_address(int(rawPts))
788
+ out = np.ctypeslib.as_array(cta)
789
+ out = np.copy(out)
790
+ out = out.reshape((-1, 3))
791
+ else:
792
+ flatverts = cmds.xform(
793
+ "{0}.vtx[*]".format(self.mesh),
794
+ translation=1,
795
+ query=1,
796
+ worldSpace=False,
797
+ )
798
+ args = [iter(flatverts)] * 3
799
+ out = list(zip(*args))
800
+
801
+ cmds.setAttr(shape.thing, 0.0)
802
+ shape.verts = out
803
+
804
+ def getShapeVertices(self, shape):
805
+ """
806
+
807
+ Parameters
808
+ ----------
809
+ shape :
810
+
811
+ Returns
812
+ -------
813
+
814
+ """
815
+ with disconnected(self.shapeNode) as cnx:
816
+ shapeCnx = cnx[self.shapeNode]
817
+ for v in six.itervalues(shapeCnx):
818
+ cmds.setAttr(v, 0.0)
819
+ cmds.setAttr(shape.thing, 1.0)
820
+ if np is None:
821
+ flatverts = cmds.xform(
822
+ "{0}.vtx[*]".format(self.mesh),
823
+ translation=1,
824
+ query=1,
825
+ worldSpace=False,
826
+ )
827
+ args = [iter(flatverts)] * 3
828
+ out = list(zip(*args))
829
+ else:
830
+ out = self.getNumpyShape(self.mesh)
831
+ return out
832
+
833
+ def pushAllShapeVertices(self, shapes, pBar=None):
834
+ """
835
+
836
+ Parameters
837
+ ----------
838
+ shapes :
839
+
840
+ pBar :
841
+ (Default value = None)
842
+
843
+ Returns
844
+ -------
845
+
846
+ """
847
+ # take all the verts stored on the shapes
848
+ # and push them back to the DCC
849
+ for shape in shapes:
850
+ self.pushShapeVertices(shape)
851
+
852
+ def pushShapeVertices(self, shape):
853
+ """
854
+
855
+ Parameters
856
+ ----------
857
+ shape :
858
+
859
+
860
+ Returns
861
+ -------
862
+
863
+ """
864
+ # Push the vertices for a specific shape back to the DCC
865
+ pass
866
+
867
+ @staticmethod
868
+ def getMeshTopology(mesh, uvName=None):
869
+ """Get the topology of a mesh
870
+
871
+ Parameters
872
+ ----------
873
+ mesh : object
874
+ The DCC Mesh to read
875
+ uvName : str, optional
876
+ The name of the uv set to read
877
+
878
+ Returns
879
+ -------
880
+ np.array :
881
+ The vertex array
882
+ np.array :
883
+ The "faces" array
884
+ np.array :
885
+ The "counts" array
886
+ np.array :
887
+ The uv positions
888
+ np.array :
889
+ The "uvFaces" array
890
+ """
891
+ # Get the MDagPath from the name of the mesh
892
+ sl = om.MSelectionList()
893
+ sl.add(mesh)
894
+ thing = om.MDagPath()
895
+ sl.getDagPath(0, thing)
896
+ meshFn = om.MFnMesh(thing)
897
+
898
+ vts = om.MPointArray()
899
+ meshFn.getPoints(vts, om.MSpace.kObject)
900
+ verts = [(vts[i].x, vts[i].y, vts[i].z) for i in range(vts.length())]
901
+
902
+ faces = []
903
+ counts = []
904
+ rawUvFaces = []
905
+
906
+ vIdx = om.MIntArray()
907
+
908
+ util = om.MScriptUtil()
909
+ util.createFromInt(0)
910
+ uvIdxPtr = util.asIntPtr()
911
+ uArray = om.MFloatArray()
912
+ vArray = om.MFloatArray()
913
+ meshFn.getUVs(uArray, vArray)
914
+ hasUvs = uArray.length() > 0
915
+
916
+ for i in range(meshFn.numPolygons()):
917
+ meshFn.getPolygonVertices(i, vIdx)
918
+ face = []
919
+ for j in reversed(range(vIdx.length())):
920
+ face.append(vIdx[j])
921
+ if hasUvs:
922
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
923
+ uvIdx = util.getInt(uvIdxPtr)
924
+ if uvIdx >= uArray.length() or uvIdx < 0:
925
+ uvIdx = 0
926
+ rawUvFaces.append(uvIdx)
927
+
928
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
929
+ faces.extend(face)
930
+ counts.append(vIdx.length())
931
+
932
+ if hasUvs:
933
+ uvs = [(uArray[i], vArray[i]) for i in range(len(vArray))]
934
+ uvFaces = rawUvFaces
935
+ else:
936
+ uvs = None
937
+ uvFaces = None
938
+
939
+ return verts, faces, counts, uvs, uvFaces
940
+
941
+ def loadMeshTopology(self):
942
+ """ """
943
+ self._faces, self._counts, self._uvs = self.getAbcFaces(self.mesh)
944
+
945
+ @classmethod
946
+ def getNumpyShape(cls, mesh, world=False):
947
+ """Get the np.array shape of the mesh connected to the smpx
948
+
949
+ Parameters
950
+ ----------
951
+ mesh : str
952
+ The name of the maya shape object
953
+ world : bool
954
+ Whether to get the points in worldspace, or local space
955
+
956
+ Returns
957
+ -------
958
+ : np.array
959
+ The point positions of the mesh
960
+
961
+ """
962
+ # This method uses some neat tricks to get data out of an MPointArray
963
+ # Basically, you get an MScriptUtil pointer to the MPointArray data
964
+ # Then you get a ctypes pointer to the MScriptUtil pointer
965
+ # Then you get a numpy pointer to the ctypes pointer
966
+ # Because these are all pointers, you're looking at the exact same
967
+ # data in memory ... So just copy the data out to a numpy array
968
+ # See: https://gist.github.com/tbttfox/9ca775bf629c7a1285c27c8d9d961bca
969
+
970
+ # Get the MPointArray of the mesh
971
+ vts = cls._getMeshVertices(mesh, world=world)
972
+
973
+ # Get the double4 pointer from the mpointarray
974
+ count = vts.length()
975
+ cc = count * 4
976
+ util = om.MScriptUtil()
977
+ util.createFromList([0.0] * cc, cc)
978
+ ptr = util.asDouble4Ptr()
979
+ vts.get(ptr)
980
+
981
+ # Build a ctypes double4 pointer
982
+ cdata = (c_double * 4) * count
983
+
984
+ # int(ptr) gives the memory address
985
+ cta = cdata.from_address(int(ptr))
986
+
987
+ # This makes numpy look at the same memory as the ctypes array
988
+ # so we can both read from and write to that data through numpy
989
+ npArray = np.ctypeslib.as_array(cta)
990
+
991
+ # Copy the data out of the numpy array, which is looking
992
+ # into the cdata array, which is looking into the ptr array
993
+ return npArray[..., :3].copy()
994
+
995
+ @staticmethod
996
+ def _getMeshVertices(mesh, world=False):
997
+ """ """
998
+ # Get the MDagPath from the name of the mesh
999
+ sl = om.MSelectionList()
1000
+ sl.add(mesh)
1001
+ thing = om.MDagPath()
1002
+ sl.getDagPath(0, thing)
1003
+ meshFn = om.MFnMesh(thing)
1004
+ vts = om.MPointArray()
1005
+ if world:
1006
+ space = om.MSpace.kWorld
1007
+ else:
1008
+ space = om.MSpace.kObject
1009
+ meshFn.getPoints(vts, space)
1010
+ return vts
1011
+
1012
+ @classmethod
1013
+ def _exportAbcVertices(cls, mesh, world=False):
1014
+ """ """
1015
+ if np is None or imathnumpy is None:
1016
+ vts = cls._getMeshVertices(mesh, world=world)
1017
+ vertices = V3fArray(vts.length())
1018
+ for i in range(vts.length()):
1019
+ vertices[i] = (vts[i].x, vts[i].y, vts[i].z)
1020
+ else:
1021
+ vts = cls.getNumpyShape(mesh, world=world)
1022
+ vertices = mkSampleVertexPoints(vts)
1023
+ return vertices
1024
+
1025
+ @staticmethod
1026
+ def getAbcFaces(mesh):
1027
+ """ """
1028
+ # Get the MDagPath from the name of the mesh
1029
+ sl = om.MSelectionList()
1030
+ sl.add(mesh)
1031
+ thing = om.MDagPath()
1032
+ sl.getDagPath(0, thing)
1033
+ meshFn = om.MFnMesh(thing)
1034
+
1035
+ faces = []
1036
+ faceCounts = []
1037
+ # uvArray = []
1038
+ uvIdxArray = []
1039
+ vIdx = om.MIntArray()
1040
+
1041
+ util = om.MScriptUtil()
1042
+ util.createFromInt(0)
1043
+ uvIdxPtr = util.asIntPtr()
1044
+ uArray = om.MFloatArray()
1045
+ vArray = om.MFloatArray()
1046
+ meshFn.getUVs(uArray, vArray)
1047
+ hasUvs = uArray.length() > 0
1048
+
1049
+ for i in range(meshFn.numPolygons()):
1050
+ meshFn.getPolygonVertices(i, vIdx)
1051
+ face = []
1052
+ for j in reversed(range(vIdx.length())):
1053
+ face.append(vIdx[j])
1054
+ if hasUvs:
1055
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
1056
+ uvIdx = util.getInt(uvIdxPtr)
1057
+ if uvIdx >= uArray.length() or uvIdx < 0:
1058
+ uvIdx = 0
1059
+ uvIdxArray.append(uvIdx)
1060
+
1061
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
1062
+ faces.extend(face)
1063
+ faceCounts.append(vIdx.length())
1064
+
1065
+ abcFaceIndices = IntArray(len(faces))
1066
+ for i in range(len(faces)):
1067
+ abcFaceIndices[i] = faces[i]
1068
+
1069
+ abcFaceCounts = IntArray(len(faceCounts))
1070
+ for i in range(len(faceCounts)):
1071
+ abcFaceCounts[i] = faceCounts[i]
1072
+
1073
+ if hasUvs:
1074
+ abcUVArray = V2fArray(len(uArray))
1075
+ for i in range(len(vArray)):
1076
+ abcUVArray[i] = (uArray[i], vArray[i])
1077
+ abcUVIdxArray = UnsignedIntArray(len(uvIdxArray))
1078
+ for i in range(len(uvIdxArray)):
1079
+ abcUVIdxArray[i] = uvIdxArray[i]
1080
+ uv = OV2fGeomParamSample(
1081
+ abcUVArray, abcUVIdxArray, GeometryScope.kFacevaryingScope
1082
+ )
1083
+ else:
1084
+ uv = None
1085
+
1086
+ return abcFaceIndices, abcFaceCounts, uv
1087
+
1088
+ def exportAbc(
1089
+ self, dccMesh, abcMesh, js, world=False, ensureCorrect=False, pBar=None
1090
+ ):
1091
+ """ """
1092
+ # export the data to alembic
1093
+ if dccMesh is None:
1094
+ dccMesh = self.mesh
1095
+
1096
+ shapeDict = {i.name: i for i in self.simplex.shapes}
1097
+
1098
+ shapeNames = js["shapes"]
1099
+ if js["encodingVersion"] > 1:
1100
+ shapeNames = [i["name"] for i in shapeNames]
1101
+ shapes = [shapeDict[i] for i in shapeNames]
1102
+
1103
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
1104
+ schema = abcMesh.getSchema()
1105
+
1106
+ if pBar is not None:
1107
+ pBar.show()
1108
+ pBar.setMaximum(len(shapes))
1109
+ spacerName = "_" * max(list(map(len, shapeNames)))
1110
+ pBar.setLabelText("Exporting:\n{0}".format(spacerName))
1111
+ QApplication.processEvents()
1112
+
1113
+ if ensureCorrect:
1114
+ # Since this code is used to both export and exportOther
1115
+ # I only want to ensure that everything is correct only if
1116
+ # I'm doing a normal export
1117
+ envelope = cmds.getAttr(self.shapeNode + ".envelope")
1118
+ cmds.setAttr(self.shapeNode + ".envelope", 1.0)
1119
+
1120
+ with disconnected(self.shapeNode) as cnx:
1121
+ shapeCnx = cnx[self.shapeNode]
1122
+ for v in six.itervalues(shapeCnx):
1123
+ cmds.setAttr(v, 0.0)
1124
+ for i, shape in enumerate(shapes):
1125
+ if pBar is not None:
1126
+ pBar.setLabelText("Exporting:\n{0}".format(shape.name))
1127
+ pBar.setValue(i)
1128
+ QApplication.processEvents()
1129
+ if pBar.wasCanceled():
1130
+ return
1131
+ cmds.setAttr(shape.thing, 1.0)
1132
+ verts = self._exportAbcVertices(dccMesh, world=world)
1133
+ if uvs is not None:
1134
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts, uvs)
1135
+ else:
1136
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts)
1137
+ schema.set(abcSample)
1138
+ cmds.setAttr(shape.thing, 0.0)
1139
+
1140
+ if ensureCorrect:
1141
+ cmds.setAttr(self.shapeNode + ".envelope", envelope)
1142
+
1143
+ def exportOtherAbc(self, dccMesh, abcMesh, js, world=False, pBar=None):
1144
+ """ """
1145
+ shapeNames = js["shapes"]
1146
+ if js["encodingVersion"] > 1:
1147
+ shapeNames = [i["name"] for i in shapeNames]
1148
+
1149
+ if pBar is not None:
1150
+ pBar.show()
1151
+ pBar.setMaximum(len(shapeNames))
1152
+ spacerName = "_" * max(list(map(len, shapeNames)))
1153
+ pBar.setLabelText("Exporting:\n{0}".format(spacerName))
1154
+ QApplication.processEvents()
1155
+
1156
+ # Get all the sliderVecs
1157
+ shapeNames, inVecs, keyIdxs = self.simplex.buildInputVectors()
1158
+ sliderVecs = [
1159
+ [0.0] * len(self.simplex.sliders) for i in range(len(self.simplex.shapes))
1160
+ ]
1161
+ for iv, idx in zip(inVecs, keyIdxs):
1162
+ sliderVecs[idx] = iv
1163
+
1164
+ # Get all the fully expanded shapes, and the activations per shape
1165
+ with disconnected(self.op) as allSliderCnx:
1166
+ sliderCnx = allSliderCnx[self.op]
1167
+ # zero all slider vals on the op to get the rest shape
1168
+ for a in six.itervalues(sliderCnx):
1169
+ cmds.setAttr(a, 0.0)
1170
+ restVerts = self.getNumpyShape(dccMesh, world=world)
1171
+
1172
+ fullShapes = np.zeros((len(self.simplex.shapes), len(restVerts), 3))
1173
+ shpValArray = np.zeros((len(self.simplex.shapes), len(self.simplex.shapes)))
1174
+ for shpIdx, shape in enumerate(self.simplex.shapes):
1175
+ if pBar is not None:
1176
+ pBar.setLabelText("Reading Full Shapes:\n{0}".format(shape.name))
1177
+ pBar.setValue(shpIdx)
1178
+ QApplication.processEvents()
1179
+ if pBar.wasCanceled():
1180
+ raise RuntimeError("Cancelled!")
1181
+
1182
+ # Set the full vec for this shape
1183
+ inVec = sliderVecs[shpIdx]
1184
+ for vi, vv in enumerate(inVec):
1185
+ cmds.setAttr(sliderCnx[self.simplex.sliders[vi].thing], vv)
1186
+
1187
+ fullShapes[shpIdx] = self.getNumpyShape(dccMesh, world=world)
1188
+
1189
+ ary = np.array(cmds.getAttr(self.op + ".weights")[0])
1190
+ # Get rid of some floating point inaccuracies
1191
+ ary[np.isclose(ary, 1.0)] = 1.0
1192
+ ary[np.isclose(ary, 0.0)] = 0.0
1193
+ shpValArray[shpIdx] = ary
1194
+
1195
+ # Figure out what order to build the deltas
1196
+ # so that the deltas exist when I try to combine them
1197
+ ctrlOrder = self.simplex.controllersByDepth()
1198
+ shapeOrder = [pp.shape for ctrl in ctrlOrder for pp in ctrl.prog.pairs]
1199
+ shapeOrder = [i for i in shapeOrder if not i.isRest]
1200
+
1201
+ # Incrementally Build the numpy array of delta shapes
1202
+ # build deltaShapeArray as a 2d array because numpy is like 10x faster on 2d arrays
1203
+ indexByShape = {v: k for k, v in enumerate(self.simplex.shapes)}
1204
+ deltaShapeArray = np.zeros((len(self.simplex.shapes), len(restVerts) * 3))
1205
+ for shpOrderIdx, shape in enumerate(shapeOrder):
1206
+ if pBar is not None:
1207
+ pBar.setLabelText("Collapsing to Deltas:\n{0}".format(shape.name))
1208
+ pBar.setValue(shpOrderIdx)
1209
+ QApplication.processEvents()
1210
+ if pBar.wasCanceled():
1211
+ raise RuntimeError("Cancelled!")
1212
+
1213
+ shpIdx = indexByShape[shape]
1214
+ base = np.dot(shpValArray[shpIdx], deltaShapeArray)
1215
+ deltaShapeArray[shpIdx] = (
1216
+ fullShapes[shpIdx] - restVerts - base.reshape((-1, 3))
1217
+ ).flatten()
1218
+
1219
+ # And move that 2d array back into 3d
1220
+ deltaShapeArray = deltaShapeArray.reshape((len(self.simplex.shapes), -1, 3))
1221
+
1222
+ # Finally write the outputs
1223
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
1224
+ schema = abcMesh.getSchema()
1225
+ for shpIdx, shape in enumerate(self.simplex.shapes):
1226
+ if pBar is not None:
1227
+ pBar.setLabelText("writing:\n{0}".format(shape.name))
1228
+ pBar.setValue(shpIdx)
1229
+ QApplication.processEvents()
1230
+ if pBar.wasCanceled():
1231
+ raise RuntimeError("Cancelled!")
1232
+ shpVerts = restVerts + deltaShapeArray[shpIdx]
1233
+ shpVerts = mkSampleVertexPoints(shpVerts)
1234
+ if uvs is not None:
1235
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts, uvs)
1236
+ else:
1237
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts)
1238
+ schema.set(abcSample)
1239
+
1240
+ # Revision tracking
1241
+ def getRevision(self):
1242
+ """ """
1243
+ try:
1244
+ return cmds.getAttr("{0}.{1}".format(self.op, "revision"))
1245
+ except ValueError:
1246
+ # object does not exist
1247
+ return None
1248
+
1249
+ @undoable
1250
+ def incrementRevision(self):
1251
+ """ """
1252
+ value = self.getRevision()
1253
+ if value is None:
1254
+ return
1255
+ cmds.setAttr("{0}.{1}".format(self.op, "revision"), value + 1)
1256
+ jsString = self.simplex.dump()
1257
+ self.setSimplexString(self.op, jsString)
1258
+ return value + 1
1259
+
1260
+ @undoable
1261
+ def setRevision(self, val):
1262
+ """
1263
+
1264
+ Parameters
1265
+ ----------
1266
+ val :
1267
+
1268
+
1269
+ Returns
1270
+ -------
1271
+
1272
+ """
1273
+ cmds.setAttr("{0}.{1}".format(self.op, "revision"), val)
1274
+
1275
+ # System level
1276
+ @undoable
1277
+ def renameSystem(self, name):
1278
+ """
1279
+
1280
+ Parameters
1281
+ ----------
1282
+ name :
1283
+
1284
+
1285
+ Returns
1286
+ -------
1287
+
1288
+ """
1289
+ if (
1290
+ self.mesh is None
1291
+ or self.ctrl is None
1292
+ or self.shapeNode is None
1293
+ or self.op is None
1294
+ or self.simplex is None
1295
+ ):
1296
+ raise ValueError("System is not set up. Cannot rename")
1297
+
1298
+ nn = self.mesh.replace(self.name, name)
1299
+ self.mesh = cmds.rename(self.mesh, nn)
1300
+
1301
+ nn = self.ctrl.replace(self.name, name)
1302
+ self.ctrl = cmds.rename(self.ctrl, nn)
1303
+
1304
+ oldNodeName = self.shapeNode
1305
+ nn = self.shapeNode.replace(self.name, name)
1306
+ self.shapeNode = cmds.rename(self.shapeNode, nn)
1307
+
1308
+ nn = self.op.replace(self.name, name)
1309
+ self.op = cmds.rename(self.op, nn)
1310
+
1311
+ for shape in self.simplex.shapes:
1312
+ shape.thing = shape.thing.replace(oldNodeName, self.shapeNode)
1313
+
1314
+ self.name = name
1315
+
1316
+ @undoable
1317
+ def deleteSystem(self):
1318
+ """ """
1319
+ cmds.delete(self.ctrl)
1320
+ cmds.delete(self.shapeNode)
1321
+ cmds.delete(self.op)
1322
+ self.ctrl = None # the object that has all the controllers on it
1323
+ self.shapeNode = None # the deformer object
1324
+ self.op = None # the simplex object
1325
+ self.simplex = None
1326
+
1327
+ # Shapes
1328
+ @undoable
1329
+ def createShape(self, shape, live=False, offset=10):
1330
+ """
1331
+
1332
+ Parameters
1333
+ ----------
1334
+ shape :
1335
+
1336
+ live :
1337
+ (Default value = False)
1338
+ offset :
1339
+ (Default value = 10)
1340
+
1341
+ Returns
1342
+ -------
1343
+
1344
+ """
1345
+ with disconnected(self.shapeNode):
1346
+ try:
1347
+ attrs = cmds.listAttr("{0}.weight[*]".format(self.shapeNode))
1348
+ except ValueError:
1349
+ pass
1350
+ # Maya throws an error if there aren't any instead of
1351
+ # just returning an empty list
1352
+ else:
1353
+ for attr in attrs:
1354
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1355
+ newShape = cmds.duplicate(self.mesh, name=shape.name)[0]
1356
+
1357
+ cmds.delete(newShape, constructionHistory=True)
1358
+ index = self._firstAvailableIndex()
1359
+ cmds.blendShape(
1360
+ self.shapeNode, edit=True, target=(self.mesh, index, newShape, 1.0)
1361
+ )
1362
+ weightAttr = "{0}.weight[{1}]".format(self.shapeNode, index)
1363
+ thing = cmds.ls(weightAttr)[0]
1364
+
1365
+ shapeIndex = len(shape.simplex.shapes) - 1
1366
+ cmds.connectAttr("{0}.weights[{1}]".format(self.op, shapeIndex), thing)
1367
+
1368
+ if live:
1369
+ cmds.xform(newShape, relative=True, translation=[offset, 0, 0])
1370
+ else:
1371
+ cmds.delete(newShape)
1372
+
1373
+ return thing
1374
+
1375
+ def _firstAvailableIndex(self):
1376
+ """ """
1377
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1378
+ idxs = set()
1379
+ if not aliases:
1380
+ return 0
1381
+ for alias in aliases:
1382
+ match = re.search(r"\[\d+\]", alias)
1383
+ if not match:
1384
+ continue # No index found for the current shape
1385
+ idxs.add(int(match.group().strip("[]")))
1386
+
1387
+ for i in range(len(idxs) + 1):
1388
+ if i not in idxs:
1389
+ return i
1390
+ # there should be no way to get here, but just in case:
1391
+ return len(idxs) + 1
1392
+
1393
+ def getShapeIndex(self, shape):
1394
+ """
1395
+
1396
+ Parameters
1397
+ ----------
1398
+ shape :
1399
+
1400
+
1401
+ Returns
1402
+ -------
1403
+
1404
+ """
1405
+ aName = cmds.attributeName(shape.thing)
1406
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1407
+ idx = aliases.index(aName)
1408
+ raw = aliases[idx + 1]
1409
+ matches = re.findall(r"\[\d+\]", raw)
1410
+ if not matches:
1411
+ raise IndexError("No index found for the current shape")
1412
+ return int(matches[-1].strip("[]"))
1413
+
1414
+ @undoable
1415
+ def extractWithDeltaShape(self, shape, live=True, offset=10.0):
1416
+ """Make a mesh representing a shape. Can be live or not.
1417
+ Also, make a shapenode that is the delta of the change being made
1418
+
1419
+ Parameters
1420
+ ----------
1421
+ shape :
1422
+
1423
+ live :
1424
+ (Default value = True)
1425
+ offset :
1426
+ (Default value = 10.0)
1427
+
1428
+ Returns
1429
+ -------
1430
+
1431
+ """
1432
+ with disconnected(self.shapeNode) as cnx:
1433
+ shapeCnx = cnx[self.shapeNode]
1434
+ for v in six.itervalues(shapeCnx):
1435
+ cmds.setAttr(v, 0.0)
1436
+
1437
+ # store the delta shape
1438
+ delta = cmds.duplicate(self.mesh, name="{0}_Delta".format(shape.name))[0]
1439
+
1440
+ # Extract the shape
1441
+ cmds.setAttr(shape.thing, 1.0)
1442
+ extracted = cmds.duplicate(
1443
+ self.mesh, name="{0}_Extract".format(shape.name)
1444
+ )[0]
1445
+
1446
+ # Store the initial shape
1447
+ init = cmds.duplicate(extracted, name="{0}_Init".format(shape.name))[0]
1448
+
1449
+ # clear old orig objects
1450
+ for item in [delta, extracted, init]:
1451
+ self._clearShapes(item, doOrig=True)
1452
+
1453
+ # build the deltaObj system
1454
+ bs = cmds.blendShape(delta, name="{0}_DeltaBS".format(shape.name))[0]
1455
+
1456
+ cmds.blendShape(bs, edit=True, target=(delta, 0, init, 1.0))
1457
+ cmds.blendShape(bs, edit=True, target=(delta, 1, extracted, 1.0))
1458
+
1459
+ cmds.setAttr("{0}.{1}".format(bs, init), -1.0)
1460
+ cmds.setAttr("{0}.{1}".format(bs, extracted), 1.0)
1461
+
1462
+ # Cleanup
1463
+ nodeDict = dict(Delta=delta, Init=init)
1464
+ repDict = self._reparentDeltaShapes(extracted, nodeDict, bs)
1465
+
1466
+ # Shift the extracted shape to the side
1467
+ cmds.xform(extracted, relative=True, translation=[offset, 0, 0])
1468
+
1469
+ if live:
1470
+ self.connectShape(shape, extracted, live, delete=False)
1471
+
1472
+ return extracted, repDict["Delta"]
1473
+
1474
+ @undoable
1475
+ def extractWithDeltaConnection(self, shape, delta, value, live=True, offset=10.0):
1476
+ """Extract a shape with a live partial delta added in.
1477
+ Useful for updating progressive shapes
1478
+
1479
+ Parameters
1480
+ ----------
1481
+ shape :
1482
+
1483
+ delta :
1484
+
1485
+ value :
1486
+
1487
+ live :
1488
+ (Default value = True)
1489
+ offset :
1490
+ (Default value = 10.0)
1491
+
1492
+ Returns
1493
+ -------
1494
+
1495
+ """
1496
+ with disconnected(self.shapeNode):
1497
+ for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
1498
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1499
+
1500
+ # Pull out the rest shape. we will blend this guy to the extraction
1501
+ extracted = cmds.duplicate(
1502
+ self.mesh, name="{0}_Extract".format(shape.name)
1503
+ )[0]
1504
+
1505
+ cmds.setAttr(shape.thing, 1.0)
1506
+ # Store the initial shape
1507
+ init = cmds.duplicate(self.mesh, name="{0}_Init".format(shape.name))[0]
1508
+
1509
+ # clear old orig objects
1510
+ for item in [init, extracted]:
1511
+ self._clearShapes(item, doOrig=True)
1512
+
1513
+ deltaPar = cmds.listRelatives(delta, parent=True)[0]
1514
+
1515
+ # build the restObj system
1516
+ cmds.select(clear=True) # 'cause maya
1517
+ bs = cmds.blendShape(extracted, name="{0}_DeltaBS".format(shape.name))[0]
1518
+ cmds.blendShape(bs, edit=True, target=(extracted, 0, init, 1.0))
1519
+ cmds.blendShape(bs, edit=True, target=(extracted, 1, deltaPar, 1.0))
1520
+
1521
+ cmds.setAttr("{0}.{1}".format(bs, init), 1.0)
1522
+ cmds.setAttr("{0}.{1}".format(bs, deltaPar), value)
1523
+
1524
+ outCnx = "{0}.worldMesh[0]".format(delta)
1525
+ inCnx = "{0}.inputTarget[0].inputTargetGroup[{1}].inputTargetItem[6000].inputGeomTarget".format(
1526
+ bs, 1
1527
+ )
1528
+ cmds.connectAttr(outCnx, inCnx, force=True)
1529
+ cmds.aliasAttr(delta, "{0}.{1}".format(bs, deltaPar))
1530
+
1531
+ # Cleanup
1532
+ nodeDict = dict(Init=init)
1533
+ self._reparentDeltaShapes(extracted, nodeDict, bs)
1534
+
1535
+ # Remove the tweak node, otherwise editing the input progressives
1536
+ # *inverts* the shape
1537
+ exShape = cmds.listRelatives(extracted, noIntermediate=1, shapes=1)[0]
1538
+ tweak = cmds.listConnections(
1539
+ exShape + ".tweakLocation", source=1, destination=0
1540
+ )
1541
+ if tweak:
1542
+ cmds.delete(tweak)
1543
+
1544
+ # Shift the extracted shape to the side
1545
+ cmds.xform(extracted, relative=True, translation=[offset, 0, 0])
1546
+
1547
+ if live:
1548
+ self.connectShape(shape, extracted, live, delete=False)
1549
+
1550
+ return extracted
1551
+
1552
+ @undoable
1553
+ def extractShape(self, shape, live=True, offset=10.0):
1554
+ """Make a mesh representing a shape. Can be live or not.
1555
+ Can also store its starting shape and delta data
1556
+
1557
+ Parameters
1558
+ ----------
1559
+ shape :
1560
+
1561
+ live :
1562
+ (Default value = True)
1563
+ offset :
1564
+ (Default value = 10.0)
1565
+
1566
+ Returns
1567
+ -------
1568
+
1569
+ """
1570
+ with disconnected(self.shapeNode):
1571
+ for attr in cmds.listAttr("{0}.weight[*]".format(self.shapeNode)):
1572
+ cmds.setAttr("{0}.{1}".format(self.shapeNode, attr), 0.0)
1573
+
1574
+ cmds.setAttr(shape.thing, 1.0)
1575
+ extracted = cmds.duplicate(
1576
+ self.mesh, name="{0}_Extract".format(shape.name)
1577
+ )[0]
1578
+
1579
+ # Shift the extracted shape to the side
1580
+ cmds.xform(extracted, relative=True, translation=[offset, 0, 0])
1581
+
1582
+ if live:
1583
+ self.connectShape(shape, extracted, live, delete=False)
1584
+ return extracted
1585
+
1586
+ @undoable
1587
+ def connectShape(self, shape, mesh=None, live=False, delete=False):
1588
+ """Force a shape to match a mesh
1589
+ The "connect shape" button is:
1590
+ mesh=None, delete=True
1591
+ The "match shape" button is:
1592
+ mesh=someMesh, delete=False
1593
+ There is a possibility of a "make live" button:
1594
+ live=True, delete=False
1595
+
1596
+ Parameters
1597
+ ----------
1598
+ shape :
1599
+
1600
+ mesh :
1601
+ (Default value = None)
1602
+ live :
1603
+ (Default value = False)
1604
+ delete :
1605
+ (Default value = False)
1606
+
1607
+ Returns
1608
+ -------
1609
+
1610
+ """
1611
+ if mesh is None:
1612
+ attrName = cmds.attributeName(shape.thing, long=True)
1613
+ mesh = "{0}_Extract".format(attrName)
1614
+
1615
+ if not cmds.objExists(mesh):
1616
+ return
1617
+
1618
+ index = self.getShapeIndex(shape)
1619
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1620
+ cnx = mesh + "Shape" if cmds.nodeType(mesh) == "transform" else mesh
1621
+
1622
+ outAttr = "{0}.worldMesh[0]".format(
1623
+ cnx
1624
+ ) # Make sure to check the right shape object
1625
+ inAttr = "{0}.inputTargetItem[6000].inputGeomTarget".format(tgn)
1626
+
1627
+ if not cmds.isConnected(outAttr, inAttr):
1628
+ cmds.connectAttr(outAttr, inAttr, force=True)
1629
+
1630
+ if not live:
1631
+ cmds.disconnectAttr(outAttr, inAttr)
1632
+ if delete:
1633
+ cmds.delete(mesh)
1634
+
1635
+ @undoable
1636
+ def extractPosedShape(self, shape):
1637
+ """
1638
+
1639
+ Parameters
1640
+ ----------
1641
+ shape :
1642
+
1643
+
1644
+ Returns
1645
+ -------
1646
+
1647
+ """
1648
+ pass
1649
+
1650
+ @undoable
1651
+ def zeroShape(self, shape):
1652
+ """Set the shape to be completely zeroed
1653
+
1654
+ Parameters
1655
+ ----------
1656
+ shape :
1657
+
1658
+
1659
+ Returns
1660
+ -------
1661
+
1662
+ """
1663
+ index = self.getShapeIndex(shape)
1664
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1665
+ shapeInput = "{0}.inputTargetItem[6000]".format(tgn)
1666
+ cmds.setAttr(
1667
+ "{0}.inputPointsTarget".format(shapeInput), 0, (), type="pointArray"
1668
+ )
1669
+ cmds.setAttr(
1670
+ "{0}.inputComponentsTarget".format(shapeInput), 0, "", type="componentList"
1671
+ )
1672
+
1673
+ @undoable
1674
+ def deleteShape(self, toDelShape):
1675
+ """Remove a shape from the system
1676
+
1677
+ Parameters
1678
+ ----------
1679
+ toDelShape :
1680
+
1681
+
1682
+ Returns
1683
+ -------
1684
+
1685
+ """
1686
+ index = self.getShapeIndex(toDelShape)
1687
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(self.shapeNode, index)
1688
+ cmds.removeMultiInstance(toDelShape.thing, b=True)
1689
+ cmds.removeMultiInstance(tgn, b=True)
1690
+ cmds.aliasAttr(toDelShape.thing, remove=True)
1691
+ self._rebuildShapeConnections()
1692
+
1693
+ def _rebuildShapeConnections(self):
1694
+ """ """
1695
+ # Rebuild the shape connections in the proper order
1696
+ cnxs = (
1697
+ cmds.listConnections(
1698
+ self.op, plugs=True, source=False, destination=True, connections=True
1699
+ )
1700
+ or []
1701
+ )
1702
+ for i, cnx in enumerate(cnxs):
1703
+ if i % 2 == 0 and cnx.startswith("{0}.weights[".format(self.op)):
1704
+ cmds.disconnectAttr(cnxs[i], cnxs[i + 1])
1705
+
1706
+ for i, shape in enumerate(self.simplex.shapes):
1707
+ cmds.connectAttr(
1708
+ "{0}.weights[{1}]".format(self.op, i), shape.thing, force=True
1709
+ )
1710
+
1711
+ @undoable
1712
+ def forceRebuildShapeConnections(self):
1713
+ """ """
1714
+ self._rebuildShapeConnections()
1715
+
1716
+ @undoable
1717
+ def renameShape(self, shape, name):
1718
+ """Change the name of the shape
1719
+
1720
+ Parameters
1721
+ ----------
1722
+ shape :
1723
+
1724
+ name :
1725
+
1726
+
1727
+ Returns
1728
+ -------
1729
+
1730
+ """
1731
+ cmds.aliasAttr(name, shape.thing)
1732
+ shape.thing = "{0}.{1}".format(self.shapeNode, name)
1733
+
1734
+ @undoable
1735
+ def convertShapeToCorrective(self, shape):
1736
+ """
1737
+
1738
+ Parameters
1739
+ ----------
1740
+ shape :
1741
+
1742
+
1743
+ Returns
1744
+ -------
1745
+
1746
+ """
1747
+ pass
1748
+
1749
+ # Falloffs
1750
+ def createFalloff(self, name):
1751
+ """
1752
+
1753
+ Parameters
1754
+ ----------
1755
+ name :
1756
+
1757
+
1758
+ Returns
1759
+ -------
1760
+
1761
+ """
1762
+ pass # for eventual live splits
1763
+
1764
+ def duplicateFalloff(self, falloff, newFalloff, newName):
1765
+ """
1766
+
1767
+ Parameters
1768
+ ----------
1769
+ falloff :
1770
+
1771
+ newFalloff :
1772
+
1773
+ newName :
1774
+
1775
+
1776
+ Returns
1777
+ -------
1778
+
1779
+ """
1780
+ pass # for eventual live splits
1781
+
1782
+ def deleteFalloff(self, falloff):
1783
+ """
1784
+
1785
+ Parameters
1786
+ ----------
1787
+ falloff :
1788
+
1789
+
1790
+ Returns
1791
+ -------
1792
+
1793
+ """
1794
+ pass # for eventual live splits
1795
+
1796
+ def setFalloffData(
1797
+ self, falloff, splitType, axis, minVal, minHandle, maxHandle, maxVal, mapName
1798
+ ):
1799
+ """
1800
+
1801
+ Parameters
1802
+ ----------
1803
+ falloff :
1804
+
1805
+ splitType :
1806
+
1807
+ axis :
1808
+
1809
+ minVal :
1810
+
1811
+ minHandle :
1812
+
1813
+ maxHandle :
1814
+
1815
+ maxVal :
1816
+
1817
+ mapName :
1818
+
1819
+
1820
+ Returns
1821
+ -------
1822
+
1823
+ """
1824
+ pass # for eventual live splits
1825
+
1826
+ def getFalloffThing(self, falloff):
1827
+ """
1828
+
1829
+ Parameters
1830
+ ----------
1831
+ falloff :
1832
+
1833
+
1834
+ Returns
1835
+ -------
1836
+
1837
+ """
1838
+ shape = [i for i in cmds.listRelatives(self.mesh, shapes=True)][0]
1839
+ return shape + "." + falloff.name
1840
+
1841
+ # Sliders
1842
+ @undoable
1843
+ def createSlider(self, slider):
1844
+ """
1845
+
1846
+ Parameters
1847
+ ----------
1848
+ slider :
1849
+
1850
+
1851
+ Returns
1852
+ -------
1853
+
1854
+ """
1855
+ index = slider.simplex.sliders.index(slider)
1856
+ cmds.addAttr(
1857
+ self.ctrl,
1858
+ longName=slider.name,
1859
+ attributeType="double",
1860
+ keyable=True,
1861
+ min=slider.minValue * self.sliderMul,
1862
+ max=slider.maxValue * self.sliderMul,
1863
+ )
1864
+ thing = "{0}.{1}".format(self.ctrl, slider.name)
1865
+ cmds.connectAttr(thing, "{0}.sliders[{1}]".format(self.op, index))
1866
+ return thing
1867
+
1868
+ @undoable
1869
+ def renameSlider(self, slider, name):
1870
+ """Set the name of a slider
1871
+
1872
+ Parameters
1873
+ ----------
1874
+ slider :
1875
+
1876
+ name :
1877
+
1878
+
1879
+ Returns
1880
+ -------
1881
+
1882
+ """
1883
+ vals = [v.value for v in slider.prog.pairs]
1884
+ cnx = cmds.listConnections(
1885
+ slider.thing, plugs=True, source=False, destination=True
1886
+ )
1887
+ cmds.deleteAttr(slider.thing)
1888
+ cmds.addAttr(
1889
+ self.ctrl,
1890
+ longName=name,
1891
+ attributeType="double",
1892
+ keyable=True,
1893
+ min=self.sliderMul * min(vals),
1894
+ max=self.sliderMul * max(vals),
1895
+ )
1896
+ newThing = "{0}.{1}".format(self.ctrl, name)
1897
+ slider.thing = newThing
1898
+ for c in cnx:
1899
+ cmds.connectAttr(newThing, c)
1900
+
1901
+ @undoable
1902
+ def setSliderRange(self, slider):
1903
+ """Set the range of a slider
1904
+
1905
+ Parameters
1906
+ ----------
1907
+ slider :
1908
+
1909
+
1910
+ Returns
1911
+ -------
1912
+
1913
+ """
1914
+ vals = [v.value for v in slider.prog.pairs]
1915
+ attrName = "{0}.{1}".format(self.ctrl, slider.name)
1916
+ cmds.addAttr(
1917
+ attrName,
1918
+ edit=True,
1919
+ min=self.sliderMul * min(vals),
1920
+ max=self.sliderMul * max(vals),
1921
+ )
1922
+
1923
+ @undoable
1924
+ def deleteSlider(self, toDelSlider):
1925
+ """
1926
+
1927
+ Parameters
1928
+ ----------
1929
+ toDelSlider :
1930
+
1931
+
1932
+ Returns
1933
+ -------
1934
+
1935
+ """
1936
+ cmds.deleteAttr(toDelSlider.thing)
1937
+
1938
+ # Rebuild the slider connections in the proper order
1939
+ # Get the sliders connections
1940
+ cnxs = cmds.listConnections(
1941
+ self.op, plugs=True, source=True, destination=False, connections=True
1942
+ )
1943
+ for i, cnx in enumerate(cnxs):
1944
+ if cnx.startswith("{0}.sliders".format(self.op)):
1945
+ cmds.disconnectAttr(cnxs[i + 1], cnxs[i])
1946
+
1947
+ for i, slider in enumerate(self.simplex.sliders):
1948
+ cmds.connectAttr(slider.thing, "{0}.sliders[{1}]".format(self.op, i))
1949
+
1950
+ @undoable
1951
+ def addProgFalloff(self, prog, falloff):
1952
+ """
1953
+
1954
+ Parameters
1955
+ ----------
1956
+ prog :
1957
+
1958
+ falloff :
1959
+
1960
+
1961
+ Returns
1962
+ -------
1963
+
1964
+ """
1965
+ pass # for eventual live splits
1966
+
1967
+ @undoable
1968
+ def removeProgFalloff(self, prog, falloff):
1969
+ """
1970
+
1971
+ Parameters
1972
+ ----------
1973
+ prog :
1974
+
1975
+ falloff :
1976
+
1977
+
1978
+ Returns
1979
+ -------
1980
+
1981
+ """
1982
+ pass # for eventual live splits
1983
+
1984
+ @undoable
1985
+ def setSlidersWeights(self, sliders, weights):
1986
+ """Set the weight of a slider. This does not change the definition
1987
+
1988
+ Parameters
1989
+ ----------
1990
+ sliders :
1991
+
1992
+ weights :
1993
+
1994
+
1995
+ Returns
1996
+ -------
1997
+
1998
+ """
1999
+ for slider, weight in zip(sliders, weights):
2000
+ try:
2001
+ cmds.setAttr(slider.thing, weight)
2002
+ except RuntimeError:
2003
+ # Probably locked or connected. Just skip it
2004
+ pass
2005
+
2006
+ @undoable
2007
+ def setSliderWeight(self, slider, weight):
2008
+ """
2009
+
2010
+ Parameters
2011
+ ----------
2012
+ slider :
2013
+
2014
+ weight :
2015
+
2016
+
2017
+ Returns
2018
+ -------
2019
+
2020
+ """
2021
+ try:
2022
+ cmds.setAttr(slider.thing, weight)
2023
+ except RuntimeError:
2024
+ # Probably locked or connected. Just skip it
2025
+ pass
2026
+
2027
+ @undoable
2028
+ def updateSlidersRange(self, sliders):
2029
+ """
2030
+
2031
+ Parameters
2032
+ ----------
2033
+ sliders :
2034
+
2035
+
2036
+ Returns
2037
+ -------
2038
+
2039
+ """
2040
+ for slider in sliders:
2041
+ vals = [v.value for v in slider.prog.pairs]
2042
+ cmds.addAttr(
2043
+ slider.thing,
2044
+ edit=True,
2045
+ min=min(vals) * self.sliderMul,
2046
+ max=max(vals) * self.sliderMul,
2047
+ )
2048
+
2049
+ def _doesDeltaExist(self, combo, target):
2050
+ """
2051
+
2052
+ Parameters
2053
+ ----------
2054
+ combo :
2055
+
2056
+ target :
2057
+
2058
+
2059
+ Returns
2060
+ -------
2061
+
2062
+ """
2063
+ dshape = "{0}_DeltaShape".format(combo.name)
2064
+ if not cmds.ls(dshape):
2065
+ return None
2066
+ par = cmds.listRelatives(dshape, allParents=1)
2067
+ if not par:
2068
+ # there is apparently a transform object with the name
2069
+ return None
2070
+
2071
+ par = cmds.ls(par[0], absoluteName=1)
2072
+ tar = cmds.ls(target, absoluteName=1)
2073
+
2074
+ if par != tar:
2075
+ # the shape exists under a different transform ... ugh
2076
+ return None
2077
+ return par + "|" + dshape
2078
+
2079
+ def _clearShapes(self, item, doOrig=False):
2080
+ """
2081
+
2082
+ Parameters
2083
+ ----------
2084
+ item :
2085
+
2086
+ doOrig :
2087
+ (Default value = False)
2088
+
2089
+ Returns
2090
+ -------
2091
+
2092
+ """
2093
+ aname = cmds.ls(item, long=1)[0]
2094
+ shapes = cmds.ls(cmds.listRelatives(item, shapes=1), long=1)
2095
+ baseName = aname.split("|")[-1]
2096
+
2097
+ primary = "{0}|{1}Shape".format(aname, baseName)
2098
+ orig = "{0}|{1}ShapeOrig".format(aname, baseName)
2099
+
2100
+ for shape in shapes:
2101
+ if shape == primary:
2102
+ continue
2103
+ elif shape == orig:
2104
+ if doOrig:
2105
+ cmds.delete(shape)
2106
+ else:
2107
+ cmds.delete(shape)
2108
+
2109
+ @undoable
2110
+ def forceRebuildSliderConnections(self):
2111
+ """ """
2112
+ self._rebuildSliderConnections()
2113
+
2114
+ def _rebuildSliderConnections(self):
2115
+ # disconnect all outputs from the ctrl
2116
+ rcnx = cmds.listConnections(
2117
+ self.ctrl, source=False, plugs=True, connections=True
2118
+ )
2119
+ for i in range(0, len(rcnx), 2):
2120
+ src, dst = rcnx[i], rcnx[i + 1]
2121
+ if cmds.getAttr(src, type=True) != "double":
2122
+ # only disconnect doubles
2123
+ continue
2124
+ cmds.disconnectAttr(src, dst)
2125
+
2126
+ # Reconnect by name
2127
+ for i, sli in enumerate(self.simplex.sliders):
2128
+ thing = self.getSliderThing(sli.name)
2129
+ cmds.connectAttr(thing, self.op + ".sliders[{0}]".format(i))
2130
+
2131
+ # Combos
2132
+ def _reparentDeltaShapes(self, par, nodeDict, bsNode, toDelete=None):
2133
+ """Reparent and clean up a single-transform delta system
2134
+
2135
+ Put all the relevant shape nodes from the nodeDict under the par,
2136
+ and rename the shapes to maya's convention. Then build a callback
2137
+ to ensure the blendshape node isn't left floating
2138
+
2139
+ par: The parent transform node
2140
+ nodeDict: A {simpleName: node} dictionary.
2141
+ bsNode: The blendshape node.
2142
+ toDelete: Any extra nodes to delte after all the node twiddling
2143
+
2144
+ Parameters
2145
+ ----------
2146
+ par :
2147
+
2148
+ nodeDict :
2149
+
2150
+ bsNode :
2151
+
2152
+ toDelete :
2153
+ (Default value = None)
2154
+
2155
+ Returns
2156
+ -------
2157
+
2158
+ """
2159
+ # Get the shapes and origs
2160
+ shapeDict = {}
2161
+ origDict = {}
2162
+
2163
+ for name, node in six.iteritems(nodeDict):
2164
+ shape = cmds.listRelatives(node, noIntermediate=1, shapes=1)[0]
2165
+ shape = cmds.ls(shape, absoluteName=1)[0]
2166
+ if shape:
2167
+ shapeDict[name] = shape
2168
+
2169
+ orig = shape + "Orig"
2170
+ orig = cmds.ls(orig)
2171
+ if orig:
2172
+ origDict[name] = orig
2173
+
2174
+ for name in nodeDict:
2175
+ for d, fmt in [(shapeDict, "{0}Shape{1}"), (origDict, "{0}Shape{1}Orig")]:
2176
+ shape = d.get(name)
2177
+ if shape is None:
2178
+ continue
2179
+ shapeUUID = cmds.ls(shape, uuid=1)[0]
2180
+ cmds.parent(shape, par, shape=True, relative=True)
2181
+ newShape = cmds.rename(cmds.ls(shapeUUID)[0], fmt.format(par, name))
2182
+ d[name] = newShape
2183
+ cmds.setAttr(newShape + ".intermediateObject", 1)
2184
+ cmds.hide(newShape)
2185
+
2186
+ cmds.delete(nodeDict[name])
2187
+
2188
+ if toDelete:
2189
+ cmds.delete(toDelete)
2190
+
2191
+ # Use the simplexDelete message attribute to keep track of what nodes
2192
+ # will need to be delete-linked when the file is reopened
2193
+ sdNode = par + ".simplexDelete"
2194
+ if not cmds.ls(sdNode):
2195
+ cmds.addAttr(par, longName="simplexDelete", attributeType="message")
2196
+ cmds.connectAttr(bsNode + ".message", sdNode)
2197
+
2198
+ # build the callback setup so the blendshape is deleted with the delta setup
2199
+ # along with a persistent scriptjob
2200
+ buildDeleterCallback(par, bsNode)
2201
+ buildDeleterScriptJob()
2202
+
2203
+ return shapeDict
2204
+
2205
+ def _createTravDelta(self, trav, target, tVal, doReparent=True):
2206
+ """Part of the traversal extraction process.
2207
+ Very similar to the combo extraction
2208
+
2209
+ Parameters
2210
+ ----------
2211
+ trav :
2212
+
2213
+ target :
2214
+
2215
+ tVal :
2216
+
2217
+
2218
+ Returns
2219
+ -------
2220
+
2221
+ """
2222
+ exists = self._doesDeltaExist(trav, target)
2223
+ if exists is not None:
2224
+ return exists
2225
+
2226
+ # Traversals *MAY* depend on floaters, but that's complicated
2227
+ # I'm just gonna ignore them for now
2228
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
2229
+
2230
+ # Get all traversal shapes
2231
+ tShapes = []
2232
+ for oTrav in self.simplex.traversals:
2233
+ tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
2234
+
2235
+ with disconnected(self.op) as cnx:
2236
+ sliderCnx = cnx[self.op]
2237
+
2238
+ # zero all slider vals on the op
2239
+ for a in six.itervalues(sliderCnx):
2240
+ cmds.setAttr(a, 0.0)
2241
+
2242
+ with disconnected(floatShapes + tShapes):
2243
+ # pull out the rest shape
2244
+ rest = cmds.duplicate(self.mesh, name="{0}_Rest".format(trav.name))[0]
2245
+
2246
+ sliDict = {}
2247
+ for pair in trav.startPoint.pairs:
2248
+ sliDict[pair.slider] = [pair.value]
2249
+ for pair in trav.endPoint.pairs:
2250
+ sliDict[pair.slider].append(pair.value)
2251
+
2252
+ for slider, (start, end) in six.iteritems(sliDict):
2253
+ vv = start + tVal * (end - start)
2254
+ cmds.setAttr(sliderCnx[slider.thing], vv)
2255
+
2256
+ deltaObj = cmds.duplicate(
2257
+ self.mesh, name="{0}_Delta".format(trav.name)
2258
+ )[0]
2259
+ base = cmds.duplicate(deltaObj, name="{0}_Base".format(trav.name))[0]
2260
+
2261
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
2262
+ for item in [rest, deltaObj, base]:
2263
+ self._clearShapes(item, doOrig=True)
2264
+
2265
+ # Build the delta blendshape setup
2266
+ bs = cmds.blendShape(deltaObj, name="{0}_DeltaBS".format(trav.name))[0]
2267
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
2268
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
2269
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
2270
+ cmds.setAttr("{0}.{1}".format(bs, target), 1.0)
2271
+ cmds.setAttr("{0}.{1}".format(bs, base), 1.0)
2272
+ cmds.setAttr("{0}.{1}".format(bs, rest), 1.0)
2273
+
2274
+ # Cleanup
2275
+ if doReparent:
2276
+ nodeDict = dict(Delta=deltaObj)
2277
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
2278
+ return repDict["Delta"]
2279
+ return deltaObj
2280
+
2281
+ @undoable
2282
+ def extractTraversalShape(self, trav, shape, live=True, offset=10.0):
2283
+ """Extract a shape from a Traversal progression
2284
+
2285
+ Parameters
2286
+ ----------
2287
+ trav :
2288
+ shape :
2289
+ live :
2290
+ (Default value = True)
2291
+ offset :
2292
+ (Default value = 10.0)
2293
+
2294
+ Returns
2295
+ -------
2296
+
2297
+ """
2298
+ floatShapes = self.simplex.getFloatingShapes()
2299
+ floatShapes = [i.thing for i in floatShapes]
2300
+
2301
+ shapeIdx = trav.prog.getShapeIndex(shape)
2302
+ val = trav.prog.pairs[shapeIdx].value
2303
+
2304
+ # TODO: Do traversals interact? Should I turn off any other traversals?
2305
+ # For now, no, but it may be a thing
2306
+ # tShapes = []
2307
+ # for oTrav in self.simplex.traversals:
2308
+ # if oTrav is trav: continue
2309
+ # tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
2310
+
2311
+ with disconnected(self.op) as cnx:
2312
+ sliderCnx = cnx[self.op]
2313
+ # zero all slider vals on the op
2314
+ for a in six.itervalues(sliderCnx):
2315
+ cmds.setAttr(a, 0.0)
2316
+
2317
+ with disconnected(floatShapes): # tShapes
2318
+
2319
+ sliDict = {}
2320
+ for pair in trav.startPoint.pairs:
2321
+ sliDict[pair.slider] = [pair.value]
2322
+ for pair in trav.endPoint.pairs:
2323
+ sliDict[pair.slider].append(pair.value)
2324
+
2325
+ for slider, (start, end) in six.iteritems(sliDict):
2326
+ vv = start + val * (end - start)
2327
+ cmds.setAttr(sliderCnx[slider.thing], vv)
2328
+
2329
+ extracted = cmds.duplicate(
2330
+ self.mesh, name="{0}_Extract".format(shape.name)
2331
+ )
2332
+ extracted = extracted[0]
2333
+ self._clearShapes(extracted)
2334
+ cmds.xform(extracted, relative=True, translation=[offset, 0, 0])
2335
+ self.connectTraversalShape(trav, shape, extracted, live=live, delete=False)
2336
+ cmds.select(extracted)
2337
+ return extracted
2338
+
2339
+ @undoable
2340
+ def connectTraversalShape(self, trav, shape, mesh=None, live=True, delete=False):
2341
+ """Connect a shape into a Traversal progression
2342
+
2343
+ Parameters
2344
+ ----------
2345
+ trav :
2346
+
2347
+ shape :
2348
+
2349
+ mesh :
2350
+ (Default value = None)
2351
+ live :
2352
+ (Default value = True)
2353
+ delete :
2354
+ (Default value = False)
2355
+
2356
+ Returns
2357
+ -------
2358
+
2359
+ """
2360
+ if mesh is None:
2361
+ attrName = cmds.attributeName(shape.thing, long=True)
2362
+ mesh = "{0}_Extract".format(attrName)
2363
+ shapeIdx = trav.prog.getShapeIndex(shape)
2364
+ tVal = trav.prog.pairs[shapeIdx].value
2365
+ delta = self._createTravDelta(trav, mesh, tVal)
2366
+ self.connectShape(shape, delta, live, delete)
2367
+ if delete:
2368
+ cmds.delete(mesh)
2369
+
2370
+ def _createComboDelta(self, combo, target, tVal, doReparent=True):
2371
+ """Part of the combo extraction process.
2372
+ Combo shapes are fixit shapes added on top of any sliders.
2373
+ This means that the actual combo-shape by itself will not look good by itself,
2374
+ and that's bad for artist interaction.
2375
+ So we must create a setup to take the final sculpted shape, and subtract
2376
+ the any direct slider deformations to get the actual "combo shape" as a delta
2377
+ It is this delta shape that is then plugged into the system
2378
+
2379
+ Parameters
2380
+ ----------
2381
+ combo :
2382
+
2383
+ target :
2384
+
2385
+ tVal :
2386
+
2387
+
2388
+ Returns
2389
+ -------
2390
+
2391
+ """
2392
+ exists = self._doesDeltaExist(combo, target)
2393
+ if exists is not None:
2394
+ return exists
2395
+
2396
+ # get floaters
2397
+ # As floaters can appear anywhere along any combo, they must
2398
+ # always be evaluated in isolation. For this reason, we will
2399
+ # always disconnect all floaters
2400
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
2401
+
2402
+ # get my shapes
2403
+ myShapes = [i.thing for i in combo.prog.getShapes()]
2404
+
2405
+ with disconnected([self.op] + floatShapes + myShapes) as cnx:
2406
+ sliderCnx = cnx[self.op]
2407
+
2408
+ # zero all slider vals on the op
2409
+ for a in six.itervalues(sliderCnx):
2410
+ cmds.setAttr(a, 0.0)
2411
+
2412
+ # pull out the rest shape
2413
+ rest = cmds.duplicate(self.mesh, name="{0}_Rest".format(combo.name))[0]
2414
+
2415
+ # set the combo values
2416
+ for pair in combo.pairs:
2417
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
2418
+
2419
+ # Get the resulting slider values for later
2420
+ # weightPairs = []
2421
+ # self.shapeNode = None # the deformer object
2422
+
2423
+ deltaObj = cmds.duplicate(self.mesh, name="{0}_Delta".format(combo.name))[0]
2424
+ base = cmds.duplicate(deltaObj, name="{0}_Base".format(combo.name))[0]
2425
+
2426
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
2427
+ for item in [rest, deltaObj, base]:
2428
+ self._clearShapes(item, doOrig=True)
2429
+
2430
+ # Build the delta blendshape setup
2431
+ bs = cmds.blendShape(deltaObj, name="{0}_DeltaBS".format(combo.name))[0]
2432
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
2433
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
2434
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
2435
+ cmds.setAttr("{0}.{1}".format(bs, target), 1.0)
2436
+ cmds.setAttr("{0}.{1}".format(bs, base), 1.0)
2437
+ cmds.setAttr("{0}.{1}".format(bs, rest), 1.0)
2438
+
2439
+ # Cleanup
2440
+ if doReparent:
2441
+ nodeDict = dict(Delta=deltaObj)
2442
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
2443
+ return repDict["Delta"]
2444
+ return deltaObj
2445
+
2446
+ @undoable
2447
+ def extractComboShape(self, combo, shape, live=True, offset=10.0):
2448
+ """Extract a shape from a combo progression
2449
+
2450
+ Parameters
2451
+ ----------
2452
+ combo :
2453
+
2454
+ shape :
2455
+
2456
+ live :
2457
+ (Default value = True)
2458
+ offset :
2459
+ (Default value = 10.0)
2460
+
2461
+ Returns
2462
+ -------
2463
+
2464
+ """
2465
+ floatShapes = self.simplex.getFloatingShapes()
2466
+ floatShapes = [i.thing for i in floatShapes]
2467
+
2468
+ shapeIdx = combo.prog.getShapeIndex(shape)
2469
+ tVal = combo.prog.pairs[shapeIdx].value
2470
+
2471
+ with disconnected(self.op) as cnx:
2472
+ sliderCnx = cnx[self.op]
2473
+ # zero all slider vals on the op
2474
+ for a in six.itervalues(sliderCnx):
2475
+ cmds.setAttr(a, 0.0)
2476
+
2477
+ with disconnected(floatShapes):
2478
+ # set the combo values
2479
+ for pair in combo.pairs:
2480
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
2481
+
2482
+ extracted = cmds.duplicate(
2483
+ self.mesh, name="{0}_Extract".format(shape.name)
2484
+ )[0]
2485
+ self._clearShapes(extracted)
2486
+ cmds.xform(extracted, relative=True, translation=[offset, 0, 0])
2487
+ self.connectComboShape(combo, shape, extracted, live=live, delete=False)
2488
+ cmds.select(extracted)
2489
+ return extracted
2490
+
2491
+ @undoable
2492
+ def connectComboShape(self, combo, shape, mesh=None, live=True, delete=False):
2493
+ """Connect a shape into a combo progression
2494
+
2495
+ Parameters
2496
+ ----------
2497
+ combo :
2498
+
2499
+ shape :
2500
+
2501
+ mesh :
2502
+ (Default value = None)
2503
+ live :
2504
+ (Default value = True)
2505
+ delete :
2506
+ (Default value = False)
2507
+
2508
+ Returns
2509
+ -------
2510
+
2511
+ """
2512
+ if mesh is None:
2513
+ attrName = cmds.attributeName(shape.thing, long=True)
2514
+ mesh = "{0}_Extract".format(attrName)
2515
+ shapeIdx = combo.prog.getShapeIndex(shape)
2516
+ tVal = combo.prog.pairs[shapeIdx].value
2517
+ delta = self._createComboDelta(combo, mesh, tVal)
2518
+ self.connectShape(shape, delta, live, delete)
2519
+ if delete:
2520
+ cmds.delete(mesh)
2521
+
2522
+ @staticmethod
2523
+ def setDisabled(op):
2524
+ """
2525
+
2526
+ Parameters
2527
+ ----------
2528
+ op :
2529
+
2530
+
2531
+ Returns
2532
+ -------
2533
+
2534
+ """
2535
+ bss = list(set(cmds.listConnections(op, type="blendShape")))
2536
+ helpers = []
2537
+ for bs in bss:
2538
+ prop = "{0}.envelope".format(bs)
2539
+ val = cmds.getAttr(prop)
2540
+ cmds.setAttr(prop, 0.0)
2541
+ if val != 0.0:
2542
+ helpers.append((prop, val))
2543
+ return helpers
2544
+
2545
+ @staticmethod
2546
+ def reEnable(helpers):
2547
+ """
2548
+
2549
+ Parameters
2550
+ ----------
2551
+ helpers :
2552
+
2553
+
2554
+ Returns
2555
+ -------
2556
+
2557
+ """
2558
+ for prop, val in helpers:
2559
+ cmds.setAttr(prop, val)
2560
+
2561
+ @undoable
2562
+ def renameCombo(self, combo, name):
2563
+ """Set the name of a Combo
2564
+
2565
+ Parameters
2566
+ ----------
2567
+ combo :
2568
+
2569
+ name :
2570
+
2571
+
2572
+ Returns
2573
+ -------
2574
+
2575
+ """
2576
+ pass
2577
+
2578
+ # Data Access
2579
+ @staticmethod
2580
+ def getSimplexOperators():
2581
+ """ """
2582
+ return cmds.ls(type="simplex_maya")
2583
+
2584
+ @staticmethod
2585
+ def getSimplexOperatorsByName(name):
2586
+ """
2587
+
2588
+ Parameters
2589
+ ----------
2590
+ name :
2591
+
2592
+
2593
+ Returns
2594
+ -------
2595
+ type
2596
+
2597
+
2598
+ """
2599
+ return cmds.ls(name, type="simplex_maya")
2600
+
2601
+ @staticmethod
2602
+ def getSimplexOperatorsOnObject(thing):
2603
+ """
2604
+
2605
+ Parameters
2606
+ ----------
2607
+ thing :
2608
+
2609
+
2610
+ Returns
2611
+ -------
2612
+ type
2613
+
2614
+
2615
+ """
2616
+ ops = cmds.ls(type="simplex_maya")
2617
+ out = []
2618
+ for op in ops:
2619
+ shapeNode = cmds.listConnections(
2620
+ "{0}.{1}".format(op, "shapeMsg"), source=True, destination=False
2621
+ )
2622
+ if not shapeNode:
2623
+ continue
2624
+
2625
+ # Now that I've got the connected blendshape node, I can check the deformer history
2626
+ # to see if I find it. Eventually, I should probably set this up to deal with
2627
+ # multi-objects, or branched hierarchies. But for now, it works
2628
+ if shapeNode[0] in (cmds.listHistory(thing, pruneDagObjects=True) or []):
2629
+ out.append(op)
2630
+ return out
2631
+
2632
+ @staticmethod
2633
+ def getSimplexString(op):
2634
+ """
2635
+
2636
+ Parameters
2637
+ ----------
2638
+ op :
2639
+
2640
+
2641
+ Returns
2642
+ -------
2643
+ type
2644
+
2645
+
2646
+ """
2647
+ return cmds.getAttr(op + ".definition")
2648
+
2649
+ @staticmethod
2650
+ def getSimplexStringOnThing(thing, systemName):
2651
+ """
2652
+
2653
+ Parameters
2654
+ ----------
2655
+ thing :
2656
+
2657
+ systemName :
2658
+
2659
+
2660
+ Returns
2661
+ -------
2662
+ type
2663
+
2664
+
2665
+ """
2666
+ ops = DCC.getSimplexOperatorsOnObject(thing)
2667
+ for op in ops:
2668
+ js = DCC.getSimplexString(op)
2669
+ jdict = json.loads(js)
2670
+ if jdict["systemName"] == systemName:
2671
+ return js
2672
+ return None
2673
+
2674
+ @staticmethod
2675
+ def setSimplexString(op, val):
2676
+ """
2677
+
2678
+ Parameters
2679
+ ----------
2680
+ op :
2681
+
2682
+ val :
2683
+
2684
+
2685
+ Returns
2686
+ -------
2687
+ type
2688
+
2689
+
2690
+ """
2691
+ return cmds.setAttr(op + ".definition", val, type="string")
2692
+
2693
+ @staticmethod
2694
+ def selectObject(thing):
2695
+ """Select an object in the DCC
2696
+
2697
+ Parameters
2698
+ ----------
2699
+ thing :
2700
+
2701
+
2702
+ Returns
2703
+ -------
2704
+
2705
+ """
2706
+ cmds.select([thing])
2707
+
2708
+ def selectCtrl(self):
2709
+ """Select the system's control object"""
2710
+ if self.ctrl:
2711
+ self.selectObject(self.ctrl)
2712
+
2713
+ @staticmethod
2714
+ def getObjectByName(name):
2715
+ """
2716
+
2717
+ Parameters
2718
+ ----------
2719
+ name :
2720
+
2721
+
2722
+ Returns
2723
+ -------
2724
+ type
2725
+
2726
+
2727
+ """
2728
+ objs = cmds.ls(name)
2729
+ if not objs:
2730
+ return None
2731
+ return objs[0]
2732
+
2733
+ @staticmethod
2734
+ def getObjectName(thing):
2735
+ """
2736
+
2737
+ Parameters
2738
+ ----------
2739
+ thing :
2740
+
2741
+
2742
+ Returns
2743
+ -------
2744
+ type
2745
+
2746
+
2747
+ """
2748
+ return thing
2749
+
2750
+ @staticmethod
2751
+ def staticUndoOpen():
2752
+ """ """
2753
+ cmds.undoInfo(chunkName="SimplexOperation", openChunk=True)
2754
+
2755
+ @staticmethod
2756
+ def staticUndoClose():
2757
+ """ """
2758
+ cmds.undoInfo(closeChunk=True)
2759
+
2760
+ def undoOpen(self):
2761
+ """ """
2762
+ if self.undoDepth == 0:
2763
+ self.staticUndoOpen()
2764
+ self.undoDepth += 1
2765
+
2766
+ def undoClose(self):
2767
+ """ """
2768
+ self.undoDepth -= 1
2769
+ if self.undoDepth == 0:
2770
+ self.staticUndoClose()
2771
+
2772
+ @classmethod
2773
+ def getPersistentFalloff(cls, thing):
2774
+ """
2775
+
2776
+ Parameters
2777
+ ----------
2778
+ thing :
2779
+
2780
+
2781
+ Returns
2782
+ -------
2783
+
2784
+ """
2785
+ return cls.getObjectName(thing)
2786
+
2787
+ @classmethod
2788
+ def loadPersistentFalloff(cls, thing):
2789
+ """
2790
+
2791
+ Parameters
2792
+ ----------
2793
+ thing :
2794
+
2795
+
2796
+ Returns
2797
+ -------
2798
+
2799
+ """
2800
+ return cls.getObjectByName(thing)
2801
+
2802
+ @classmethod
2803
+ def getPersistentShape(cls, thing):
2804
+ """
2805
+
2806
+ Parameters
2807
+ ----------
2808
+ thing :
2809
+
2810
+
2811
+ Returns
2812
+ -------
2813
+
2814
+ """
2815
+ return cls.getObjectName(thing)
2816
+
2817
+ @classmethod
2818
+ def loadPersistentShape(cls, thing):
2819
+ """
2820
+
2821
+ Parameters
2822
+ ----------
2823
+ thing :
2824
+
2825
+
2826
+ Returns
2827
+ -------
2828
+
2829
+ """
2830
+ return cls.getObjectByName(thing)
2831
+
2832
+ @classmethod
2833
+ def getPersistentSlider(cls, thing):
2834
+ """
2835
+
2836
+ Parameters
2837
+ ----------
2838
+ thing :
2839
+
2840
+
2841
+ Returns
2842
+ -------
2843
+
2844
+ """
2845
+ return cls.getObjectName(thing)
2846
+
2847
+ @classmethod
2848
+ def loadPersistentSlider(cls, thing):
2849
+ """
2850
+
2851
+ Parameters
2852
+ ----------
2853
+ thing :
2854
+
2855
+
2856
+ Returns
2857
+ -------
2858
+
2859
+ """
2860
+ return cls.getObjectByName(thing)
2861
+
2862
+ @staticmethod
2863
+ def getSelectedObjects():
2864
+ """ """
2865
+ # For maya, only return transform nodes
2866
+ return cmds.ls(sl=True, transforms=True)
2867
+
2868
+ @undoable
2869
+ def importObj(self, path):
2870
+ """
2871
+
2872
+ Parameters
2873
+ ----------
2874
+ path :
2875
+
2876
+
2877
+ Returns
2878
+ -------
2879
+
2880
+ """
2881
+ current = set(cmds.ls(transforms=True))
2882
+ cmds.file(path, i=True, type="OBJ", ignoreVersion=True)
2883
+ new = set(cmds.ls(transforms=True))
2884
+ shapes = set(cmds.ls(shapes=True))
2885
+ new = new - current - shapes
2886
+ imp = new.pop()
2887
+ return imp
2888
+
2889
+ @staticmethod
2890
+ def _getDeformerChain(chkObj):
2891
+ # Get a deformer chain
2892
+ memo = []
2893
+ while chkObj and chkObj not in memo:
2894
+ memo.append(chkObj)
2895
+
2896
+ typ = cmds.nodeType(chkObj)
2897
+ if typ == "mesh":
2898
+ cnx = cmds.listConnections(chkObj + ".inMesh") or [None]
2899
+ chkObj = cnx[0]
2900
+ elif typ == "groupParts":
2901
+ cnx = cmds.listConnections(
2902
+ chkObj + ".inputGeometry", destination=False, shapes=True
2903
+ ) or [None]
2904
+ chkObj = cnx[0]
2905
+ else:
2906
+ cnx = cmds.ls(chkObj, type="geometryFilter") or [None]
2907
+ chkObj = cnx[0]
2908
+ if chkObj: # we have a deformer
2909
+ cnx = cmds.listConnections(chkObj + ".input[0].inputGeometry") or [
2910
+ None
2911
+ ]
2912
+ chkObj = cnx[0]
2913
+ return memo
2914
+
2915
+ # Freezing stuff
2916
+ def primeShapes(self, combo):
2917
+ """Make sure the upstream shapes of this combo are primed and ready.
2918
+ Priming here means the deltas are stored and available on the blendshape node
2919
+ """
2920
+ # Maya doesn't populate the delta plugs on the blendshape node unless
2921
+ # you have a mesh connection while the value for that shape is turned to 1
2922
+ upstreams = []
2923
+ comboUps = self.simplex.getComboUpstreams(combo)
2924
+ for u in comboUps:
2925
+ upstreams.append(u.prog.getShapeAtValue(1.0))
2926
+ for pair in combo.pairs:
2927
+ sli, val = pair.slider, pair.value
2928
+ upstreams.append(sli.prog.getShapeAtValue(val))
2929
+
2930
+ with disconnected(self.shapeNode) as cnx:
2931
+ shapeCnx = cnx[self.shapeNode]
2932
+ for v in six.itervalues(shapeCnx):
2933
+ cmds.setAttr(v, 0.0)
2934
+
2935
+ for shape in upstreams:
2936
+ cmds.setAttr(shape.thing, 1.0)
2937
+ try:
2938
+ # Make sure to check for any already incoming connections
2939
+ index = self.getShapeIndex(shape)
2940
+ tgn = "{0}.inputTarget[0].inputTargetGroup[{1}]".format(
2941
+ self.shapeNode, index
2942
+ )
2943
+ isConnected = cmds.listConnections(
2944
+ tgn, source=True, destination=False
2945
+ )
2946
+
2947
+ if not isConnected:
2948
+ shapeGeo = cmds.duplicate(self.mesh, name=shape.name)[0]
2949
+ shape.connectShape(mesh=shapeGeo, live=False, delete=True)
2950
+
2951
+ finally:
2952
+ cmds.setAttr(shape.thing, 0.0)
2953
+
2954
+ def getFreezeThing(self, combo):
2955
+ # If the blendshape shape has an incoming connection whose shape name
2956
+ # ends with 'FreezeShape' and the shape's parent is the ctrl
2957
+ ret = []
2958
+ shapes = combo.prog.getShapes()
2959
+ shapes = [i for i in shapes if not i.isRest]
2960
+
2961
+ shapePlugFmt = (
2962
+ ".inputTarget[{meshIdx}].inputTargetGroup[{shapeIdx}].inputTargetItem[6000]"
2963
+ )
2964
+
2965
+ for shape in shapes:
2966
+ shpIdx = self.getShapeIndex(shape)
2967
+ shpPlug = (
2968
+ self.shapeNode
2969
+ + shapePlugFmt.format(meshIdx=0, shapeIdx=shpIdx)
2970
+ + ".inputGeomTarget"
2971
+ )
2972
+
2973
+ cnx = cmds.listConnections(shpPlug, shapes=True, destination=False) or []
2974
+ for cc in cnx:
2975
+ if not cc.endswith("FreezeShape"):
2976
+ continue
2977
+ par = cmds.listRelatives(cc, parent=True)
2978
+ if par and par[0] == self.ctrl:
2979
+ # Can't use list history to get the chain because it's a pseudo-cycle
2980
+ ret.extend(self._getDeformerChain(cc))
2981
+
2982
+ if ret:
2983
+ self.primeShapes(combo)
2984
+
2985
+ return ret
2986
+
2987
+
2988
+ class SliderDispatch(QtCore.QObject):
2989
+ valueChanged = Signal()
2990
+
2991
+ def __init__(self, node, parent=None):
2992
+ super(SliderDispatch, self).__init__(parent)
2993
+ mObject = getMObject(node)
2994
+ self.callbackID = om.MNodeMessage.addAttributeChangedCallback(
2995
+ mObject, self.emitValueChanged
2996
+ )
2997
+
2998
+ def emitValueChanged(self, *args, **kwargs):
2999
+ self.valueChanged.emit()
3000
+
3001
+ def disconnectCallbacks(self):
3002
+ om.MMessage.removeCallback(self.callbackID)
3003
+ self.callbackID = None
3004
+
3005
+ def __del__(self):
3006
+ self.disconnectCallbacks()
3007
+
3008
+
3009
+ class Dispatch(QtCore.QObject):
3010
+ beforeNew = Signal()
3011
+ afterNew = Signal()
3012
+ beforeOpen = Signal()
3013
+ afterOpen = Signal()
3014
+ undo = Signal()
3015
+ redo = Signal()
3016
+
3017
+ def __init__(self, parent=None):
3018
+ super(Dispatch, self).__init__(parent)
3019
+ self.callbackIDs = []
3020
+ self.connectCallbacks()
3021
+
3022
+ def connectCallbacks(self):
3023
+ if self.callbackIDs:
3024
+ self.disconnectCallbacks()
3025
+
3026
+ self.callbackIDs.append(
3027
+ om.MSceneMessage.addCallback(
3028
+ om.MSceneMessage.kBeforeNew, self.emitBeforeNew
3029
+ )
3030
+ )
3031
+ self.callbackIDs.append(
3032
+ om.MSceneMessage.addCallback(om.MSceneMessage.kAfterNew, self.emitAfterNew)
3033
+ )
3034
+ self.callbackIDs.append(
3035
+ om.MSceneMessage.addCallback(
3036
+ om.MSceneMessage.kBeforeOpen, self.emitBeforeOpen
3037
+ )
3038
+ )
3039
+ self.callbackIDs.append(
3040
+ om.MSceneMessage.addCallback(
3041
+ om.MSceneMessage.kAfterOpen, self.emitAfterOpen
3042
+ )
3043
+ )
3044
+ self.callbackIDs.append(
3045
+ om.MEventMessage.addEventCallback("Undo", self.emitUndo)
3046
+ )
3047
+ self.callbackIDs.append(
3048
+ om.MEventMessage.addEventCallback("Redo", self.emitRedo)
3049
+ )
3050
+
3051
+ def disconnectCallbacks(self):
3052
+ for i in self.callbackIDs:
3053
+ om.MMessage.removeCallback(i)
3054
+ self.callbackIDs = []
3055
+
3056
+ def emitBeforeNew(self, *args, **kwargs):
3057
+ self.beforeNew.emit()
3058
+
3059
+ def emitAfterNew(self, *args, **kwargs):
3060
+ self.afterNew.emit()
3061
+
3062
+ def emitBeforeOpen(self, *args, **kwargs):
3063
+ self.beforeOpen.emit()
3064
+
3065
+ def emitAfterOpen(self, *args, **kwargs):
3066
+ self.afterOpen.emit()
3067
+
3068
+ def emitUndo(self, *args, **kwargs):
3069
+ self.undo.emit()
3070
+
3071
+ def emitRedo(self, *args, **kwargs):
3072
+ self.redo.emit()
3073
+
3074
+ def __del__(self):
3075
+ self.disconnectCallbacks()
3076
+
3077
+
3078
+ DISPATCH = Dispatch()
3079
+
3080
+
3081
+ def rootWindow():
3082
+ """Returns the currently active QT main window
3083
+ Only works for QT UI's like Maya
3084
+ """
3085
+ # for MFC apps there should be no root window
3086
+ window = None
3087
+ if QApplication.instance():
3088
+ inst = QApplication.instance()
3089
+ window = inst.activeWindow()
3090
+ # Ignore QSplashScreen's, they should never be considered the root window.
3091
+ if isinstance(window, QSplashScreen):
3092
+ return None
3093
+ # If the application does not have focus try to find A top level widget
3094
+ # that doesn't have a parent and is a QMainWindow or QDialog
3095
+ if window is None:
3096
+ windows = []
3097
+ dialogs = []
3098
+ for w in QApplication.instance().topLevelWidgets():
3099
+ if w.parent() is None:
3100
+ if isinstance(w, QMainWindow):
3101
+ windows.append(w)
3102
+ elif isinstance(w, QDialog):
3103
+ dialogs.append(w)
3104
+ if windows:
3105
+ window = windows[0]
3106
+ elif dialogs:
3107
+ window = dialogs[0]
3108
+
3109
+ # grab the root window
3110
+ if window:
3111
+ while True:
3112
+ parent = window.parent()
3113
+ if not parent:
3114
+ break
3115
+ if isinstance(parent, QSplashScreen):
3116
+ break
3117
+ window = parent
3118
+
3119
+ return window
3120
+
3121
+
3122
+ SIMPLEX_RESET_SCRIPTJOB = """
3123
+ import maya.cmds as cmds
3124
+ import maya.OpenMaya as om
3125
+
3126
+ def simplexDelCB(node, dgMod, clientData):
3127
+ xNode, dName = clientData
3128
+ dNode = getMObject(dName)
3129
+ if dNode and not dNode.isNull():
3130
+ dgMod.deleteNode(dNode)
3131
+
3132
+ def getMObject(name):
3133
+ selected = om.MSelectionList()
3134
+ try:
3135
+ selected.add(name, True)
3136
+ except RuntimeError:
3137
+ return None
3138
+ if selected.isEmpty():
3139
+ return None
3140
+ thing = om.MObject()
3141
+ selected.getDependNode(0, thing)
3142
+ return thing
3143
+
3144
+ # get all .simplexDelete message attributes
3145
+ delAttrs = cmds.ls("*.simplexDelete")
3146
+ if delAttrs:
3147
+ # get all their connections
3148
+ cnx = cmds.listConnections(delAttrs, plugs=True, connections=True, destination=False)
3149
+
3150
+ # Set up the deletion callback
3151
+ mmIds = []
3152
+ for i in range(0, len(cnx), 2):
3153
+ parName, delName = cmds.ls(cnx[i:i+2], long=True, objectsOnly=True)
3154
+ pNode = getMObject(parName)
3155
+ dNode = getMObject(delName)
3156
+ om.MNodeMessage.addNodeAboutToDeleteCallback(pNode, simplexDelCB, (dNode, delName))
3157
+ """
3158
+
3159
+
3160
+ def buildDeleterScriptJob():
3161
+ dcbName = "SimplexDeleterCallback"
3162
+ if not cmds.ls(dcbName):
3163
+ cmds.scriptNode(
3164
+ scriptType=1,
3165
+ beforeScript=SIMPLEX_RESET_SCRIPTJOB,
3166
+ name=dcbName,
3167
+ sourceType="python",
3168
+ )
3169
+
3170
+
3171
+ def simplexDelCB(node, dgMod, clientData):
3172
+ xNode, dName = clientData
3173
+ dNode = getMObject(dName)
3174
+ if dNode and not dNode.isNull():
3175
+ dgMod.deleteNode(dNode)
3176
+
3177
+
3178
+ def getMObject(name):
3179
+ selected = om.MSelectionList()
3180
+ try:
3181
+ selected.add(name, True)
3182
+ except RuntimeError:
3183
+ return None
3184
+ if selected.isEmpty():
3185
+ return None
3186
+ thing = om.MObject()
3187
+ selected.getDependNode(0, thing)
3188
+ return thing
3189
+
3190
+
3191
+ def buildDeleterCallback(parName, delName):
3192
+ pNode = getMObject(parName)
3193
+ dNode = getMObject(delName)
3194
+ idNum = om.MNodeMessage.addNodeAboutToDeleteCallback(
3195
+ pNode, simplexDelCB, (dNode, delName)
3196
+ )
3197
+ return idNum