Python源码示例:pymel.core.delete()
示例1
def cleanup_intermediate_objects(progress_controller=None):
"""Delete unused intermediate objects
deletes any unused intermediate object in the current scene
"""
if progress_controller is None:
progress_controller = ProgressControllerBase()
unused_intermediate_objects = []
all_meshes = pm.ls(type='mesh')
progress_controller.maximum = len(all_meshes)
for node in all_meshes:
if len(node.inputs()) == 0 \
and len(node.outputs()) == 0 \
and node.intermediateObject.get() \
and node.referenceFile() is None:
unused_intermediate_objects.append(node)
progress_controller.increment()
pm.delete(unused_intermediate_objects)
progress_controller.complete()
示例2
def _fetch_system_from_scene(self):
"""
Get all SpaceSwitch system in the scene
"""
self.aSceneSpaceSwitch = []
self.ui.cbSysList.clear()
self.ui.cbSysList.addItem("--- Select a system ---")
lstNetworkNode = libSerialization.getNetworksByClass(SpaceSwitcherLogic.__name__)
for pNet in lstNetworkNode:
pData = libSerialization.import_network(pNet)
# Check to ensure the data is valid, delete it if not
if pData.nDriven is not None and pData.nSwConst is not None and pData.nSwConstRecept is not None:
self.ui.cbSysList.addItem(pData.nDriven.name())
self.aSceneSpaceSwitch.append(pData)
else:
print("System {0} will be deleted because some data is invalid. Driven = {1}, Const = {2}, "
"Const Recept = {3}".format(pNet, pData.nDriven, pData.nSwConst, pData.nSwConstRecept))
pymel.delete(pNet)
示例3
def _update_lstParent(self, pSpData):
"""
Update the parent list for the selected system
"""
self.createModel.clear()
if pSpData:
self.ui.lstParent.setEnabled(True)
self.createModel.appendRow(self.parentItem)
for iIdx, nParentInfo in enumerate(pSpData.aDrivers):
newParentItem = QtGui.QStandardItem(nParentInfo.name())
newParentItem.setEditable(False)
# Prevent any delete action when the sysem is referenced
if pymel.referenceQuery(self.pSelSpSys.nSwConst, isNodeReferenced=True):
newParentItem.setCheckable(False)
else:
newParentItem.setCheckable(True)
self.createModel.appendRow(newParentItem)
else:
self.ui.lstParent.setEnabled(False)
self.createModel.appendRow(self.parentItem)
示例4
def populateData(self):
lstNetworkNode = libSerialization.getNetworksByClass(PoseReaderData.__name__)
aToDel = []
for pNet in lstNetworkNode:
pData = libSerialization.import_network(pNet)
#Ensure that the network is valid, if not, delete the network node
for sVar in pData.__dict__ :
#print "{0} --> {1}".format(sVar, pData.__dict__[sVar])
if not (pData.__dict__[sVar]): #TODO --> Delete invalid system node ?
aToDel.append(pNet)
break;
if not aToDel: self.addItem(pData)
if aToDel:
pymel.delete(aToDel)
#We could use the function pymel.spaceLocator() :P
示例5
def hold_ctrl_shapes(ctrl, parent=None):
"""
Make a snapshot of all shapes of a specific ctrls.
"""
shapes = filter(lambda x: isinstance(x, pymel.nodetypes.CurveShape), ctrl.getShapes())
snapshot_transform = pymel.duplicate(ctrl, parentOnly=True, returnRootsOnly=True)[0]
for shape in shapes:
shape_snapshot = _duplicate_shape(shape)
tmp_transform = shape_snapshot.getParent()
shape_snapshot.setParent(snapshot_transform, s=True, r=True)
pymel.delete(tmp_transform)
if parent:
snapshot_transform.setParent(parent)
else:
snapshot_transform.setParent(world=True)
snapshot_transform.rename('{0}Snapshot'.format(ctrl.name()))
return snapshot_transform
示例6
def process(self, context, plugin):
import pymel.core as pm
# Get the errored instances
failed = []
for result in context.data["results"]:
if (result["error"] is not None and result["instance"] is not None
and result["instance"] not in failed):
failed.append(result["instance"])
# Apply pyblish.logic to get the instances for the plug-in
instances = api.instances_by_plugin(failed, plugin)
for instance in instances:
for node in instance[0].members():
io = pm.ls(node.getShapes(), intermediateObjects=True)
pm.delete(io)
示例7
def process(self, context, plugin):
import pymel.core as pm
# Get the errored instances
failed = []
for result in context.data["results"]:
if (result["error"] is not None and result["instance"] is not None
and result["instance"] not in failed):
failed.append(result["instance"])
# Apply pyblish.logic to get the instances for the plug-in
instances = api.instances_by_plugin(failed, plugin)
for instance in instances:
for node in instance[0].members():
pm.delete(pm.cluster(node))
示例8
def testPyCmds():
start = time.time()
helix = cmds.polyHelix(**HELIX_OPTS)
pHelix = helix[0]
size = cmds.polyEvaluate(v=True)
for i in xrange(size):
x = RAND.uniform(LOW, HIGH)
attrib = '%s.vtx[%s]' % (pHelix, i)
cmds.move(x, attrib, x=True)
cmds.delete(pHelix)
end = time.time()
return end-start
示例9
def testPyMel():
start = time.time()
helix = pm.polyHelix(**HELIX_OPTS)
pHelix = helix[0]
# 20020 loops
for v in pHelix.vtx:
# strangly, its faster to make a new vector
# object every time, as opposed to creating it
# once and changing the x value each time???
vector = pm.dt.Vector(x=RAND.uniform(LOW, HIGH))
v.translateBy(vector)
pm.delete(pHelix)
end = time.time()
return end-start
示例10
def delete(camera):
"""deletes the vertigo setup from the given camera
"""
global vertigo_attr_name
global vertigo_global_attr_name
camera_shape = camera.getShape()
expression = camera_shape.connections(type=pm.nt.Expression)
vertigo_loc = camera.attr(vertigo_attr_name).inputs()[0]
world_loc = camera.attr(vertigo_global_attr_name).inputs()[0]
# delete them
pm.delete(expression)
pm.delete(vertigo_loc)
pm.delete(world_loc)
示例11
def duplicate(self, class_=None, prefix="", suffix=""):
"""duplicates itself and returns a new joint hierarchy
:param class_: The class of the created JointHierarchy. Default value
is JointHierarchy
:param prefix: Prefix for newly created joints
:param suffix: Suffix for newly created joints
"""
if class_ is None:
class_ = self.__class__
new_start_joint = pm.duplicate(self.start_joint)[0]
all_hierarchy = list(reversed(new_start_joint.listRelatives(ad=1, type=pm.nt.Joint)))
new_end_joint = all_hierarchy[len(self.joints) - 2]
# delete anything below
pm.delete(new_end_joint.listRelatives(ad=1))
new_hierarchy = class_(start_joint=new_start_joint, end_joint=new_end_joint)
for j, nj in zip(self.joints, new_hierarchy.joints):
nj.rename("{prefix}{joint}{suffix}".format(prefix=prefix, suffix=suffix, joint=j.name()))
return new_hierarchy
示例12
def delete_unused_intermediate_shapes(cls):
"""clears unused intermediate shape nodes
"""
ignored_node_types = [
'nodeGraphEditorInfo',
'shadingEngine',
]
def filter_funct(x):
return x.type() not in ignored_node_types
unused_nodes = []
for node in pm.ls(type=pm.nt.Mesh):
if len(filter(filter_funct, node.inputs())) == 0 and \
len(filter(filter_funct, node.outputs())) == 0 \
and node.attr('intermediateObject').get():
unused_nodes.append(node)
pm.delete(unused_nodes)
示例13
def delete_all_others(self, shot): # delete all useless shots and cameras
special_cams = ['perspShape', 'frontShape', 'sideShape', 'topShape']
unused_shots = pm.ls(type="shot")
# unused_camera = pm.ls("camera*", type="transform")
unused_camera = [node.getParent()
for node in pm.ls(type='camera')
if node.name() not in special_cams]
clear_cams_list = set(unused_camera)
sel_camera = shot.currentCamera.get()
unused_shots.remove(shot)
clear_cams_list.remove(sel_camera)
pm.delete(unused_shots)
pm.delete(clear_cams_list)
shot.track.set(1)
print("shot is in order")
示例14
def clear_scene(self, keep_shot):
# delete all other shot nodes
all_shots = pm.ls(type='shot')
shots_to_delete = []
for shot in all_shots:
if shot.name() != keep_shot.name():
shots_to_delete.append(shot)
for shot in shots_to_delete:
if shot:
pm.delete(shot)
# set some attrs and delete cameras
if keep_shot:
keep_shot.track.set(1)
keep_shot.shotName.lock()
shot_camera = keep_shot.currentCamera.get()
exclude_cams = ['perspShape', 'frontShape', 'sideShape', 'topShape', shot_camera.getShape()]
unused_cameras = [node.getParent()
for node in pm.ls(type='camera')
if node.name() not in exclude_cams]
pm.delete(unused_cameras)
示例15
def orient_choose_direction(self, joint, jointUnder, frontAxis):
#TODO : Validate frontAxis
if frontAxis == "x":
frontInt = 0
elif frontAxis == "z":
frontInt = 2
returnVal = 1
transform_1 = DrawNode(Shape.transform, 'direction1')
transform_1.temp_constrain(joint)
transform_2 = DrawNode(Shape.transform, "direction2")
transform_2.temp_constrain(jointUnder)
frontTransform = transform_1.transform[frontInt] - \
transform_2.transform[frontInt]
if frontTransform > 0:
returnVal = -1
transform_1.delete()
transform_2.delete()
return returnVal
示例16
def set_zero_joint(self):
#Removes Zero Joint from Joint Chain
pm.joint(self.jointChain[0], e=True, zso=True, oj='xyz', sao='xup')
self.zeroJoint = self.jointChain[0]
self._zeroPos = pm.dt.Point(pm.getAttr(self._zeroJoint.translate))
self.jointChain.remove(self.jointChain[0])
self.jointPos.remove(self.jointPos[0])
pm.joint(self.jointChain[1], e=True, zso=True, oj='xyz', sao='yup')
for i in range(1, len(self.jointChain)):
pm.joint(self.jointChain[i], e=True, zso=True, oj='xyz', sao='yup')
#sets Start End Num Of Joints again
self._numOfJoints = len(self._jointChain)
#Orient Zero Joint
temporalGroup = DrawNode(Shape.transform, 'temporalGroup')
pm.parent(self.startJoint, temporalGroup.drawnNode)
print(pm.getAttr(self.zeroJoint.jointOrient))
pm.setAttr(self.zeroJoint.jointOrientX, 0)
pm.parent(self.startJoint, self.zeroJoint)
temporalGroup.delete()
示例17
def create_axialCor(self):
# Create Axial Correction group
if self._axialCor is not None:
temp_grp = pm.group(self.drawnNode, n=(self._axialCor + "_#"))
self.ofsGrp.append(temp_grp)
else:
name = (self.drawnNode + "_axialCor")
self._axialCor = self._draw(Shape.transform,
(name))
pm.delete(pm.parentConstraint(self.drawnNode, self.axialCor, mo=0))
pm.parent(self._drawnNode, self._axialCor)
#pm.delete(self.create_parentConst(self.drawnNode, self.axialCor))
#pm.parent(self._drawnNode, self.axialCor)
# Create Point Constrain
示例18
def getDock(name='LightingManagerDock'):
"""
This function creates a dock with the given name.
It's an example of how we can mix Maya's UI elements with Qt elements
Args:
name: The name of the dock to create
Returns:
QtWidget.QWidget: The dock's widget
"""
# First lets delete any conflicting docks
deleteDock(name)
# Then we create a dockControl dock using Maya's UI tools
# This gives us back the name of the dock created
# <=Maya2016: In Maya 2016 and below, we just give our Light Managers object name to the dockControl.
# You can see this name when we do self.setObjectName in the LightManagers __init__ method
ctrl = pm.dockControl(name, area='right', content='lightingManager', allowedArea='all', label="Lighting Manager")
# And then we return the control name
return ctrl
示例19
def _adjust_firstKey(self, iTime, vRestT, vRestRot):
"""
Adjust the offset of the first constraint key in the system to prevent a snap when we move keys
"""
pymel.setCurrentTime(iTime)
aWeight = self.nSwConst.getWeightAliasList()
for i, w in enumerate(aWeight):
if w.get() == 1:
iParentIdx = self._get_adjusted_index(i)
# Create a node as a fake parent to have an easiest way to extract the matrix
nTempDriven = pymel.createNode("transform")
nTempDriven.setTranslation(vRestT, space="world")
nTempDriven.setRotation(vRestRot, space="world")
vTrans = self._get_tm_offset(self.aDrivers[iParentIdx], _nDriven=nTempDriven, _type="t")
vRot = self._get_tm_offset(self.aDrivers[iParentIdx], _nDriven=nTempDriven, _type="r")
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateX.set(vTrans[0])
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateY.set(vTrans[1])
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateZ.set(vTrans[2])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateX.set(vRot[0])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateY.set(vRot[1])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateZ.set(vRot[2])
pymel.setKeyframe(self.nSwConst.target[iParentIdx].targetOffsetTranslate, t=iTime, ott="step")
pymel.setKeyframe(self.nSwConst.target[iParentIdx].targetOffsetRotate, t=iTime, ott="step")
pymel.keyTangent(self.nSwConst.target[iParentIdx].targetOffsetTranslate, t=iTime,
ott="step") # Force step
pymel.keyTangent(self.nSwConst.target[iParentIdx].targetOffsetRotate, t=iTime, ott="step") # Force step
pymel.delete(nTempDriven)
示例20
def _event_edtFrame_mousePress(self, event, iRow=0):
"""
Generate a right click on the QLineEdit with the frame number to allow the user to delete a key
"""
if event.button() == QtCore.Qt.RightButton:
# Get data
pFrameCell = self.ui.tblFrameInfo.item(iRow, self.ID_COL_FRAME)
iFrame = pFrameCell.data(QtCore.Qt.UserRole)
menu = QtWidgets.QMenu()
action_sel_parent = menu.addAction('Remove')
action_sel_parent.triggered.connect(partial(self._event_rcMenu_deleteKey, iFrame))
menu.exec_(QtGui.QCursor.pos())
示例21
def _event_btnRemove_pressed(self, iRow):
"""
Delete the key in the same row than the delete button
"""
pFrameCell = self.ui.tblFrameInfo.item(iRow, self.ID_COL_FRAME)
iFrame = pFrameCell.data(QtCore.Qt.UserRole)
self.pSelSpSys.deleteKey(iFrame)
self._update_tblFrameInfo(self.pSelSpSys)
示例22
def on_action_axisChange(self, iRow, iCol, *args):
pCell = self.ui.tblData.item(iRow,iCol)
pData = pCell.data(QtCore.Qt.UserRole)
pData.nChildLoc.axis.set(args[0])
#Delete old connection
pymel.disconnectAttr(pData.nMD.input1X)
lstXCon = pData.nDecM.outputRotateX.listConnections()
pymel.disconnectAttr(pData.nDecM.outputRotateX)
pymel.delete(lstXCon)
lstYCon = pData.nDecM.outputRotateY.listConnections()
pymel.disconnectAttr(pData.nDecM.outputRotateY)
pymel.delete(lstYCon)
lstZCon = pData.nDecM.outputRotateZ.listConnections()
pymel.disconnectAttr(pData.nDecM.outputRotateZ)
pymel.delete(lstZCon)
if args[0] == 0:
pymel.connectAttr(pData.nDecM.outputRotateX, pData.nMD.input1X, f=True)
elif args[0] == 1:
pymel.connectAttr(pData.nDecM.outputRotateY, pData.nMD.input1X, f=True)
elif args[0] == 2:
pymel.connectAttr(pData.nDecM.outputRotateZ, pData.nMD.input1X, f=True)
#Change the axis connection of the system to connect in the good axis
示例23
def deleteSystem(self, pData):
aToDel = [pData.__dict__[sName] for sName in pData.__dict__ if sName != "nParent" and sName != "nChild"]
pymel.delete(aToDel)
self.refresh()
示例24
def fetch_all_ctrls_shapes():
"""
Restore the snapshots of all shapes of all ctrls.
"""
aSources = get_all_ctrlsnapshots()
for oSource in aSources:
sTargetName = oSource.name()[:-8]
if pymel.objExists(sTargetName):
oTarget = pymel.PyNode(str(sTargetName))
fetch_ctrl_shapes(oSource, oTarget)
#pymel.delete(oSource)
else:
pymel.warning("Can't find {0}".format(sTargetName))
示例25
def save_all_ctrls_shapes(path=None, **kwargs):
# Resolve current path
current_path = cmds.file(q=True, sceneName=True)
if not current_path:
pymel.warning("Please save your scene!")
return
# Resolve path
if path is None:
path = get_default_path_snapshot(current_path)
cmds.undoInfo(openChunk=True)
snapshots = hold_all_ctrls_shapes(**kwargs)
if snapshots:
pymel.select(snapshots)
cmds.file(rename=path)
cmds.file(exportSelected=True, type='mayaAscii', prompt=False, force=True)
cmds.file(rename=current_path)
pymel.delete(snapshots)
print('Exported shapes to: {0}'.format(path))
return True
cmds.undoInfo(closeChunk=True)
return False
示例26
def copy(self, mesh):
self.cluster_list = []
self.point_dict = {}
self.cls_weight_dict = {}
dummy = common.TemporaryReparent().main(mode='create')
common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='cut')
cluster = cmds.ls(cmds.listHistory(mesh), type='cluster', l=True)
for cls in cluster:
set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
cmds.select(set_node)
vertices = cmds.ls(sl=True)
vertices = cmds.filterExpand(vertices, sm=31)
cmds.select(vertices, r=True)
try:
weights = cmds.percent(cls, q=True, v=True)
print weights
#値が取れないときアンドゥするとなぜか直ることがある
except Exception as e:
print e.message
cmds.delete(cls)
cmds.undo()
set_node = cmds.ls(cmds.listHistory(cls, f=True), type='objectSet', l=True)[0]
vertices = cmds.ls(sl=True)
vertices = cmds.filterExpand(vertices, sm=31)
cmds.select(vertices, r=True)
weights = cmds.percent(cls, q=True, v=True)
self.cluster_list.append(cls)
self.cls_weight_dict[cls] = weights
self.point_dict[cls] = vertices
common.TemporaryReparent().main(mesh, dummyParent=dummy, mode='parent')#コピーのおわったメッシュの子供を元に戻す
common.TemporaryReparent().main(dummyParent=dummy, mode='delete')#ダミー親削除
return self.point_dict, self.cls_weight_dict
示例27
def duplicate_with_skin(nodes, parentNode=None):
#親子付けがあってもエラーはかないように修正
print nodes
# リストタイプじゃなかったらリストに変換する
if not isinstance(nodes, list):
nodes = [nodes]
dupObjs = []
for node in nodes:
#子供のノード退避用ダミーペアレントを用意
dummy = common.TemporaryReparent().main(mode='create')
common.TemporaryReparent().main(node,dummyParent=dummy, mode='cut')
#複製
dup = cmds.duplicate(node)[0]
#ウェイト転送メソッドをSimpleWeightコピペに変更
weight.SimpleWeightCopyPaste().main(node, mode='copy', saveName=__name__, weightFile=node)
weight.SimpleWeightCopyPaste().main(dup, mode='paste', saveName=__name__, weightFile=node)
#親子付けを戻す
common.TemporaryReparent().main(node,dummyParent=dummy, mode='parent')
#ダミーペアレントを削除
common.TemporaryReparent().main(dummyParent=dummy, mode='delete')
if parentNode is not None:
cmds.parent(dup, parentNode)
dupObjs.append(dup)
return dupObjs
#シーン内、もしくは入力メッシュ内にゼロポリゴンオブジェクトがあるかどうか調べる関数
示例28
def cleanOrphaneControllerTags(tag):
"""Security check, delete tags without controlObject plug
Arguments:
tag (controllers tag list): The tags to check
Returns:
list: The valid tags with controller object plugged
"""
if not isinstance(tag, list):
tag = [tag]
validTags = []
for t in tag:
if not t.controllerObject.connections():
pm.displayWarning("The controller tag: %s have not controller "
"object input. Auto Deleted!" % t.name())
pm.delete(t)
reorderControllerChildrenTags(t)
else:
validTags.append(t)
return validTags
##########################################################
# PICK WALK
##########################################################
示例29
def clearSprings(model=None):
"""Delete baked animation from spring
Args:
model (dagNode): The rig top node
"""
# filters the root node from selection
if not model:
model = getRootNode()
springNodes = getControlers(model, gSuffix=PLOT_GRP_SUFFIX)
pairblends = [sn.listConnections(type="pairBlend")[0]
for sn in springNodes]
for pb in pairblends:
animCrvs = pb.listConnections(type="animCurveTA")
for fcrv in animCrvs:
for conn in fcrv.listConnections(connections=True,
destination=True,
plugs=True):
pm.disconnectAttr(conn[0], conn[1])
# reset the value to 0
attrs = ["inRotateX1", "inRotateY1", "inRotateZ1"]
for attr in attrs:
pb.attr(attr).set(0)
# delete fcurves
pm.delete(animCrvs)
示例30
def findLenghtFromParam(crv, param):
"""
Find lengtht from a curve parameter
Arguments:
param (float): The parameter to get the legth
crv (curve): The source curve.
Returns:
float: Curve uLength
Example:
.. code-block:: python
oParam, oLength = cur.getCurveParamAtPosition(upRope, cv)
uLength = cur.findLenghtFromParam(upRope, oParam)
u = uLength / oLength
"""
node = pm.createNode("arcLengthDimension")
pm.connectAttr(crv.getShape().attr("worldSpace[0]"),
node.attr("nurbsGeometry"))
node.attr("uParamValue").set(param)
uLength = node.attr("arcLength").get()
pm.delete(node.getParent())
return uLength
# ========================================