def addBaseCap(*args):
sel = cmds.ls(sl=True, type="transform")
if sel < 2:
cmds.warning("You don't have two things selected (cap and one ctrl minimum)!")
return
newCap = sel[0]
ctrls = sel[1:]
for ctrl in ctrls:
tempCap = cmds.connectionInfo("{0}.tempBaseCap".format(ctrl), sfd=True).partition(".")[0]
dupe = rig.swapDupe(newCap, tempCap, delete=True, name="{0}_baseCap".format(ctrl))
cmds.setAttr("{0}.v".format(dupe), 1)
cmds.connectAttr("{0}.rotateBaseCap".format(ctrl), "{0}.rotateY".format(dupe))
cmds.connectAttr("{0}.message".format(dupe), "{0}.tempBaseCap".format(ctrl))
# if not already, parent cap replace obj in folder and hide
par = cmds.listRelatives(newCap, p=True)
if not par or par[0] != "pastaRigSetupComponents_Grp":
cmds.parent(newCap, "pastaRigSetupComponents_Grp")
cmds.setAttr("{0}.v".format(newCap), 0)
cmds.select(ctrls, r=True)
python类warning()的实例源码
def getValues(*args):
try:
obj = cmds.ls(sl=True, transforms = True)[0]
#currentFrame = cmds.currentTime(q = True)
step = cmds.intFieldGrp(widgets['stepIFG'], q = True, v1 = True)
frmVal = cmds.radioButtonGrp(widgets["frmRBG"], q=True, sl=True)
suffix = cmds.textFieldGrp(widgets["sufTFG"], q = True, tx = True)
name = "%s_%s"%(obj, suffix)
if frmVal == 1:
frameStart = int(cmds.playbackOptions(query=True, min=True))
frameEnd = int(cmds.playbackOptions(query=True, max=True))
else:
frameStart = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v1 = True)
frameEnd = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v2 = True)
makeSequence(obj, name, frameStart, frameEnd, step)
except:
cmds.warning("Select one object with a transform")
def getObjectList(*args):
"""gets the list of object of type txt"""
objs = []
objText = getTypeText()
if objText in typeList:
objs = cmds.ls(type=objText)
else:
cmds.warning("This instance of Maya doesn't recognize that type of object: {0}!".format(objText))
return()
if objs:
#---------------- check if we're promoting shapes
#---------------- if yes, send out list to see which elements are shapes and promote them, return a new list into obj ie. objs = promoteList(objs), this will return either the same list or an ammended list
addObjectsToScrollList(objs)
else:
cmds.warning("No objects found of type: {0}".format(objText))
def getAttr(*args):
"""grabs the selected channel from the selected obj and puts the enum values into the list"""
#--------here could require a channel of a specific name, then you could do it automagically (check for "follow", "spaces", "space", "ss", etc)
obj = cmds.textFieldGrp(widgets["objTFG"], q=True, tx=True)
cmds.select(obj, r=True)
channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True)
print channels
if (channels and (len(channels)==1)):
if (cmds.attributeQuery(channels[0], node=obj, enum=True)):
enumValue = cmds.attributeQuery(channels[0], node=obj, listEnum=True)
values = enumValue[0].split(":")
for value in values:
cmds.textScrollList(widgets["spacesTSL"], e=True, append=value)
#----------create a button for each one???
#----------or have them be double clicked???
else:
cmds.warning("select only the enum space switch channel")
def populateList(*args):
xform = None
tsl = widgets["defTSL"]
cmds.textScrollList(tsl, e=True, removeAll=True)
cmpnts = cmds.filterExpand(ex=False, sm=[28, 31])
if cmpnts:
xform = cmpnts[0].partition(".")[0]
if not cmpnts:
sel = cmds.ls(sl=True, type="transform")
if sel:
xform = sel[0]
if not xform:
cmds.warning("You must select a piece of geo or some components on a piece of geo!")
return()
cmds.textFieldGrp(widgets["objTFG"], e=True, tx=xform)
defs = getDeformers(xform)
for d in defs:
cmds.textScrollList(tsl, e=True, a=d)
def connect_param(src, tgt, attrType, prm, force=False, *args):
"""
connects the indiv chnls based on the checkbox sorting in connect_attrs
args:
src (string): source object
tgt (string): target object
attrType (string): attr short name (t, r, s)
prm (string): specific channel name (x, y, z)
force (bool): value for force flag. Defaults to False
return:
None
"""
try:
cmds.connectAttr("{0}.{1}{2}".format(src, attrType, prm), "{0}.{1}{2}".format(tgt, attrType, prm), force=force)
except:
cmds.warning(
"there was an issue connecting to {0}{1} of {2}. Make sure the channels are free!".format(attrType, prm,
tgt))
def locked_attr(*args):
"""
creates a locked attr (I use as a separator). Uses the long name as the nice name (literal name in channel box)
"""
attrName = cmds.textFieldButtonGrp(widgets["lockAttrTFBG"], q=True, tx=True)
if attrName:
sel = cmds.ls(sl=True)
if sel:
for obj in sel:
try:
cmds.addAttr(obj, ln=attrName, nn=attrName, at="enum", en="-----", k=True)
cmds.setAttr("%s.%s" % (obj, attrName), l=True)
except:
cmds.warning("Failed to add %s to %s, skipping!" % (attrName, obj))
else:
cmds.warning("Please select some objects to add attr to!")
else:
cmds.warning("Please enter a name for the attr!")
def add_zero_one_attribute(attrType, *args):
"""
adds an attribute with range of 0 to 1 to each selected obj
:param attrType: either "short" or "float"
:param args:
:return:
"""
sel = cmds.ls(sl=True)
if not sel:
cmds.warning("You need to select an object add attrs to!")
return()
attrName = cmds.textFieldGrp(widgets["newAttrTFG"], q=True, tx=True)
if not attrName:
cmds.warning("Please enter a name for the attribute in the field!")
return()
for obj in sel:
try:
cmds.addAttr(obj, ln=attrName, at=attrType, min=0, max=1, dv=0, k=True)
except:
cmds.warning("Couldn't add attr: {0} to object: {1}. Skipping.".format(attrName, obj))
def connectShapeVis(*args):
"""Connects the attr from the assoc. text field to the shape Visibility of selected objects"""
sel = cmds.ls(sl=True, type="transform")
driver = cmds.textFieldButtonGrp(widgets["toShapeVis"], q=True, tx=True)
if sel:
if driver:
for obj in sel:
shapes = cmds.listRelatives(obj, s=True)
for shape in shapes:
try:
cmds.connectAttr(driver, "%s.v" % shape, f=True)
cmds.warning("Connected %s to %s" % (driver, shape))
except:
cmds.warning("Couldn't connect %s to %s. Sorry! Check the Script Editor." % (driver, shape))
else:
cmds.warning("You need to select an object to connect the shape.vis!")
def shape_from_element(element):
"""Return shape of given 'element'
Supports components, meshes, and surfaces
"""
try:
# Get either shape or transform, based on element-type
node = cmds.ls(element, objectsOnly=True)[0]
except:
cmds.warning("Could not find node in %s" % element)
return None
if cmds.nodeType(node) == 'transform':
try:
return cmds.listRelatives(node, shapes=True)[0]
except:
cmds.warning("Could not find shape in %s" % element)
return None
else:
return node
def channelbox_command_cboxReset(box, menuItem, key, *args):
with sysCmd.Undo(0):
confirm = cmds.confirmDialog(t="Reset to Default",
m="Delete all saved data and modified settings associated with this Channel Box?",
icon="critical", button=["Reset", "Cancel"])
if confirm == "Reset":
default_states = box.menu_default_states
for k, v in default_states.iteritems():
# compare keys containing a default state with items that exist in the edit menu or others
# specified and restore them
box.saved_states[k] = v
sysCmd.channelbox_pickle_delete_state(box)
# box.re_init(box) # re-initialize to update our changes in the display
cmds.warning("Please close the ChannelBox UI and re-open it for changes to take effect")
def combine(nodes):
"""Produce a new mesh with the contents of `nodes`
Arguments:
nodes (list): Path to shapes
"""
unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite")
count = 0
for node in nodes:
# Are we dealing with transforms, or shapes directly?
shapes = cmds.listRelatives(node, shapes=True) or [node]
for shape in shapes:
try:
cmds.connectAttr(shape + ".outMesh",
unite + ".inputPoly[%s]" % count, force=True)
cmds.connectAttr(shape + ".worldMatrix",
unite + ".inputMat[%s]" % count, force=True)
count += 1
except Exception:
cmds.warning("'%s' is not a polygonal mesh" % shape)
if count:
output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape")
cmds.connectAttr(unite + ".output", output + ".inMesh", force=True)
return output
else:
cmds.delete(unite)
return None
def parent_group(source, transferTransform=True):
"""Create and transfer transforms to parent group"""
assert cmds.objExists(source), "%s does not exist" % source
assert cmds.nodeType(source) == "transform", (
"%s must be transform" % source)
parent = cmds.listRelatives(source, parent=True)
if transferTransform:
group = cmds.createNode("transform", n="%s_parent" % source)
match_transform(group, source)
try:
cmds.parent(source, group)
except Exception:
cmds.warning("Failed to parent child under new parent")
cmds.delete(group)
if parent:
cmds.parent(group, parent[0])
else:
cmds.select(source)
group = cmds.group(n="%s_parent" % source)
return group
def connect_matching_attributes(source, target):
"""Connect matching attributes from source to target
Arguments:
source (str): Absolute path to node from which to connect
target (str): Target node
Example:
>>> # Select two matching nodes
>>> source = cmds.createNode("transform", name="source")
>>> target = cmds.createNode("transform", name="target")
>>> cmds.select([source, target], replace=True)
>>> source, target = cmds.ls(selection=True)
>>> connect_matching_attributes(source, target)
"""
dsts = cmds.listAttr(target, keyable=True)
for src in cmds.listAttr(source, keyable=True):
if src not in dsts:
continue
try:
src = "." + src
cmds.connectAttr(source + src,
target + src,
force=True)
except RuntimeError as e:
cmds.warning("Could not connect %s: %s" % (src, e))
def transfer_outgoing_connections(*args):
"""Connect outgoing connections from first to second selected node"""
try:
src, dst = cmds.ls(selection=True)
except ValueError:
return cmds.warning("Select source and destination nodes")
commands.transfer_outgoing_connections(src, dst)
def auto_connect(*args):
"""Connect `src` to `dst` via the most likely input and output"""
try:
commands.auto_connect(*cmds.ls(selection=True))
except TypeError:
cmds.warning("Select only source and destination nodes.")
def setPresetColor(widget, preset):
"""
Apply a preset color to the given widget using style sheets
Args:
widget: A QWidget to apply styling to
preset: A string name of the preset color
"""
if preset in DesignViewPanel.PRESET_COLORS:
widget.setStyleSheet('background-color: {0};'.format(DesignViewPanel.PRESET_COLORS[preset]))
else:
cmds.warning('preset color not found: `{0}`'.format(preset))
def BT_DisconnectSetup(set = None):
if not set:
return False
if not BT_IsSetupConnected(set = set):
cmds.warning('Setup already disconnected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
numOutputs = cmds.getAttr(btNode +'.output', size = True)
print numOutputs
tempMult = None
for i in range(0, numOutputs):
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1')
cmds.select(cl = True)
return True
def __init__( self, parent = BT_GetMayaWindow() ):
super(BT_UIForm, self).__init__(parent)
uicPath = BT_FindUIFile()
if not uicPath:
return None
self.ui = None
if BT_MayaVersionNumber < 2014:
self.ui = uic.loadUi(uicPath, self)
else:
loader = QtUiTools.QUiLoader()
self.ui = loader.load(uicPath, self)
self.ui.loadSelectedButton.clicked.connect(self.loadSelectedSet)
self.ui.connectButton.clicked.connect(self.connectSetup)
self.ui.disconnectButton.clicked.connect(self.disconnectSetup)
self.ui.setToBaseButton.clicked.connect(self.setToBasePose)
self.ui.setToSelectedButton.clicked.connect(self.setToPose)
self.ui.addPoseButton.clicked.connect(self.addPose)
self.ui.deletePoseButton.clicked.connect(self.deletePose)
self.ui.updateSelectedButton.clicked.connect(self.updatePose)
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(self, "Blend Transforms", "Units set to centimetres.", "Okay")
self.ui.show()
def BT_DisconnectSetup(set = None):
if not set:
return False
if not BT_IsSetupConnected(set = set):
cmds.warning('Setup already disconnected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
numOutputs = cmds.getAttr(btNode +'.output', size = True)
print numOutputs
tempMult = None
for i in range(0, numOutputs):
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1')
cmds.select(cl = True)
return True