Python源码示例:pymel.core.select()
示例1
def _event_edtFrame_changed(self, iRow):
"""
Manage a frame change in the frame info table
"""
pCellQLine = self.ui.tblFrameInfo.cellWidget(iRow, self.ID_COL_FRAME)
if pCellQLine.text() != "":
pCellFrame = self.ui.tblFrameInfo.item(iRow, self.ID_COL_FRAME)
iOldFrame = pCellFrame.data(QtCore.Qt.UserRole)
# pCellParent = self.ui.tblFrameInfo.item(iRow, self.ID_COL_PARENT)
# iParentIdx = pCellParent.data(QtCore.Qt.UserRole)
iNewFrame = int(pCellQLine.text())
# Prevent the user to move a key on a frame already constrained
if not (iNewFrame in self.aConstrainedFrame):
self.pSelSpSys.moveKey(iNewFrame, iOldFrame)
self._update_tblFrameInfo(self.pSelSpSys)
else:
pCellQLine.setText(str(iOldFrame))
pymel.select(self.nSelDriven)
示例2
def gear_curvecns_op(crv, inputs=[]):
"""
create mGear curvecns node.
Arguments:
crv (nurbsCurve): Nurbs curve.
inputs (List of dagNodes): Input object to drive the curve. Should be
same number as crv points.
Also the order should be the same as the points
Returns:
pyNode: The curvecns node.
"""
pm.select(crv)
node = pm.deformer(type="mgear_curveCns")[0]
for i, item in enumerate(inputs):
pm.connectAttr(item + ".worldMatrix", node + ".inputs[%s]" % i)
return node
示例3
def controllerWalkUp(node, add=False):
"""Walk up in the hierachy using the controller tag
Arguments:
node (dagNode or list of dagNode): Node with controller tag
add (bool, optional): If true add to selection
"""
oParent = []
if not isinstance(node, list):
node = [node]
for n in node:
tag = getWalkTag(n)
if tag:
cnx = tag.parent.connections()
if cnx:
oParent.append(cnx[0])
else:
pm.displayWarning("The selected object: %s without Controller tag "
"will be skipped" % n.name())
if oParent:
pm.select(_getControllerWalkNodes(oParent), add=add)
else:
pm.displayWarning("No parent to walk Up.")
示例4
def transformWalkUp(node, add=False):
"""Walks to the parent transform dagNode on the hierarcy
Arguments:
node (dagNode or list of dagNode): dagNode to walk
add (bool, optional): if True, will add to the selection
"""
oParent = []
if not isinstance(node, list):
node = [node]
for n in node:
p = n.listRelatives(p=True)
if p:
oParent.append(p)
if oParent:
pm.select(oParent, add=add)
else:
pm.displayWarning("No parent to walk Up.")
示例5
def transformWalkDown(node, add=False, multi=False):
"""Walks to the child transform dagNode on the hierarcy
Arguments:
node (dagNode or list of dagNode): dagNode to walk
add (bool, optional): if True, will add to the selection
multi (bool, optional): if True will select all the childrens
"""
oChild = []
if not isinstance(node, list):
node = [node]
for n in node:
relatives = n.listRelatives(typ='transform')
if relatives:
if multi:
oChild = oChild + relatives
else:
oChild.append(relatives[0])
if oChild:
pm.select(oChild, add=add)
else:
pm.displayWarning("No child to walk Down.")
示例6
def transformWalkRight(node, add=False, multi=False):
"""Pick walks to the right the next sibling transform on the hierarchy
Arguments:
node (dagNode or list of dagNode): dagNode transform to navegate
the hierarchy
add (bool, optional): If true add to selection
multi (bool, optional): If true, selects all the siblings
"""
sib = _getTransformWalkSiblings(node, "right", multi)
pm.select(sib, add=add)
# =====================================================
# Walk mirror
示例7
def select_all_child_controls(control, *args): # @unusedVariable
""" Selects all child controls from the given control
This function uses Maya's controller nodes and commands to find relevant
dependencies between controls
Args:
control (str): parent animation control (transform node)
*args: State of the menu item (if existing) send by mgear's dagmenu
"""
# gets controller node from the given control. Returns if none is found
tag = cmds.ls(cmds.listConnections(control), type="controller")
if not tag:
return
# query child controls
children = get_all_tag_children(tag)
# adds to current selection the children elements
cmds.select(children, add=True)
示例8
def setup_stretchy_spline_ik_curve(cls):
"""
"""
selection = pm.ls(sl=1)
curve = selection[0]
curve_info = pm.createNode("curveInfo")
mult_div = pm.createNode("multiplyDivide")
curve_shape = pm.listRelatives(curve, s=1)
curve_shape[0].worldSpace >> curve_info.ic
curve_info.arcLength >> mult_div.input1X
curve_length = curve_info.arcLength.get()
mult_div.input2X.set(curve_length)
mult_div.operation.set(2)
pm.select(mult_div, curve_info, curve_shape[0], add=True)
示例9
def finalize_setup(self):
"""does final clean up
"""
self.check_main_control()
# group the node together
parent_group = pm.nt.Transform(name='SquashStretchBendRiggerGroup#')
pm.parent(self.main_control.getParent(), parent_group)
pm.parent(self.aim_locator1, parent_group)
if self.use_squash:
pm.parent(self.squash_handle, parent_group)
pm.parent(self.bend_handle, parent_group)
# set visibilities
self.aim_locator1.v.set(0)
if self.use_squash:
self.squash_handle.v.set(0)
self.bend_handle.v.set(0)
# as a gesture select the main control
pm.select(self.main_control)
示例10
def assign_random_material_color(cls):
"""assigns a lambert with a random color to the selected object
"""
selected = pm.selected()
# create the lambert material
lambert = pm.shadingNode('lambert', asShader=1)
# create the shading engine
shading_engine = pm.nt.ShadingEngine()
lambert.outColor >> shading_engine.surfaceShader
# randomize the lambert color
import random
h = random.random() # 0-1
s = random.random() * 0.5 + 0.25 # 0.25-0.75
v = random.random() * 0.5 + 0.5 # 0.5 - 1
from anima.utils import hsv_to_rgb
r, g, b = hsv_to_rgb(h, s, v)
lambert.color.set(r, g, b)
pm.sets(shading_engine, fe=selected)
pm.select(selected)
示例11
def check_sequence_name(progress_controller=None):
"""Sequence name is properly set
checks if the sequence name attribute is properly set
"""
if progress_controller is None:
progress_controller = ProgressControllerBase()
# do not consider referenced shot nodes
shots = pm.ls(type='shot')
progress_controller.maximum = len(shots)
shot = None
for s in shots:
if s.referenceFile() is None:
shot = s
break
progress_controller.increment()
progress_controller.complete()
sequencer = shot.outputs(type='sequencer')[0]
sequence_name = sequencer.sequence_name.get()
if sequence_name == '' or sequence_name is None:
pm.select(sequencer)
raise PublishError('Please enter a sequence name!!!')
示例12
def jobReloadUI(self, *args):
""" This scriptJob active when we got one new scene in order to reload the UI.
"""
import maya.cmds as cmds
cmds.select(clear=True)
cmds.evalDeferred("import sys; sys.modules['dpAutoRigSystem.dpAutoRig'].DP_AutoRig_UI()", lowestPriority=True)
示例13
def populateJoints(self, *args):
""" This function is responsable to list all joints or only dpAR joints in the interface in order to use in skinning.
"""
# get current jointType (all or just dpAutoRig joints):
jntSelectedRadioButton = cmds.radioCollection(self.allUIs["jntCollection"], query=True, select=True)
chooseJnt = cmds.radioButton(jntSelectedRadioButton, query=True, annotation=True)
# list joints to be populated:
jointList, sortedJointList = [], []
allJointList = cmds.ls(selection=False, type="joint")
if chooseJnt == "allJoints":
jointList = allJointList
cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=False)
cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=False)
elif chooseJnt == "dpARJoints":
cmds.checkBox(self.allUIs["_JntCB"], edit=True, enable=True)
cmds.checkBox(self.allUIs["_JisCB"], edit=True, enable=True)
displayJnt = cmds.checkBox(self.allUIs["_JntCB"], query=True, value=True)
displayJis = cmds.checkBox(self.allUIs["_JisCB"], query=True, value=True)
for jointNode in allJointList:
if cmds.objExists(jointNode+'.'+BASE_NAME+'joint'):
if displayJnt:
if "_Jnt" in jointNode:
jointList.append(jointNode)
if displayJis:
if "_Jis" in jointNode:
jointList.append(jointNode)
# sort joints by name filter:
jointName = cmds.textField(self.allUIs["jointNameTF"], query=True, text=True)
if jointList:
if jointName:
sortedJointList = utils.filterName(jointName, jointList, " ")
else:
sortedJointList = jointList
# populate the list:
cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, removeAll=True)
cmds.textScrollList( self.allUIs["jntTextScrollLayout"], edit=True, append=sortedJointList)
# atualize of footerB text:
self.atualizeSkinFooter()
示例14
def reloadPopulatedGeoms(self, *args):
""" This function reloads the list all selected geometries in the interface in order to use in skinning if necessary.
"""
# store current selected items in the geometry list to skin:
geomSelectedList = cmds.textScrollList( self.allUIs["modelsTextScrollLayout"], query=True, selectItem=True)
# populate again the list of geometries:
self.populateGeoms()
# re-select the old selected items in the list if possible:
if geomSelectedList:
try:
cmds.textScrollList( self.allUIs["modelsTextScrollLayout"], edit=True, selectItem=geomSelectedList)
except:
pass
示例15
def mousePressEventEdt(self, event, iCol=0, iRow=0):
if event.button() == QtCore.Qt.RightButton:
pCell = self.ui.tblData.item(iRow,iCol)
pData = pCell.data(QtCore.Qt.UserRole) #Attr set function
menu = QtWidgets.QMenu()
action_sel_child = menu.addAction('Select Child')
action_sel_child.triggered.connect(partial(pymel.select, pData.nChildLoc))
action_sel_parent = menu.addAction('Select Parent');
action_sel_parent.triggered.connect(partial(pymel.select, pData.nParentLoc))
action_sel_parent = menu.addAction('Select Bones');
action_sel_parent.triggered.connect(partial(pymel.select, [pData.nParent, pData.nChild]))
action_sel_parent = menu.addAction('Delete');
action_sel_parent.triggered.connect(partial(self.deleteSystem, pData))
menu.exec_(QtGui.QCursor.pos())
示例16
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
示例17
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
示例18
def paste(self, mesh):
if not self.cluster_list:
return
for cls in self.cluster_list:
weights = self.cls_weight_dict[cls]
print 'paste cls :',cls
cmds.select(cl=True)
points = self.point_dict[cls]
newcls = cmds.cluster(points, n=cls)
for i, v in enumerate(points):
cmds.percent(newcls[0], v, v=(weights[i]))
return newcls
#ポリゴンメッシュをウェイト付きで複製する関数
示例19
def cehck_zero_poly_object(mesh=None, pop_msg=True):
#mesh 入力メッシュ
#pop_msg 探索結果を表示するかどうか
if mesh == None:
polyMeshes = common.search_polygon_mesh(cmds.ls(tr=True))
else:
polyMeshes = common.search_polygon_mesh(mesh)
zeroPolyObj = []
if polyMeshes == None:
if pop_msg:
cmds.confirmDialog( title="Check",message='Zero Polygon Object Count : 0')
return zeroPolyObj
for p in polyMeshes:
vtx = cmds.polyListComponentConversion(p, tv=True)
if vtx == []:
zeroPolyObj.append(p)
if not pop_msg:
return zeroPolyObj
if zeroPolyObj == []:
cmds.confirmDialog( title="Check",message='Zero Polygon Object Count : 0')
else:
msg = 'Zero Polygon Object Count : '+str(len(zeroPolyObj))
for p in zeroPolyObj:
msg+='\n[ '+p+' ]'
cmds.confirmDialog( title="Check",message=msg )
cmds.select(zeroPolyObj, r=True)
return zeroPolyObj
#スキニングを保ったままメッシュマージする関数
示例20
def gear_curveslide2_op(outcrv,
incrv,
position=0,
maxstretch=1,
maxsquash=1,
softness=0):
"""Apply a sn_curveslide2_op operator
Arguments:
outcrv (NurbsCurve): Out Curve.
incrv (NurbsCurve): In Curve.
position (float): Default position value (from 0 to 1).
maxstretch (float): Default maxstretch value (from 1 to infinite).
maxsquash (float): Default maxsquash value (from 0 to 1).
softness (float): Default softness value (from 0 to 1).
Returns:
pyNode: The newly created operator.
"""
pm.select(outcrv)
node = pm.deformer(type="mgear_slideCurve2")[0]
pm.connectAttr(incrv + ".local", node + ".master_crv")
pm.connectAttr(incrv + ".worldMatrix", node + ".master_mat")
pm.setAttr(node + ".master_length", pm.arclen(incrv))
pm.setAttr(node + ".slave_length", pm.arclen(incrv))
pm.setAttr(node + ".position", 0)
pm.setAttr(node + ".maxstretch", 1)
pm.setAttr(node + ".maxsquash", 1)
pm.setAttr(node + ".softness", 0)
return node
示例21
def controllerWalkDown(node, add=False, multi=False):
"""Walk down in the hierachy using the controller tag
Arguments:
node (dagNode or list of dagNode): Node with controller tag
add (bool, optional): If true add to selection
"""
oChild = []
if not isinstance(node, list):
node = [node]
for n in node:
tag = getWalkTag(n)
if tag:
cnx = cleanOrphaneControllerTags(tag.children.connections())
else:
pm.displayWarning("The selected object: %s without Controller tag "
"will be skipped" % n.name())
if cnx:
if multi:
oChild = oChild + cnx
else:
oChild.append(cnx[0])
if oChild:
pm.select(_getControllerWalkNodes(oChild), add=add)
else:
pm.displayWarning("No child to walk Down.")
示例22
def controllerWalkLeft(node, add=False, multi=False):
"""Pick walks the next sibling to the left using controller tag
Arguments:
node (TYPE): Description
add (bool, optional): If true add to selection
multi (bool, optional): If true, selects all the siblings
"""
nodes = _getControllerWalkSiblings(pm.selected(), "left", multi)
pm.select(nodes, add=add)
示例23
def transformWalkLeft(node, add=False, multi=False):
"""Pick walks to the left the next sibling transform on the hierarchy
Arguments:
node (dagNode or list of dagNode): dagNode transform to navegate
the hierarchy
add (bool, optional): If true add to selection
multi (bool, optional): If true, selects all the siblings
"""
sib = _getTransformWalkSiblings(node, "left", multi)
pm.select(sib, add=add)
示例24
def walkMirror(node, add=False):
"""Select the mirror dagNode
Arguments:
node (dagNode or list of dagNode): The dagNode to look for a mirror
add (bool, optional): If true add to selection
"""
mN = getMirror(node)
pm.select(mN, add=add)
# =====================================================
# Main walkers
示例25
def selAll(model):
"""Select all controlers
Args:
model (PyNode): Rig top node
"""
controlers = getControlers(model)
pm.select(controlers)
示例26
def selGroup(model, groupSuffix):
"""Select the members of a given set
Args:
model (PyNode): Rig top node
groupSuffix (str): Set suffix name
"""
controlers = getControlers(model, groupSuffix)
pm.select(controlers)
示例27
def quickSel(model, channel, mouse_button):
"""Select the object stored on the quick selection attributes
Args:
model (PyNode): The rig top node
channel (str): The quick selection channel name
mouse_button (QtSignal): Clicked mouse button
Returns:
None
"""
qs_attr = model.attr("quicksel%s" % channel)
if mouse_button == QtCore.Qt.LeftButton: # Call Selection
names = qs_attr.get().split(",")
if not names:
return
pm.select(clear=True)
for name in names:
ctl = dag.findChild(model, name)
if ctl:
ctl.select(add=True)
elif mouse_button == QtCore.Qt.MidButton: # Save Selection
names = [sel.name().split("|")[-1]
for sel in pm.ls(selection=True)
if sel.name().endswith("_ctl")]
qs_attr.set(",".join(names))
elif mouse_button == QtCore.Qt.RightButton: # Key Selection
names = qs_attr.get().split(",")
if not names:
return
else:
keyObj(model, names)
##################################################
# KEY
##################################################
# ================================================
示例28
def instance(self, source_transform_node):
"""instances the given nodes hierarchy
"""
# duplicate the given node
# then replace the instanceable nodes with instances
# find instanceable nodes in the node and dupNode
source_hierarchy = self.walk_hierarchy(source_transform_node)
# if there is no node in the sourceHierarchy just return
# the instance of the given node
if len(source_hierarchy) < 1:
dup_node = pm.duplicate(source_transform_node, ilf=1, rc=True)[0]
pm.select(dup_node)
return
dup_node = pm.duplicate(source_transform_node, rc=True)[0]
dup_hierarchy = self.walk_hierarchy(dup_node)
for i, node in enumerate(dup_hierarchy):
shape = node.getShape()
if shape is not None and isinstance(shape,
tuple(self._instanceables)):
# instance the corresponding sourceNode
source_node = source_hierarchy[i]
new_instance_node = pm.duplicate(source_node, ilf=True)[0]
pm.parent(new_instance_node, node.getParent(), r=False)
pm.delete(node)
pm.select(dup_node)
return dup_node
示例29
def create_preview_curve(self, side):
"""creates preview curves
"""
# create two joints
j1 = pm.createNode('joint')
j2 = pm.createNode('joint')
j1.t.set(-0.5, 0, 0)
j2.t.set(0.5, 0, 0)
self.joints[side] += [j1, j2]
# create one nurbs curve
preview_curve = pm.curve(
d=1,
p=[(-0.5, 0, 0),
(0.5, 0, 0)],
k=[0, 1]
)
self.preview_curves[side].append(preview_curve)
# bind the joints to the curveShape
pm.select([preview_curve, j1, j2])
skin_cluster = pm.skinCluster()
self.store_nodes([
j1, j2, preview_curve, skin_cluster
])
示例30
def select_joints_deforming_object(cls):
selection = pm.ls(sl=1)
conn = pm.listHistory(selection[0])
skin_cluster = ""
for i in range(0, len(conn)):
if conn[i].type() == "skinCluster":
skin_cluster = conn[i]
break
conn = pm.listConnections(skin_cluster)
joints = []
for item in conn:
if item.type() == "joint":
joints.append(item)
pm.select(joints)