Python源码示例:pymel.core.selected()
示例1
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)
示例2
def _event_cbSys_selChanged(self, _iIdx):
"""
Manage the system change with the combo box. select the node related to the system selected in the combo box
"""
# Prevent a node selection when the comboBox index changed during selection changed callback
if not self.bInSelChanged:
if _iIdx > 0:
pCurSys = self.aSceneSpaceSwitch[_iIdx - 1]
pymel.select(pCurSys.nDriven)
else: # If the no system index is selected, but a node is selected in the scene, put back the selected system
for i, pSp in enumerate(self.aSceneSpaceSwitch):
if pSp.nDriven == self.nSelDriven:
# Change the index, but prevent the event to select back the node
self.bInSelChanged = True
self.ui.cbSysList.setCurrentIndex(i + 1)
self.bInSelChanged = False
break
示例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 smart_reset(*args):
"""Reset the SRT or the selected channels
Checks first if we have channels selected. If not, will try to reset SRT
Args:
*args: Dummy
"""
attributes = getSelectedChannels()
if attributes:
reset_selected_channels_value(objects=None, attributes=attributes)
else:
reset_SRT()
##########################################################
# GETTERS
##########################################################
示例5
def getSelectedChannels(userDefine=False):
"""Get the selected channels on the channel box
Arguments:
userDefine (bool, optional): If True, will return only the user
defined channels. Other channels will be skipped.
Returns:
list: The list of selected channels names
"""
# fetch core's main channelbox
attrs = pm.channelBox(get_channelBox(), q=True, sma=True)
if userDefine:
oSel = pm.selected()[0]
uda = oSel.listAttr(ud=True)
if attrs:
attrs = [x for x in attrs if oSel.attr(x) in uda]
else:
return None
return attrs
示例6
def getSelectedObjectChannels(oSel=None, userDefine=False, animatable=False):
"""Get the selected object channels.
Arguments:
oSel (None, optional): The pynode with channels to get
userDefine (bool, optional): If True, will return only the user
defined channels. Other channels will be skipped.
animatable (bool, optional): If True, only animatable parameters
will be return
Returns:
list: The list of the selected object channels names
"""
if not oSel:
oSel = pm.selected()[0]
channels = [x.name().rsplit(".", 1)[1]
for x in oSel.listAttr(ud=userDefine, k=animatable)]
return channels
##########################################################
# UTIL
##########################################################
示例7
def rivet_per_face():
"""creates hair follicles per selected face
"""
sel_list = pm.ls(sl=1, fl=1)
follicles = []
locators = []
for face in sel_list:
# use the center of the face as the follicle position
p = reduce(lambda x, y: x + y, face.getPoints()) / face.numVertices()
obj = pm.spaceLocator(p=p)
locators.append(obj)
shape = face.node()
uv = face.getUVAtPoint(p, space='world')
follicle_transform, follicle = create_follicle(shape, uv)
pm.parent(obj, follicle_transform)
follicles.append(follicle)
return follicles, locators
示例8
def create_bbox(nodes, per_selection=False):
"""creates bounding boxes for the selected objects
:param bool per_selection: If True will create a BBox for each
given object
"""
if per_selection:
for node in nodes:
return cube_from_bbox(node.boundingBox())
else:
bbox = pm.dt.BoundingBox()
for node in nodes:
bbox.expand(node.boundingBox().min())
bbox.expand(node.boundingBox().max())
return cube_from_bbox(bbox)
示例9
def reset_tweaks(cls):
"""Resets the tweaks on the selected deformed objects
"""
for obj in pm.ls(sl=1):
for tweak_node in pm.ls(obj.listHistory(), type=pm.nt.Tweak):
try:
for i in tweak_node.pl[0].cp.get(mi=1):
tweak_node.pl[0].cv[i].vx.set(0)
tweak_node.pl[0].cv[i].vy.set(0)
tweak_node.pl[0].cv[i].vz.set(0)
except TypeError:
try:
for i in tweak_node.vl[0].vt.get(mi=1):
tweak_node.vl[0].vt[i].vx.set(0)
tweak_node.vl[0].vt[i].vy.set(0)
tweak_node.vl[0].vt[i].vz.set(0)
except TypeError:
pass
示例10
def create(self):
# reverse_foot_controller = pm.selected()[0]
# foot_ik_ankle_joint = pm.selected()[0]
# foot_ik_ball_joint = pm.selected()[0]
# foot_ik_tip_joint = pm.selected()[0]
#
# attrs = [
# 'tipHeading',
# 'tipRoll',
# 'tipBank',
# 'ballRoll',
# 'ballBank'
# ]
#
#
# for attr in attrs:
# pm.addAttr(reverse_foot_controller, ln=attr, at='float', k=1)
#
# reverse_foot_controller.tipHeading >> foot_ik_tip_joint.ry
# reverse_foot_controller.tipRoll >> foot_ik_tip_joint.rx
# reverse_foot_controller.tipBank >> foot_ik_tip_joint.rz
#
# reverse_foot_controller.ballRoll >> foot_ik_ball_joint.rx
# reverse_foot_controller.ballBank >> foot_ik_ball_joint.rz
pass
示例11
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)
示例12
def open_node_in_browser(cls):
# get selected nodes
node_attrs = {
'file': 'fileTextureName',
'aiImage': 'filename',
'aiStandIn': 'dso',
}
import os
from anima.utils import open_browser_in_location
for node in pm.ls(sl=1):
type_ = pm.objectType(node)
# special case: if transform use shape
if type_ == 'transform':
node = node.getShape()
type_ = pm.objectType(node)
attr_name = node_attrs.get(type_)
if attr_name:
# if any how it contains a "#" character use the path
path = node.getAttr(attr_name)
if "#" in path:
path = os.path.dirname(path)
open_browser_in_location(path)
示例13
def export_shader_attributes(cls):
"""exports the selected shader attributes to a JSON file
"""
# get data
data = []
nodes = pm.ls(sl=1)
for node in nodes:
node_attr_data = {}
attrs = node.listAttr()
for attr in attrs:
try:
value = attr.get()
if not isinstance(value, pm.PyNode):
node_attr_data[attr.shortName()] = value
except TypeError:
continue
data.append(node_attr_data)
# write data
import json
with open(cls.node_attr_info_temp_file_path, 'w') as f:
json.dump(data, f)
示例14
def randomize_light_color_temp(cls, min_field, max_field):
"""Randomizes the color temperature of selected lights
:param min:
:param max:
:return:
"""
min = pm.floatField(min_field, q=1, v=1)
max = pm.floatField(max_field, q=1, v=1)
cls.randomize_attr(
[node.getShape() for node in pm.ls(sl=1)],
'aiColorTemperature',
min,
max,
1
)
示例15
def randomize_light_intensity(cls, min_field, max_field):
"""Randomizes the intensities of selected lights
:param min:
:param max:
:return:
"""
min = pm.floatField(min_field, q=1, v=1)
max = pm.floatField(max_field, q=1, v=1)
cls.randomize_attr(
[node.getShape() for node in pm.ls(sl=1)],
'aiExposure',
min,
max,
0.1
)
示例16
def smooth_selected_keyframes(cls, iteration=10):
"""smooths the selected keyframes
:param iteration:
:return:
"""
from anima.utils import smooth_array
node = pm.keyframe(q=1, sl=1, n=1)[0]
keyframe_indices = pm.keyframe(q=1, sl=1, iv=1)
keyframe_values = pm.keyframe(q=1, sl=1, vc=1)
for i in range(iteration):
keyframe_values = smooth_array(keyframe_values)
# restore the keyframe values
for i, v in zip(keyframe_indices, keyframe_values):
pm.keyframe(node, e=1, index=i, vc=v)
示例17
def _callback_scene_undoRedo(self, *args):
"""
Ensure to refresh the UI on a undo in the scene
"""
if self.pSelSpSys and pymel.selected():
self._update_info(self.pSelSpSys)
else:
self._update_info(None)
示例18
def CallFnOnNetworkByClass(_sFn, _sCls):
fnFilter = lambda x: libSerialization.isNetworkInstanceOfClass(x, _sCls)
networks = libSerialization.getConnectedNetworks(pymel.selected(), key=fnFilter, recursive=False)
for network in networks:
rigPart = libSerialization.import_network(network)
if not hasattr(rigPart, _sFn):
logging.warning("Can't find attribute {0} in {1}".format(_sFn, network)); continue
try:
getattr(rigPart, _sFn)()
except Exception, e:
print str(e)
示例19
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.")
示例20
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)
示例21
def controllerWalkRight(node, add=False, multi=False):
""" Pick walks the next sibling to the right 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(), "right", multi)
pm.select(nodes, add=add)
# =====================================================
# transform walkers
示例22
def reset_selected_channels_value(objects=None, attributes=None):
"""Reset the the selected channels if not attribute is provided
Args:
objects (None, optional): The objects to reset the channels
attribute (list, optional): The attribute to reset
"""
if not objects:
objects = cmds.ls(selection=True)
if not attributes:
attributes = getSelectedChannels()
for obj in objects:
for attr in attributes:
set_default_value(obj, attr)
示例23
def get_selected_channels_full_path():
"""Get the selected channels full path from channel box
This function will collect channels from any area of the channel box. This
include, Main, shape, input and output
Returns:
list: list of channels full path
"""
attrs = []
node = pm.ls(sl=True)
if node:
node = node[0]
collect_attrs(
node, attrs, pm.channelBox(get_channelBox(), q=True, sma=True))
# if the attr is from shape node, we need to search in all shapes
collect_attrs(node,
attrs,
pm.channelBox(get_channelBox(), q=True, ssa=True),
shapes=True)
collect_attrs(
node, attrs, pm.channelBox(get_channelBox(), q=True, sha=True))
collect_attrs(
node, attrs, pm.channelBox(get_channelBox(), q=True, soa=True))
return attrs
示例24
def keySel():
"""Key selected controls"""
pm.setKeyframe()
# ================================================
示例25
def mirrorPose(flip=False, nodes=None):
"""Summary
Args:
flip (bool, optiona): Set the function behaviout to flip
nodes (None, [PyNode]): Controls to mirro/flip the pose
"""
if nodes is None:
nodes = pm.selected()
pm.undoInfo(ock=1)
try:
nameSpace = False
if nodes:
nameSpace = getNamespace(nodes[0])
mirrorEntries = []
for oSel in nodes:
mirrorEntries.extend(gatherMirrorData(nameSpace, oSel, flip))
for dat in mirrorEntries:
applyMirror(nameSpace, dat)
except Exception as e:
pm.displayWarning("Flip/Mirror pose fail")
import traceback
traceback.print_exc()
print e
finally:
pm.undoInfo(cck=1)
示例26
def resetSelTrans():
"""Reset the transfom values (SRT) for the selected objects"""
with pm.UndoChunk():
for obj in pm.selected():
transform.resetTransform(obj)
示例27
def collect_selected_curve_data(objs=None):
"""Generate a dictionary descriving the curve data from selected objs
Args:
objs (None, optional): Optionally a list of object can be provided
"""
if not objs:
objs = pm.selected()
return collect_curve_data(objs)
示例28
def bBoxData(obj=None, yZero=False, *args):
"""Get bounding box data of a mesh object
Arguments:
obj (dagNode): Mesh object
yZero (bool): If True, sets the Y axis value to 0 in world space
args:
Returns:
list: center, radio, bounding box full data
"""
volCenter = False
if not obj:
obj = pm.selected()[0]
shapes = pm.listRelatives(obj, ad=True, s=True)
if shapes:
bb = pm.polyEvaluate(shapes, b=True)
volCenter = [(axis[0] + axis[1]) / 2 for axis in bb]
if yZero:
volCenter[1] = bb[1][0]
radio = max([bb[0][1] - bb[0][0], bb[2][1] - bb[2][0]]) / 1.7
return volCenter, radio, bb
#################################################
# CLOSEST LOCATIONS
#################################################
示例29
def addSelectedObjects(self):
onionCore.viewRenderOverrideInstance.addSelectedOnion()
for obj in pm.selected():
self.mOnionObjectSet.add(obj)
self.refreshObjectList()
#
示例30
def removeSelectedObjects(self):
onionCore.viewRenderOverrideInstance.removeSelectedOnion()
for obj in pm.selected():
if obj in self.mOnionObjectSet:
self.mOnionObjectSet.remove(obj)
self.refreshObjectList()
#