def _maintained_selection_context():
"""Maintain selection during context
Example:
>>> scene = cmds.file(new=True, force=True)
>>> node = cmds.createNode("transform", name="Test")
>>> cmds.select("persp")
>>> with maintained_selection():
... cmds.select("Test", replace=True)
>>> "Test" in cmds.ls(selection=True)
False
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
python类select()的实例源码
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 make_planar(joints):
for joint in joints:
parent = cmds.listRelatives(joint, parent=True, path=True)
if not parent:
log.warning('Cannot make %s planar because it does not have a parent.', joint)
continue
children = _unparent_children(joint)
if not children:
log.warning('Cannot make %s planar because it does not have any children.', joint)
continue
cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), u=(0, 1, 0), worldUpType='object', worldUpObject=parent[0]))
cmds.makeIdentity(joint, apply=True)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def make_position_planar(*args):
sel = cmds.ls(sl=True, type='joint')
if len(sel) <= 3:
raise RuntimeError('Select 3 joints to make a plane and then additional joints to move onto that plane.')
a, b, c = [get_position(sel[i]) for i in range(3)]
ab = (b - a).normal()
ac = (c - a).normal()
normal = (ab ^ ac).normal()
joints = sel[3:]
for joint in joints:
children = _unparent_children(joint)
p = get_position(joint)
pa = a - p
dot = pa*normal
p = p + (normal*dot)
cmds.xform(joint, ws=True, t=(p.x, p.y, p.z))
_reparent_children(joint, children)
if sel:
cmds.select(sel)
def align_with_child(joints):
"""Aligns the up axis of the given joints with their respective child joint.
@param joints: List of joints to orient.
"""
for joint in joints:
children = _unparent_children(joint)
if children:
cmds.delete(cmds.aimConstraint(children[0], joint, aim=(1, 0, 0), upVector=(0, 1, 0),
worldUpType="objectrotation", worldUpVector=(0, 1, 0),
worldUpObject=children[0]))
cmds.makeIdentity(joint, apply=True)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def orient_to_world(joints):
"""Orients the given joints with the world.
@param joints: Joints to orient.
"""
for joint in joints:
children = _unparent_children(joint)
print children
parent = cmds.listRelatives(joint, parent=True, path=True)
orig_joint = joint.split('|')[-1]
if parent:
joint = cmds.parent(joint, world=True)[0]
cmds.joint(joint, e=True, oj='none', zso=True)
if parent:
joint = cmds.parent(joint, parent)[0]
print 'Renaming {0} to {1}'.format(joint, orig_joint)
joint = cmds.rename(joint, orig_joint)
_reparent_children(joint, children)
if joints:
cmds.select(joints)
def create_selected(self):
"""Create the curves selected in the curve list."""
curves = []
sel = cmds.ls(sl=True)
target = sel[0] if sel else None
for item in self.control_list.selectedItems():
text = item.text()
control_file = os.path.join(CONTROLS_DIRECTORY, '{0}.json'.format(text))
fh = open(control_file, 'r')
data = json.load(fh)
fh.close()
curve = create_curve(data)
if target:
cmds.delete(cmds.parentConstraint(target, curve))
curves.append(curve)
if curves:
cmds.select(curves)
def setUp(self):
self.group = cmds.createNode('transform', name='skeleton_grp')
cmds.select(cl=True)
j1 = cmds.joint(p=(0, 10, 0))
cmds.joint(p=(1, 9, 0))
cmds.joint(p=(2, 8, 0))
j = cmds.joint(p=(3, 9, 0))
cmds.joint(p=(4, 6, 0))
cmds.joint(p=(5, 5, 0))
cmds.joint(p=(6, 3, 0))
self.cube = cmds.polyCube()[0]
cmds.parent(self.cube, j)
cmds.parent(j1, self.group)
self.translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')]
self.rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')]
self.orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
def doit(radius=5., num=36):
cmds.loadPlugin('rotationDriver', qt=True)
node = cmds.createNode('composeRotate')
node_or = node + '.outRotate'
node_h = node + '.bendH'
node_v = node + '.bendV'
shiftX = radius * 1.25
top0 = _plotBendHV(node_or, node_h, node_v, 'plotStereoProj', radius, num)
cmds.setAttr(top0 + '.tx', -shiftX)
cmds.setAttr(node + '.method', 1)
top1 = _plotBendHV(node_or, node_h, node_v, 'plotExpmap', radius, num)
cmds.setAttr(top1 + '.tx', shiftX)
cmds.delete(node)
cmds.select([top0, top1])
def WeaponBinder():
# Call of Duty specific
for x in xrange(0, len(GUN_BASE_TAGS)):
try:
# Select both tags and parent them
cmds.select(GUN_BASE_TAGS[x], replace = True)
cmds.select(VIEW_HAND_TAGS[x], toggle = True)
# Connect
cmds.connectJoint(connectMode = True)
# Parent
mel.eval("parent " + GUN_BASE_TAGS[x] + " " + VIEW_HAND_TAGS[x])
# Reset the positions of both bones
cmds.setAttr(GUN_BASE_TAGS[x] + ".t", 0, 0, 0)
cmds.setAttr(GUN_BASE_TAGS[x] + ".jo", 0, 0, 0)
cmds.setAttr(GUN_BASE_TAGS[x] + ".rotate", 0, 0, 0)
# Reset the rotation of the parent tag
cmds.setAttr(VIEW_HAND_TAGS[x] + ".jo", 0, 0, 0)
cmds.setAttr(VIEW_HAND_TAGS[x] + ".rotate", 0, 0, 0)
# Remove
cmds.select(clear = True)
except:
pass
# Place a notetrack
def SelectKeyframes():
# Clear current selection
cmds.select(clear=True)
# Get a list of bones
boneList = cmds.ls(type = 'joint')
# Iterate and select ones with frames on loc/rot/scale
for bone in boneList:
# Check for loc
keysTranslate = cmds.keyframe(bone + ".translate", query=True, timeChange=True)
keysRotate = cmds.keyframe(bone + ".rotate", query=True, timeChange=True)
keysScale = cmds.keyframe(bone + ".scale", query=True, timeChange=True)
# Check for frames
if keysTranslate is not None:
if len(keysTranslate) >= 1:
cmds.select(bone, add=True)
if keysRotate is not None:
if len(keysRotate) >= 1:
cmds.select(bone, add=True)
if keysScale is not None:
if len(keysScale) >= 1:
cmds.select(bone, add=True)
# Cleans namespaces
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 scale_the_objects(scaleVal, *args):
"""
does the scaling bits
"""
sel = cmds.ls(sl=True, type="transform")
if sel:
for obj in sel:
if (rig.isType(obj, "nurbsSurface")) or (rig.isType(obj, "nurbsCurve")):
piv = cmds.xform(obj, q=True, ws=True, rp=True)
cvs = cmds.select((obj + ".cv[*]"))
cmds.scale(scaleVal, scaleVal, scaleVal, cvs, pivot=piv)
elif rig.isType(obj, "mesh"):
piv = cmds.xform(obj, q=True, ws=True, rp=True)
vs = cmds.select((obj + ".vtx[*]"))
cmds.scale(scaleVal, scaleVal, scaleVal, vs, pivot=piv)
else:
cmds.warning("{0} isn't a nurbs or poly object, so it was skipped".format(obj))
# clear and reselect all
if sel:
cmds.select(cl=True)
cmds.select(sel)
return (True)
return (False)
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 preciseRemovePercent(keepNum, *args):
"""selects the exact amount of things to remove and randomly selects which from the selection list"""
sel = cmds.ls(sl=True, fl=True)
remNum = (100.0-keepNum)/100.0
remCount = int(remNum*len(sel))
count = 0
ch = []
if sel:
while len(ch)<remCount:
x = random.choice(sel)
if x not in ch:
ch.append(x)
newSel = [g for g in sel if g not in ch]
cmds.select(newSel, r=True)
print len(newSel), "objects remaining"
def selectComponents(*args):
sel = cmds.ls(sl=True)
if sel:
for obj in sel:
shape = cmds.listRelatives(obj, s=True)[0]
if cmds.objectType(shape) == "nurbsCurve":
cmds.select(cmds.ls("{}.cv[*]".format(obj), fl=True))
elif cmds.objectType(shape) == "mesh":
cmds.select(cmds.ls("{}.vtx[*]".format(obj), fl=True))
else:
return
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)
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)
def groupOrient(target='none',orig='none', group="GRP"):
"""
groups the second object and snaps the group to the second (point and orient). The group arg is to name the suffix you want the group to have (default is '_GRP')
Arguments: target (to be constrained to), orig (obj to move), group (suffix for group)
"""
if (target == "none"):
sel = getTwoSelection()
target = sel[0]
orig = sel[1]
cmds.select(orig)
grpName = "%s_%s"%(orig,group)
cmds.group(name=grpName)
pc = cmds.pointConstraint(target, grpName)
oc = cmds.orientConstraint(target, grpName)
cmds.delete(pc)
cmds.delete(oc)
cmds.select(clear=True)
return(grpName)
def import_animation(*args):
"""imports the anim (from rand selection of list items) onto selected objs"""
lo, hi = cmds.intFieldGrp(widgets["rangeIFG"], q=True, v=True)
rand = cmds.radioButtonGrp(widgets["randRBG"], q=True, sl=True)
clips = cmds.textScrollList(widgets["animTSL"], q=True, si=True)
path = cmds.textFieldButtonGrp(widgets["impPathTFG"], q=True, tx=True)
options = {"targetTime":3, "time": 1, "option":"insert", "connect":1}
delKeys = cmds.checkBoxGrp(widgets["delCBG"], q=True, v1=True)
sel = cmds.ls(sl=True)
for obj in sel:
startF = cmds.currentTime(q=True)
if rand == 1:
startF = random.randint(lo, hi)
cmds.currentTime(startF)
if delKeys:
delete_later_keys(obj, startF)
cmds.select(obj, r=True)
myClip = random.choice(clips)
animPath = "{0}/{1}".format(path, myClip)
cmds.file(animPath, i = True, type = "animImport", ignoreVersion = True, options = "targetTime={0};time={1};copies=1;option={2};pictures=0;connect={3};".format(options["targetTime"], startF, options["option"], options["connect"]), preserveReferences=True)
cmds.select(sel, r=True)
def follicleUI(*args):
"""UI for the script"""
if cmds.window("folWin", exists=True):
cmds.deleteUI("folWin")
widgets["win"] = cmds.window("folWin", t="zbw_makeFollicle", w=300, h=100)
widgets["mainCLO"] = cmds.columnLayout()
# widgets["polyFrame"] = cmds.frameLayout(l="Polygon Vert(s) Follicle")
# widgets["polyCLO"] = cmds.columnLayout()
widgets["text"] = cmds.text("Select one or two vertices (2 will get avg position) and run")
widgets["nameTFG"] = cmds.textFieldGrp(l="FollicleName:", cal=([1, "left"],[2,"left"]), cw=([1,100],[2,200]), tx="follicle")
cmds.separator(h=10)
widgets["button"] = cmds.button(w=300, h=50, bgc=(0.6,.8,.6), l="Add follicle to vert(s)", c=getUV)
# cmds.setParent(widgets["mainCLO"])
# widgets["nurbsFrame"] = cmds.frameLayout(l="Nurbs select")
cmds.showWindow(widgets["win"])
cmds.window(widgets["win"], e=True, w=300, h=100)
#-------could also select edit point????
#-------multiple selection and average uv position? Orrrr option to create multiple UV's, one on each vertex
#-------grab an edge and convert to 2 verts and get average. . .
#-------have option for distributed (select 2 verts and number of follicles, spread that num between the two uv positions)
def addObjectsToScrollList(objs):
"""puts the list of things in the textScrollList"""
clearScrollList()
stringSearch = cmds.checkBox(widgets["stringMatchCB"], q=True, v=True)
searchText = ""
checkedObjs = []
if stringSearch:
searchText = getSearchText()
if stringSearch and searchText:
for obj in objs:
# check if the string is in the name of obj
if searchText.lower() in obj.lower():
checkedObjs.append(obj)
else:
checkedObjs = objs
for x in checkedObjs:
#---------------- here add rt click functions to select all shapes or select transform (if shape)
cmds.textScrollList(widgets["resultsTSL"], e=True, a=x, doubleClickCommand=selectItemInList)
def bevelEdges(*args):
"""select obj, this will randomly bevel some edges"""
cutoffRaw = cmds.intSliderGrp(widgets["bpercISG"], q=True, v=True)
cutoff = cutoffRaw/100.0
sel = cmds.ls(sl=True)
for obj in sel:
edges = cmds.ls("%s.e[*]"%obj, fl=True)
bevelList = []
for edge in edges:
rand = random.uniform(0,1)
if rand <= cutoff:
bevelList.append(edge)
cmds.select(cl=True)
cmds.select(bevelList, r=True)
cmds.polyBevel(fraction = .5, offset = .05)
cmds.select(sel, r=True)
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 get_source_and_targets(*args):
"""
checks current selection, first sel is source, remaining are targets
args:
None
Return:
list (string, list): [0] is the source, [1] is the list of targets
or
None
"""
sel = cmds.ls(sl=True)
if sel and len(sel) > 1:
src = sel[0]
tgts = sel[1:]
return (src, tgts)
else:
cmds.warning("You need to select at least two objects!")
return (None, None)
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 maintained_selection():
"""Maintain selection during context
Example:
>>> scene = cmds.file(new=True, force=True)
>>> node = cmds.createNode("transform", name="Test")
>>> cmds.select("persp")
>>> with maintained_selection():
... cmds.select("Test", replace=True)
>>> "Test" in cmds.ls(selection=True)
False
"""
previous_selection = cmds.ls(selection=True)
try:
yield
finally:
if previous_selection:
cmds.select(previous_selection,
replace=True,
noExpand=True)
else:
cmds.select(deselect=True,
noExpand=True)
def get_goz_objs():
"""Grab meshes from selection, filter out extraneous DAG objects and
freeze transforms on objects.
"""
objs = cmds.ls(selection=True, type='mesh', dag=True)
if objs:
xforms = cmds.listRelatives(objs, parent=True, fullPath=True)
# freeze transform
cmds.makeIdentity(xforms, apply=True, t=1, r=1, s=1, n=0)
cmds.select(xforms)
objs = cmds.ls(selection=True)
return objs
#------------------------------------------------------------------------------
# Renaming
#------------------------------------------------------------------------------