def set_defaults(*args):
"""Set currently selected values from channel box to their default value
If no channel is selected, default all keyable attributes.
"""
for node in cmds.ls(selection=True):
selected_channels = read_selected_channels()
for channel in (selected_channels or
cmds.listAttr(node, keyable=True)):
try:
default = cmds.attributeQuery(channel,
node=node,
listDefault=True)[0]
except Exception:
continue
else:
cmds.setAttr(node + "." + channel, default)
python类attributeQuery()的实例源码
def loadSelectedSet(self):
selection = BT_GetSelectedSet()
if not selection:
return False
if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
return False
self.ui.poseList.clear()
self.ui.setEdit.setText(selection)
poses = BT_GetPosesFromSet(selection)
if not poses:
return False
self.ui.poseList.addItems(poses)
return True
def loadSelectedSet(self):
selection = BT_GetSelectedSet()
if not selection:
return False
if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
return False
self.ui.poseList.clear()
self.ui.setEdit.setText(selection)
poses = BT_GetPosesFromSet(selection)
if not poses:
return False
self.ui.poseList.addItems(poses)
return True
def loadSelectedSet(self):
selection = BT_GetSelectedSet()
if not selection:
return False
if not cmds.attributeQuery('Blend_Node', ex = True, n = selection):
cmds.warning('Blend_Node attribute not found! This set might not be connected to a BlendTransforms node yet.')
return False
self.ui.poseList.clear()
self.ui.setEdit.setText(selection)
poses = BT_GetPosesFromSet(selection)
if not poses:
return False
self.ui.poseList.addItems(poses)
return True
def getObj(*args):
#get selection and put it in the widgets["objTFG"]
clearList()
sel = cmds.ls(sl=True, type="transform")
if (sel and (len(sel)==1)):
cmds.textFieldGrp(widgets["objTFG"], e=True, tx=sel[0])
else:
cmds.warning("you must select one object with the \"follow\" attribute")
#------------maybe add attr onto end of obj text, then you don't have to get it later if you needed to ???
#now create a button for each value in the "follow" attr
#channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
enumValueStr = cmds.attributeQuery("follow", node=sel[0], listEnum=True)[0]
values = enumValueStr.split(":")
for i in range(0,len(values)):
#pick a random color?
r = random.uniform(0.5,1)
g = random.uniform(0.5,1)
b = random.uniform(0.5,1)
color = (r, g, b)
#here create the button
cmds.button(l=values[i], w=125, p=widgets["bottomRCLO"], bgc=color, h=50, c=partial(switchMatchSpace, i))
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 create(obj):
"""Tell ZBrush to treat `obj` as a new object.
Under the hood this changes a gozbruhBrush ID to match object name.
"""
# does not change selection:
cmds.delete(obj, constructionHistory=True)
shape = cmds.ls(obj, type='mesh', dag=True)[0]
xform = cmds.listRelatives(shape, parent=True, fullPath=True)[0]
goz_check_xform = cmds.attributeQuery(
'gozbruhBrushID', node=xform, exists=True)
goz_check_shape = cmds.attributeQuery(
'gozbruhBrushID', node=shape, exists=True)
if goz_check_shape:
cmds.setAttr(shape + '.gozbruhBrushID', obj, type='string')
if goz_check_xform:
cmds.setAttr(xform + '.gozbruhBrushID', obj, type='string')
return xform
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 getRootAndCOM(node):
'''
Given either the root or COM, return root and COM based on connections.
'''
com = None
root = None
if mc.attributeQuery(COM_ATTR, node=node, exists=True):
com = node
messageCon = mc.listConnections(com+'.'+COM_ATTR, source=True, destination=False)
if not messageCon:
raise RuntimeError('Could not determine root from COM, please select root and run again.')
root = messageCon[0]
else:
messageCon = mc.listConnections(node+'.message', source=False, destination=True, plugs=True)
if messageCon:
for each in messageCon:
eachNode, attr = each.rsplit('.',1)
if attr == COM_ATTR:
com = eachNode
root = node
break
return root, com
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 set_info_to_scene(search_key, context):
# add info about particular scene
skey_link = 'skey://{0}&context={1}'.format(search_key, context)
if not cmds.attributeQuery('tacticHandler_skey', node='defaultObjectSet', exists=True):
cmds.addAttr('defaultObjectSet', longName='tacticHandler_skey', dataType='string')
cmds.setAttr('defaultObjectSet.tacticHandler_skey', skey_link, type='string')
def BT_Setup(set = None):
if not set:
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
if not transforms:
return False
if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
else:
return False
btNode = cmds.createNode("BlendTransforms")
cmds.setAttr(set +'.Blend_Node', btNode, type = "string")
for i in range(0, len(transforms)):
baseMatrix = cmds.xform(transforms[i], q = True, m = True)
baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
baseRotOffset = [0.0, 0.0, 0.0]
if cmds.objectType(transforms[i], isType = 'joint'):
baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]
btAttr = 'transforms[' +str(i) +'].baseMatrix'
btScaleAttr = 'transforms[' +str(i) +'].baseScale'
btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'
BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
return True
def BT_Setup(set = None):
if not set:
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
if not transforms:
return False
if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
else:
return False
btNode = cmds.createNode("BlendTransforms")
cmds.setAttr(set +'.Blend_Node', btNode, type = "string")
for i in range(0, len(transforms)):
baseMatrix = cmds.xform(transforms[i], q = True, m = True)
baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
baseRotOffset = [0.0, 0.0, 0.0]
if cmds.objectType(transforms[i], isType = 'joint'):
baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]
btAttr = 'transforms[' +str(i) +'].baseMatrix'
btScaleAttr = 'transforms[' +str(i) +'].baseScale'
btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'
BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
return True
def BT_Setup(set = None):
if not set:
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
if not transforms:
return False
if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
else:
return False
btNode = cmds.createNode("BlendTransforms")
cmds.setAttr(set +'.Blend_Node', btNode, type = "string")
for i in range(0, len(transforms)):
baseMatrix = cmds.xform(transforms[i], q = True, m = True)
baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
baseRotOffset = [0.0, 0.0, 0.0]
if cmds.objectType(transforms[i], isType = 'joint'):
baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]
btAttr = 'transforms[' +str(i) +'].baseMatrix'
btScaleAttr = 'transforms[' +str(i) +'].baseScale'
btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'
BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
return True
def doSpaceMatch(*args):
#check for correct attrs
obj = cmds.textFieldButtonGrp(widgets["objTFG"], q=True, tx=True)
#look for message attr re: constraint
if (cmds.attributeQuery("spaceConstraint", node=obj, exists=True)):
constraint = cmds.listConnections("%s.spaceConstraint"%obj)
else:
cmds.warning("this object has no \"spaceConstraint\" message attribute and thus is not set up for this matching")
#----------look for string attributes for weights of constraints
#get ws pos of obj before
ws1Pos = cmds.xform(obj, q=True, ws=True, t=True)
ws1Rot = cmds.xform(obj, q=True, ws=True, ro=True)
#pull the constraint info from the message and string attrs
#attr = cmds.listAttr(sel,ud=True )
#-----------here just key the space value!!!
#switch the spaces, set up "cases", i.e. if world, then set all to 0 except world, etc
cmds.setAttr("group1_parentConstraint1.pCube1W0", 0)
cmds.setAttr("group1_parentConstraint1.pCube2W1", 1)
#set ws pos, rot of obj after
cmds.xform(obj, ws=True, t=ws1Pos)
cmds.xform(obj, ws=True, ro=ws1Rot)
#add in scriptjob?
#-----------try this
#set up constraints as normal, maybe DO NOT have to moniter them specifically, set them up as SDKs
#constraint goes in as message mapped "spaceConstraint"
#create string attrs for constraint, each space attrname = space , attrVal = constraintAttr(ie. nameW1)
#Create one tab to set it up
#creat one tab to do it - get spaces
def multiplyFloats(*args):
sel = cmds.ls(sl=True)
attrs = getChannels()
mult = cmds.floatFieldGrp(widgets["multFFG"], q=True, v1=True)
for obj in sel:
for attr in attrs:
if (cmds.attributeQuery(attr, node=obj, exists=True)):
current = cmds.getAttr("{0}.{1}".format(obj, attr))
newVal = current * mult
cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
def transfer_attrs(*args):
"""
transfers attrs and connections from second obj to first object selected
"""
tgt, src = get_source_and_targets()
if not tgt or len(src) > 1:
cmds.warning("Select only one target then one source obj to transfer the attributes and connections!")
return ()
attrs = cmds.channelBox('mainChannelBox', q=True, selectedMainAttributes=True)
if not attrs:
cmds.warning("You have to select at least one attr on last object selected to transfer!")
return ()
for attr in attrs:
attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked = get_channel_attributes(
src[0], attr)
if not attrType == "enum":
# create attribute
if not cmds.attributeQuery(attr, node=tgt, exists=True):
if hasMin and not hasMax:
cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], dv=value, k=True)
elif hasMax and not hasMin:
cmds.addAttr(tgt, ln=attr, at=attrType, max=attrMax[0], dv=value, k=True)
elif hasMin and hasMax:
cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], max=attrMax[0], dv=value, k=True)
else:
cmds.addAttr(tgt, ln=attr, at=attrType, dv=value, k=True)
else:
cmds.warning("The attribute: {0} already exists. Skipping creation!".format(attr))
# lock
if locked:
cmds.setAttr("{0}.{1}".format(tgt, attr), l=True)
else:
cmds.warning("I don't do enums at the moment!")
# connect tgt attr to connection, forced
if inConnection:
cmds.connectAttr(inConnection[0], "{0}.{1}".format(tgt, attr))
if outConnection:
for conn in outConnection:
cmds.connectAttr("{0}.{1}".format(tgt, attr), conn, force=True)
def load(file_path, obj_name, parent_name):
"""Import a file exported from ZBrush.
This is the command sent over the Maya command port from ZBrush.
Parameters
----------
file_path : str
Path to the file that we are importing
obj_name : str
Name of the object being imported
parent_name : str
Name of the parent for the object being imported
"""
file_name = utils.split_file_name(file_path)
_cleanup(file_name)
cmds.file(file_path, i=True,
usingNamespaces=False,
removeDuplicateNetworks=True)
# Set smoothing options if necessary
if cmds.optionVar(ex='gozbruh_smooth') and not cmds.optionVar(q='gozbruh_smooth'):
cmds.displaySmoothness(obj_name, du=0, dv=0, pw=4, ps=1, po=1)
if not cmds.attributeQuery("gozbruhParent", n=obj_name, ex=True):
cmds.addAttr(obj_name, longName='gozbruhParent', dataType='string')
cmds.setAttr(obj_name + '.gozbruhParent', parent_name, type='string')
def getMaterialName(self, sg):
mat = cmds.listConnections(sg + ".surfaceShader")
if not mat:
if cmds.attributeQuery("miMaterialShader",n=sg, ex=1):
mat = cmds.listConnections(sg + ".miMaterialShader")
if not mat:
return 'noShader'
if self.op['expgeogrp_mtl'][1]:
tok = self.tokenPrefix(self.op['expgeogrp_mtl'][1])
for t in tok:
if t in mat[0]:
return mat[0]
return self.textVariables['defShader']
return mat[0]
def getNodesOfTypeBelow(node, nodeType):
nodes = []
allKids = mc.listRelatives(node, ad=True, pa=True)
for kid in allKids:
if mc.attributeQuery(PUP_ID_PREFIX+nodeType, exists=True, node=kid):
nodes.append(kid)
return nodes
def getTag(node, tag):
ntAttr = PUP_ID_PREFIX+tag
if mc.attributeQuery(ntAttr, exists=True, node=node):
return mc.getAttr(node+'.'+ntAttr)
return False
def showAllControls(puppet, *args):
elements = mc.listRelatives(puppet, pa=True)
for element in elements:
for visAttr in ('geoVisibility','controlVisibility','secondaryControlVisibility'):
if mc.attributeQuery(visAttr, exists=True, node=element):
mc.setAttr(element+'.'+visAttr, 1)
def isNodePuppetControl(node):
if mc.attributeQuery(PUP_ID_PREFIX+'nodeType', exists=True, node=node):
return True
if getNodeType(node) == 'control':
return True
return False
def getSpaceSwitchData(node):
data = {}
attrs = mc.listAttr(node, userDefined=True, keyable=True)
if not attrs:
return data
ssAttrs = [x for x in attrs if 'paceSwitch' in x]
for attr in ssAttrs:
enumValues = []
spaceEnum = 'space'
if attr == 'spaceSwitch':
if not 'space' in attrs:
spaceEnum = 'spaceSwitch'
enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
elif 'SpaceSwitch' in attr:
baseName = attr.replace('SpaceSwitch','')
if baseName + 'Space' in attrs:
spaceEnum = baseName+'Space'
else:
spaceEnum = attr
if spaceEnum in attrs and mc.attributeQuery(spaceEnum, node=node, attributeType=True) == 'enum':
enumValues = mc.attributeQuery(spaceEnum, node=node, listEnum=True)
if not enumValues:
continue
data[attr] = {}
data[attr]['enumValues'] = enumValues[0].split(':')
data[attr]['currentValue'] = mc.getAttr(node+'.'+spaceEnum, asString=True)
return data
def getMirrorAxis(node):
axis = []
if mc.attributeQuery('mirrorAxis', exists=True, node=node):
mirrorAxis = mc.getAttr('{}.mirrorAxis'.format(node))
if mirrorAxis and not hasFlippedParent(node):
axis = mirrorAxis.split(',')
return axis
def copyPose(fromNode, toNode, flip=False):
attrs = mc.listAttr(fromNode, keyable=True)
if not attrs:
return
#if attributes are aliased, get the real names for mirroring axis
aliases = mc.aliasAttr(fromNode, query=True)
if aliases:
for alias,real in zip(aliases[::2],aliases[1::2]):
if alias in attrs:
attrs.remove(alias)
attrs.append(real)
axis = getMirrorAxis(toNode)
for attr in attrs:
if attr == 'mirrorAxis':
continue
if not mc.attributeQuery(attr, node=toNode, exists=True):
continue
fromPlug = '{}.{}'.format(fromNode, attr)
toPlug = '{}.{}'.format(toNode, attr)
fromValue = mc.getAttr(fromPlug)
toValue = mc.getAttr(toPlug)
if attr in axis:
fromValue *= -1.0
toValue *= -1.0
try:
utl.setAnimValue(toPlug, fromValue)
except:pass
if flip:
try:
utl.setAnimValue(fromPlug, toValue)
except:pass
def editPivot(self, *args):
sel = mc.ls(sl=True)
if not sel:
om.MGlobal.displayWarning('Nothing selected.')
return
if len(sel) > 1:
om.MGlobal.displayWarning('Only works on one node at a time.')
return
if mc.attributeQuery('ml_pivot_handle', exists=True, node=sel[0]):
#we have a pivot handle selected
return
self.node = sel[0]
if is_pivot_connected(sel[0]):
driverAttr = pivot_driver_attr(sel[0])
if driverAttr:
self.editPivotDriver(driverAttr)
else:
om.MGlobal.displayWarning('Pivot attribute is connected, unable to edit.')
return
self.editPivotHandle()
def editPivotDriver(self, driver):
self.pivotDriver = driver
#get driver range
node,attr = driver.split('.',1)
value = mc.getAttr(driver)
minValue = mc.attributeQuery(attr, node=node, minimum=True)[0]
maxValue = mc.attributeQuery(attr, node=node, maximum=True)[0]
#create a ui with a slider
self.pivotDriverWindow = 'ml_pivot_editPivotDriverUI'
if mc.window(self.pivotDriverWindow, exists=True):
mc.deleteUI(self.pivotDriverWindow)
window = mc.window(self.pivotDriverWindow, width=1, height=1)
mc.columnLayout()
self.floatSlider = mc.floatSliderButtonGrp(label=attr,
field=True,
value=value,
buttonLabel='Bake',
minValue=minValue,
maxValue=maxValue,
buttonCommand=self.doEditPivotDriver )
mc.showWindow( window )
mc.window(self.pivotDriverWindow, edit=True, width=1, height=1)
def channelBox(*args):
channels = utl.getSelectedChannels()
if not channels:
return
sel = mc.ls(sl=True)
clear()
for each in sel:
for c in channels:
if mc.attributeQuery(c, node=each, exists=True):
mc.selectionConnection('graphEditor1FromOutliner', edit=True, select=each+'.'+c)