def _output_node(source, type, suffix):
newname = lib.unique(name=source.rsplit("_", 1)[0] + suffix)
node = cmds.createNode(type)
node = [cmds.listRelatives(node, parent=True) or node][0]
node = cmds.rename(node, newname)
try:
cmds.parent(node, source)
match_transform(node, source)
except Exception:
cmds.warning("Could not create %s" % node)
cmds.delete(node)
return node
python类warning()的实例源码
def save(self):
# We start off by getting the name in the text field
name = self.saveNameField.text()
# If the name is not given, then we will not continue and we'll warn the user
# The strip method will remove empty characters from the string, so that if the user entered spaces, it won't be valid
if not name.strip():
cmds.warning("You must give a name!")
return
# We use our library to save with the given name
self.library.save(name)
# Then we repopulate our UI with the new data
self.populate()
# And finally, lets remove the text in the name field so that they don't accidentally overwrite the file
self.saveNameField.setText('')
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 Exception:
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 Exception:
cmds.warning("Could not find shape in %s" % element)
return None
else:
return node
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")
def _clone(worldspace=False):
"""Clone selected objects in viewport
Arguments:
worldspace (bool): Whether or not to append a transformGeometry to
resulting clone.
"""
clones = list()
for node in cmds.ls(selection=True, long=True):
shape = _find_shape(node)
type = cmds.nodeType(shape)
if type not in ("mesh", "nurbsSurface", "nurbsCurve"):
cmds.warning("Skipping '{node}': cannot clone nodes "
"of type '{type}'".format(**locals()))
continue
cloned = commands.clone(shape, worldspace=worldspace)
clones.append(cloned)
if not clones:
return
# Select newly created transform nodes in the viewport
transforms = list()
for clone in clones:
transform = cmds.listRelatives(clone, parent=True, fullPath=True)[0]
transforms.append(transform)
cmds.select(transforms, replace=True)
def _find_shape(element):
"""Return shape of given 'element'
Supports components, meshes, and surfaces
Arguments:
element (str): Path to component, mesh or surface
Returns:
str of path if found, None otherwise
"""
# Get either shape or transform, based on element-type
node = cmds.ls(element, objectsOnly=True, long=True)[0]
if cmds.nodeType(node) == "transform":
try:
return cmds.listRelatives(node, shapes=True, fullPath=True)[0]
except IndexError:
return cmds.warning("Could not find shape in %s" % element)
else:
return node
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 updatePose(self):
uiSet = str(self.ui.setEdit.text())
ind = self.ui.poseList.currentRow()
currentItem = self.ui.poseList.currentItem().text()
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
if not uiSet:
return False
if ind < 0:
return False
BT_AddPose(set = uiSet, index = ind)
return True
def deletePose(self):
uiSet = str(self.ui.setEdit.text())
currentItem = self.ui.poseList.currentItem().text()
if not uiSet:
return False
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
poseIndex = self.ui.poseList.currentRow()
BT_DeletePose(set = uiSet, poseIndex = poseIndex)
poses = BT_GetPosesFromSet(uiSet)
self.ui.poseList.clear()
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 BT_ConnectSetup(set = None):
if not set or not cmds.objExists(set):
return False
if BT_IsSetupConnected(set = set):
cmds.warning('Setup already connected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
for i in range(0, len(transforms)):
try:
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
except:
pass
mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
if mults:
cmds.delete(mults)
return True
def deletePose(self):
uiSet = str(self.ui.setEdit.text())
currentItem = self.ui.poseList.currentItem().text()
if not uiSet:
return False
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
poseIndex = self.ui.poseList.currentRow()
BT_DeletePose(set = uiSet, poseIndex = poseIndex)
poses = BT_GetPosesFromSet(uiSet)
self.ui.poseList.clear()
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 BT_DoSetup():
sets = cmds.ls(sl = True, type = 'objectSet')
if len(sets) <= 0:
cmds.warning("Select a set.")
return False
set = sets[0]
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")
result = BT_Setup(set = set)
if not result:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
return False
print('Success!')
return True
def BT_ConnectSetup(set = None):
if not set or not cmds.objExists(set):
return False
if BT_IsSetupConnected(set = set):
cmds.warning('Setup already connected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
for i in range(0, len(transforms)):
try:
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
except:
pass
mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
if mults:
cmds.delete(mults)
return True
def updatePose(self):
uiSet = str(self.ui.setEdit.text())
ind = self.ui.poseList.currentRow()
currentItem = self.ui.poseList.currentItem().text()
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
if not uiSet:
return False
if ind < 0:
return False
BT_AddPose(set = uiSet, index = ind)
return True
def deletePose(self):
uiSet = str(self.ui.setEdit.text())
currentItem = self.ui.poseList.currentItem().text()
if not uiSet:
return False
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
poseIndex = self.ui.poseList.currentRow()
BT_DeletePose(set = uiSet, poseIndex = poseIndex)
poses = BT_GetPosesFromSet(uiSet)
self.ui.poseList.clear()
self.ui.poseList.addItems(poses)
return True
def BT_DoSetup():
sets = cmds.ls(sl = True, type = 'objectSet')
if len(sets) <= 0:
cmds.warning("Select a set.")
return False
set = sets[0]
unitResult = BT_SetUnits()
if unitResult:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay")
result = BT_Setup(set = set)
if not result:
QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay")
return False
print('Success!')
return True
def updatePose(self):
uiSet = str(self.ui.setEdit.text())
ind = self.ui.poseList.currentRow()
currentItem = self.ui.poseList.currentItem().text()
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Update Pose', 'Really Update ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
if not uiSet:
return False
if ind < 0:
return False
BT_AddPose(set = uiSet, index = ind)
return True
def deletePose(self):
uiSet = str(self.ui.setEdit.text())
currentItem = self.ui.poseList.currentItem().text()
if not uiSet:
return False
if BT_IsSetupConnected(uiSet):
cmds.warning('Disconnect setup first!')
return False
result = QtGui.QMessageBox.question(self, 'Delete Pose', 'Really Delete ' +str(currentItem) +' ?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if result != QtGui.QMessageBox.Yes:
return False
poseIndex = self.ui.poseList.currentRow()
BT_DeletePose(set = uiSet, poseIndex = poseIndex)
poses = BT_GetPosesFromSet(uiSet)
self.ui.poseList.clear()
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 BT_ConnectSetup(set = None):
if not set or not cmds.objExists(set):
return False
if BT_IsSetupConnected(set = set):
cmds.warning('Setup already connected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
for i in range(0, len(transforms)):
try:
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
except:
pass
mults = cmds.listConnections(btNode, d = True, type = 'multiplyDivide')
if mults:
cmds.delete(mults)
return True
def to_curve_fn(curve):
shape = None
if cmds.nodeType(curve, 'nurbsCurve'):
shape = curve
else:
child = cmds.listRelatives(curve, shapes=True, noIntermediate=True)
if child:
shape = child[0]
else:
cmds.warning('Not a proper nurbsCurve: {}'.format(curve))
raise Exception('Not a proper nurbsCurve: {}'.format(curve))
sel = om.MSelectionList()
sel.add(shape)
dep = sel.getDagPath(0)
fn = om.MFnNurbsCurve(dep)
return fn
def populateCrvField(tfgKey="", *args):
if tfgKey not in ["cntrPivTFBG", "cntrPiv2TFBG", "upLoc2TFBG", "upLocTFBG"]:
sel = cmds.ls(sl=True)
if sel and len(sel)!=1:
cmds.warning("only select the curve you want to rig up!")
else:
if rig.isType(sel[0], "nurbsCurve"):
cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
else:
cmds.warning("That's not a curve!")
else:
sel = cmds.ls(sl=True)
if sel and len(sel)!=1:
cmds.warning("only select the object you want to rig up!")
else:
cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0])
if tfgKey == "upLocTFBG":
cmds.textFieldButtonGrp(widgets["upLoc2TFBG"], e=True, tx=sel[0])
if tfgKey == "cntrPivTFBG":
cmds.textFieldButtonGrp(widgets["cntrPiv2TFBG"], e=True, tx=sel[0])
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 move_pivot(end, *args):
"""
Args:
end (int): parameter value (0 or 1 from buttons) the point on curve will return, start or end
*args:
"""
check = False
sel = cmds.ls(sl=True, exactType = "transform")
if sel:
for x in sel:
check = rig.isType(x, "nurbsCurve")
if check:
# get curve info
pos = cmds.pointOnCurve(x, parameter = end, position = True)
cmds.xform(x, ws=True, piv=pos)
else:
cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
def reparameter(*args):
"""
reparameterizes curves to be from 0-1
Args:
Returns:
"""
sel = cmds.ls(sl=True, exactType = "transform")
check = False
newCrvs = []
if sel:
for x in sel:
check = rig.isType(x, "nurbsCurve")
if check:
crv = x
newCrv = cmds.rebuildCurve(crv, constructionHistory=False, rebuildType = 0, keepControlPoints=True, keepRange = 0, replaceOriginal=True, name = "{0}_RB".format(crv))[0]
# reconnect parents and children of orig curve
else:
cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
cmds.select(sel, r=True)
def align_along_curve(*args):
"""
aligns and objet along a curve at given param
Args:
*args:
Returns:
void
"""
sel = cmds.ls(sl=True, type="transform")
if len(sel) != 2:
cmds.warning("You need to select curve then object to align!")
return()
crv = sel[0]
obj = sel[1]
if not rig.isType(crv, "nurbsCurve"):
cmds.warning("select curve first, THEN object")
return()
param = cmds.floatFieldGrp(widgets["alExFFG"], q=True, v1=True)
rig.align_to_curve(crv, obj, param)
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 capReplace(*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:
oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0]
dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap)
cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe))
cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl))
cmds.setAttr("{0}.v".format(dupe), 1)
# 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)