-
Notifications
You must be signed in to change notification settings - Fork 36
/
cmdx.py
9065 lines (6945 loc) · 258 KB
/
cmdx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import re
import os
import sys
import json
import time as time_
import math
import types
import logging
import operator
import traceback
import collections
import contextlib
from functools import wraps
from itertools import chain
from maya import cmds
from maya.api import OpenMaya as om, OpenMayaAnim as oma, OpenMayaUI as omui
from maya import OpenMaya as om1, OpenMayaMPx as ompx1, OpenMayaUI as omui1
__version__ = "0.6.4"
IS_VENDORED = "." in __name__
PY3 = sys.version_info[0] == 3
# Bypass assertion error on unsupported Maya versions
IGNORE_VERSION = bool(os.getenv("CMDX_IGNORE_VERSION"))
# Output profiling information to console
# CAREFUL! This will flood your console. Use sparingly.
TIMINGS = bool(os.getenv("CMDX_TIMINGS"))
# Do not perform any caching of nodes or plugs
SAFE_MODE = bool(os.getenv("CMDX_SAFE_MODE"))
# Increase performance by not protecting against
# fatal crashes (e.g. operations on deleted nodes)
# This can be useful when you know for certain that a
# series of operations will happen in isolation, such
# as during an auto rigging build or export process.
ROGUE_MODE = not SAFE_MODE and bool(os.getenv("CMDX_ROGUE_MODE"))
ENABLE_PEP8 = True
# Support undo/redo (mandatory)
ENABLE_UNDO = True
# Required
ENABLE_PLUG_REUSE = True
if PY3:
long = int
string_types = str,
else:
long = long
string_types = str, basestring, unicode
try:
__maya_version__ = int(cmds.about(version=True))
except (AttributeError, ValueError):
__maya_version__ = 2015 # E.g. Preview Release 95
if not IGNORE_VERSION:
assert __maya_version__ >= 2015, "Requires Maya 2015 or newer"
# Hack for static typing analysis
#
# the test below only passes in the IDE such as VSCode
# Maya doesn't know or care about the `typing` library
MYPY = False
if MYPY:
from typing import *
# Fake-declare some Python2-only types to fix Pylance
# analyzer false positives (Pylance is Python3-only)
basestring = unicode = str
long = int
buffer = bytearray
file = object
del MYPY
self = sys.modules[__name__]
self.installed = False
log = logging.getLogger("cmdx")
# Aliases - API 1.0
om1 = om1
omui1 = omui1
# Aliases - API 2.0
om = om
oma = oma
omui = omui
# Accessible via `cmdx.NodeReuseCount` etc.
Stats = self
Stats.NodeInitCount = 0
Stats.NodeReuseCount = 0
Stats.PlugReuseCount = 0
Stats.LastTiming = None
# Node reuse depends on this member
if not hasattr(om, "MObjectHandle"):
log.warning("Node reuse might not work in this version of Maya "
"(OpenMaya.MObjectHandle not found)")
# DEPRECATED
MTime = om.MTime
MDistance = om.MDistance
MAngle = om.MAngle
TimeType = om.MTime
DistanceType = om.MDistance
AngleType = om.MAngle
ColorType = om.MColor
ExistError = type("ExistError", (RuntimeError,), {})
LockedError = type("LockedError", (ValueError,), {})
DoNothing = None
# Reusable objects, for performance
GlobalDagNode = om.MFnDagNode()
GlobalDependencyNode = om.MFnDependencyNode()
First = 0
Last = -1
# Animation curve tangents, from MFnAnimCurve::TangentType
Stepped = 5
Linear = 2
Smooth = 4
# Animation blend nodes
# Because type checking against MFn.kBlendNodeBase doesn't work :(
AnimBlendTypes = (
om.MFn.kBlendNodeAdditiveRotation,
om.MFn.kBlendNodeAdditiveScale,
om.MFn.kBlendNodeBoolean,
om.MFn.kBlendNodeDouble,
om.MFn.kBlendNodeDoubleAngle,
om.MFn.kBlendNodeDoubleLinear,
om.MFn.kBlendNodeEnum,
om.MFn.kBlendNodeFloat,
om.MFn.kBlendNodeFloatAngle,
om.MFn.kBlendNodeFloatLinear,
om.MFn.kBlendNodeInt16,
om.MFn.kBlendNodeInt32,
om.MFn.kBlendNodeTime,
)
history = dict()
class ModifierError(RuntimeError):
def __init__(self, history):
tasklist = list()
for task in history:
cmd, args, kwargs = task
tasklist += [
"%s(%s)" % (cmd, ", ".join(map(repr, args)))
]
message = (
"An unexpected internal failure occurred, "
"these tasks were attempted:\n- " +
"\n- ".join(tasklist)
)
self.history = history
super(ModifierError, self).__init__(message)
def withTiming(text="{func}() {time:.2f} ns"):
"""Append timing information to a function
Example:
@withTiming()
def function():
pass
"""
try:
perf_counter = time_.perf_counter
# Python 2.7
except AttributeError:
perf_counter = time_.clock
def timings_decorator(func):
if not TIMINGS:
# Do not wrap the function.
# This yields zero cost to runtime performance
return func
@wraps(func)
def func_wrapper(*args, **kwargs):
t0 = perf_counter()
try:
return func(*args, **kwargs)
finally:
t1 = perf_counter()
duration = (t1 - t0) * 10 ** 6 # microseconds
Stats.LastTiming = duration
log.debug(
text.format(func=func.__name__,
time=duration)
)
return func_wrapper
return timings_decorator
@contextlib.contextmanager
def _undo_chunk(name):
try:
cmds.undoInfo(chunkName=name, openChunk=True)
yield
finally:
cmds.undoInfo(chunkName=name, closeChunk=True)
def _isalive(mobj):
"""Make as sure as humanly-possible that this mobject is safe"""
# Rare case of an empty MObject being passed, e.g. MObject()
if mobj.isNull():
return False
handle = om.MObjectHandle(mobj)
# The node has been destroyed, e.g. new scene or flushed undo
if not handle.isValid():
return False
# The node is present in the scene, but has been removed. Could
# potentially be undone and given new life. We don't care.
if not handle.isAlive():
return False
return True
def _camel_to_title(text):
"""Convert camelCase `text` to Title Case
Example:
>>> _camel_to_title("mixedCase")
'Mixed Case'
>>> _camel_to_title("myName")
'My Name'
>>> _camel_to_title("you")
'You'
>>> _camel_to_title("You")
'You'
>>> _camel_to_title("This is That")
'This Is That'
"""
return re.sub(
r"((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))",
r" \1", text
).title().replace(" ", " ")
def protected(func):
"""Prevent fatal crashes from illegal access to deleted nodes"""
if ROGUE_MODE:
return func
@wraps(func)
def func_wrapper(*args, **kwargs):
node = args[0]
assert isinstance(node, Node), "arg[0] should have been a cmdx.Node"
if node.destroyed or not _isalive(node._mobject):
raise ExistError("Cannot perform operation on deleted node")
return func(*args, **kwargs)
return func_wrapper
def add_metaclass(metaclass):
"""Add metaclass to Python 2 and 3 class
Helper decorator, from six.py
"""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get("__slots__")
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slots_var in slots:
orig_vars.pop(slots_var)
orig_vars.pop("__dict__", None)
orig_vars.pop("__weakref__", None)
if hasattr(cls, "__qualname__"):
orig_vars["__qualname__"] = cls.__qualname__
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
class _Type(int):
"""Facilitate use of isinstance(space, _Type)"""
MFn = om.MFn
kDagNode = _Type(om.MFn.kDagNode)
kShape = _Type(om.MFn.kShape)
kMesh = _Type(om.MFn.kMesh)
kTransform = _Type(om.MFn.kTransform)
kJoint = _Type(om.MFn.kJoint)
kSet = _Type(om.MFn.kSet)
kDeformer = _Type(om.MFn.kGeometryFilt)
kConstraint = _Type(om.MFn.kConstraint)
class _Space(int):
"""Facilitate use of isinstance(space, _Space)"""
# Spaces
sWorld = _Space(om.MSpace.kWorld)
sObject = _Space(om.MSpace.kObject)
sTransform = _Space(om.MSpace.kTransform)
sPostTransform = _Space(om.MSpace.kPostTransform)
sPreTransform = _Space(om.MSpace.kPreTransform)
kXYZ = om.MEulerRotation.kXYZ
kYZX = om.MEulerRotation.kYZX
kZXY = om.MEulerRotation.kZXY
kXZY = om.MEulerRotation.kXZY
kYXZ = om.MEulerRotation.kYXZ
kZYX = om.MEulerRotation.kZYX
class _Unit(int):
"""A Maya unit, for unit-attributes such as Angle and Distance
Because the resulting classes are subclasses of `int`, there
is virtually no run-time performance penalty to using it as
an integer. No additional Python is called, most notably when
passing the integer class to the Maya C++ binding (which wouldn't
call our overridden methods anyway).
The added overhead to import time is neglible.
"""
def __new__(cls, unit, enum):
self = super(_Unit, cls).__new__(cls, enum)
self._unit = unit
return self
def __call__(self, enum):
return self._unit(enum, self)
# Angular units
Degrees = _Unit(om.MAngle, om.MAngle.kDegrees)
Radians = _Unit(om.MAngle, om.MAngle.kRadians)
AngularMinutes = _Unit(om.MAngle, om.MAngle.kAngMinutes)
AngularSeconds = _Unit(om.MAngle, om.MAngle.kAngSeconds)
def AngleUiUnit():
"""Dynamic angle UI unit
Unlike other angle units, this can be modified by the user at run-time
hence it needs to be a function rather than a variable.
"""
return _Unit(om.MAngle, om.MAngle.uiUnit())
# Distance units
Millimeters = _Unit(om.MDistance, om.MDistance.kMillimeters)
Centimeters = _Unit(om.MDistance, om.MDistance.kCentimeters)
Meters = _Unit(om.MDistance, om.MDistance.kMeters)
Kilometers = _Unit(om.MDistance, om.MDistance.kKilometers)
Inches = _Unit(om.MDistance, om.MDistance.kInches)
Feet = _Unit(om.MDistance, om.MDistance.kFeet)
Miles = _Unit(om.MDistance, om.MDistance.kMiles)
Yards = _Unit(om.MDistance, om.MDistance.kYards)
def DistanceUiUnit():
"""Dynamic distance UI unit
Unlike other distance units, this can be modified by the user at run-time
hence it needs to be a function rather than a variable.
"""
return _Unit(om.MDistance, om.MDistance.uiUnit())
# Time units
Milliseconds = _Unit(om.MTime, om.MTime.kMilliseconds)
Minutes = _Unit(om.MTime, om.MTime.kMinutes)
Seconds = _Unit(om.MTime, om.MTime.kSeconds)
def TimeUiUnit():
"""Unlike other time units, this can be modified by the user at run-time"""
return _Unit(om.MTime, om.MTime.uiUnit())
# Alias
UiUnit = TimeUiUnit
_Cached = type("Cached", (object,), {}) # For isinstance(x, _Cached)
Cached = _Cached()
_data = collections.defaultdict(dict)
class Singleton(type):
"""Re-use previous instances of Node
Cost: 14 microseconds
This enables persistent state of each node, even when
a node is discovered at a later time, such as via
:func:`DagNode.parent()` or :func:`DagNode.descendents()`
Arguments:
mobject (MObject): Maya API object to wrap
exists (bool, optional): Whether or not to search for
an existing Python instance of this node
Example:
>>> nodeA = createNode("transform", name="myNode")
>>> nodeB = createNode("transform", parent=nodeA)
>>> encode("|myNode") is nodeA
True
>>> nodeB.parent() is nodeA
True
"""
_instances = {}
@withTiming()
def __call__(cls, mobject, exists=True, modifier=None):
handle = om.MObjectHandle(mobject)
hsh = handle.hashCode()
hx = "%x" % hsh
if exists and handle.isValid():
try:
node = cls._instances[hx]
assert not node._destroyed
except KeyError:
pass
except AssertionError:
# He's dead Jim
cls._instances.pop(hx)
else:
Stats.NodeReuseCount += 1
return node
# It hasn't been instantiated before, let's do that.
# But first, make sure we instantiate the right type
if mobject.hasFn(om.MFn.kDagContainer):
sup = ContainerNode
elif mobject.hasFn(om.MFn.kContainer):
sup = ContainerNode
elif mobject.hasFn(om.MFn.kDagNode):
sup = DagNode
elif mobject.hasFn(om.MFn.kSet):
sup = ObjectSet
elif mobject.hasFn(om.MFn.kAnimCurve):
sup = AnimCurve
else:
sup = Node
self = super(Singleton, sup).__call__(mobject, exists)
self._hashCode = hsh
self._hexStr = hx
cls._instances[hx] = self
return self
@add_metaclass(Singleton)
class Node(object):
"""A Maya dependency node
Example:
>>> _ = cmds.file(new=True, force=True)
>>> decompose = createNode("decomposeMatrix", name="decompose")
>>> str(decompose)
'decompose'
>>> alias = encode(decompose.name())
>>> decompose == alias
True
>>> transform = createNode("transform")
>>> transform["tx"] = 5
>>> transform["worldMatrix"][0] >> decompose["inputMatrix"]
>>> decompose["outputTranslate"]
cmdx.Plug("decompose", "outputTranslate") == (5.0, 0.0, 0.0)
>>> decompose["outputTranslate"].read()
(5.0, 0.0, 0.0)
"""
_Fn = om.MFnDependencyNode
# Module-level cache of previously created instances of Node
_Cache = dict()
def __eq__(self, other):
"""MObject supports this operator explicitly"""
# On scene-open, an old MObject can reference a new node,
# most typically the `top` camera node. Therefore, it isn't
# enough to only compare MObject to MObject
try:
# Better to ask forgivness than permission
return (
_isalive(self._mobject) and
_isalive(other._mobject) and
self._mobject == other._mobject
)
except AttributeError:
return str(self) == str(other)
def __ne__(self, other):
try:
return self._mobject != other._mobject
except AttributeError:
return str(self) != str(other)
def __str__(self):
return self.name(namespace=True)
def __repr__(self):
cls_name = '{}.{}'.format(__name__, self.__class__.__name__)
return '{}("{}")'.format(cls_name, self.name(namespace=True))
def __add__(self, other):
"""Support legacy + '.attr' behavior
Example:
>>> node = createNode("transform")
>>> getAttr(node + ".tx")
0.0
>>> delete(node)
"""
return self[other.strip(".")]
def __contains__(self, other):
"""Does the attribute `other` exist?"""
return self.hasAttr(other)
def __getitem__(self, key):
"""Get plug from self
Arguments:
key (str, tuple): String lookup of attribute,
optionally pass tuple to include unit.
Example:
>>> _new()
>>> node = createNode("transform")
>>> node["translate"] = (1, 1, 1)
>>> node["translate", Meters]
cmdx.Plug("transform1", "translate") == (0.01, 0.01, 0.01)
>>> node["translate", Meters].read()
(0.01, 0.01, 0.01)
"""
unit = None
cached = False
if isinstance(key, (list, tuple)):
key, items = key[0], key[1:]
for item in items:
if isinstance(item, _Unit):
unit = item
elif isinstance(item, int):
unit = item
elif isinstance(item, _Cached):
cached = True
if cached:
try:
return CachedPlug(self._state["values"][key, unit])
except KeyError:
pass
assert isinstance(key, str), (
"%s was not the name of an attribute" % key
)
try:
plug = self.findPlug(key)
except RuntimeError:
raise ExistError("%s.%s" % (self.path(), key))
return Plug(self, plug, unit=unit, key=key)
def __setitem__(self, key, value):
"""Support item assignment of new attributes or values
Example:
>>> _ = cmds.file(new=True, force=True)
>>> node = createNode("transform", name="myNode")
>>> node["myAttr"] = Double(default=1.0)
>>> node["myAttr"] == 1.0
True
>>> node["rotateX", Degrees] = 1.0
>>> node["rotateX"] = Degrees(1)
>>> node["rotateX", Degrees]
cmdx.Plug("myNode", "rotateX") == 1.0
>>> node["rotateX", Degrees].read()
1.0
>>> node["myDist"] = Distance()
>>> node["myDist"] = node["translateX"]
>>> node["myDist", Centimeters] = node["translateX", Meters]
>>> round(node["rotateX", Radians], 3)
0.017
>>> try:
... node["myDist"] = Distance()
... except Exception as e:
... assert isinstance(e, ExistError)
... else:
... assert False
>>>
>>> try:
... node["notExist"] = 5
... except Exception as f:
... assert isinstance(f, ExistError)
... else:
... assert False
>>>
>>> node["myString"] = String()
>>> node["myString"]
cmdx.Plug("myNode", "myString") == ""
>>> node["myString"] = "Hello, world!"
>>> node["myString"]
cmdx.Plug("myNode", "myString") == "Hello, world!"
>>>
>>> delete(node)
"""
if isinstance(value, Plug):
value = value.read()
unit = None
if isinstance(key, (list, tuple)):
key, unit = key
# Convert value to the given unit
if isinstance(value, (list, tuple, om.MVector)):
value = list(unit(v) for v in value)
else:
value = unit(value)
# Create a new attribute
elif isinstance(value, (tuple, list)):
if isinstance(value[0], type):
if issubclass(value[0], _AbstractAttribute):
Attribute, kwargs = value
attr = Attribute(key, **kwargs)
try:
return self.addAttr(attr.create())
except RuntimeError:
# NOTE: I can't be sure this is the only occasion
# where this exception is thrown. Stay catious.
raise ExistError(key)
plug = self.findPlug(key)
plug = Plug(self, plug, unit=unit)
# Else, write it immediately
plug.write(value)
def __hash__(self):
"""Support storing in set() and as key in dict()"""
return hash(self.path())
def __delitem__(self, key):
self.deleteAttr(key)
@withTiming()
def __init__(self, mobject, exists=True):
"""Initialise Node
Private members:
mobject (om.MObject): Wrap this MObject
fn (om.MFnDependencyNode): The corresponding function set
destroyed (bool): Has this node been destroyed by Maya?
state (dict): Optional state for performance
"""
self._mobject = mobject
self._destroyed = False
self._hashCode = None
self._state = {
"values": dict(),
"callbacks": list()
}
# There is no humanly possible way of knowing when
# an MObject is destroyed, other than to listen for
# it via a callback. Please correct me if I'm wrong,
# callbacks are death.
self._state["callbacks"] += [
# Monitor node deletion, to prevent accidental
# use of MObject past its lifetime which may
# result in a fatal crash.
om.MNodeMessage.addNodeDestroyedCallback(
mobject,
self._onDestroyed, # func
None # clientData
)
]
Stats.NodeInitCount += 1
def __del__(self):
"""Clean up callbacks on garbage collection
These may/should clean up themselves alongside node
destruction, but in case they don't we make extra sure.
"""
for callback in self._state["callbacks"]:
try:
om.MMessage.removeCallback(callback)
except RuntimeError:
pass
self._state["callbacks"].clear()
def _onDestroyed(self, mobject, _=None):
self._destroyed = True
@property
def _fn(self):
if SAFE_MODE:
assert _isalive(self._mobject)
return self._Fn(self._mobject)
def plugin(self):
"""Return the user-defined class of the plug-in behind this node"""
return type(self._fn.userNode())
def instance(self):
"""Return the current plug-in instance of this node"""
return self._fn.userNode()
def object(self):
"""Return MObject of this node"""
return self._mobject
def isAlive(self):
"""The node exists somewhere in memory"""
return not self._destroyed
@property
def data(self):
"""Special handling for data stored in the instance
Normally, the initialisation of data could happen in the __init__,
but for some reason the postConstructor of a custom plug-in calls
__init__ twice for every unique hex, which causes any data added
there to be wiped out once the postConstructor is done.
"""
return _data[self.hex]
@property
def exists(self):
"""The node exists in both memory *and* scene
Example:
>>> node = createNode("joint")
>>> node.exists
True
>>> cmds.delete(str(node))
>>> node.exists
False
>>> _ = cmds.file(new=True, force=True)
>>> node.exists
False
"""
return _isalive(self._mobject)
@property
def removed(self):
return not _isalive(self._mobject)
@property
def destroyed(self):
return self._destroyed
@property
def hashCode(self):
"""Return MObjectHandle.hashCode of this node
This a guaranteed-unique integer (long in Python 2)
similar to the UUID of Maya 2016
"""
return self._hashCode
@property
def hexStr(self):
"""Return unique hashCode as hexadecimal string
Example:
>>> node = createNode("transform")
>>> node.hexStr == format(node.hashCode, "x")
True
"""
return self._hexStr
# Alias
code = hashCode
hex = hexStr
@property
def typeId(self):
"""Return the native maya.api.MTypeId of this node
Example:
>>> node = createNode("transform")
>>> node.typeId == tTransform
True
"""
return self._fn.typeId
@property
def typeName(self):
return self._fn.typeName
def isA(self, type):
"""Evaluate whether self is of `type`
Arguments:
type (MTypeId, str, list, int): any kind of type to check
- MFn function set constant
- MTypeId objects
- nodetype names
Example:
>>> node = createNode("transform")
>>> node.isA(kTransform)
True
>>> node.isA(kShape)
False
>>> node.isA((kShape, kTransform))
True
"""
if isinstance(type, om.MTypeId):
return type == self._fn.typeId
elif isinstance(type, string_types):
return type == self._fn.typeName
elif isinstance(type, (tuple, list)):
return any(self.isA(t) for t in type)
elif isinstance(type, int):
return self._mobject.hasFn(type)
cmds.warning("Unsupported argument passed to isA('%s')" % type)
return False
def lock(self, value=True):
self._fn.isLocked = value
def isLocked(self):
return self._fn.isLocked
def isReferenced(self):
return self._fn.isFromReferencedFile
@property
def storable(self):
"""Whether or not to save this node with the file"""
# How is this value queried?
return None
@storable.setter
def storable(self, value):
# The original function is a double negative
self._fn.setDoNotWrite(not bool(value))
# Module-level branch; evaluated on import
@withTiming("findPlug() reuse {time:.4f} ns")
def findPlug(self, name, cached=False, safe=True):
"""Cache previously found plugs, for performance
Cost: 4.9 microseconds/call
Part of the time taken in querying an attribute is the
act of finding a plug given its name as a string.
This causes a 25% reduction in time taken for repeated
attribute queries. Though keep in mind that state is stored
in the `cmdx` object which currently does not survive rediscovery.
That is, if a node is created and later discovered through a call
to `encode`, then the original and discovered nodes carry one
state each.
Additional challenges include storing the same plug for both
long and short name of said attribute, which is currently not
the case.
Arguments:
name (str): Name of plug to find
cached (bool, optional): (DEPRECATED) Return cached plug, or
throw an exception. Default to False, which
means it will run Maya's findPlug() and cache
the result.
safe (bool, optional): (DEPRECATED) Always find the plug through
Maya's API, defaults to True. This will not perform
any caching and is intended for use during debugging
to spot whether caching is causing trouble.
Example:
>>> node = createNode("transform")
>>> plug1 = node.findPlug("translateX")
>>> isinstance(plug1, om.MPlug)
True
>>> plug1 == node.findPlug("translateX")
True
"""
assert isinstance(name, string_types), "%s was not string" % name
# `findPlug` has a tendency of bringing Maya down with it.
# Let's not give it the satisfaction.
if not _isalive(self._mobject):
raise ExistError
try:
# We always want a non-networked plug. It's safer and as-fast.
# https://forums.autodesk.com/t5/maya-programming/maya-api-what-is-a-networked-plug-and-do-i-want-it-or-not/td-p/7182472
want_networked_plug = False
plug = self._fn.findPlug(name, want_networked_plug)
except RuntimeError:
raise ExistError("%s.%s" % (self.path(), name))
return plug
def update(self, attrs):
"""Apply a series of attributes all at once
This operates similar to a Python dictionary.
Arguments:
attrs (dict): Key/value pairs of name and attribute
Examples:
>>> _new()
>>> node = createNode("transform")
>>> node.update({"tx": 5.0, ("ry", Degrees): 30.0})
>>> node["tx"]
cmdx.Plug("transform1", "translateX") == 5.0