def add_top_level_ctrl(origCtrl, type, geo, *args):
"""
creates a new ctrl, orients it to the geo and parent constrains the orig ctrl rig under itself
:param origCtrl: the control we're working from
:param type: the ctrl type of shape see zbw_rig.createControl for options
:param geo: the geo to orient to
:param args:
:return: topCtrl (the new ctrl), grp (the top ctrl grp freeze grp)
"""
# THIS IS THE XTRA CTRL LAYER, THIS ORIENTS CTRL AND CONNECTS ORIG CTRL TO THE NEW CTRL
origCtrlPos = cmds.xform(origCtrl, q=True, ws=True, rp=True)
topCtrl = rig.createControl(name="{0}_moveCtrl".format(origCtrl.rpartition("_")[0]), type=type, axis="z",
color="yellow")
grp = rig.groupFreeze(topCtrl)
cmds.xform(grp, ws=True, t=origCtrlPos)
nc = cmds.normalConstraint(geo, grp, worldUpType="vector", upVector=(0, 1, 0))
cmds.delete(nc)
pc = cmds.parentConstraint(topCtrl, origCtrl, mo=True)
sc = cmds.scaleConstraint(topCtrl, origCtrl, mo=True)
return(topCtrl, grp)
python类delete()的实例源码
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
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 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 create_curve(control):
"""Create a curve.
:param control: A data dictionary generated from the dump function.
:return: The created curve.
"""
periodic = control['form'] == 2
degree = control['degree']
points = control['cvs']
points = points + points[:degree] if periodic else points
curve = cmds.curve(degree=degree, p=points, n=control['name'], per=periodic, k=control['knots'])
cmds.xform(curve, ws=True, matrix=control['xform'])
cmds.xform(curve, piv=control['pivot'])
cmds.delete(curve, constructionHistory=True)
cmds.setAttr('{0}.overrideEnabled'.format(curve), control['overrideEnabled'])
cmds.setAttr('{0}.overrideRGBColors'.format(curve), control['overrideRGBColors'])
cmds.setAttr('{0}.overrideColorRGB'.format(curve), *control['overrideColorRGB'])
cmds.setAttr('{0}.overrideColor'.format(curve), control['overrideColor'])
return curve
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 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 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 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 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 ResetSceneAnim():
# Loop through them all
SceneJoints = cmds.ls(type="joint")
# Loop
for name in SceneJoints:
# Disconnect if required
ResetBoneKeyframes(DagPathFromJoint(name, False).transform())
# Check for undo
if (cmds.objExists(name + ".seanimUndoT")):
# Reset to it
ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0]
ResetScale = cmds.getAttr(name + ".seanimUndoS")[0]
ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0]
# Apply
cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2])
cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2])
cmds.setAttr(name + ".r", 0, 0, 0)
cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2])
# Remove notetracks
if cmds.objExists("SENotes"):
# Delete
cmds.delete("SENotes")
# Processes a joint, creating it's rest position, and returning a dag path
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 positionsAlongCurve(crv="", numPts = 3, *args):
"""
returns list of numPts evenly distributed world positions along given nurbs crv
"""
if not crv:
return
if isType(crv, "nurbsCurve"):
posList = []
shp = cmds.listRelatives(crv, s=True)[0]
poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo")
cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc))
cmds.setAttr("{}.turnOnPercentage".format(poc), 1)
lineLen = cmds.arclen(crv, ch=False)
dist = float(numPts)/lineLen
for x in range(0, numPts+1):
perc = 1.0/numPts
cmds.setAttr("{}.parameter".format(poc),x*perc)
print x*perc
pos = cmds.getAttr("{}.position".format(poc))[0]
posList.append(pos)
cmds.delete(poc)
return(posList)
def create(obj):
"""Tell ZBrush to treat `obj` as a new object.
Under the hood this changes a gozbruhBrush ID to match object name.
"""
# does not change selection:
cmds.delete(obj, constructionHistory=True)
shape = cmds.ls(obj, type='mesh', dag=True)[0]
xform = cmds.listRelatives(shape, parent=True, fullPath=True)[0]
goz_check_xform = cmds.attributeQuery(
'gozbruhBrushID', node=xform, exists=True)
goz_check_shape = cmds.attributeQuery(
'gozbruhBrushID', node=shape, exists=True)
if goz_check_shape:
cmds.setAttr(shape + '.gozbruhBrushID', obj, type='string')
if goz_check_xform:
cmds.setAttr(xform + '.gozbruhBrushID', obj, type='string')
return xform
def _cleanup(name):
"""Removes un-used nodes on import of obj
"""
# Don't delete the old mesh if gozbruh_delete option var exists and is set to
# false, simply rename it
if cmds.optionVar(ex='gozbruh_delete') and not cmds.optionVar(q='gozbruh_delete'):
if cmds.objExists(name):
cmds.rename(name, name + '_old')
else:
if cmds.objExists(name):
cmds.delete(name)
for node in GARBAGE_NODES:
node = name + '_' + node
if cmds.objExists(node):
cmds.delete(node)
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
def doit(cage_tgt=None):
if not cage_tgt:
cage_tgt = cmds.ls(sl=True, o=True)
cage = cage_tgt[0]
tgt = cage_tgt[1:]
cmds.loadPlugin('greenCageDeformer.py', qt=True)
deformer = cmds.deformer(tgt, type='greenCageDeformer')[0]
freezer = cmds.createNode('transformGeometry')
cmds.connectAttr(cage + '.o', freezer + '.ig')
cmds.connectAttr(cage + '.wm', freezer + '.txf')
cmds.connectAttr(freezer + '.og', deformer + '.bc')
cmds.disconnectAttr(freezer + '.og', deformer + '.bc')
cmds.delete(freezer)
cmds.connectAttr(cage + '.w', deformer + '.ic')
cmds.dgeval(cmds.listConnections(deformer + '.og', s=False, d=True, sh=True, p=True))
#doit([cmds.polyCube(w=2.5, d=2.5, h=2.5)[0], cmds.polySphere()[0]])
def ui():
'''
User interface for arc tracer
'''
globalScale = 1
if mc.optionVar(exists='ml_arcTracer_brushGlobalScale'):
globalScale = mc.optionVar(query='ml_arcTracer_brushGlobalScale')
with utl.MlUi('ml_arcTracer', 'Arc Tracer', width=400, height=180, info='''Select objects to trace.
Choose camera space or worldspace arc.
Press clear to delete the arcs, or retrace to redo the last arc.''') as win:
win.buttonWithPopup(label='Trace Camera', command=traceCamera, annotation='Trace an arc as an overlay over the current camera.',
shelfLabel='cam', shelfIcon='flowPathObj')#motionTrail
win.buttonWithPopup(label='Trace World', command=traceWorld, annotation='Trace an arc in world space.',
shelfLabel='world', shelfIcon='flowPathObj')
win.buttonWithPopup(label='Retrace Previous', command=retraceArc, annotation='Retrace the previously traced arc.',
shelfLabel='retrace', shelfIcon='flowPathObj')
win.buttonWithPopup(label='Clear Arcs', command=clearArcs, annotation='Clear all arcs.',
shelfLabel='clear', shelfIcon='flowPathObj')
fsg = mc.floatSliderGrp( label='Line Width', minValue=0.1, maxValue=5, value=globalScale)
mc.floatSliderGrp(fsg, edit=True, dragCommand=partial(setLineWidthCallback, fsg))
def snap(node, snapTo):
#duplicate the node we want snap
dup = mc.duplicate(node, parentOnly=True)[0]
#unlock translates and rotates
for a in ('.t','.r'):
for b in 'xyz':
mc.setAttr(dup+a+b, lock=False)
mc.parentConstraint(snapTo, dup)
for a in ('.t','.r'):
for b in ('x','y','z'):
try:
mc.setAttr(node+a+b, mc.getAttr(dup+a+b))
except StandardError:
pass
mc.delete(dup)
def copySkinComponents(source, destinationVerts):
if not mc.listRelatives(source, shapes=True):
raise RuntimeError('Source object must be geometry.')
sourceSkin = getSkinCluster(source)
if not sourceSkin:
raise RuntimeError("Source mesh doesn't have a skinCluster to copy from.")
destMesh = mc.ls(destinationVerts[0], o=True)[0]
destMesh = mc.listRelatives(destMesh, parent=True)[0]
destSkin = copySkinInfluences(source, destMesh)
tempSet = mc.sets(destinationVerts)
mc.select(source, tempSet)
mc.copySkinWeights(noMirror=True,
surfaceAssociation='closestPoint',
influenceAssociation='closestJoint',
normalize=True)
mc.delete(tempSet)
mc.select(destinationVerts)
def minimizeRotationCurves(obj):
'''
Sets rotation animation to the value closest to zero.
'''
rotateCurves = mc.keyframe(obj, attribute=('rotateX','rotateY', 'rotateZ'), query=True, name=True)
if not rotateCurves or len(rotateCurves) < 3:
return
keyTimes = mc.keyframe(rotateCurves, query=True, timeChange=True)
tempFrame = sorted(keyTimes)[0] - 1
#set a temp frame
mc.setKeyframe(rotateCurves, time=(tempFrame,), value=0)
#euler filter
mc.filterCurve(rotateCurves)
#delete temp key
mc.cutKey(rotateCurves, time=(tempFrame,))
def cutKey(self, includeSubFrames=False, **kwargs):
'''
Wrapper for the cutKey command. Curve and time arguments will be provided based on
how this object was intitialized, otherwise usage is the same as maya's cutKey command.
Option to delete sub-frames.
'''
if not 'includeUpperBound' in kwargs:
kwargs['includeUpperBound'] = False
if self.selected:
mc.cutKey(sl=True, **kwargs)
return
if not 'time' in kwargs:
if includeSubFrames:
kwargs['time'] = (round(self.time[0])-0.5, round(self.time[-1])+0.5)
else:
kwargs['time'] = self.time
mc.cutKey(self.curves, **kwargs)
def cleanup(self):
'''
Clean up the mess we made.
'''
try:
mc.lockNode(self.pivotHandle, lock=False)
mc.delete(self.pivotHandle)
except: pass
try:
if mc.scriptJob(exists=self.scriptJob):
mc.scriptJob(kill=self.scriptJob, force=True)
except: pass
pivotHandles = mc.ls('*.ml_pivot_handle', o=True)
if pivotHandles:
for each in pivotHandles:
mc.lockNode(each, lock=False)
mc.delete(each)
def match_transform(src, dst):
"""Transform `src` to `dst`, taking worldspace into account
Arguments:
src (str): Absolute path to source transform
dst (str): Absolute path to destination transform
"""
try:
parent = cmds.listRelatives(src, parent=True)[0]
except Exception:
parent = None
node_decompose = cmds.createNode("decomposeMatrix")
node_multmatrix = cmds.createNode("multMatrix")
connections = {
dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]",
node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix",
node_decompose + ".outputTranslate": src + ".translate",
node_decompose + ".outputRotate": src + ".rotate",
node_decompose + ".outputScale": src + ".scale",
}
if parent:
connections.update({
parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]"
})
for s, d in connections.iteritems():
cmds.connectAttr(s, d, force=True)
cmds.refresh()
cmds.delete([node_decompose, node_multmatrix])
def combine(nodes):
"""Produce a new mesh with the contents of `nodes`
Arguments:
nodes (list): Path to shapes
"""
unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite")
count = 0
for node in nodes:
# Are we dealing with transforms, or shapes directly?
shapes = cmds.listRelatives(node, shapes=True) or [node]
for shape in shapes:
try:
cmds.connectAttr(shape + ".outMesh",
unite + ".inputPoly[%s]" % count, force=True)
cmds.connectAttr(shape + ".worldMatrix",
unite + ".inputMat[%s]" % count, force=True)
count += 1
except Exception:
cmds.warning("'%s' is not a polygonal mesh" % shape)
if count:
output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape")
cmds.connectAttr(unite + ".output", output + ".inMesh", force=True)
return output
else:
cmds.delete(unite)
return None
def parent_group(source, transferTransform=True):
"""Create and transfer transforms to parent group"""
assert cmds.objExists(source), "%s does not exist" % source
assert cmds.nodeType(source) == "transform", (
"%s must be transform" % source)
parent = cmds.listRelatives(source, parent=True)
if transferTransform:
group = cmds.createNode("transform", n="%s_parent" % source)
match_transform(group, source)
try:
cmds.parent(source, group)
except Exception:
cmds.warning("Failed to parent child under new parent")
cmds.delete(group)
if parent:
cmds.parent(group, parent[0])
else:
cmds.select(source)
group = cmds.group(n="%s_parent" % source)
return group
def get_knots(curve):
"""Gets the list of knots of a curve so it can be recreated.
:param curve: Curve to query.
:return: A list of knot values that can be passed into the curve creation command.
"""
curve = shortcuts.get_shape(curve)
info = cmds.createNode('curveInfo')
cmds.connectAttr('{0}.worldSpace'.format(curve), '{0}.inputCurve'.format(info))
knots = cmds.getAttr('{0}.knots[*]'.format(info))
cmds.delete(info)
return knots
def create_transform_stack(node, count=2):
"""Creates a transform stack above the given node.
Any previous transform stack will be deleted.
:param node: Node to parent into a transform stack.
:param count: Number of transforms to add in the stack.
:return: A list of the transform nodes created starting from top to bottom.
"""
previous_parent = cmds.listRelatives(node, parent=True, path=True)
if previous_parent:
previous_parent = previous_parent[0]
while previous_parent and STACK_ATTRIBUTE in (cmds.listAttr(previous_parent, ud=True) or []):
parent = cmds.listRelatives(previous_parent, parent=True, path=True)
if parent:
cmds.parent(node, parent)
parent = parent[0]
else:
cmds.parent(node, world=True)
cmds.delete(previous_parent)
previous_parent = parent
nulls = []
for i in reversed(range(count)):
name = '_'.join(node.split('_')[:-1])
name = '{0}_{1}nul'.format(name, i+1)
null = cmds.createNode('transform', name=name)
nulls.append(null)
cmds.addAttr(null, ln=STACK_ATTRIBUTE, at='message')
cmds.connectAttr('{0}.message'.format(node), '{0}.{1}'.format(null, STACK_ATTRIBUTE))
cmds.delete(cmds.parentConstraint(node, null))
if previous_parent:
cmds.parent(null, previous_parent)
previous_parent = null
cmds.parent(node, previous_parent)
return nulls
def setUp(self):
self.joint1 = cmds.joint(p=(-0.5, -0.5, 0))
self.joint2 = cmds.joint(p=(0, 0.0, 0))
self.joint3 = cmds.joint(p=(0.5, 0.5, 0))
self.shape = cmds.polyCube()[0]
cmds.delete(self.shape, ch=True)
self.skin = cmds.skinCluster(self.joint1, self.joint2, self.joint3, self.shape)[0]
self.expected = {
'bindMethod': 1,
'blendWeights': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
'dropoffRate': 4.0,
'heatmapFalloff': 0.0,
'maintainMaxInfluences': False,
'maxInfluences': 2,
'name': u'skinCluster1',
'normalizeWeights': 1,
'shape': u'pCube1',
'skinningMethod': 0,
'useComponents': False,
'weightDistribution': 0,
'weights': {
u'joint1': [0.9, 0.5, 0.5, 0.0, 0.5, 0.0, 0.9, 0.5],
u'joint2': [0.10000000000000002,
0.5,
0.5,
0.5,
0.5,
0.5,
0.10000000000000002,
0.5],
u'joint3': [0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0]}
}