def clone_special(*args):
"""Clone in localspace, and preserve user-defined attributes"""
for transform in cmds.ls(selection=True, long=True):
if cmds.nodeType(transform) != "transform":
cmds.warning("Skipping '%s', not a `transform`" % transform)
continue
shape = _find_shape(transform)
type = cmds.nodeType(shape)
if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
cmds.warning("Skipping '{transform}': cannot clone nodes "
"of type '{type}'".format(**locals()))
continue
cloned = commands.clone(shape, worldspace=False)
new_transform = cmds.listRelatives(cloned,
parent=True,
fullPath=True)[0]
new_transform = cmds.rename(new_transform,
new_transform.rsplit(":", 1)[-1])
for attr in cmds.listAttr(transform,
userDefined=True) or list():
try:
cmds.addAttr(new_transform, longName=attr, dataType="string")
except Exception:
continue
value = cmds.getAttr(transform + "." + attr)
cmds.setAttr(new_transform + "." + attr, value, type="string")
# Connect visibility
cmds.connectAttr(transform + ".visibility",
new_transform + ".visibility")
python类getAttr()的实例源码
def offset_orient(joints, amount, axis):
"""Offsets the orient by the given amount
@param joints: Joints to orient.
@param amount: Amount to offset by.
@param axis: Which axis X, Y or Z
"""
for joint in joints:
children = _unparent_children(joint)
attribute = '{0}.jointOrient{1}'.format(joint, axis)
orient = cmds.getAttr(attribute)
orient += amount
cmds.setAttr(attribute, orient)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def mirror(joint, search_for, replace_with):
joints = [joint, ] + (cmds.listRelatives(joint, ad=True, path=True) or [])
for joint in joints:
mirrored_joint = joint.replace(search_for, replace_with)
if cmds.objExists(mirrored_joint):
translate = list(cmds.getAttr('{0}.t'.format(joint))[0])
parent = cmds.listRelatives(joint, parent=True, path=True)
if parent and search_for not in parent[0]:
translate[2] *= -1.0
else:
translate = [x * -1.0 for x in translate]
cmds.setAttr('{0}.t'.format(mirrored_joint), *translate)
rotate = cmds.getAttr('{0}.r'.format(joint))[0]
cmds.setAttr('{0}.r'.format(mirrored_joint), *rotate)
scale = cmds.getAttr('{0}.s'.format(joint))[0]
cmds.setAttr('{0}.s'.format(mirrored_joint), *scale)
def __init__(self, controls=None, **kwargs):
"""Constructor
:param controls: A list of dictionaries describing the contorls nodes that need to be created.
See cmt.rig.control.dump.
{
'name': node,
'cvs': cmds.getAttr('{0}.cv[*]'.format(node)),
'degree': cmds.getAttr('{0}.degree'.format(node)),
'form': cmds.getAttr('{0}.form'.format(node)),
'xform': cmds.xform(node, q=True, matrix=True),
'knots': get_knots(node),
'pivot': cmds.xform(node, q=True, rp=True),
'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)),
'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)),
'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0],
'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)),
}
"""
super(Component, self).__init__(**kwargs)
self.controls = controls or []
self.control_list = fields.ListField(name='controls',
value=[control['name'] for control in self.controls],
help_text='Controls that will be created.',
parent=self)
def assert_hierarachies_match(self):
self.assertEqual(7, len(cmds.ls(type='joint')))
# Make sure the joint orients are the same
translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')]
rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')]
orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
for orient, new_orient in zip(self.orients, orients):
self.assertListAlmostEqual(orient, new_orient)
for translate, new_translate in zip(self.translates, translates):
self.assertListAlmostEqual(translate, new_translate)
for rotate, new_rotate in zip(self.rotates, rotates):
self.assertListAlmostEqual(rotate, new_rotate)
# The geometry should not have been exported
self.assertFalse(cmds.objExists(self.cube))
self.assertTrue(cmds.objExists(self.group))
self.assertEqual('joint1', cmds.listRelatives(self.group, children=True)[0])
def playblast_snapshot(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None):
current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
if range is None:
range = playback_selection_range()
print range
if range is None:
start = cmds.playbackOptions( q=True,min=True )
end = cmds.playbackOptions( q=True,max=True )
range = [start, end]
cmds.playblast(frame =int((range[0] + range[1])/2), cf = path, fmt="image", orn=hud, os=offscreen, wh = scene_resolution(), p=scale, v=False)
cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
def ResetSceneAnim():
# Loop through them all
SceneJoints = cmds.ls(type="joint")
# Loop
for name in SceneJoints:
# Disconnect if required
ResetBoneKeyframes(DagPathFromJoint(name, False).transform())
# Check for undo
if (cmds.objExists(name + ".seanimUndoT")):
# Reset to it
ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0]
ResetScale = cmds.getAttr(name + ".seanimUndoS")[0]
ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0]
# Apply
cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2])
cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2])
cmds.setAttr(name + ".r", 0, 0, 0)
cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2])
# Remove notetracks
if cmds.objExists("SENotes"):
# Delete
cmds.delete("SENotes")
# Processes a joint, creating it's rest position, and returning a dag path
def array_builder(self, attrName):
frame = attrName.split('.')[-1]
if pm.frameLayout(frame, exists=True):
pm.deleteUI(frame)
pm.frameLayout(frame, collapse=False)
pm.rowLayout(numberOfColumns=2)
acmd = partial(self.add_multiInstance, attrName)
rcmd = partial(self.rem_multiInstance, attrName)
pm.button(label='New Item', command=acmd)
pm.button(label='Remove Last Item', command=rcmd)
pm.setParent('..')
array_length = pm.getAttr(attrName, s=True)
for i in xrange(array_length):
index_attr = '{}[{}]'.format(attrName, i)
pm.attrControlGrp(
attribute=index_attr,
label=index_attr.split('.')[-1])
pm.setParent('..')
def create_hair_system(nucleus=None):
'''Create a hair system, add it to the specified nucleus or active nucleus'''
if not nucleus:
nucleus = get_nucleus()
hair_system = cmds.createNode('hairSystem')
cmds.connectAttr('time1.outTime', hair_system + '.currentTime')
index = cmds.getAttr(nucleus + '.inputActive', size=True)
input_active = '{}.inputActive[{}]'.format(nucleus, index)
input_start = '{}.inputActiveStart[{}]'.format(nucleus, index)
output_object = '{}.outputObjects[{}]'.format(nucleus, index)
cmds.setAttr(hair_system + '.active', 1)
cmds.connectAttr(hair_system + '.currentState', input_active)
cmds.connectAttr(hair_system + '.startState', input_start)
cmds.connectAttr(output_object, hair_system + '.nextState')
cmds.connectAttr(nucleus + '.startFrame', hair_system + '.startFrame')
return hair_system
def read(node):
"""Return user-defined attributes from `node`
"""
data = dict()
for attr in cmds.listAttr(node, userDefined=True) or list():
try:
value = cmds.getAttr(node + "." + attr)
except:
# Some attributes cannot be read directly,
# such as mesh and color attributes. These
# are considered non-essential to this
# particular publishing pipeline.
value = None
data[attr] = value
return data
def fileLoad(*args):
sel = cmds.ls(sl=True)
origTexture = sel[0]
ctrls = sel[1:]
# get path
path = cmds.getAttr("{0}.fileTextureName".format(origTexture))
if not path:
cmds.warning("No file present in {0}. Cancelling!".format(origTexture))
return
for ctrl in ctrls:
ctrlFile = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True).partition(".")[0]
# add path to ctrl file
cmds.setAttr("{0}.fileTextureName".format(ctrlFile), path, type="string")
def positionsAlongCurve(crv="", numPts = 3, *args):
"""
returns list of numPts evenly distributed world positions along given nurbs crv
"""
if not crv:
return
if isType(crv, "nurbsCurve"):
posList = []
shp = cmds.listRelatives(crv, s=True)[0]
poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc))
cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
lineLen = cmds.arclen(crv, ch=False)
dist = float(numPts)/lineLen
for x in range(0, numPts+1):
perc = 1.0/numPts
cmds.setAttr("{}.parameter".format(poc),x*perc)
print x*perc
pos = cmds.getAttr("{}.position".format(poc))[0]
posList.append(pos)
cmds.delete(poc)
return(posList)
def createJointsAlongCurve(crv="", numJnts=3, *args):
jnts = []
crvShp = cmds.listRelatives(crv, s=True)[0]
poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
cmds.connectAttr("{}.local".format(crvShp), "{}.inputCurve".format(poc))
cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
lineLen = cmds.arclen(crv)
dist = float(numJnts)/lineLen
for x in range(0, numJnts+1):
perc = 1.0/numJnts
cmds.setAttr("{}.parameter".format(poc),x*perc)
print x*perc
pos = cmds.getAttr("{}.position".format(poc))[0]
jnt = cmds.joint(p=pos)
jnts.append(jnt)
# add one joint at the end to orient
return(jnts)
def orientJointChain(*args):
#---------------- this doens't actually work. dot doesn't represent the relationship btw orients
cmds.joint(jnts[0], e=True, oj="xyz", secondaryAxisOrient="ydown", ch=True, zso=True)
#print cmds.getAttr("{}.jointOrient".format(cmds.ls(sl=True)[0]))
for y in range(1, len(jnts)):
v1 = cmds.getAttr("{}.jointOrient".format(jnts[0]))[0]
v2 = cmds.getAttr("{}.jointOrient".format(jnts[y]))[0]
dotN = mth.dotN(v1, v2) # figure out how to reverse joint orientation
if dotN < 0:
print jnts[y], "dot neg"
# reorient (inverse secondary axis)
# for jnt in jnts:
# print mth.dotN(cmds.getAttr("{}.jointOrient".format(jnts[0]))[0], cmds.getAttr("{}.jointOrient".format(jnt))[0])
def randomizeFloats(*args):
sel = cmds.ls(sl=True)
attrs = getChannels()
minn = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v1=True)
maxx = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v2=True)
rel = cmds.checkBox(widgets["floatCB"], q=True, v=True)
for obj in sel:
for attr in attrs:
if (cmds.attributeQuery(attr, node=obj, exists=True)):
rand = getRandomFloat(minn, maxx)
current = 0.0
if rel:
current = cmds.getAttr("{0}.{1}".format(obj, attr))
newVal = rand + current
cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
def get_channel_attributes(obj, chnl):
"""
gets and returns attributes of given channel on given object
"""
attrType = cmds.attributeQuery(chnl, node=obj, at=True)
hasMin = cmds.attributeQuery(chnl, node=obj, mne=True)
hasMin = cmds.attributeQuery(chnl, node=obj, mne=True)
hasMax = cmds.attributeQuery(chnl, node=obj, mxe=True)
attrMin = None
if hasMin:
attrMin = cmds.attributeQuery(chnl, node=obj, min=True)
attrMax = None
if hasMax:
attrMax = cmds.attributeQuery(chnl, node=obj, max=True)
value = cmds.getAttr("{0}.{1}".format(obj, chnl))
inConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=False, source=True)
outConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=True, source=False)
locked = cmds.getAttr("{0}.{1}".format(obj, chnl), lock=True)
return (attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked)
def toggle_sel_shape_vis(*args):
"""toggles the selected transforms' shape visibility"""
sel = cmds.ls(sl=True, type="transform")
if sel:
for obj in sel:
shp = cmds.listRelatives(obj, s=True)
if not shp:
return ()
for s in shp:
currVal = cmds.getAttr("{0}.visibility".format(s))
newVal = 0
if currVal == 0:
newVal = 1
elif currVal == 1:
newVal = 0
cmds.setAttr("{0}.visibility".format(s), newVal)
def JntSegScl(*args):
"""turns on/off selected jnts seg scale compensate attr"""
jnts = cmds.ls(sl=True, type="joint")
if not jnts:
cmds.warning("No joints selected!")
return ()
for jnt in jnts:
currVal = cmds.getAttr("{0}.segmentScaleCompensate".format(jnt))
if currVal == 0:
newVal = 1
elif currVal == 1:
newVal = 0
cmds.setAttr("{0}.segmentScaleCompensate".format(jnt), newVal)
def read(node):
"""Return user-defined attributes from `node`"""
data = dict()
for attr in cmds.listAttr(node, userDefined=True) or list():
try:
value = cmds.getAttr(node + "." + attr)
except ValueError:
# Some attributes cannot be read directly,
# such as mesh and color attributes. These
# are considered non-essential to this
# particular publishing pipeline.
value = None
data[attr] = value
return data
def getNodeAttributes(node):
'''
Get Maya node attributes
'''
attributes = cmds.listAttr(node)
attr = {}
attr['nodeName'] = node
attr['nodeType'] = cmds.nodeType(node)
for attribute in attributes:
if '.' in attribute:
continue
try:
val = cmds.getAttr(node + '.' + attribute)
except RuntimeError:
continue
attr[attribute] = val
return attr
def getAttribFromNode(self, name, attr, aType, default=None):
#name mast be shape
transformOnly = ['visibility']
fAttr = '.'.join([name, attr])
value = default
if cmds.attributeQuery( attr, node=name, exists=True ) and not attr.lower() in transformOnly:
value = cmds.getAttr( fAttr )
else:
trnsfrm = self.getTransform(name)
if trnsfrm:
if cmds.attributeQuery( attr, node=trnsfrm, exists=True ):
fAttr = '.'.join([trnsfrm, attr])
value = cmds.getAttr( fAttr )
if not value is None:
if isinstance(value, list):
if isinstance(value[0], tuple):
value = list(value[0])
try:
value = aType(value)
except:
pass
return value
def snap(node, snapTo):
#duplicate the node we want snap
dup = mc.duplicate(node, parentOnly=True)[0]
#unlock translates and rotates
for a in ('.t','.r'):
for b in 'xyz':
mc.setAttr(dup+a+b, lock=False)
mc.parentConstraint(snapTo, dup)
for a in ('.t','.r'):
for b in ('x','y','z'):
try:
mc.setAttr(node+a+b, mc.getAttr(dup+a+b))
except StandardError:
pass
mc.delete(dup)
def getMirrorMap(nodes=None):
'''
Returns a map of all paired nodes within a puppet
'''
puppets = getPuppets(nodes)
puppets = mc.ls(puppets, long=True)[0]
allNodes = mc.ls('*.mirrorIndex', o=True, long=True, recursive=True)
found = {}
pairs = {}
for node in allNodes:
for puppet in puppets:
if not node.startswith(puppet):
continue
value = mc.getAttr('{}.mirrorIndex'.format(node))
if value in found.keys():
pairs[found[value]] = node
pairs[node] = found[value]
continue
found[value] = node
return pairs
def flipPose(nodes, *args):
nodes = mc.ls(nodes, long=True)
flipPairs = getMirrorPairs(nodes)
flipSingles = [x for x in nodes if x not in flipPairs.keys()]
#do the singles:
for node in flipSingles:
for axis in getMirrorAxis(node):
plug = '{}.{}'.format(node,axis)
if mc.getAttr(plug, keyable=True):
try:
utl.setAnimValue(plug, mc.getAttr(plug)*-1.0)
except:pass
#do the pairs
done = []
for node, mirror in flipPairs.items():
if node not in done:
copyPose(node, mirror, flip=True)
done.append(mirror)
def isNodeVisible(node):
'''
Simply return whether or not the node can be seen.
'''
if not mc.attributeQuery('visibility', node=node, exists=True):
return False
if not mc.getAttr(node+'.v'):
return False
if mc.attributeQuery('intermediateObject', node=node, exists=True):
if mc.getAttr(node+'.intermediateObject'):
return False
if not mc.getAttr(node+'.lodVisibility'):
return False
if mc.getAttr(node+'.overrideEnabled') and not mc.getAttr(node+'.overrideVisibility'):
return False
parent = mc.listRelatives(node, parent=True, pa=True)
if parent:
return isNodeVisible(parent[0])
return True
def isWorldSpaceControl(obj):
#first, if the object itself doesn't inherit transforms, it's a world space node.
if not mc.getAttr(obj+'.inheritsTransform'):
return True
#walk up the hierarchy testing for any rotation value on x or z, or inherit transform
parent = mc.listRelatives(obj, parent=True)
while(parent):
if not mc.getAttr(parent[0]+'.inheritsTransform'):
return True
for attr in ('.rx','.rz'):
if mc.getAttr(parent[0]+attr) != 0:
return False
parent = mc.listRelatives(parent, parent=True)
return True
def colorShape(obj, rgb=None, hsv=None):
if not rgb:
if hsv and len(hsv) == 3:
rgb = colorsys.hsv_to_rgb(*hsv)
else:
raise RuntimeError('colorShape requires an rgb or hsv input.')
mc.setAttr('{}.overrideEnabled'.format(obj), 1)
mc.setAttr('{}.overrideRGBColors'.format(obj), 1)
mc.setAttr('{}.overrideColorRGB'.format(obj), *rgb)
shapes = mc.listRelatives(obj, shapes=True, pa=True)
for shape in shapes:
#if mc.getAttr('{}.overrideEnabled'.format(shape)):
mc.setAttr('{}.overrideEnabled'.format(shape), 1)
mc.setAttr('{}.overrideRGBColors'.format(shape), 1)
mc.setAttr('{}.overrideColorRGB'.format(shape), *rgb)
def main():
sel = mc.ls(sl=True)
if not sel:
return
for each in sel:
plug = each+'.v'
try:
locked = mc.getAttr(plug, lock=True)
if locked:
mc.setAttr(plug, lock=False)
if mc.getAttr(plug):
mc.setAttr(plug, 0)
else:
mc.setAttr(plug, 1)
if locked:
mc.setAttr(plug, lock=True)
except:
pass
def get_skey_from_scene():
skey = cmds.getAttr('defaultObjectSet.tacticHandler_skey')
return skey
def process(self, instance):
from maya import cmds
missing = list()
for member in ("controls_SET",
"out_SET"):
if member not in instance:
missing.append(member)
assert not missing, "\"%s\" is missing members: %s" % (
instance, ", ".join("\"" + member + "\"" for member in missing))
# Ensure all output has IDs.
# As user may inadvertently add to the out_SET without
# realising, and some of the new members may be non-meshes,
# or meshes without and ID
missing = list()
for node in cmds.sets("out_SET", query=True) or list():
# Only check transforms with shapes that are meshes
shapes = cmds.listRelatives(node, shapes=True) or list()
meshes = cmds.ls(shapes, type="mesh")
if not meshes:
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))