def new_strand(hair_system=None):
if not hair_system:
selection = cmds.ls(sl=True, dag=True, leaf=True, type='hairSystem')
if selection:
hair_system = selection[0]
start = om.MVector(0, 0, 0)
end = om.MVector(0, 0, 24)
start_loc = cmds.spaceLocator(name='strand_start#')[0]
end_loc = cmds.spaceLocator(name='strand_end#')[0]
cmds.xform(end_loc, ws=True, translation=end)
tta = cmds.createNode('transformsToArrays')
cmds.connectAttr(start_loc + '.worldMatrix', tta + '.inTransforms[0].inMatrix')
cmds.connectAttr(end_loc + '.worldMatrix', tta + '.inTransforms[1].inMatrix')
pcc = cmds.createNode('pointCloudToCurve')
cmds.connectAttr(tta + '.outPositionPP', pcc + '.inArray')
expand_grp = cmds.group([start_loc, end_loc], name='strand_expand_grp#')
curve, curve_shape = curve_between(start, end, name='strand_curve#')
cmds.connectAttr(pcc + '.outCurve', curve_shape + '.create')
root_grp = cmds.group(empty=True, name='strand_grp#')
cmds.parent([expand_grp, curve], root_grp)
follicle_nodes, out_curve_nodes = add_curve_to_system(curve_shape, hair_system)
follicle_shape = follicle_nodes[1]
cmds.setAttr(follicle_shape + '.pointLock', 3)
cmds.setAttr(follicle_shape + '.sampleDensity', 24)
python类createNode()的实例源码
def unique_name(name, format="%02d", namespace="", prefix="", suffix=""):
"""Return unique `name`
The function takes into consideration an optional `namespace`
and `suffix`. The suffix is included in evaluating whether a
name exists - such as `name` + "_GRP" - but isn't included
in the returned value.
If a namespace is provided, only names within that namespace
are considered when evaluating whether the name is unique.
Arguments:
format (str, optional): The `name` is given a number, this determines
how this number is formatted. Defaults to a padding of 2.
E.g. my_name01, my_name02.
namespace (str, optional): Only consider names within this namespace.
suffix (str, optional): Only consider names with this suffix.
Example:
>>> name = cmds.createNode("transform", name="MyName")
>>> cmds.objExists(name)
True
>>> unique = unique_name(name)
>>> cmds.objExists(unique)
False
"""
iteration = 1
unique = prefix + (name + format % iteration) + suffix
while cmds.objExists(namespace + ":" + unique):
iteration += 1
unique = prefix + (name + format % iteration) + suffix
if suffix:
return unique[:-len(suffix)]
return unique
def connect_transform(driver, driven, source=WorldSpace, compensate=False):
"""Connect translation, rotation and scale via decomposeMatrix
Arguments:
driver (str): Absolute path to driver
driven (str): Absolute path to driven
source (str, optional): Either WorldSpace or LocalSpace,
default WorldSpace
compensate (bool, optional): Whether or not to take into account
the current transform, default False.
Returns:
output (list): Newly created nodes
"""
outputattr = ".matrix" if source == LocalSpace else ".worldMatrix[0]"
assert cmds.objExists(driver), "%s not found" % driver
assert cmds.objExists(driven), "%s not found" % driven
decompose = driver + "_decompose"
output = [decompose]
if not cmds.objExists(decompose):
decompose = cmds.createNode("decomposeMatrix", name=decompose)
if compensate:
multMatrix = cmds.createNode(
"multMatrix", name=driver + "_multMatrix")
# Compensate for drivens parentMatrix.
cmds.connectAttr(driver + outputattr,
multMatrix + ".matrixIn[0]")
cmds.connectAttr(driven + ".parentInverseMatrix",
multMatrix + ".matrixIn[1]")
cmds.connectAttr(multMatrix + ".matrixSum",
decompose + ".inputMatrix")
output.append(multMatrix)
else:
cmds.connectAttr(driver + outputattr,
decompose + ".inputMatrix")
# Drive driven with compensated driver.
cmds.connectAttr(decompose + ".outputTranslate", driven + ".t")
cmds.connectAttr(decompose + ".outputRotate", driven + ".r")
cmds.connectAttr(decompose + ".outputScale", driven + ".s")
return output
def clone(shape, worldspace=False):
"""Clone `shape`
Arguments:
shape (str): Absolute path to shape
worldspace (bool, optional): Whether or not to consider worldspace
Returns:
node (str): Newly created clone
"""
type = cmds.nodeType(shape)
assert type in ("mesh", "nurbsSurface", "nurbsCurve"), (
"clone() works on polygonal and nurbs surfaces")
src, dst = {
"mesh": (".outMesh", ".inMesh"),
"nurbsSurface": (".local", ".create"),
"nurbsCurve": (".local", ".create"),
}[type]
nodetype = cmds.nodeType(shape)
name = lib.unique(name=shape.rsplit("|")[-1])
clone = cmds.createNode(nodetype, name=name)
cmds.connectAttr(shape + src, clone + dst, force=True)
if worldspace:
transform = cmds.createNode("transformGeometry",
name=name + "_transformGeometry")
cmds.connectAttr(shape + src,
transform + ".inputGeometry", force=True)
cmds.connectAttr(shape + ".worldMatrix[0]",
transform + ".transform", force=True)
cmds.connectAttr(transform + ".outputGeometry",
clone + dst, force=True)
# Assign default shader
cmds.sets(clone, addElement="initialShadingGroup")
return clone
def follicle(*args):
supported = ["mesh", "nurbsSurface"]
selection = cmds.ls(sl=1)
new_follicles = []
for sel in selection:
uv = lib.uv_from_element(sel)
geometry_shape = lib.shape_from_element(sel)
geometry_transform = cmds.listRelatives(geometry_shape, parent=True)[0]
# Figure out output connection
inputs = [".inputMesh", ".inputSurface"]
outputs = [".outMesh", ".local"]
failed = False
type = cmds.nodeType(geometry_shape)
if type not in supported:
failed = True
shapes = cmds.listRelatives(geometry_shape, shapes=True)
if shapes:
geometry_shape = shapes[0]
type = cmds.nodeType(geometry_shape)
if type in supported:
failed = False
if failed:
cmds.error("Skipping '%s': Type not accepted" % type)
return
input = inputs[supported.index(type)]
output = outputs[supported.index(type)]
# Make follicle
follicle = cmds.createNode("follicle",
name=geometry_transform + "_follicleShape1")
follicle_transform = cmds.listRelatives(follicle, parent=True)[0]
follicle_transform = cmds.rename(follicle_transform,
geometry_transform + "_follicle1")
# Set U and V value
cmds.setAttr(follicle + ".parameterU", uv[0])
cmds.setAttr(follicle + ".parameterV", uv[1])
# Make the connections
cmds.connectAttr(follicle + ".outTranslate",
follicle_transform + ".translate")
cmds.connectAttr(follicle + ".outRotate",
follicle_transform + ".rotate")
cmds.connectAttr(geometry_shape + output,
follicle + input)
# Select last
new_follicles.append(follicle_transform)
# Select newly created follicles
if new_follicles:
cmds.select(new_follicles, r=1)
return new_follicles
def create_spine(start_joint, end_joint, lower_control, upper_control, name='spine'):
spline_chain, original_chain = shortcuts.duplicate_chain(start_joint, end_joint, prefix='ikSpine_')
# Create the spline ik
ikh, effector, curve = cmds.ikHandle(
name='{0}_ikh'.format(name), solver='ikSplineSolver',
startJoint=spline_chain[0], endEffector=spline_chain[-1], parentCurve=False,
simplifyCurve=False)
effector = cmds.rename(effector, '{0}_eff'.format(name))
curve = cmds.rename(curve, '{0}_crv'.format(name))
# Create the joints to skin the curve
curve_start_joint = cmds.duplicate(start_joint, parentOnly=True, name='{0}CurveStart_jnt'.format(name))
cmds.parent(curve_start_joint, lower_control)
curve_end_joint = cmds.duplicate(end_joint, parentOnly=True, name='{0}CurveEnd_jnt'.format(name))
cmds.parent(curve_end_joint, upper_control)
# Skin curve
cmds.skinCluster(curve_start_joint, curve_end_joint, curve, name='{0}_scl'.format(name), tsb=True)
# Create stretch network
curve_info = cmds.arclen(curve, constructionHistory=True)
mdn = cmds.createNode('multiplyDivide', name='{0}Stretch_mdn'.format(name))
cmds.connectAttr('{0}.arcLength'.format(curve_info), '{0}.input1X'.format(mdn))
cmds.setAttr('{0}.input2X'.format(mdn), cmds.getAttr('{0}.arcLength'.format(curve_info)))
cmds.setAttr('{0}.operation'.format(mdn), 2) # Divide
# Connect to joints
for joint in spline_chain[1:]:
tx = cmds.getAttr('{0}.translateX'.format(joint))
mdl = cmds.createNode('multDoubleLinear', name='{0}Stretch_mdl'.format(joint))
cmds.setAttr('{0}.input1'.format(mdl), tx)
cmds.connectAttr('{0}.outputX'.format(mdn), '{0}.input2'.format(mdl))
cmds.connectAttr('{0}.output'.format(mdl), '{0}.translateX'.format(joint))
# Setup advanced twist
cmds.setAttr('{0}.dTwistControlEnable'.format(ikh), True)
cmds.setAttr('{0}.dWorldUpType'.format(ikh), 4) # Object up
cmds.setAttr('{0}.dWorldUpAxis'.format(ikh), 0) # Positive Y Up
cmds.setAttr('{0}.dWorldUpVectorX'.format(ikh), 0)
cmds.setAttr('{0}.dWorldUpVectorY'.format(ikh), 1)
cmds.setAttr('{0}.dWorldUpVectorZ'.format(ikh), 0)
cmds.setAttr('{0}.dWorldUpVectorEndX'.format(ikh), 0)
cmds.setAttr('{0}.dWorldUpVectorEndY'.format(ikh), 1)
cmds.setAttr('{0}.dWorldUpVectorEndZ'.format(ikh), 0)
cmds.connectAttr('{0}.worldMatrix[0]'.format(lower_control), '{0}.dWorldUpMatrix'.format(ikh))
cmds.connectAttr('{0}.worldMatrix[0]'.format(upper_control), '{0}.dWorldUpMatrixEnd'.format(ikh))
# Constrain original chain back to spline chain
for ik_joint, joint in zip(spline_chain, original_chain):
if joint == end_joint:
cmds.pointConstraint(ik_joint, joint, mo=True)
cmds.orientConstraint(upper_control, joint, mo=True)
else:
cmds.parentConstraint(ik_joint, joint)
def test_types(self):
print("start : node type test.")
cmds.file(new=True, f=True)
m = mtn.M(cmds.polyCube()[0])
_name = m.name()
m2 = mtn.M(_name)
assert(m.nodeType() == u'transform')
assert(hash(m) == hash(m2))
assert(hash(m.t) == hash(m2.attr("t")))
assert(hash(m.translate) == hash(m2.attr("t")))
assert(hash(m.t) == hash(m2.attr("translate")))
assert(hash(m.t.tx) == hash(m2.attr("translate").tx))
assert(hash(m.tx) == hash(m2.attr("translate").attr("tx")))
assert(hash(m.translateX) == hash(m2.attr("translate").attr("tx")))
assert(hash(m.pim) == hash(m2.attr("pim")))
assert(hash(m.pim) == hash(m2.pim))
assert(hash(m.pim[0]) != hash(m2.pim))
assert(hash(m.pim[0]) == hash(m2.pim[0]))
assert(hash(mtn.M(_name+".translateX")) == hash(mtn.M(_name).attr("t").attr("tx")))
assert(hash(mtn.M(_name+".translateX")) == hash(mtn.M(_name).attr("t.translateX")))
assert(m == m2)
assert(m.t == m2.attr("t"))
assert(m.translate == m2.attr("t"))
assert(m.t == m2.attr("translate"))
assert(m.t.tx == m2.attr("translate").tx)
assert(m.tx == m2.attr("translate").attr("tx"))
assert(m.translateX == m2.attr("translate").attr("tx"))
assert(m.pim == m2.attr("pim"))
assert(m.pim == m2.pim)
assert(m.pim[0] != m2.pim)
assert(m.pim[0] == m2.pim[0])
assert(mtn.M(_name+".translateX") == mtn.M(_name).attr("t").attr("tx"))
assert(mtn.M(_name+".translateX") == mtn.M(_name).attr("t.translateX"))
j = mtn.M(cmds.createNode(u"joint"))
assert(j.nodeType() == u'joint')
t = mtn.M(u"time1")
assert(t.nodeType() == u'time')
print("end : node type test.")
def follicle(surface="none", folName="none", u=0.5, v=0.5, *args):
"""
creates a follicle on a surface based on the uv input.
Args are: surface, folName, u, v
"""
#------------do a bit more checking here to make sure the shapes, numbers etc work out
if surface=="none":
#decide if surface is polymesh or nurbsSurface
surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
else:
surfaceXform = surface
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
if folName == "none":
folShapeName = "myFollicleShape"
folXformName = "myFollicle"
else:
folShapeName = "%sShape"%folName
folXformName = folName
#------------test if follicle exists
#create the follicle
folShape = cmds.createNode("follicle", n=folShapeName)
folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
cmds.rename(folXform, folXformName)
#connect up the follicle!
#connect the matrix of the surface to the matrix of the follicle
cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)
#check for surface type, poly or nurbs and connect the matrix into the follicle
if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
elif (cmds.nodeType(surfaceShape)=="mesh"):
cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
else:
cmds.warning("not the right kind of selection. Need a poly or nurbs surface")
#connect the transl, rots from shape to transform of follicle
cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)
cmds.setAttr("%s.parameterU"%folShape, u)
cmds.setAttr("%s.parameterV"%folShape, v)
cmds.setAttr("%s.translate"%folXform, l=True)
cmds.setAttr("%s.rotate"%folXform, l=True)
return(folXform, folShape)
def zbw_follicle(surface="none", folName="none", u=0.5, v=0.5, *args):
#------------do a bit more checking here to make sure the shapes, numbers etc work out
if surface=="none":
#decide if surface is polymesh or nurbsSurface
surfaceXform = cmds.ls(sl=True, dag=True, type="transform")[0]
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
else:
surfaceXform = surface
surfaceShape = cmds.listRelatives(surfaceXform, shapes=True)[0]
if folName == "none":
folShapeName = "myFollicleShape"
folXformName = "myFollicle"
else:
folShapeName = "%sShape"%folName
folXformName = folName
#create the follicle
folShape = cmds.createNode("follicle", n=folShapeName)
folXform = cmds.listRelatives(folShape, p=True, type="transform")[0]
cmds.rename(folXform, folXformName)
#connect up the follicle!
#connect the matrix of the surface to the matrix of the follicle
cmds.connectAttr("%s.worldMatrix[0]"%surfaceShape, "%s.inputWorldMatrix"%folShape)
#check for surface type, poly or nurbs and connect the matrix into the follicle
if (cmds.nodeType(surfaceShape)=="nurbsSurface"):
cmds.connectAttr("%s.local"%surfaceShape, "%s.inputSurface"%folShape)
elif (cmds.nodeType(surfaceShape)=="mesh"):
cmds.connectAttr("%s.outMesh"%surfaceShape, "%s.inputMesh"%folShape)
else:
cmds.warning("not the right kind of selection. Need a poly or nurbs surface")
#connect the transl, rots from shape to transform of follicle
cmds.connectAttr("%s.outTranslate"%folShape, "%s.translate"%folXform)
cmds.connectAttr("%s.outRotate"%folShape, "%s.rotate"%folXform)
cmds.setAttr("%s.parameterU"%folShape, u)
cmds.setAttr("%s.parameterV"%folShape, v)
cmds.setAttr("%s.translate"%folXform, l=True)
cmds.setAttr("%s.rotate"%folXform, l=True)
return(folXform, folShape)
def unparentShape(objs=None):
if not objs:
objs = mc.ls(sl=True)
if not objs:
OpenMaya.MGlobal.displayWarning('Please select one or more nodes with shapes to unparent.')
return
elif not isinstance(objs, (list,tuple)):
objs = [objs]
#are these shapes or transforms
transforms = list()
shapes = list()
for obj in objs:
nodeType = mc.nodeType(obj)
if nodeType in ('mesh','nurbsCurve','nurbsSurface','locator','annotationShape'):
shapes.append(obj)
elif nodeType in ('transform', 'joint', 'ikHandle'):
if not mc.listRelatives(obj, shapes=True, path=True, noIntermediate=True):
OpenMaya.MGlobal.displayWarning(obj+' has no shapes, skipping.')
return
transforms.append(obj)
else:
OpenMaya.MGlobal.displayWarning(obj+' must be a shape, or a transform with shapes. Skipping')
return
for each in transforms:
childShapes = mc.listRelatives(each, shapes=True, path=True, noIntermediate=True)
shapes.extend([x for x in childShapes if x not in shapes])
#shapes that share a common parent get unparented together
newTransforms = dict()
for each in shapes:
shapeParent = mc.listRelatives(each, parent=True, fullPath=True)[0]
if not shapeParent in newTransforms:
newTransforms[shapeParent] = mc.createNode('transform', name='unparentedShape#')
newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], shapeParent)[0]
mc.setAttr(newTransforms[shapeParent]+'.translate', 0,0,0)
mc.setAttr(newTransforms[shapeParent]+'.rotate', 0,0,0)
mc.setAttr(newTransforms[shapeParent]+'.scale', 1,1,1)
newTransforms[shapeParent] = mc.parent(newTransforms[shapeParent], world=True)[0]
shape = mc.parent(each, newTransforms[shapeParent], shape=True, relative=True)[0]
return newTransforms.values()