simplex-solver 3.2.2__cp39-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 (84) hide show
  1. simplex_solver-3.2.2.dist-info/DELVEWHEEL +2 -0
  2. simplex_solver-3.2.2.dist-info/METADATA +94 -0
  3. simplex_solver-3.2.2.dist-info/RECORD +84 -0
  4. simplex_solver-3.2.2.dist-info/WHEEL +5 -0
  5. simplex_solver.libs/.load-order-simplex_solver-3.2.2 +1 -0
  6. simplex_solver.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll +0 -0
  7. simplexui/__init__.py +86 -0
  8. simplexui/_version.py +1 -0
  9. simplexui/channelBox.py +867 -0
  10. simplexui/comboCheckDialog.py +396 -0
  11. simplexui/commands/__init__.py +16 -0
  12. simplexui/commands/alembicCommon.py +1148 -0
  13. simplexui/commands/alembic_walker.py +299 -0
  14. simplexui/commands/applyCorrectives.py +452 -0
  15. simplexui/commands/correctiveInterface.py +259 -0
  16. simplexui/commands/expandedExport.py +434 -0
  17. simplexui/commands/hdf5Convert.py +62 -0
  18. simplexui/commands/mayaCorrectiveInterface.py +159 -0
  19. simplexui/commands/mayatonumpy.py +416 -0
  20. simplexui/commands/mesh.py +1085 -0
  21. simplexui/commands/poseblendlib.py +168 -0
  22. simplexui/commands/reorderSimplexPoints.py +102 -0
  23. simplexui/commands/replaceDefinitionJson.py +74 -0
  24. simplexui/commands/rigidAlign.py +97 -0
  25. simplexui/commands/unsubdivide.py +1222 -0
  26. simplexui/commands/uvTransfer.py +976 -0
  27. simplexui/dragFilter.py +334 -0
  28. simplexui/falloffDialog.py +504 -0
  29. simplexui/img/ChefHead.png +0 -0
  30. simplexui/img/frozen.png +0 -0
  31. simplexui/interface/__init__.py +30 -0
  32. simplexui/interface/dummyInterface.py +1313 -0
  33. simplexui/interface/mayaInterface.py +2294 -0
  34. simplexui/interfaceModel.py +655 -0
  35. simplexui/interfaceModelTrees.py +456 -0
  36. simplexui/items/__init__.py +50 -0
  37. simplexui/items/accessor.py +145 -0
  38. simplexui/items/combo.py +645 -0
  39. simplexui/items/dragItem.py +44 -0
  40. simplexui/items/falloff.py +748 -0
  41. simplexui/items/group.py +267 -0
  42. simplexui/items/progression.py +613 -0
  43. simplexui/items/shape.py +384 -0
  44. simplexui/items/simplex.py +1734 -0
  45. simplexui/items/slider.py +632 -0
  46. simplexui/items/stack.py +147 -0
  47. simplexui/items/traversal.py +780 -0
  48. simplexui/items/treeItem.py +441 -0
  49. simplexui/main.pyw +22 -0
  50. simplexui/menu/__init__.py +73 -0
  51. simplexui/menu/dummyPlugins/__init__.py +16 -0
  52. simplexui/menu/genericPlugins/__init__.py +16 -0
  53. simplexui/menu/genericPlugins/_builtins.py +270 -0
  54. simplexui/menu/genericPlugins/checkPossibleCombos.py +48 -0
  55. simplexui/menu/genericPlugins/exportSplit.py +67 -0
  56. simplexui/menu/genericPlugins/showFalloffs.py +26 -0
  57. simplexui/menu/genericPlugins/showTraversals.py +26 -0
  58. simplexui/menu/genericPlugins/simplexUvTransfer.py +106 -0
  59. simplexui/menu/genericPlugins/unsubdivide.py +72 -0
  60. simplexui/menu/mayaPlugins/__init__.py +16 -0
  61. simplexui/menu/mayaPlugins/exportOther.py +53 -0
  62. simplexui/menu/mayaPlugins/extractProgressives.py +68 -0
  63. simplexui/menu/mayaPlugins/freezeCombo.py +247 -0
  64. simplexui/menu/mayaPlugins/generateShapeIncrementals.py +99 -0
  65. simplexui/menu/mayaPlugins/importObjs.py +199 -0
  66. simplexui/menu/mayaPlugins/linearizeTraversal.py +60 -0
  67. simplexui/menu/mayaPlugins/makeShelfBtn.py +67 -0
  68. simplexui/menu/mayaPlugins/relaxToSelection.py +76 -0
  69. simplexui/menu/mayaPlugins/reloadDefinition.py +44 -0
  70. simplexui/menu/mayaPlugins/snapToNeutral.py +71 -0
  71. simplexui/menu/mayaPlugins/softSelectToCluster.py +201 -0
  72. simplexui/menu/mayaPlugins/tweakMix.py +136 -0
  73. simplexui/menu/mayaPlugins/updateRestShape.py +113 -0
  74. simplexui/pysimplex.lib +0 -0
  75. simplexui/pysimplex.pyd +0 -0
  76. simplexui/simplexDialog.py +1547 -0
  77. simplexui/travCheckDialog.py +419 -0
  78. simplexui/traversalDialog.py +299 -0
  79. simplexui/ui/comboCheckDialog.ui +475 -0
  80. simplexui/ui/falloffDialog.ui +243 -0
  81. simplexui/ui/simplexDialog.ui +1458 -0
  82. simplexui/ui/travCheckDialog.ui +488 -0
  83. simplexui/ui/traversalDialog.ui +532 -0
  84. simplexui/utils.py +307 -0
@@ -0,0 +1,2294 @@
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
+ from __future__ import annotations
18
+
19
+ import json
20
+ import re
21
+ from contextlib import contextmanager
22
+ from functools import wraps
23
+ from typing import TYPE_CHECKING
24
+
25
+ import maya.cmds as cmds
26
+ import maya.OpenMaya as om
27
+ import numpy as np
28
+ from alembic.AbcGeom import GeometryScope, OPolyMeshSchemaSample, OV2fGeomParamSample
29
+ from imath import IntArray, UnsignedIntArray, V2fArray, V3fArray
30
+ from Qt import QtCore
31
+ from Qt.QtCore import Signal
32
+ from Qt.QtWidgets import (
33
+ QApplication,
34
+ QDialog,
35
+ QMainWindow,
36
+ QMessageBox,
37
+ QSplashScreen,
38
+ )
39
+
40
+ from ..commands.alembicCommon import buildAbc, mkSampleVertexPoints
41
+ from ..commands.mayatonumpy import mayaToNumpy
42
+
43
+
44
+ if TYPE_CHECKING:
45
+ from ..items.simplex import Simplex, Shape
46
+
47
+
48
+ # UNDO STACK INTEGRATION
49
+ @contextmanager
50
+ def undoContext(inst: DCC | None = None):
51
+ if inst is None:
52
+ DCC.staticUndoOpen()
53
+ else:
54
+ inst.undoOpen()
55
+ try:
56
+ yield
57
+ finally:
58
+ if inst is None:
59
+ DCC.staticUndoClose()
60
+ else:
61
+ inst.undoClose()
62
+
63
+
64
+ def undoable(f):
65
+ @wraps(f)
66
+ def stacker(*args, **kwargs):
67
+ inst = None
68
+ if args and isinstance(args[0], DCC):
69
+ inst = args[0]
70
+ with undoContext(inst):
71
+ return f(*args, **kwargs)
72
+
73
+ return stacker
74
+
75
+
76
+ def doDisconnect(targets, testCnxType=("double", "float")):
77
+ """Temporarily disconnect inputs from a list of nodes and plugs"""
78
+ if not isinstance(targets, (list, tuple)):
79
+ targets = [targets]
80
+ targets = list(set(targets))
81
+ cnxs = {}
82
+ for target in targets:
83
+ tcnx = {}
84
+ cnxs[target] = tcnx
85
+
86
+ cnx = cmds.listConnections(
87
+ target, plugs=True, destination=False, source=True, connections=True
88
+ )
89
+ if cnx is None:
90
+ cnx = []
91
+
92
+ for i in range(0, len(cnx), 2):
93
+ cnxType = cmds.getAttr(cnx[i], type=True)
94
+ if cnxType not in testCnxType:
95
+ continue
96
+ tcnx[cnx[i + 1]] = cnx[i]
97
+ cmds.disconnectAttr(cnx[i + 1], cnx[i])
98
+ return cnxs
99
+
100
+
101
+ def doReconnect(cnxs) -> None:
102
+ for tdict in cnxs.values():
103
+ for s, d in tdict.items():
104
+ if not cmds.isConnected(s, d):
105
+ cmds.connectAttr(s, d, force=True)
106
+
107
+
108
+ @contextmanager
109
+ def disconnected(targets, testCnxType=("double", "float")):
110
+ cnxs = doDisconnect(targets, testCnxType=testCnxType)
111
+ try:
112
+ yield cnxs
113
+ finally:
114
+ doReconnect(cnxs)
115
+
116
+
117
+ def split_trailing_digits(s: str) -> tuple[str, str]:
118
+ """Split trailing digits from a string into (prefix, digits)."""
119
+ match = re.match(r"^(.*?)(\d+)?$", s)
120
+ if match:
121
+ return match.group(1), match.group(2) or ""
122
+ return s, ""
123
+
124
+
125
+ class DCC:
126
+ program = "maya"
127
+
128
+ def __init__(self, simplex, stack=None) -> None:
129
+ if not cmds.pluginInfo("simplex_maya", query=True, loaded=True):
130
+ cmds.loadPlugin("simplex_maya")
131
+ self.undoDepth: int = 0
132
+ self.name: str = "" # the name of the system
133
+ self.mesh: str = "" # the mesh object with the system
134
+ self.ctrl: str = "" # the object that has all the controllers on it
135
+ self.shapeNode: str = "" # the deformer object
136
+ self.hasPoseNode = False
137
+ self.poseNode: str = "" # the pose deformer object
138
+ self.op: str = "" # the simplex object
139
+ self.simplex: Simplex = simplex # the abstract representation of the setup
140
+ self._live: bool = True
141
+ self.sliderMul: float = self.simplex.sliderMul
142
+
143
+ # def __deepcopy__(self, memo):
144
+ # I don't actually need to define this here because I know that
145
+ # all of the maya "objects" store here are just strings
146
+ # But if they *weren't* (like in XSI) I would need to skip
147
+ # the maya objects when deepcopying, otherwise I might access
148
+ # a deleted scene node and crash everything
149
+ # And if we did skip things, I would also need to store a
150
+ # persistent accessor to use in case we get back to here
151
+ # through an undo
152
+
153
+ def _checkAllShapeValidity(self, shapeNames):
154
+ """Check shapes to see if they exist, and either gather the missing files, or
155
+ Load the proper data onto the shapes
156
+ """
157
+ # Keep the set ordered, but make a set for quick checking
158
+ missingNameSet = set()
159
+ missingNames = []
160
+ seen = set()
161
+
162
+ # Get the blendshape weight names
163
+ try:
164
+ # GOOD GOD. This is because in maya 2016.5, if you delete a multi-instance
165
+ # then listAttr, *it lists the deleted ones, and skips the ones at the end*
166
+ # So I have to use aliasAttr and filter for the weights
167
+ aliases = cmds.aliasAttr(self.shapeNode, query=True) or []
168
+ attrs = [
169
+ aliases[i]
170
+ for i in range(0, len(aliases), 2)
171
+ if aliases[i + 1].startswith("weight[")
172
+ ]
173
+ attrs = set(attrs)
174
+
175
+ except ValueError:
176
+ attrs = set()
177
+
178
+ for shapeName in shapeNames:
179
+ if shapeName in seen:
180
+ continue
181
+ seen.add(shapeName)
182
+ if shapeName not in attrs:
183
+ if shapeName not in missingNameSet:
184
+ missingNameSet.add(shapeName)
185
+ missingNames.append(shapeName)
186
+ return missingNames, len(attrs)
187
+
188
+ @classmethod
189
+ def _removeExtraShapeNodes(cls, tfm) -> None:
190
+ shapeNodes = cmds.listRelatives(tfm, shapes=True, noIntermediate=True)
191
+ if len(shapeNodes) > 1:
192
+ keeper = None
193
+ todel = []
194
+ for sn in shapeNodes:
195
+ tfmChk = "".join(sn.rsplit("Shape", 1))
196
+ if tfmChk == tfm:
197
+ keeper = sn
198
+ else:
199
+ todel.append(sn)
200
+ if keeper is not None:
201
+ cmds.delete(todel)
202
+
203
+ def preLoad(self, simp, simpDict, create: bool = True, pBar=None) -> None:
204
+ cmds.undoInfo(state=False)
205
+ try:
206
+ if pBar is not None:
207
+ pBar.setLabelText("Loading Connections")
208
+ QApplication.processEvents()
209
+ ev = simpDict["encodingVersion"]
210
+
211
+ shapeNames = simpDict.get("shapes")
212
+ if not shapeNames:
213
+ return
214
+
215
+ if ev > 1:
216
+ shapeNames = [i["name"] for i in shapeNames]
217
+
218
+ toMake, nextIndex = self._checkAllShapeValidity(shapeNames)
219
+
220
+ if not toMake:
221
+ return
222
+
223
+ if not create:
224
+ if pBar is not None:
225
+ msg = "Some shapes are Missing:\n{}\n\nCreate them?"
226
+ msg = msg.format(", ".join(toMake))
227
+ btns = (
228
+ QMessageBox.StandardButton.Yes
229
+ | QMessageBox.StandardButton.Cancel
230
+ )
231
+ bret = QMessageBox.question(pBar, "Missing Shapes", msg, btns)
232
+ if not bret & QMessageBox.StandardButton.Yes:
233
+ raise RuntimeError(f"Missing Shapes: {toMake}")
234
+ else:
235
+ raise RuntimeError(f"Missing Shapes: {toMake}")
236
+
237
+ if pBar is not None:
238
+ spacer = "_" * max(list(map(len, toMake)))
239
+ pBar.setMaximum(len(toMake))
240
+ pBar.setLabelText(f"Creating Empty Shape:\n{spacer}")
241
+ pBar.setValue(0)
242
+ QApplication.processEvents()
243
+
244
+ baseShape = cmds.duplicate(self.mesh)[0]
245
+ cmds.delete(baseShape, constructionHistory=True)
246
+ self._removeExtraShapeNodes(baseShape)
247
+
248
+ for i, shapeName in enumerate(toMake):
249
+ if pBar is not None:
250
+ pBar.setLabelText(f"Creating Empty Shape:\n{shapeName}")
251
+ pBar.setValue(i)
252
+ QApplication.processEvents()
253
+
254
+ baseShape = cmds.rename(baseShape, shapeName)
255
+
256
+ index = self._firstAvailableIndex()
257
+ cmds.blendShape(
258
+ self.shapeNode, edit=True, target=(self.mesh, index, baseShape, 1.0)
259
+ )
260
+ weightAttr = f"{self.shapeNode}.weight[{index}]"
261
+ thing = cmds.ls(weightAttr)[0]
262
+
263
+ cmds.connectAttr(f"{self.op}.weights[{nextIndex}]", thing)
264
+ nextIndex += 1
265
+
266
+ cmds.delete(baseShape)
267
+ except Exception:
268
+ cmds.undoInfo(state=True)
269
+ raise
270
+
271
+ def postLoad(self, simp, preRet) -> None:
272
+ cmds.undoInfo(state=True)
273
+
274
+ def checkForErrors(self, window) -> None:
275
+ """Check for any DCC specific errors
276
+
277
+ Parameters
278
+ ----------
279
+ window : QMainWindow
280
+ The simplex window
281
+ """
282
+ shapeNodes = cmds.listRelatives(self.mesh, shapes=True, noIntermediate=True)
283
+ if len(shapeNodes) > 1:
284
+ msg = (
285
+ "The current mesh has multiple shape nodes.",
286
+ "The UI will still mostly work, but extracting/connecting shapes"
287
+ "may fail in unexpected ways.",
288
+ )
289
+ QMessageBox.warning(window, "Multiple Shape Nodes", "\n".join(msg))
290
+
291
+ def _getOpNodes(self, thing: str) -> list[str]:
292
+ hist: list[str] = cmds.listHistory(thing)
293
+ rawShapeNodes = cmds.ls(hist, type="blendShape")
294
+ rawPoseNodes = cmds.ls(hist, type="blendPose")
295
+
296
+ # Find any simplex ops connected to the history
297
+ # that have the given name
298
+ ops: list[str] = []
299
+ rawOps: list[str] = []
300
+ for sn in rawShapeNodes + rawPoseNodes:
301
+ op = (
302
+ cmds.listConnections(
303
+ f"{sn}.message",
304
+ source=False,
305
+ destination=True,
306
+ type="simplex_maya",
307
+ )
308
+ or []
309
+ )
310
+ rawOps.extend(op)
311
+ rawOps = list(set(rawOps))
312
+
313
+ for op in rawOps:
314
+ js = cmds.getAttr(op + ".definition") or ""
315
+ sn = json.loads(js).get("systemName")
316
+ if sn == self.name:
317
+ ops.append(op)
318
+
319
+ if len(ops) > 1:
320
+ raise RuntimeError(
321
+ "Found too many Simplex systems with the same name on the same object"
322
+ )
323
+ return ops
324
+
325
+ def _getShapeNodes(self, ops: list[str]):
326
+ shapeNodes = []
327
+ for op in ops:
328
+ try:
329
+ sn = cmds.listConnections(
330
+ f"{op}.shapeMsg",
331
+ source=True,
332
+ destination=False,
333
+ type="blendShape",
334
+ )
335
+ except ValueError:
336
+ continue
337
+ if sn:
338
+ shapeNodes.append(sn[0])
339
+ return shapeNodes
340
+
341
+ def _getPoseNodes(self, ops: list[str]):
342
+ poseNodes = []
343
+ for op in ops:
344
+ try:
345
+ sn = cmds.listConnections(
346
+ f"{op}.poseMsg",
347
+ source=True,
348
+ destination=False,
349
+ type="blendPose",
350
+ )
351
+ except ValueError:
352
+ continue
353
+ if sn:
354
+ poseNodes.append(sn[0])
355
+ return poseNodes
356
+
357
+ def _getCtrlNodes(self, ops: list[str]):
358
+ ctrlCnx = []
359
+ for op in ops:
360
+ ccnx = cmds.listConnections(
361
+ f"{op}.ctrlMsg",
362
+ source=True,
363
+ destination=False,
364
+ )
365
+ if ccnx:
366
+ ctrlCnx.append(ccnx[0])
367
+ return ctrlCnx
368
+
369
+ def _createShapeNode(self, name, mesh) -> str:
370
+ intermediates = [
371
+ shp
372
+ for shp in cmds.listRelatives(mesh, shapes=True, path=True)
373
+ if cmds.getAttr(shp + ".intermediateObject")
374
+ ]
375
+ meshToFreeze = mesh if not intermediates else intermediates[0]
376
+ isIntermediate = cmds.getAttr(meshToFreeze + ".intermediateObject")
377
+
378
+ # Unlock the normals on the rest head because blendshapes don't work with locked normals
379
+ # and you can't really do this after the blendshape has been created
380
+ cmds.polyNormalPerVertex(meshToFreeze, unFreezeNormal=True)
381
+ cmds.polySoftEdge(meshToFreeze, angle=180, constructionHistory=True)
382
+ cmds.setAttr(meshToFreeze + ".intermediateObject", 0)
383
+ cmds.delete(meshToFreeze, constructionHistory=True)
384
+ cmds.setAttr(meshToFreeze + ".intermediateObject", isIntermediate)
385
+
386
+ name = f"{name}_BS"
387
+ return cmds.blendShape(mesh, name=name, frontOfChain=True)[0]
388
+
389
+ def _createPoseNode(self, name) -> str:
390
+ name = f"{name}_BP"
391
+ return cmds.createNode("blendPose", name=name)
392
+
393
+ def _createSimplexNode(self, name):
394
+ op = cmds.createNode("simplex_maya", name=name)
395
+ cmds.addAttr(op, longName="revision", attributeType="long")
396
+ cmds.addAttr(op, longName="shapeMsg", attributeType="message")
397
+ cmds.addAttr(op, longName="poseMsg", attributeType="message")
398
+ cmds.addAttr(op, longName="ctrlMsg", attributeType="message")
399
+ return op
400
+
401
+ def _createControlNode(self, name, op):
402
+ tfmAttrs = [".tx", ".ty", ".tz", ".rx", ".ry", ".rz", ".sx", ".sy", ".sz", ".v"]
403
+ ctrl = cmds.group(empty=True, name=f"{name}_CTRL")
404
+ for attr in tfmAttrs:
405
+ cmds.setAttr(ctrl + attr, keyable=False, channelBox=False)
406
+ cmds.addAttr(ctrl, longName="solver", attributeType="message")
407
+ cmds.connectAttr(
408
+ f"{ctrl}.solver",
409
+ f"{op}.ctrlMsg",
410
+ )
411
+ return ctrl
412
+
413
+ # System IO
414
+ @undoable
415
+ def loadNodes(self, simp, thing, create: bool = True, pBar=None) -> None:
416
+ """Create a new system based on the simplex tree
417
+ Build any DCC objects that are missing if create=True
418
+ Raises a runtime error if missing objects are found and
419
+ create=False
420
+ """
421
+ self.name = simp.name
422
+ self.mesh = thing
423
+
424
+ ops = self._getOpNodes(thing)
425
+ sns = self._getShapeNodes(ops)
426
+ cc = self._getCtrlNodes(ops)
427
+
428
+ if not create and (not sns or not ops or not cc):
429
+ types = []
430
+ if not sns:
431
+ types.append("blendShape")
432
+ if not ops:
433
+ types.append("simplex_maya")
434
+ if not cc:
435
+ types.append("CTRL")
436
+
437
+ raise RuntimeError(
438
+ "Creation turned off and some objects are missing: {}".format(
439
+ ", ".join(types)
440
+ )
441
+ )
442
+
443
+ self.op = ops[0] if ops else self._createSimplexNode(self.name)
444
+ self.ctrl = cc[0] if cc else self._createControlNode(self.name, self.op)
445
+
446
+ self.shapeNode = sns[0] if sns else self._createShapeNode(self.name, self.mesh)
447
+ if not cmds.isConnected(f"{self.shapeNode}.message", f"{self.op}.shapeMsg"):
448
+ cmds.connectAttr(f"{self.shapeNode}.message", f"{self.op}.shapeMsg")
449
+
450
+ if self.hasPoseNode:
451
+ pns = self._getPoseNodes(ops)
452
+ self.poseNode = pns[0] if pns else self._createPoseNode(self.name)
453
+ if not cmds.isConnected(f"{self.poseNode}.message", f"{self.op}.poseMsg"):
454
+ cmds.connectAttr(f"{self.poseNode}.message", f"{self.op}.poseMsg")
455
+
456
+ def getShapeThing(self, shapeName):
457
+ s = cmds.ls(f"{self.shapeNode}.{shapeName}")
458
+ if not s:
459
+ return None
460
+ return s[0]
461
+
462
+ def getSliderThing(self, sliderName):
463
+ things = cmds.ls(f"{self.ctrl}.{sliderName}")
464
+ if not things:
465
+ return None
466
+ return things[0]
467
+
468
+ @classmethod
469
+ def buildDummyMesh(cls, name: str):
470
+ importHeadShape = cmds.createNode("mesh", name=name + "Shape")
471
+ badPar = cmds.listRelatives(importHeadShape, parent=True)[0]
472
+ importHead = cmds.rename(badPar, name)
473
+ return importHead, importHeadShape
474
+
475
+ @classmethod
476
+ @undoable
477
+ def buildRestAbc(cls, abcMesh, name):
478
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
479
+ cmds.loadPlugin("AbcImport")
480
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
481
+ raise RuntimeError("Unable to load the AbcImport plugin")
482
+
483
+ abcPath = str(abcMesh.getArchive())
484
+
485
+ abcNode = cmds.createNode("AlembicNode")
486
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
487
+ cmds.setAttr(abcNode + ".speed", 24) # Is this needed anymore?
488
+ cmds.setAttr(abcNode + ".time", 0)
489
+
490
+ importHead, importHeadShape = cls.buildDummyMesh("{0}_SIMPLEX".format(name))
491
+
492
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
493
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
494
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
495
+ cmds.sets(importHead, edit=True, forceElement="initialShadingGroup")
496
+ cmds.delete(abcNode)
497
+ return importHead
498
+
499
+ @classmethod
500
+ def vertCount(cls, mesh: str):
501
+ return cmds.polyEvaluate(mesh, vertex=True)
502
+
503
+ @undoable
504
+ def loadAbcPoses(self, abcMesh, js, pBar=None) -> None:
505
+ pass
506
+
507
+ @undoable
508
+ def loadAbc(self, abcMesh, js, pBar=None) -> None:
509
+ # UGH, I *REALLY* hate that this is faster
510
+ # But if I want to be "pure" about it, I should just bite the bullet
511
+ # and do the direct alembic manipulation in C++
512
+
513
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
514
+ cmds.loadPlugin("AbcImport")
515
+ if not cmds.pluginInfo("AbcImport", query=True, loaded=True):
516
+ raise RuntimeError("Unable to load the AbcImport plugin")
517
+
518
+ abcPath = str(abcMesh.getArchive())
519
+
520
+ abcNode = cmds.createNode("AlembicNode")
521
+ cmds.setAttr(abcNode + ".abc_File", abcPath, type="string")
522
+
523
+ timeUnits = {
524
+ "game": 15,
525
+ "film": 24,
526
+ "pal": 25,
527
+ "ntsc": 30,
528
+ "show": 48,
529
+ "palf": 50,
530
+ "ntscf": 60,
531
+ }
532
+
533
+ fps = cmds.currentUnit(time=True, query=True)
534
+ if isinstance(fps, str):
535
+ if fps.endswith("fps"):
536
+ fps = fps[:-3]
537
+ if fps in timeUnits:
538
+ fps = timeUnits[fps]
539
+ fps = float(fps)
540
+
541
+ cmds.setAttr(abcNode + ".speed", fps)
542
+
543
+ shapes = js["shapes"]
544
+ shapeDict = {i.name: i for i in self.simplex.shapes}
545
+
546
+ if js["encodingVersion"] > 1:
547
+ shapes = [i["name"] for i in shapes]
548
+
549
+ importHead, importHeadShape = self.buildDummyMesh("importHead")
550
+
551
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
552
+ cmds.polyEvaluate(importHead, vertex=True) # Force a refresh
553
+ cmds.disconnectAttr(abcNode + ".outPolyMesh[0]", importHeadShape + ".inMesh")
554
+
555
+ importRest = cmds.duplicate(self.mesh, name="importRest")[0]
556
+ cmds.delete(importRest, constructionHistory=True)
557
+ self._removeExtraShapeNodes(importRest)
558
+
559
+ importBS: str = cmds.blendShape(importRest, importHead)[0]
560
+ cmds.blendShape(importBS, edit=True, weight=[(0, 1.0)])
561
+ # Maybe get shapeNode from self.mesh??
562
+ importOrig = [
563
+ i for i in cmds.listRelatives(importHead, shapes=True) if i.endswith("Orig")
564
+ ][0]
565
+ cmds.connectAttr(abcNode + ".outPolyMesh[0]", importOrig + ".inMesh")
566
+ cmds.delete(importRest)
567
+
568
+ if pBar is not None:
569
+ pBar.show()
570
+ pBar.setMaximum(len(shapes))
571
+ longName = max(shapes, key=len)
572
+ pBar.setValue(1)
573
+ pBar.setLabelText("Loading:\n{}".format("_" * len(longName)))
574
+
575
+ for i, shapeName in enumerate(shapes):
576
+ if pBar is not None:
577
+ pBar.setValue(i)
578
+ pBar.setLabelText(f"Loading:\n{shapeName}")
579
+ QApplication.processEvents()
580
+ if pBar.wasCanceled():
581
+ return
582
+ index = self.getShapeIndex(shapeDict[shapeName])
583
+ cmds.setAttr(abcNode + ".time", i)
584
+
585
+ outAttr = f"{importHead}.worldMesh[0]"
586
+ tgn = f"{self.shapeNode}.inputTarget[0].inputTargetGroup[{index}]"
587
+ inAttr = f"{tgn}.inputTargetItem[6000].inputGeomTarget"
588
+
589
+ cmds.connectAttr(outAttr, inAttr, force=True)
590
+ cmds.disconnectAttr(outAttr, inAttr)
591
+ cmds.delete(abcNode)
592
+ cmds.delete(importHead)
593
+
594
+ def getAllShapeVertices(self, shapes, pBar=None) -> None:
595
+ sl = om.MSelectionList()
596
+ sl.add(self.mesh)
597
+ thing = om.MDagPath()
598
+ sl.getDagPath(0, thing)
599
+ meshFn = om.MFnMesh(thing)
600
+ _ptCount = meshFn.numVertices()
601
+ with disconnected(self.shapeNode) as cnx:
602
+ shapeCnx = cnx[self.shapeNode]
603
+ for v in shapeCnx.values():
604
+ cmds.setAttr(v, 0.0)
605
+
606
+ if pBar is not None:
607
+ # find the longest name for displaying stuff
608
+ sns = "_" * max(list(map(len, [s.name for s in shapes])))
609
+ pBar.setLabelText(f"Getting Shape:\n{sns}")
610
+ pBar.setMaximum(len(shapes))
611
+ QApplication.processEvents()
612
+
613
+ for i, shape in enumerate(shapes):
614
+ if pBar is not None:
615
+ pBar.setLabelText(f"Getting Shape:\n{shape.name}")
616
+ pBar.setValue(i)
617
+ QApplication.processEvents()
618
+
619
+ cmds.setAttr(shape.thing, 1.0)
620
+ mpts = om.MPointArray()
621
+ meshFn.getPoints(mpts)
622
+ out = mayaToNumpy(mpts)[:, :3]
623
+
624
+ cmds.setAttr(shape.thing, 0.0)
625
+ shape.verts = out
626
+
627
+ def getShapeVertices(self, shape):
628
+ with disconnected(self.shapeNode) as cnx:
629
+ shapeCnx = cnx[self.shapeNode]
630
+ for v in shapeCnx.values():
631
+ cmds.setAttr(v, 0.0)
632
+ cmds.setAttr(shape.thing, 1.0)
633
+ out = self.getNumpyShape(self.mesh)
634
+ return out
635
+
636
+ def pushAllShapeVertices(self, shapes, pBar=None) -> None:
637
+ # take all the verts stored on the shapes
638
+ # and push them back to the DCC
639
+ for shape in shapes:
640
+ self.pushShapeVertices(shape)
641
+
642
+ def pushShapeVertices(self, shape) -> None:
643
+ # Push the vertices for a specific shape back to the DCC
644
+ pass
645
+
646
+ @classmethod
647
+ def getMeshTopology(cls, mesh, uvName=None):
648
+ """Get the topology of a mesh
649
+
650
+ Parameters
651
+ ----------
652
+ mesh : object
653
+ The DCC Mesh to read
654
+ uvName : str, optional
655
+ The name of the uv set to read
656
+
657
+ Returns
658
+ -------
659
+ np.array :
660
+ The vertex array
661
+ np.array :
662
+ The "faces" array
663
+ np.array :
664
+ The "counts" array
665
+ np.array :
666
+ The uv positions
667
+ np.array :
668
+ The "uvFaces" array
669
+ """
670
+ # Get the MDagPath from the name of the mesh
671
+ sl = om.MSelectionList()
672
+ sl.add(mesh)
673
+ thing = om.MDagPath()
674
+ sl.getDagPath(0, thing)
675
+ meshFn = om.MFnMesh(thing)
676
+
677
+ vts = om.MPointArray()
678
+ meshFn.getPoints(vts, om.MSpace.kObject)
679
+ verts = [(vts[i].x, vts[i].y, vts[i].z) for i in range(vts.length())]
680
+
681
+ faces = []
682
+ counts = []
683
+ rawUvFaces = []
684
+
685
+ vIdx = om.MIntArray()
686
+
687
+ util = om.MScriptUtil()
688
+ util.createFromInt(0)
689
+ uvIdxPtr = util.asIntPtr()
690
+ uArray = om.MFloatArray()
691
+ vArray = om.MFloatArray()
692
+ meshFn.getUVs(uArray, vArray)
693
+ hasUvs = uArray.length() > 0
694
+
695
+ for i in range(meshFn.numPolygons()):
696
+ meshFn.getPolygonVertices(i, vIdx)
697
+ face = []
698
+ for j in reversed(range(vIdx.length())):
699
+ face.append(vIdx[j])
700
+ if hasUvs:
701
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
702
+ uvIdx = util.getInt(uvIdxPtr)
703
+ if uvIdx >= uArray.length() or uvIdx < 0:
704
+ uvIdx = 0
705
+ rawUvFaces.append(uvIdx)
706
+
707
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
708
+ faces.extend(face)
709
+ counts.append(vIdx.length())
710
+
711
+ if hasUvs:
712
+ uvs = [(uArray[i], vArray[i]) for i in range(len(vArray))]
713
+ uvFaces = rawUvFaces
714
+ else:
715
+ uvs = None
716
+ uvFaces = None
717
+
718
+ return verts, faces, counts, uvs, uvFaces
719
+
720
+ def loadMeshTopology(self) -> None:
721
+ self._faces, self._counts, self._uvs = self.getAbcFaces(self.mesh)
722
+
723
+ @classmethod
724
+ def getNumpyShape(cls, mesh: str, world=False):
725
+ """Get the np.array shape of the mesh connected to the smpx
726
+
727
+ Parameters
728
+ ----------
729
+ mesh : str
730
+ The name of the maya shape object
731
+ world : bool
732
+ Whether to get the points in worldspace, or local space
733
+
734
+ Returns
735
+ -------
736
+ : np.array
737
+ The point positions of the mesh
738
+ """
739
+ vts = cls._getMeshVertices(mesh, world=world)
740
+ ret = mayaToNumpy(vts)
741
+ return ret[..., :3].copy()
742
+
743
+ @classmethod
744
+ def _getMeshVertices(cls, mesh: str, world=False):
745
+ """ """
746
+ # Get the MDagPath from the name of the mesh
747
+ sl = om.MSelectionList()
748
+ sl.add(mesh)
749
+ thing = om.MDagPath()
750
+ sl.getDagPath(0, thing)
751
+ meshFn = om.MFnMesh(thing)
752
+ vts = om.MPointArray()
753
+ if world:
754
+ space = om.MSpace.kWorld
755
+ else:
756
+ space = om.MSpace.kObject
757
+ meshFn.getPoints(vts, space)
758
+ return vts
759
+
760
+ @classmethod
761
+ def _exportAbcVertices(cls, mesh, world=False):
762
+ vts = cls._getMeshVertices(mesh, world=world)
763
+ vertices = V3fArray(vts.length())
764
+ for i in range(vts.length()):
765
+ vertices[i] = (vts[i].x, vts[i].y, vts[i].z)
766
+ return vertices
767
+
768
+ @classmethod
769
+ def getAbcFaces(cls, mesh: str):
770
+ # Get the MDagPath from the name of the mesh
771
+ sl = om.MSelectionList()
772
+ sl.add(mesh)
773
+ thing = om.MDagPath()
774
+ sl.getDagPath(0, thing)
775
+ meshFn = om.MFnMesh(thing)
776
+
777
+ faces = []
778
+ faceCounts = []
779
+ # uvArray = []
780
+ uvIdxArray = []
781
+ vIdx = om.MIntArray()
782
+
783
+ util = om.MScriptUtil()
784
+ util.createFromInt(0)
785
+ uvIdxPtr = util.asIntPtr()
786
+ uArray = om.MFloatArray()
787
+ vArray = om.MFloatArray()
788
+ meshFn.getUVs(uArray, vArray)
789
+ hasUvs = uArray.length() > 0
790
+
791
+ for i in range(meshFn.numPolygons()):
792
+ meshFn.getPolygonVertices(i, vIdx)
793
+ face = []
794
+ for j in reversed(range(vIdx.length())):
795
+ face.append(vIdx[j])
796
+ if hasUvs:
797
+ meshFn.getPolygonUVid(i, j, uvIdxPtr)
798
+ uvIdx = util.getInt(uvIdxPtr)
799
+ if uvIdx >= uArray.length() or uvIdx < 0:
800
+ uvIdx = 0
801
+ uvIdxArray.append(uvIdx)
802
+
803
+ face = [vIdx[j] for j in reversed(range(vIdx.length()))]
804
+ faces.extend(face)
805
+ faceCounts.append(vIdx.length())
806
+
807
+ abcFaceIndices = IntArray(len(faces))
808
+ for i in range(len(faces)):
809
+ abcFaceIndices[i] = faces[i]
810
+
811
+ abcFaceCounts = IntArray(len(faceCounts))
812
+ for i in range(len(faceCounts)):
813
+ abcFaceCounts[i] = faceCounts[i]
814
+
815
+ if hasUvs:
816
+ abcUVArray = V2fArray(len(uArray))
817
+ for i in range(len(vArray)):
818
+ abcUVArray[i] = (uArray[i], vArray[i])
819
+ abcUVIdxArray = UnsignedIntArray(len(uvIdxArray))
820
+ for i in range(len(uvIdxArray)):
821
+ abcUVIdxArray[i] = uvIdxArray[i]
822
+ uv = OV2fGeomParamSample(
823
+ abcUVArray, abcUVIdxArray, GeometryScope.kFacevaryingScope
824
+ )
825
+ else:
826
+ uv = None
827
+
828
+ return abcFaceIndices, abcFaceCounts, uv
829
+
830
+ def exportAbc(
831
+ self,
832
+ dccMesh,
833
+ abcMesh,
834
+ js,
835
+ world: bool = False,
836
+ ensureCorrect: bool = False,
837
+ pBar=None,
838
+ ) -> None:
839
+ # export the data to alembic
840
+ if dccMesh is None:
841
+ dccMesh = self.mesh
842
+
843
+ shapeDict = {i.name: i for i in self.simplex.shapes}
844
+
845
+ shapeNames = js["shapes"]
846
+ if js["encodingVersion"] > 1:
847
+ shapeNames = [i["name"] for i in shapeNames]
848
+ shapes = [shapeDict[i] for i in shapeNames]
849
+
850
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
851
+ schema = abcMesh.getSchema()
852
+
853
+ if pBar is not None:
854
+ pBar.show()
855
+ pBar.setMaximum(len(shapes))
856
+ spacerName = "_" * max(list(map(len, shapeNames)))
857
+ pBar.setLabelText(f"Exporting:\n{spacerName}")
858
+ QApplication.processEvents()
859
+
860
+ if ensureCorrect:
861
+ # Since this code is used to both export and exportOther
862
+ # I only want to ensure that everything is correct only if
863
+ # I'm doing a normal export
864
+ envelope = cmds.getAttr(self.shapeNode + ".envelope")
865
+ cmds.setAttr(self.shapeNode + ".envelope", 1.0)
866
+
867
+ with disconnected(self.shapeNode) as cnx:
868
+ shapeCnx = cnx[self.shapeNode]
869
+ for v in shapeCnx.values():
870
+ cmds.setAttr(v, 0.0)
871
+ for i, shape in enumerate(shapes):
872
+ if pBar is not None:
873
+ pBar.setLabelText(f"Exporting:\n{shape.name}")
874
+ pBar.setValue(i)
875
+ QApplication.processEvents()
876
+ if pBar.wasCanceled():
877
+ return
878
+ cmds.setAttr(shape.thing, 1.0)
879
+ verts = self._exportAbcVertices(dccMesh, world=world)
880
+ if uvs is not None:
881
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts, uvs)
882
+ else:
883
+ abcSample = OPolyMeshSchemaSample(verts, faces, counts)
884
+ schema.set(abcSample)
885
+ cmds.setAttr(shape.thing, 0.0)
886
+
887
+ if ensureCorrect:
888
+ cmds.setAttr(self.shapeNode + ".envelope", envelope)
889
+
890
+ def exportOtherAbc(self, dccMesh, abcMesh, js, world=False, pBar=None):
891
+ """ """
892
+ shapeNames = js["shapes"]
893
+ if js["encodingVersion"] > 1:
894
+ shapeNames = [i["name"] for i in shapeNames]
895
+
896
+ if pBar is not None:
897
+ pBar.show()
898
+ pBar.setMaximum(len(shapeNames))
899
+ spacerName = "_" * max(list(map(len, shapeNames)))
900
+ pBar.setLabelText("Exporting:\n{0}".format(spacerName))
901
+ QApplication.processEvents()
902
+
903
+ # Get all the sliderVecs
904
+ shapeNames, inVecs, keyIdxs = self.simplex.buildInputVectors()
905
+ sliderVecs = [
906
+ [0.0] * len(self.simplex.sliders) for i in range(len(self.simplex.shapes))
907
+ ]
908
+ for iv, idx in zip(inVecs, keyIdxs):
909
+ sliderVecs[idx] = iv
910
+
911
+ # Get all the fully expanded shapes, and the activations per shape
912
+ with disconnected(self.op) as allSliderCnx:
913
+ sliderCnx = allSliderCnx[self.op]
914
+ # zero all slider vals on the op to get the rest shape
915
+ for a in sliderCnx.values():
916
+ cmds.setAttr(a, 0.0)
917
+ restVerts = self.getNumpyShape(dccMesh, world=world)
918
+
919
+ fullShapes = np.zeros((len(self.simplex.shapes), len(restVerts), 3))
920
+ shpValArray = np.zeros((len(self.simplex.shapes), len(self.simplex.shapes)))
921
+ for shpIdx, shape in enumerate(self.simplex.shapes):
922
+ if pBar is not None:
923
+ pBar.setLabelText("Reading Full Shapes:\n{0}".format(shape.name))
924
+ pBar.setValue(shpIdx)
925
+ QApplication.processEvents()
926
+ if pBar.wasCanceled():
927
+ raise RuntimeError("Cancelled!")
928
+
929
+ # Set the full vec for this shape
930
+ inVec = sliderVecs[shpIdx]
931
+ for vi, vv in enumerate(inVec):
932
+ cmds.setAttr(sliderCnx[self.simplex.sliders[vi].thing], vv)
933
+
934
+ fullShapes[shpIdx] = self.getNumpyShape(dccMesh, world=world)
935
+
936
+ ary = np.array(cmds.getAttr(self.op + ".weights")[0])
937
+ # Get rid of some floating point inaccuracies
938
+ ary[np.isclose(ary, 1.0)] = 1.0
939
+ ary[np.isclose(ary, 0.0)] = 0.0
940
+ shpValArray[shpIdx] = ary
941
+
942
+ deltaShapeArray = self._collapseDeltas(
943
+ self.simplex, restVerts, shpValArray, fullShapes, pBar=pBar
944
+ )
945
+
946
+ # Finally write the outputs
947
+ faces, counts, uvs = self.getAbcFaces(dccMesh)
948
+ schema = abcMesh.getSchema()
949
+ for shpIdx, shape in enumerate(self.simplex.shapes):
950
+ if pBar is not None:
951
+ pBar.setLabelText("writing:\n{0}".format(shape.name))
952
+ pBar.setValue(shpIdx)
953
+ QApplication.processEvents()
954
+ if pBar.wasCanceled():
955
+ raise RuntimeError("Cancelled!")
956
+ shpVerts = restVerts + deltaShapeArray[shpIdx]
957
+ shpVerts = mkSampleVertexPoints(shpVerts)
958
+ if uvs is not None:
959
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts, uvs)
960
+ else:
961
+ abcSample = OPolyMeshSchemaSample(shpVerts, faces, counts)
962
+ schema.set(abcSample)
963
+
964
+ @classmethod
965
+ def _collapseDeltas(cls, smpx, restVerts, shpValArray, fullShapes, pBar=None):
966
+ # Figure out what order to build the deltas
967
+ # so that the deltas exist when I try to combine them
968
+ ctrlOrder = smpx.controllersByDepth()
969
+ shapeOrder = [pp.shape for ctrl in ctrlOrder for pp in ctrl.prog.pairs]
970
+ shapeOrder = [i for i in shapeOrder if not i.isRest]
971
+
972
+ # Incrementally Build the numpy array of delta shapes
973
+ # build deltaShapeArray as a 2d array because numpy is like 10x faster on 2d arrays
974
+ indexByShape = {v: k for k, v in enumerate(smpx.shapes)}
975
+ deltaShapeArray = np.zeros((len(smpx.shapes), len(restVerts) * 3))
976
+ for shpOrderIdx, shape in enumerate(shapeOrder):
977
+ if pBar is not None:
978
+ pBar.setLabelText("Collapsing to Deltas:\n{0}".format(shape.name))
979
+ pBar.setValue(shpOrderIdx)
980
+ QApplication.processEvents()
981
+ if pBar.wasCanceled():
982
+ raise RuntimeError("Cancelled!")
983
+
984
+ shpIdx = indexByShape[shape]
985
+ base = np.dot(shpValArray[shpIdx], deltaShapeArray)
986
+ deltaShapeArray[shpIdx] = (
987
+ fullShapes[shpIdx] - restVerts - base.reshape((-1, 3))
988
+ ).flatten()
989
+
990
+ # And move that 2d array back into 3d
991
+ deltaShapeArray = deltaShapeArray.reshape((len(smpx.shapes), -1, 3))
992
+ return deltaShapeArray
993
+
994
+ def deleteObj(self, thing) -> None:
995
+ """Delete the given object"""
996
+ cmds.delete(thing)
997
+
998
+ def exportMesh(self, mesh, path) -> None:
999
+ """Export a mesh to the given path"""
1000
+ faces, counts, uvs = self.getAbcFaces(mesh)
1001
+ shape = self.getNumpyShape(mesh)
1002
+ name = mesh.split('|')[-1]
1003
+ buildAbc(path, shape, faces, counts, uvs, name=name)
1004
+
1005
+ # Revision tracking
1006
+ def getRevision(self):
1007
+ try:
1008
+ return cmds.getAttr(f"{self.op}.revision")
1009
+ except ValueError:
1010
+ # object does not exist
1011
+ return None
1012
+
1013
+ @undoable
1014
+ def incrementRevision(self):
1015
+ value = self.getRevision()
1016
+ if value is None:
1017
+ return
1018
+ cmds.setAttr(f"{self.op}.revision", value + 1)
1019
+ jsString = self.simplex.dump()
1020
+ self.setSimplexString(self.op, jsString)
1021
+ return value + 1
1022
+
1023
+ @undoable
1024
+ def setRevision(self, val) -> None:
1025
+ cmds.setAttr(f"{self.op}.revision", val)
1026
+
1027
+ # System level
1028
+ @undoable
1029
+ def renameSystem(self, name) -> None:
1030
+ if (
1031
+ self.mesh is None
1032
+ or self.ctrl is None
1033
+ or self.shapeNode is None
1034
+ or self.op is None
1035
+ or self.simplex is None
1036
+ ):
1037
+ raise ValueError("System is not set up. Cannot rename")
1038
+
1039
+ nn = self.mesh.replace(self.name, name)
1040
+ self.mesh = cmds.rename(self.mesh, nn)
1041
+
1042
+ nn = self.ctrl.replace(self.name, name)
1043
+ self.ctrl = cmds.rename(self.ctrl, nn)
1044
+
1045
+ oldNodeName = self.shapeNode
1046
+ nn = self.shapeNode.replace(self.name, name)
1047
+ self.shapeNode = cmds.rename(self.shapeNode, nn)
1048
+
1049
+ nn = self.op.replace(self.name, name)
1050
+ self.op = cmds.rename(self.op, nn)
1051
+
1052
+ for shape in self.simplex.shapes:
1053
+ shape.thing = shape.thing.replace(oldNodeName, self.shapeNode)
1054
+
1055
+ self.name = name
1056
+
1057
+ @undoable
1058
+ def deleteSystem(self) -> None:
1059
+ cmds.delete(self.ctrl)
1060
+ cmds.delete(self.shapeNode)
1061
+ cmds.delete(self.op)
1062
+ self.ctrl = None # the object that has all the controllers on it
1063
+ self.shapeNode = None # the deformer object
1064
+ self.op = None # the simplex object
1065
+ self.simplex = None
1066
+
1067
+ # Shapes
1068
+ @undoable
1069
+ def createShape(self, shape, live: bool = False, offset: int = 10):
1070
+ with disconnected(self.shapeNode):
1071
+ try:
1072
+ attrs = cmds.listAttr(f"{self.shapeNode}.weight[*]")
1073
+ except ValueError:
1074
+ pass
1075
+ # Maya throws an error if there aren't any instead of
1076
+ # just returning an empty list
1077
+ else:
1078
+ for attr in attrs:
1079
+ cmds.setAttr(f"{self.shapeNode}.{attr}", 0.0)
1080
+ newShape = cmds.duplicate(self.mesh, name=shape.name)[0]
1081
+
1082
+ cmds.delete(newShape, constructionHistory=True)
1083
+ index = self._firstAvailableIndex()
1084
+ cmds.blendShape(
1085
+ self.shapeNode, edit=True, target=(self.mesh, index, newShape, 1.0)
1086
+ )
1087
+ weightAttr = f"{self.shapeNode}.weight[{index}]"
1088
+ thing = cmds.ls(weightAttr)[0]
1089
+
1090
+ shapeIndex = len(shape.simplex.shapes) - 1
1091
+ cmds.connectAttr(f"{self.op}.weights[{shapeIndex}]", thing)
1092
+
1093
+ if live:
1094
+ cmds.xform(newShape, relative=True, translation=[offset, 0, 0])
1095
+ else:
1096
+ cmds.delete(newShape)
1097
+
1098
+ return thing
1099
+
1100
+ def _firstAvailableIndex(self) -> int:
1101
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1102
+ idxs = set()
1103
+ if not aliases:
1104
+ return 0
1105
+ for alias in aliases:
1106
+ match = re.search(r"\[\d+\]", alias)
1107
+ if not match:
1108
+ continue # No index found for the current shape
1109
+ idxs.add(int(match.group().strip("[]")))
1110
+
1111
+ for i in range(len(idxs) + 1):
1112
+ if i not in idxs:
1113
+ return i
1114
+ # there should be no way to get here, but just in case:
1115
+ return len(idxs) + 1
1116
+
1117
+ def getShapeIndex(self, shape: Shape) -> int:
1118
+ aName = cmds.attributeName(shape.thing)
1119
+ aliases = cmds.aliasAttr(self.shapeNode, query=True)
1120
+ idx = aliases.index(aName)
1121
+ raw = aliases[idx + 1]
1122
+ matches = re.findall(r"\[\d+\]", raw)
1123
+ if not matches:
1124
+ raise IndexError("No index found for the current shape")
1125
+ return int(matches[-1].strip("[]"))
1126
+
1127
+ @undoable
1128
+ def extractWithDeltaShape(self, shape, live: bool = True, offset: float = 10.0):
1129
+ """Make a mesh representing a shape. Can be live or not.
1130
+ Also, make a shapenode that is the delta of the change being made
1131
+ """
1132
+ with disconnected(self.shapeNode) as cnx:
1133
+ shapeCnx = cnx[self.shapeNode]
1134
+ for v in shapeCnx.values():
1135
+ cmds.setAttr(v, 0.0)
1136
+
1137
+ # store the delta shape
1138
+ delta = cmds.duplicate(self.mesh, name=f"{shape.name}_Delta")[0]
1139
+
1140
+ # Extract the shape
1141
+ cmds.setAttr(shape.thing, 1.0)
1142
+ extracted = cmds.duplicate(self.mesh, name=f"{shape.name}_Extract")[0]
1143
+
1144
+ # Store the initial shape
1145
+ init = cmds.duplicate(extracted, name=f"{shape.name}_Init")[0]
1146
+
1147
+ # clear old orig objects
1148
+ for item in [delta, extracted, init]:
1149
+ self._clearShapes(item, doOrig=True)
1150
+
1151
+ # build the deltaObj system
1152
+ bs = cmds.blendShape(delta, name=f"{shape.name}_DeltaBS")[0]
1153
+
1154
+ cmds.blendShape(bs, edit=True, target=(delta, 0, init, 1.0))
1155
+ cmds.blendShape(bs, edit=True, target=(delta, 1, extracted, 1.0))
1156
+
1157
+ cmds.setAttr(f"{bs}.{init}", -1.0)
1158
+ cmds.setAttr(f"{bs}.{extracted}", 1.0)
1159
+
1160
+ # Cleanup
1161
+ nodeDict = {"Delta": delta, "Init": init}
1162
+ repDict = self._reparentDeltaShapes(extracted, nodeDict, bs)
1163
+
1164
+ # Shift the extracted shape to the side
1165
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1166
+
1167
+ if live:
1168
+ self.connectShape(shape, extracted, live, delete=False)
1169
+
1170
+ return extracted, repDict["Delta"]
1171
+
1172
+ @undoable
1173
+ def extractWithDeltaConnection(
1174
+ self, shape, delta, value, live: bool = True, offset: float = 10.0
1175
+ ):
1176
+ """Extract a shape with a live partial delta added in.
1177
+ Useful for updating progressive shapes
1178
+ """
1179
+ with disconnected(self.shapeNode):
1180
+ for attr in cmds.listAttr(f"{self.shapeNode}.weight[*]"):
1181
+ cmds.setAttr(f"{self.shapeNode}.{attr}", 0.0)
1182
+
1183
+ # Pull out the rest shape. we will blend this guy to the extraction
1184
+ extracted = cmds.duplicate(self.mesh, name=f"{shape.name}_Extract")[0]
1185
+
1186
+ cmds.setAttr(shape.thing, 1.0)
1187
+ # Store the initial shape
1188
+ init = cmds.duplicate(self.mesh, name=f"{shape.name}_Init")[0]
1189
+
1190
+ # clear old orig objects
1191
+ for item in [init, extracted]:
1192
+ self._clearShapes(item, doOrig=True)
1193
+
1194
+ deltaPar = cmds.listRelatives(delta, parent=True)[0]
1195
+
1196
+ # build the restObj system
1197
+ cmds.select(clear=True) # 'cause maya
1198
+ bs = cmds.blendShape(extracted, name=f"{shape.name}_DeltaBS")[0]
1199
+ cmds.blendShape(bs, edit=True, target=(extracted, 0, init, 1.0))
1200
+ cmds.blendShape(bs, edit=True, target=(extracted, 1, deltaPar, 1.0))
1201
+
1202
+ cmds.setAttr(f"{bs}.{init}", 1.0)
1203
+ cmds.setAttr(f"{bs}.{deltaPar}", value)
1204
+
1205
+ outCnx = f"{delta}.worldMesh[0]"
1206
+ inCnx = f"{bs}.inputTarget[0].inputTargetGroup[{1}].inputTargetItem[6000].inputGeomTarget"
1207
+ cmds.connectAttr(outCnx, inCnx, force=True)
1208
+ cmds.aliasAttr(delta, f"{bs}.{deltaPar}")
1209
+
1210
+ # Cleanup
1211
+ nodeDict = {"Init": init}
1212
+ self._reparentDeltaShapes(extracted, nodeDict, bs)
1213
+
1214
+ # Remove the tweak node, otherwise editing the input progressives
1215
+ # *inverts* the shape
1216
+ exShape = cmds.listRelatives(extracted, noIntermediate=1, shapes=1)[0]
1217
+ tweak = cmds.listConnections(
1218
+ exShape + ".tweakLocation", source=1, destination=0
1219
+ )
1220
+ if tweak:
1221
+ cmds.delete(tweak)
1222
+
1223
+ # Shift the extracted shape to the side
1224
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1225
+ self.connectShape(shape, extracted, live, delete=False)
1226
+
1227
+ return extracted
1228
+
1229
+ @undoable
1230
+ def extractShape(self, shape, live: bool = True, offset: float = 10.0):
1231
+ """Make a mesh representing a shape. Can be live or not.
1232
+ Can also store its starting shape and delta data
1233
+ """
1234
+ with disconnected(self.shapeNode):
1235
+ for attr in cmds.listAttr(f"{self.shapeNode}.weight[*]"):
1236
+ cmds.setAttr(f"{self.shapeNode}.{attr}", 0.0)
1237
+
1238
+ cmds.setAttr(shape.thing, 1.0)
1239
+ extracted = cmds.duplicate(self.mesh, name=f"{shape.name}_Extract")[0]
1240
+
1241
+ # Shift the extracted shape to the side
1242
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1243
+ if live:
1244
+ self.connectShape(shape, extracted, live, delete=False)
1245
+ return extracted
1246
+
1247
+ @undoable
1248
+ def connectShape(self, shape, mesh=None, live=False, delete=False) -> None:
1249
+ """Force a shape to match a mesh
1250
+ The "connect shape" button is:
1251
+ mesh=None, delete=True
1252
+ The "match shape" button is:
1253
+ mesh=someMesh, delete=False
1254
+ There is a possibility of a "make live" button:
1255
+ live=True, delete=False
1256
+ """
1257
+ if mesh is None:
1258
+ attrName = cmds.attributeName(shape.thing, long=True)
1259
+ mesh = f"{attrName}_Extract"
1260
+
1261
+ chk = cmds.ls(mesh)
1262
+ if not chk:
1263
+ return
1264
+ if len(chk) > 1:
1265
+ msg = "Multiple objects with the same name found in file:\n"
1266
+ msg += '\n'.join(chk)
1267
+ raise ValueError(msg)
1268
+
1269
+ index = self.getShapeIndex(shape)
1270
+ tgn = f"{self.shapeNode}.inputTarget[0].inputTargetGroup[{index}]"
1271
+ cnx = mesh + "Shape" if cmds.nodeType(mesh) == "transform" else mesh
1272
+
1273
+ outAttr = f"{cnx}.worldMesh[0]" # Make sure to check the right shape object
1274
+ inAttr = f"{tgn}.inputTargetItem[6000].inputGeomTarget"
1275
+
1276
+ if not cmds.isConnected(outAttr, inAttr):
1277
+ cmds.connectAttr(outAttr, inAttr, force=True)
1278
+
1279
+ if not live:
1280
+ cmds.disconnectAttr(outAttr, inAttr)
1281
+
1282
+ if delete:
1283
+ cmds.delete(mesh)
1284
+
1285
+ @undoable
1286
+ def extractPosedShape(self, shape) -> None:
1287
+ pass
1288
+
1289
+ @undoable
1290
+ def zeroShape(self, shape) -> None:
1291
+ """Set the shape to be completely zeroed"""
1292
+ index = self.getShapeIndex(shape)
1293
+ tgn = f"{self.shapeNode}.inputTarget[0].inputTargetGroup[{index}]"
1294
+ shapeInput = f"{tgn}.inputTargetItem[6000]"
1295
+ cmds.setAttr(f"{shapeInput}.inputPointsTarget", 0, (), type="pointArray")
1296
+ cmds.setAttr(f"{shapeInput}.inputComponentsTarget", 0, "", type="componentList")
1297
+
1298
+ @undoable
1299
+ def deleteShape(self, toDelShape) -> None:
1300
+ """Remove a shape from the system"""
1301
+ index = self.getShapeIndex(toDelShape)
1302
+ tgn = f"{self.shapeNode}.inputTarget[0].inputTargetGroup[{index}]"
1303
+ cmds.removeMultiInstance(toDelShape.thing, b=True)
1304
+ cmds.removeMultiInstance(tgn, b=True)
1305
+ cmds.aliasAttr(toDelShape.thing, remove=True)
1306
+ self._rebuildShapeConnections()
1307
+
1308
+ def _rebuildShapeConnections(self) -> None:
1309
+ # Rebuild the shape connections in the proper order
1310
+ cnxs = (
1311
+ cmds.listConnections(
1312
+ self.op, plugs=True, source=False, destination=True, connections=True
1313
+ )
1314
+ or []
1315
+ )
1316
+ for i, cnx in enumerate(cnxs):
1317
+ if i % 2 == 0 and cnx.startswith(f"{self.op}.weights["):
1318
+ cmds.disconnectAttr(cnxs[i], cnxs[i + 1])
1319
+
1320
+ for i, shape in enumerate(self.simplex.shapes):
1321
+ cmds.connectAttr(f"{self.op}.weights[{i}]", shape.thing, force=True)
1322
+
1323
+ @undoable
1324
+ def forceRebuildShapeConnections(self) -> None:
1325
+ self._rebuildShapeConnections()
1326
+
1327
+ @undoable
1328
+ def renameShape(self, shape, name) -> None:
1329
+ """Change the name of the shape"""
1330
+ cmds.aliasAttr(name, shape.thing)
1331
+ shape.thing = f"{self.shapeNode}.{name}"
1332
+
1333
+ @undoable
1334
+ def convertShapeToCorrective(self, shape) -> None:
1335
+ pass
1336
+
1337
+ # Falloffs
1338
+ def createFalloff(self, name) -> None:
1339
+ pass # for eventual live splits
1340
+
1341
+ def duplicateFalloff(self, falloff, newFalloff, newName) -> None:
1342
+ pass # for eventual live splits
1343
+
1344
+ def deleteFalloff(self, falloff) -> None:
1345
+ pass # for eventual live splits
1346
+
1347
+ def setFalloffData(
1348
+ self, falloff, splitType, axis, minVal, minHandle, maxHandle, maxVal, mapName
1349
+ ) -> None:
1350
+ pass # for eventual live splits
1351
+
1352
+ def getFalloffThing(self, falloff):
1353
+ shape = cmds.listRelatives(self.mesh, shapes=True)[0]
1354
+ return shape + "." + falloff.name
1355
+
1356
+ # Sliders
1357
+ @undoable
1358
+ def createSlider(self, slider) -> str:
1359
+ index = slider.simplex.sliders.index(slider)
1360
+ cmds.addAttr(
1361
+ self.ctrl,
1362
+ longName=slider.name,
1363
+ attributeType="double",
1364
+ keyable=True,
1365
+ min=slider.minValue * self.sliderMul,
1366
+ max=slider.maxValue * self.sliderMul,
1367
+ )
1368
+ thing = f"{self.ctrl}.{slider.name}"
1369
+ cmds.connectAttr(thing, f"{self.op}.sliders[{index}]")
1370
+ return thing
1371
+
1372
+ @undoable
1373
+ def renameSlider(self, slider, name) -> None:
1374
+ """Set the name of a slider"""
1375
+ vals = [v.value for v in slider.prog.pairs]
1376
+ cnx = cmds.listConnections(
1377
+ slider.thing, plugs=True, source=False, destination=True
1378
+ )
1379
+ cmds.deleteAttr(slider.thing)
1380
+ cmds.addAttr(
1381
+ self.ctrl,
1382
+ longName=name,
1383
+ attributeType="double",
1384
+ keyable=True,
1385
+ min=self.sliderMul * min(vals),
1386
+ max=self.sliderMul * max(vals),
1387
+ )
1388
+ newThing = f"{self.ctrl}.{name}"
1389
+ slider.thing = newThing
1390
+ for c in cnx:
1391
+ cmds.connectAttr(newThing, c)
1392
+
1393
+ @undoable
1394
+ def setSliderRange(self, slider) -> None:
1395
+ """Set the range of a slider"""
1396
+ vals = [v.value for v in slider.prog.pairs]
1397
+ attrName = f"{self.ctrl}.{slider.name}"
1398
+ cmds.addAttr(
1399
+ attrName,
1400
+ edit=True,
1401
+ min=self.sliderMul * min(vals),
1402
+ max=self.sliderMul * max(vals),
1403
+ )
1404
+
1405
+ @undoable
1406
+ def deleteSlider(self, toDelSlider) -> None:
1407
+ cmds.deleteAttr(toDelSlider.thing)
1408
+
1409
+ # Rebuild the slider connections in the proper order
1410
+ # Get the sliders connections
1411
+ cnxs = cmds.listConnections(
1412
+ self.op, plugs=True, source=True, destination=False, connections=True
1413
+ )
1414
+ for i, cnx in enumerate(cnxs):
1415
+ if cnx.startswith(f"{self.op}.sliders"):
1416
+ cmds.disconnectAttr(cnxs[i + 1], cnxs[i])
1417
+
1418
+ for i, slider in enumerate(self.simplex.sliders):
1419
+ cmds.connectAttr(slider.thing, f"{self.op}.sliders[{i}]")
1420
+
1421
+ @undoable
1422
+ def addProgFalloff(self, prog, falloff) -> None:
1423
+ pass # for eventual live splits
1424
+
1425
+ @undoable
1426
+ def removeProgFalloff(self, prog, falloff) -> None:
1427
+ pass # for eventual live splits
1428
+
1429
+ @undoable
1430
+ def setSlidersWeights(self, sliders, weights) -> None:
1431
+ """Set the weight of a slider. This does not change the definition"""
1432
+ for slider, weight in zip(sliders, weights):
1433
+ try:
1434
+ cmds.setAttr(slider.thing, weight)
1435
+ except RuntimeError:
1436
+ # Probably locked or connected. Just skip it
1437
+ pass
1438
+
1439
+ @undoable
1440
+ def setSliderWeight(self, slider, weight) -> None:
1441
+ try:
1442
+ cmds.setAttr(slider.thing, weight)
1443
+ except RuntimeError:
1444
+ # Probably locked or connected. Just skip it
1445
+ pass
1446
+
1447
+ @undoable
1448
+ def updateSlidersRange(self, sliders) -> None:
1449
+ for slider in sliders:
1450
+ vals = [v.value for v in slider.prog.pairs]
1451
+ cmds.addAttr(
1452
+ slider.thing,
1453
+ edit=True,
1454
+ min=min(vals) * self.sliderMul,
1455
+ max=max(vals) * self.sliderMul,
1456
+ )
1457
+
1458
+ def _doesDeltaExist(self, combo, target):
1459
+ dshape = f"{combo.name}_DeltaShape"
1460
+ if not cmds.ls(dshape):
1461
+ return None
1462
+ par = cmds.listRelatives(dshape, allParents=1)
1463
+ if not par:
1464
+ # there is apparently a transform object with the name
1465
+ return None
1466
+
1467
+ par = cmds.ls(par[0], absoluteName=1)
1468
+ tar = cmds.ls(target, absoluteName=1)
1469
+
1470
+ if par != tar:
1471
+ # the shape exists under a different transform ... ugh
1472
+ return None
1473
+ return par + "|" + dshape
1474
+
1475
+ def _clearShapes(self, item, doOrig=False) -> None:
1476
+ aname = cmds.ls(item, long=1)[0]
1477
+ shapes = cmds.ls(cmds.listRelatives(item, shapes=1), long=1)
1478
+ baseName = aname.split("|")[-1]
1479
+ baseName, digits = split_trailing_digits(baseName)
1480
+
1481
+ primary = f"{aname}|{baseName}Shape{digits}"
1482
+
1483
+ origs = []
1484
+ others = []
1485
+ for shape in shapes:
1486
+ base, digits = split_trailing_digits(shape)
1487
+ if base.endswith('Orig'):
1488
+ origs.append(shape)
1489
+ else:
1490
+ others.append(shape)
1491
+
1492
+ for shape in others:
1493
+ if shape == primary:
1494
+ continue
1495
+ cmds.delete(shape)
1496
+
1497
+ if doOrig:
1498
+ cmds.delete(origs)
1499
+ else:
1500
+ # Don't delete the first orig
1501
+ if len(origs) > 1:
1502
+ origs = sorted(origs)
1503
+ cmds.delete(origs[1:])
1504
+
1505
+ @undoable
1506
+ def forceRebuildSliderConnections(self) -> None:
1507
+ self._rebuildSliderConnections()
1508
+
1509
+ def _rebuildSliderConnections(self) -> None:
1510
+ # disconnect all outputs from the ctrl
1511
+ rcnx = cmds.listConnections(
1512
+ self.ctrl, source=False, plugs=True, connections=True
1513
+ )
1514
+ for i in range(0, len(rcnx), 2):
1515
+ src, dst = rcnx[i], rcnx[i + 1]
1516
+ if cmds.getAttr(src, type=True) != "double":
1517
+ # only disconnect doubles
1518
+ continue
1519
+ cmds.disconnectAttr(src, dst)
1520
+
1521
+ # Reconnect by name
1522
+ for i, sli in enumerate(self.simplex.sliders):
1523
+ thing = self.getSliderThing(sli.name)
1524
+ cmds.connectAttr(thing, self.op + f".sliders[{i}]")
1525
+
1526
+ # Combos
1527
+ def _reparentDeltaShapes(self, par, nodeDict, bsNode, toDelete=None):
1528
+ """Reparent and clean up a single-transform delta system
1529
+
1530
+ Put all the relevant shape nodes from the nodeDict under the par,
1531
+ and rename the shapes to maya's convention. Then build a callback
1532
+ to ensure the blendshape node isn't left floating
1533
+
1534
+ par: The parent transform node
1535
+ nodeDict: A {simpleName: node} dictionary.
1536
+ bsNode: The blendshape node.
1537
+ toDelete: Any extra nodes to delte after all the node twiddling
1538
+ """
1539
+ # Get the shapes and origs
1540
+ shapeDict = {}
1541
+ origDict = {}
1542
+
1543
+ for name, node in nodeDict.items():
1544
+ shape = cmds.listRelatives(node, noIntermediate=1, shapes=1)[0]
1545
+ shape = cmds.ls(shape, absoluteName=1)[0]
1546
+ if shape:
1547
+ shapeDict[name] = shape
1548
+
1549
+ orig = shape + "Orig"
1550
+ orig = cmds.ls(orig)
1551
+ if orig:
1552
+ origDict[name] = orig
1553
+
1554
+ for name in nodeDict:
1555
+ for d, fmt in [(shapeDict, "{0}Shape{1}"), (origDict, "{0}Shape{1}Orig")]:
1556
+ shape = d.get(name)
1557
+ if shape is None:
1558
+ continue
1559
+ shapeUUID = cmds.ls(shape, uuid=1)[0]
1560
+ cmds.parent(shape, par, shape=True, relative=True)
1561
+ newShape = cmds.rename(cmds.ls(shapeUUID)[0], fmt.format(par, name))
1562
+ d[name] = newShape
1563
+ cmds.setAttr(newShape + ".intermediateObject", 1)
1564
+ cmds.hide(newShape)
1565
+
1566
+ cmds.delete(nodeDict[name])
1567
+
1568
+ if toDelete:
1569
+ cmds.delete(toDelete)
1570
+
1571
+ # Use the simplexDelete message attribute to keep track of what nodes
1572
+ # will need to be delete-linked when the file is reopened
1573
+ sdNode = par + ".simplexDelete"
1574
+ if not cmds.ls(sdNode):
1575
+ cmds.addAttr(par, longName="simplexDelete", attributeType="message")
1576
+ cmds.connectAttr(bsNode + ".message", sdNode)
1577
+
1578
+ # build the callback setup so the blendshape is deleted with the delta setup
1579
+ # along with a persistent scriptjob
1580
+ buildDeleterCallback(par, bsNode)
1581
+ buildDeleterScriptJob()
1582
+
1583
+ return shapeDict
1584
+
1585
+ def _createTravDelta(self, trav, target, tVal, doReparent=True):
1586
+ """Part of the traversal extraction process.
1587
+ Very similar to the combo extraction
1588
+ """
1589
+ exists = self._doesDeltaExist(trav, target)
1590
+ if exists is not None:
1591
+ return exists
1592
+
1593
+ # Traversals *MAY* depend on floaters, but that's complicated
1594
+ # I'm just gonna ignore them for now
1595
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
1596
+
1597
+ # Get all traversal shapes
1598
+ tShapes = []
1599
+ for oTrav in self.simplex.traversals:
1600
+ tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
1601
+
1602
+ with disconnected(self.op) as cnx:
1603
+ sliderCnx = cnx[self.op]
1604
+
1605
+ # zero all slider vals on the op
1606
+ for a in sliderCnx.values():
1607
+ cmds.setAttr(a, 0.0)
1608
+
1609
+ with disconnected(floatShapes + tShapes):
1610
+ # pull out the rest shape
1611
+ rest = cmds.duplicate(self.mesh, name=f"{trav.name}_Rest")[0]
1612
+
1613
+ sliDict = {}
1614
+ for pair in trav.startPoint.pairs:
1615
+ sliDict[pair.slider] = [pair.value]
1616
+ for pair in trav.endPoint.pairs:
1617
+ sliDict[pair.slider].append(pair.value)
1618
+
1619
+ for slider, (start, end) in sliDict.items():
1620
+ vv = start + tVal * (end - start)
1621
+ cmds.setAttr(sliderCnx[slider.thing], vv)
1622
+
1623
+ deltaObj = cmds.duplicate(self.mesh, name=f"{trav.name}_Delta")[0]
1624
+ base = cmds.duplicate(deltaObj, name=f"{trav.name}_Base")[0]
1625
+
1626
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
1627
+ for item in [rest, deltaObj, base]:
1628
+ self._clearShapes(item, doOrig=True)
1629
+
1630
+ # Build the delta blendshape setup
1631
+ bs = cmds.blendShape(deltaObj, name=f"{trav.name}_DeltaBS")[0]
1632
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
1633
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
1634
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
1635
+ cmds.setAttr(f"{bs}.{target}", 1.0)
1636
+ cmds.setAttr(f"{bs}.{base}", 1.0)
1637
+ cmds.setAttr(f"{bs}.{rest}", 1.0)
1638
+
1639
+ # Cleanup
1640
+ if doReparent:
1641
+ nodeDict = {"Delta": deltaObj}
1642
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
1643
+ return repDict["Delta"]
1644
+ return deltaObj
1645
+
1646
+ @undoable
1647
+ def extractTraversalShape(
1648
+ self, trav, shape, live: bool = True, offset: float = 10.0
1649
+ ):
1650
+ """Extract a shape from a Traversal progression"""
1651
+ floatShapes = self.simplex.getFloatingShapes()
1652
+ floatShapes = [i.thing for i in floatShapes]
1653
+
1654
+ shapeIdx = trav.prog.getShapeIndex(shape)
1655
+ val = trav.prog.pairs[shapeIdx].value
1656
+
1657
+ # TODO: Do traversals interact? Should I turn off any other traversals?
1658
+ # For now, no, but it may be a thing
1659
+ # tShapes = []
1660
+ # for oTrav in self.simplex.traversals:
1661
+ # if oTrav is trav: continue
1662
+ # tShapes.extend([i.thing for i in oTrav.prog.getShapes()])
1663
+
1664
+ with disconnected(self.op) as cnx:
1665
+ sliderCnx = cnx[self.op]
1666
+ # zero all slider vals on the op
1667
+ for a in sliderCnx.values():
1668
+ cmds.setAttr(a, 0.0)
1669
+
1670
+ with disconnected(floatShapes): # tShapes
1671
+ sliDict = {}
1672
+ for pair in trav.startPoint.pairs:
1673
+ sliDict[pair.slider] = [pair.value]
1674
+ for pair in trav.endPoint.pairs:
1675
+ sliDict[pair.slider].append(pair.value)
1676
+
1677
+ for slider, (start, end) in sliDict.items():
1678
+ vv = start + val * (end - start)
1679
+ cmds.setAttr(sliderCnx[slider.thing], vv)
1680
+
1681
+ extracted = cmds.duplicate(self.mesh, name=f"{shape.name}_Extract")
1682
+ extracted = extracted[0]
1683
+ self._clearShapes(extracted)
1684
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1685
+ if live:
1686
+ self.connectTraversalShape(trav, shape, extracted, live=live, delete=False)
1687
+ cmds.select(extracted)
1688
+ return extracted
1689
+
1690
+ @undoable
1691
+ def connectTraversalShape(
1692
+ self, trav, shape, mesh=None, live=True, delete=False
1693
+ ) -> None:
1694
+ """Connect a shape into a Traversal progression"""
1695
+ if mesh is None:
1696
+ attrName = cmds.attributeName(shape.thing, long=True)
1697
+ mesh = f"{attrName}_Extract"
1698
+
1699
+ chk = cmds.ls(mesh)
1700
+ if not chk:
1701
+ return
1702
+ if len(chk) > 1:
1703
+ msg = "Multiple objects with the same name found in file:\n"
1704
+ msg += '\n'.join(chk)
1705
+ raise ValueError(msg)
1706
+
1707
+ shapeIdx = trav.prog.getShapeIndex(shape)
1708
+ tVal = trav.prog.pairs[shapeIdx].value
1709
+ delta = self._createTravDelta(trav, mesh, tVal)
1710
+
1711
+ if live:
1712
+ self.connectShape(shape, delta, live, delete)
1713
+
1714
+ if delete:
1715
+ cmds.delete(mesh)
1716
+
1717
+ def _createComboDelta(self, combo, target, tVal, doReparent=True):
1718
+ """Part of the combo extraction process.
1719
+ Combo shapes are fixit shapes added on top of any sliders.
1720
+ This means that the actual combo-shape by itself will not look good by itself,
1721
+ and that's bad for artist interaction.
1722
+ So we must create a setup to take the final sculpted shape, and subtract
1723
+ the any direct slider deformations to get the actual "combo shape" as a delta
1724
+ It is this delta shape that is then plugged into the system
1725
+ """
1726
+ exists = self._doesDeltaExist(combo, target)
1727
+ if exists is not None:
1728
+ return exists
1729
+
1730
+ # get floaters
1731
+ # As floaters can appear anywhere along any combo, they must
1732
+ # always be evaluated in isolation. For this reason, we will
1733
+ # always disconnect all floaters
1734
+ floatShapes = [i.thing for i in self.simplex.getFloatingShapes()]
1735
+
1736
+ # get my shapes
1737
+ myShapes = [i.thing for i in combo.prog.getShapes()]
1738
+
1739
+ with disconnected([self.op] + floatShapes + myShapes) as cnx:
1740
+ sliderCnx = cnx[self.op]
1741
+
1742
+ # zero all slider vals on the op
1743
+ for a in sliderCnx.values():
1744
+ cmds.setAttr(a, 0.0)
1745
+
1746
+ # pull out the rest shape
1747
+ rest = cmds.duplicate(self.mesh, name=f"{combo.name}_Rest")[0]
1748
+
1749
+ # set the combo values
1750
+ for pair in combo.pairs:
1751
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
1752
+
1753
+ # Get the resulting slider values for later
1754
+ # weightPairs = []
1755
+ # self.shapeNode = None # the deformer object
1756
+
1757
+ deltaObj = cmds.duplicate(self.mesh, name=f"{combo.name}_Delta")[0]
1758
+ base = cmds.duplicate(deltaObj, name=f"{combo.name}_Base")[0]
1759
+
1760
+ # clear out all non-primary shapes so we don't have those 'Orig1' things floating around
1761
+ for item in [rest, deltaObj, base]:
1762
+ self._clearShapes(item, doOrig=True)
1763
+
1764
+ # Build the delta blendshape setup
1765
+ bs = cmds.blendShape(deltaObj, name=f"{combo.name}_DeltaBS")[0]
1766
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 0, target, 1.0))
1767
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 1, base, 1.0))
1768
+ cmds.blendShape(bs, edit=True, target=(deltaObj, 2, rest, 1.0))
1769
+ cmds.setAttr(f"{bs}.{target}", 1.0)
1770
+ cmds.setAttr(f"{bs}.{base}", 1.0)
1771
+ cmds.setAttr(f"{bs}.{rest}", 1.0)
1772
+
1773
+ # Cleanup
1774
+ if doReparent:
1775
+ nodeDict = {"Delta": deltaObj}
1776
+ repDict = self._reparentDeltaShapes(target, nodeDict, bs, [rest, base])
1777
+ return repDict["Delta"]
1778
+ return deltaObj
1779
+
1780
+ @undoable
1781
+ def extractComboShape(self, combo, shape, live: bool = True, offset: float = 10.0):
1782
+ """Extract a shape from a combo progression"""
1783
+ floatShapes = self.simplex.getFloatingShapes()
1784
+ floatShapes = [i.thing for i in floatShapes]
1785
+
1786
+ shapeIdx = combo.prog.getShapeIndex(shape)
1787
+ tVal = combo.prog.pairs[shapeIdx].value
1788
+
1789
+ with disconnected(self.op) as cnx:
1790
+ sliderCnx = cnx[self.op]
1791
+ # zero all slider vals on the op
1792
+ for a in sliderCnx.values():
1793
+ cmds.setAttr(a, 0.0)
1794
+
1795
+ with disconnected(floatShapes):
1796
+ # set the combo values
1797
+ for pair in combo.pairs:
1798
+ cmds.setAttr(sliderCnx[pair.slider.thing], pair.value * tVal)
1799
+
1800
+ extracted = cmds.duplicate(self.mesh, name=f"{shape.name}_Extract")[0]
1801
+
1802
+ self._clearShapes(extracted)
1803
+ cmds.xform(extracted, relative=True, translation=(offset, 0, 0))
1804
+
1805
+ if live:
1806
+ self.connectComboShape(combo, shape, extracted, live=live, delete=False)
1807
+
1808
+ cmds.select(extracted)
1809
+ return extracted
1810
+
1811
+ @undoable
1812
+ def connectComboShape(
1813
+ self, combo, shape, mesh=None, live=True, delete=False
1814
+ ) -> None:
1815
+ """Connect a shape into a combo progression"""
1816
+ if mesh is None:
1817
+ attrName = cmds.attributeName(shape.thing, long=True)
1818
+ mesh = f"{attrName}_Extract"
1819
+
1820
+ chk = cmds.ls(mesh)
1821
+ if not chk:
1822
+ return
1823
+ if len(chk) > 1:
1824
+ msg = "Multiple objects with the same name found in file:\n"
1825
+ msg += '\n'.join(chk)
1826
+ raise ValueError(msg)
1827
+ mesh = chk[0]
1828
+
1829
+ progShapeIdx = combo.prog.getShapeIndex(shape)
1830
+ tVal = combo.prog.pairs[progShapeIdx].value
1831
+
1832
+ delta = self._createComboDelta(combo, mesh, tVal)
1833
+ if live:
1834
+ self.connectShape(shape, delta, live, delete)
1835
+
1836
+ if delete:
1837
+ cmds.delete(mesh)
1838
+
1839
+ @classmethod
1840
+ def setDisabled(cls, op):
1841
+ bss = list(set(cmds.listConnections(op, type="blendShape")))
1842
+ helpers = []
1843
+ for bs in bss:
1844
+ prop = f"{bs}.envelope"
1845
+ val = cmds.getAttr(prop)
1846
+ cmds.setAttr(prop, 0.0)
1847
+ if val != 0.0:
1848
+ helpers.append((prop, val))
1849
+ return helpers
1850
+
1851
+ @classmethod
1852
+ def reEnable(cls, helpers) -> None:
1853
+ for prop, val in helpers:
1854
+ cmds.setAttr(prop, val)
1855
+
1856
+ @undoable
1857
+ def renameCombo(self, combo, name) -> None:
1858
+ """Set the name of a Combo"""
1859
+ pass
1860
+
1861
+ # Data Access
1862
+ @classmethod
1863
+ def getSimplexOperators(cls):
1864
+ """ """
1865
+ return cmds.ls(type="simplex_maya")
1866
+
1867
+ @classmethod
1868
+ def getSimplexOperatorsByName(cls, name):
1869
+ return cmds.ls(name, type="simplex_maya")
1870
+
1871
+ @classmethod
1872
+ def getSimplexOperatorsOnObject(cls, thing):
1873
+ ops = cmds.ls(type="simplex_maya")
1874
+ out = []
1875
+ for op in ops:
1876
+ shapeNode = cmds.listConnections(
1877
+ f"{op}.shapeMsg", source=True, destination=False
1878
+ )
1879
+ if not shapeNode:
1880
+ continue
1881
+
1882
+ # Now that I've got the connected blendshape node, I can check the deformer history
1883
+ # to see if I find it. Eventually, I should probably set this up to deal with
1884
+ # multi-objects, or branched hierarchies. But for now, it works
1885
+ if shapeNode[0] in (cmds.listHistory(thing, pruneDagObjects=True) or []):
1886
+ out.append(op)
1887
+ return out
1888
+
1889
+ @classmethod
1890
+ def getSimplexString(cls, op):
1891
+ return cmds.getAttr(op + ".definition")
1892
+
1893
+ @classmethod
1894
+ def getSimplexStringOnThing(cls, thing, systemName):
1895
+ ops = DCC.getSimplexOperatorsOnObject(thing)
1896
+ for op in ops:
1897
+ js = DCC.getSimplexString(op)
1898
+ jdict = json.loads(js)
1899
+ if jdict["systemName"] == systemName:
1900
+ return js
1901
+ return None
1902
+
1903
+ @classmethod
1904
+ def setSimplexString(cls, op: str, val: str):
1905
+ return cmds.setAttr(op + ".definition", val, type="string")
1906
+
1907
+ @classmethod
1908
+ def selectObject(cls, thing: str) -> None:
1909
+ """Select an object in the DCC"""
1910
+ cmds.select([thing])
1911
+
1912
+ def selectCtrl(self) -> None:
1913
+ """Select the system's control object"""
1914
+ if self.ctrl:
1915
+ self.selectObject(self.ctrl)
1916
+
1917
+ @classmethod
1918
+ def getObjectByName(cls, name):
1919
+ objs = cmds.ls(name)
1920
+ if not objs:
1921
+ return None
1922
+ if len(objs) > 1:
1923
+ raise ValueError("Multiple objects with the same name found")
1924
+ return objs[0]
1925
+
1926
+ @classmethod
1927
+ def getObjectName(cls, thing):
1928
+ return thing
1929
+
1930
+ @classmethod
1931
+ def staticUndoOpen(cls) -> None:
1932
+ cmds.undoInfo(chunkName="SimplexOperation", openChunk=True)
1933
+
1934
+ @classmethod
1935
+ def staticUndoClose(cls) -> None:
1936
+ cmds.undoInfo(closeChunk=True)
1937
+
1938
+ def undoOpen(self) -> None:
1939
+ if self.undoDepth == 0:
1940
+ self.staticUndoOpen()
1941
+ self.undoDepth += 1
1942
+
1943
+ def undoClose(self) -> None:
1944
+ self.undoDepth -= 1
1945
+ if self.undoDepth == 0:
1946
+ self.staticUndoClose()
1947
+
1948
+ @classmethod
1949
+ def getPersistentFalloff(cls, thing):
1950
+ return cls.getObjectName(thing)
1951
+
1952
+ @classmethod
1953
+ def loadPersistentFalloff(cls, thing):
1954
+ return cls.getObjectByName(thing)
1955
+
1956
+ @classmethod
1957
+ def getPersistentShape(cls, thing):
1958
+ return cls.getObjectName(thing)
1959
+
1960
+ @classmethod
1961
+ def loadPersistentShape(cls, thing):
1962
+ return cls.getObjectByName(thing)
1963
+
1964
+ @classmethod
1965
+ def getPersistentSlider(cls, thing):
1966
+ return cls.getObjectName(thing)
1967
+
1968
+ @classmethod
1969
+ def loadPersistentSlider(cls, thing):
1970
+ return cls.getObjectByName(thing)
1971
+
1972
+ @classmethod
1973
+ def getSelectedObjects(cls):
1974
+ """ """
1975
+ # For maya, only return transform nodes
1976
+ return cmds.ls(sl=True, transforms=True)
1977
+
1978
+ @undoable
1979
+ def importObj(self, path):
1980
+ current = set(cmds.ls(transforms=True))
1981
+ cmds.file(path, i=True, type="OBJ", ignoreVersion=True)
1982
+ new = set(cmds.ls(transforms=True))
1983
+ shapes = set(cmds.ls(shapes=True))
1984
+ new = new - current - shapes
1985
+ imp = new.pop()
1986
+ return imp
1987
+
1988
+ @classmethod
1989
+ def _getDeformerChain(cls, chkObj):
1990
+ # Get a deformer chain
1991
+ memo = []
1992
+ while chkObj and chkObj not in memo:
1993
+ memo.append(chkObj)
1994
+
1995
+ typ = cmds.nodeType(chkObj)
1996
+ if typ == "mesh":
1997
+ cnx = cmds.listConnections(chkObj + ".inMesh") or [None]
1998
+ chkObj = cnx[0]
1999
+ elif typ == "groupParts":
2000
+ cnx = cmds.listConnections(
2001
+ chkObj + ".inputGeometry", destination=False, shapes=True
2002
+ ) or [None]
2003
+ chkObj = cnx[0]
2004
+ else:
2005
+ cnx = cmds.ls(chkObj, type="geometryFilter") or [None]
2006
+ chkObj = cnx[0]
2007
+ if chkObj: # we have a deformer
2008
+ cnx = cmds.listConnections(chkObj + ".input[0].inputGeometry") or [
2009
+ None
2010
+ ]
2011
+ chkObj = cnx[0]
2012
+ return memo
2013
+
2014
+ # Freezing stuff
2015
+ def primeShapes(self, combo) -> None:
2016
+ """Make sure the upstream shapes of this combo are primed and ready.
2017
+ Priming here means the deltas are stored and available on the blendshape node
2018
+ """
2019
+ # Maya doesn't populate the delta plugs on the blendshape node unless
2020
+ # you have a mesh connection while the value for that shape is turned to 1
2021
+ upstreams = []
2022
+ comboUps = self.simplex.getComboUpstreams(combo)
2023
+ for u in comboUps:
2024
+ upstreams.append(u.prog.getShapeAtValue(1.0))
2025
+ for pair in combo.pairs:
2026
+ sli, val = pair.slider, pair.value
2027
+ upstreams.append(sli.prog.getShapeAtValue(val))
2028
+
2029
+ with disconnected(self.shapeNode) as cnx:
2030
+ shapeCnx = cnx[self.shapeNode]
2031
+ for v in shapeCnx.values():
2032
+ cmds.setAttr(v, 0.0)
2033
+
2034
+ for shape in upstreams:
2035
+ cmds.setAttr(shape.thing, 1.0)
2036
+ try:
2037
+ # Make sure to check for any already incoming connections
2038
+ index = self.getShapeIndex(shape)
2039
+ tgn = f"{self.shapeNode}.inputTarget[0].inputTargetGroup[{index}]"
2040
+ isConnected = cmds.listConnections(
2041
+ tgn, source=True, destination=False
2042
+ )
2043
+
2044
+ if not isConnected:
2045
+ shapeGeo = cmds.duplicate(self.mesh, name=shape.name)[0]
2046
+ shape.connectShape(mesh=shapeGeo, live=False, delete=True)
2047
+
2048
+ finally:
2049
+ cmds.setAttr(shape.thing, 0.0)
2050
+
2051
+ def getFreezeThing(self, combo):
2052
+ # If the blendshape shape has an incoming connection whose shape name
2053
+ # ends with 'FreezeShape' and the shape's parent is the ctrl
2054
+ ret = []
2055
+ shapes = combo.prog.getShapes()
2056
+ shapes = [i for i in shapes if not i.isRest]
2057
+
2058
+ shapePlugFmt = (
2059
+ ".inputTarget[{meshIdx}].inputTargetGroup[{shapeIdx}].inputTargetItem[6000]"
2060
+ )
2061
+
2062
+ for shape in shapes:
2063
+ shpIdx = self.getShapeIndex(shape)
2064
+ shpPlug = (
2065
+ self.shapeNode
2066
+ + shapePlugFmt.format(meshIdx=0, shapeIdx=shpIdx)
2067
+ + ".inputGeomTarget"
2068
+ )
2069
+
2070
+ cnx = cmds.listConnections(shpPlug, shapes=True, destination=False) or []
2071
+ for cc in cnx:
2072
+ if not cc.endswith("FreezeShape"):
2073
+ continue
2074
+ par = cmds.listRelatives(cc, parent=True)
2075
+ if par and par[0] == self.ctrl:
2076
+ # Can't use list history to get the chain because it's a pseudo-cycle
2077
+ ret.extend(self._getDeformerChain(cc))
2078
+
2079
+ if ret:
2080
+ self.primeShapes(combo)
2081
+
2082
+ return ret
2083
+
2084
+
2085
+ class SliderDispatch(QtCore.QObject):
2086
+ valueChanged = Signal()
2087
+
2088
+ def __init__(self, node, parent=None) -> None:
2089
+ super().__init__(parent)
2090
+ mObject = getMObject(node)
2091
+ self.callbackID = om.MNodeMessage.addAttributeChangedCallback(
2092
+ mObject, self.emitValueChanged
2093
+ )
2094
+
2095
+ def emitValueChanged(self, *args, **kwargs) -> None:
2096
+ self.valueChanged.emit()
2097
+
2098
+ def disconnectCallbacks(self) -> None:
2099
+ om.MMessage.removeCallback(self.callbackID)
2100
+ self.callbackID = None
2101
+
2102
+ def __del__(self) -> None:
2103
+ self.disconnectCallbacks()
2104
+
2105
+
2106
+ class Dispatch(QtCore.QObject):
2107
+ beforeNew = Signal()
2108
+ afterNew = Signal()
2109
+ beforeOpen = Signal()
2110
+ afterOpen = Signal()
2111
+ undo = Signal()
2112
+ redo = Signal()
2113
+
2114
+ def __init__(self, parent=None) -> None:
2115
+ super().__init__(parent)
2116
+ self.callbackIDs = []
2117
+ self.connectCallbacks()
2118
+
2119
+ def connectCallbacks(self) -> None:
2120
+ if self.callbackIDs:
2121
+ self.disconnectCallbacks()
2122
+
2123
+ self.callbackIDs.append(
2124
+ om.MSceneMessage.addCallback(
2125
+ om.MSceneMessage.kBeforeNew, self.emitBeforeNew
2126
+ )
2127
+ )
2128
+ self.callbackIDs.append(
2129
+ om.MSceneMessage.addCallback(om.MSceneMessage.kAfterNew, self.emitAfterNew)
2130
+ )
2131
+ self.callbackIDs.append(
2132
+ om.MSceneMessage.addCallback(
2133
+ om.MSceneMessage.kBeforeOpen, self.emitBeforeOpen
2134
+ )
2135
+ )
2136
+ self.callbackIDs.append(
2137
+ om.MSceneMessage.addCallback(
2138
+ om.MSceneMessage.kAfterOpen, self.emitAfterOpen
2139
+ )
2140
+ )
2141
+ self.callbackIDs.append(
2142
+ om.MEventMessage.addEventCallback("Undo", self.emitUndo)
2143
+ )
2144
+ self.callbackIDs.append(
2145
+ om.MEventMessage.addEventCallback("Redo", self.emitRedo)
2146
+ )
2147
+
2148
+ def disconnectCallbacks(self) -> None:
2149
+ for i in self.callbackIDs:
2150
+ om.MMessage.removeCallback(i)
2151
+ self.callbackIDs = []
2152
+
2153
+ def emitBeforeNew(self, *args, **kwargs) -> None:
2154
+ self.beforeNew.emit()
2155
+
2156
+ def emitAfterNew(self, *args, **kwargs) -> None:
2157
+ self.afterNew.emit()
2158
+
2159
+ def emitBeforeOpen(self, *args, **kwargs) -> None:
2160
+ self.beforeOpen.emit()
2161
+
2162
+ def emitAfterOpen(self, *args, **kwargs) -> None:
2163
+ self.afterOpen.emit()
2164
+
2165
+ def emitUndo(self, *args, **kwargs) -> None:
2166
+ self.undo.emit()
2167
+
2168
+ def emitRedo(self, *args, **kwargs) -> None:
2169
+ self.redo.emit()
2170
+
2171
+ def __del__(self) -> None:
2172
+ self.disconnectCallbacks()
2173
+
2174
+
2175
+ DISPATCH = Dispatch()
2176
+
2177
+
2178
+ def rootWindow():
2179
+ """Returns the currently active QT main window
2180
+ Only works for QT UI's like Maya
2181
+ """
2182
+ # for MFC apps there should be no root window
2183
+ window = None
2184
+ if QApplication.instance():
2185
+ inst = QApplication.instance()
2186
+ window = inst.activeWindow()
2187
+ # Ignore QSplashScreen's, they should never be considered the root window.
2188
+ if isinstance(window, QSplashScreen):
2189
+ return None
2190
+ # If the application does not have focus try to find A top level widget
2191
+ # that doesn't have a parent and is a QMainWindow or QDialog
2192
+ if window is None:
2193
+ windows = []
2194
+ dialogs = []
2195
+ for w in QApplication.instance().topLevelWidgets():
2196
+ if w.parent() is None:
2197
+ if isinstance(w, QMainWindow):
2198
+ windows.append(w)
2199
+ elif isinstance(w, QDialog):
2200
+ dialogs.append(w)
2201
+ if windows:
2202
+ window = windows[0]
2203
+ elif dialogs:
2204
+ window = dialogs[0]
2205
+
2206
+ # grab the root window
2207
+ if window:
2208
+ while True:
2209
+ parent = window.parent()
2210
+ if not parent:
2211
+ break
2212
+ if isinstance(parent, QSplashScreen):
2213
+ break
2214
+ window = parent
2215
+
2216
+ return window
2217
+
2218
+
2219
+ SIMPLEX_RESET_SCRIPTJOB = """
2220
+ import maya.cmds as cmds
2221
+ import maya.OpenMaya as om
2222
+
2223
+ def simplexDelCB(node, dgMod, clientData):
2224
+ xNode, dName = clientData
2225
+ dNode = getMObject(dName)
2226
+ if dNode and not dNode.isNull():
2227
+ dgMod.deleteNode(dNode)
2228
+
2229
+ def getMObject(name):
2230
+ selected = om.MSelectionList()
2231
+ try:
2232
+ selected.add(name, True)
2233
+ except RuntimeError:
2234
+ return None
2235
+ if selected.isEmpty():
2236
+ return None
2237
+ thing = om.MObject()
2238
+ selected.getDependNode(0, thing)
2239
+ return thing
2240
+
2241
+ # get all .simplexDelete message attributes
2242
+ delAttrs = cmds.ls("*.simplexDelete")
2243
+ if delAttrs:
2244
+ # get all their connections
2245
+ cnx = cmds.listConnections(delAttrs, plugs=True, connections=True, destination=False)
2246
+
2247
+ # Set up the deletion callback
2248
+ mmIds = []
2249
+ for i in range(0, len(cnx), 2):
2250
+ parName, delName = cmds.ls(cnx[i:i+2], long=True, objectsOnly=True)
2251
+ pNode = getMObject(parName)
2252
+ dNode = getMObject(delName)
2253
+ om.MNodeMessage.addNodeAboutToDeleteCallback(pNode, simplexDelCB, (dNode, delName))
2254
+ """
2255
+
2256
+
2257
+ def buildDeleterScriptJob() -> None:
2258
+ dcbName = "SimplexDeleterCallback"
2259
+ if not cmds.ls(dcbName):
2260
+ cmds.scriptNode(
2261
+ scriptType=1,
2262
+ beforeScript=SIMPLEX_RESET_SCRIPTJOB,
2263
+ name=dcbName,
2264
+ sourceType="python",
2265
+ )
2266
+
2267
+
2268
+ def simplexDelCB(_node, dgMod, clientData) -> None:
2269
+ _xNode, dName = clientData
2270
+ dNode = getMObject(dName)
2271
+ if dNode and not dNode.isNull():
2272
+ dgMod.deleteNode(dNode)
2273
+
2274
+
2275
+ def getMObject(name):
2276
+ selected = om.MSelectionList()
2277
+ try:
2278
+ selected.add(name, True)
2279
+ except RuntimeError:
2280
+ return None
2281
+ if selected.isEmpty():
2282
+ return None
2283
+ thing = om.MObject()
2284
+ selected.getDependNode(0, thing)
2285
+ return thing
2286
+
2287
+
2288
+ def buildDeleterCallback(parName, delName):
2289
+ pNode = getMObject(parName)
2290
+ dNode = getMObject(delName)
2291
+ idNum = om.MNodeMessage.addNodeAboutToDeleteCallback(
2292
+ pNode, simplexDelCB, (dNode, delName)
2293
+ )
2294
+ return idNum