Python源码示例:pymel.core.createNode()
示例1
def _duplicate_shape(old_shape):
new_shape = pymel.createNode('nurbsCurve')
# Transfert various attributes
mel_dst = '{0}.create'.format(new_shape) # prevent annoying pymel warning
pymel.connectAttr(old_shape.local, mel_dst)
new_shape.create.evaluate() # Force maya to cache the shape before unconnecting
pymel.disconnectAttr(old_shape.local, mel_dst)
# Transfert various attributes
for att_name in transferable_shape_attrs:
att_old = old_shape.attr(att_name)
att_new = new_shape.attr(att_name)
att_new.set(att_old.get())
return new_shape
示例2
def gear_intmatrix_op(mA, mB, blend=0):
"""
create mGear interpolate Matrix node.
Arguments:
mA (matrix): Input matrix A.
mB (matrix): Input matrix A.
blend (float or connection): Blending value.
Returns:
pyNode: Newly created mGear_intMatrix node
"""
node = pm.createNode("mgear_intMatrix")
pm.connectAttr(mA, node + ".matrixA")
pm.connectAttr(mB, node + ".matrixB")
if (isinstance(blend, str)
or isinstance(blend, unicode)
or isinstance(blend, pm.Attribute)):
pm.connectAttr(blend, node + ".blend")
else:
pm.setAttr(node + ".blend", blend)
return node
示例3
def gear_inverseRotorder_op(out_obj, in_obj):
"""
Apply a sn_inverseRotorder_op operator
Arguments:
out_obj (dagNode): Output object.
in_obj (dagNode): Input object.
Returns:
pyNode: The newly created operator.
"""
node = pm.createNode("mgear_inverseRotOrder")
pm.connectAttr(in_obj + ".ro", node + ".ro")
pm.connectAttr(node + ".output", out_obj + ".ro")
return node
示例4
def createDecomposeMatrixNode(m):
"""
Create and connect a decomposeMatrix node.
Arguments:
m(str or attr): The matrix attribute name.
Returns:
pyNode: the newly created node.
>>> dm_node = nod.createDecomposeMatrixNode(mulmat_node+".output")
"""
node = pm.createNode("decomposeMatrix")
pm.connectAttr(m, node + ".inputMatrix")
return node
示例5
def createCurveInfoNode(crv):
"""Create and connect a curveInfo node.
Arguments:
crv (dagNode): The curve.
Returns:
pyNode: the newly created node.
>>> crv_node = nod.createCurveInfoNode(self.slv_crv)
"""
node = pm.createNode("curveInfo")
shape = pm.listRelatives(crv, shapes=True)[0]
pm.connectAttr(shape + ".local", node + ".inputCurve")
return node
# TODO: update using plusMinusAverage node
示例6
def createVertexPositionNode(inShape,
vId=0,
output=None,
name="mgear_vertexPosition"):
"""Creates a mgear_vertexPosition node"""
node = pm.createNode("mgear_vertexPosition", n=name)
inShape.worldMesh.connect(node.inputShape)
node.vertex.set(vId)
if output:
pm.connectAttr(output.parentInverseMatrix,
node.drivenParentInverseMatrix)
pm.connectAttr(node.output, output.translate)
return node
#############################################
# CREATE MULTI NODES
#############################################
示例7
def create_shot(self, name='', handle=default_handle_count):
"""Creates a new shot.
:param str name: A string value for the newly created shot name, if
skipped or given empty, the next empty shot name will be generated.
:param int handle: An integer value for the handle attribute. Default
is 10.
:returns: The created :class:`~pm.nt.Shot` instance
"""
shot = pm.createNode('shot')
shot.shotName.set(name)
shot.set_handle(handle=handle)
shot.set_output('')
# connect to the sequencer
shot.message >> self.shots.next_available
return shot
示例8
def create_arnold_stand_in(path=None):
"""A fixed version of original arnold script of SolidAngle Arnold core API
"""
if not pm.objExists('ArnoldStandInDefaultLightSet'):
pm.createNode(
"objectSet",
name="ArnoldStandInDefaultLightSet",
shared=True
)
pm.lightlink(
object='ArnoldStandInDefaultLightSet',
light='defaultLightSet'
)
stand_in = pm.createNode('aiStandIn', n='ArnoldStandInShape')
# temp fix until we can correct in c++ plugin
stand_in.setAttr('visibleInReflections', True)
stand_in.setAttr('visibleInRefractions', True)
pm.sets('ArnoldStandInDefaultLightSet', add=stand_in)
if path:
stand_in.setAttr('dso', path)
return stand_in
示例9
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)
示例10
def test_next_available_with_all_connected_attribute(self):
"""testing if the next available attribute will be returned when no
empty plugs are present
"""
sequence_manager = pm.ls(type=pm.nt.SequenceManager)[0]
# connect new sequences
seq1 = pm.createNode('sequence')
seq2 = pm.createNode('sequence')
seq3 = pm.createNode('sequence')
seq1.message >> sequence_manager.sequences[0]
seq2.message >> sequence_manager.sequences[1]
seq3.message >> sequence_manager.sequences[2]
attr = sequence_manager.sequences.next_available
self.assertIsInstance(
attr,
pm.general.Attribute
)
self.assertEqual(
3,
sequence_manager.sequences.next_available.index()
)
示例11
def createFollicle(target=None, param=[0.5,0.5], name="follicle"):
"""
Create follicle.
:param target: `PyNode` target that the follicle connected to
:param param: `list` [u, v] follicle uv parameter
:param name: `string` follicle name
:return: `PyNode` follicle ransform node
"""
follicle = pm.createNode("follicle")
follicle.parameterU.set(param[0])
follicle.parameterV.set(param[1])
if target:
targetShape = target.getShape()
targetShape.worldMatrix.connect(follicle.inputWorldMatrix)
if targetShape.nodeType() == "nurbsSurface":
targetShape.local.connect(follicle.inputSurface)
elif targetShape.nodeType() == "mesh":
targetShape.outMesh.connect(follicle.inputMesh)
folTransform = follicle.getParent()
follicle.outRotate.connect(folTransform.rotate)
follicle.outTranslate.connect(folTransform.translate)
pm.rename(folTransform, name)
return folTransform
示例12
def createParentTransform(suffix="grp", targetNode=None):
"""
Create a parent transform of the node that matches the node position.
:param suffix: `string` parent node name
:param targetNode: `PyNode` node to add parent transform
:return: `PyNode` result transform node
"""
if not targetNode:
try:
targetNode = pm.ls(sl=True)[0]
except:
print "No target node is specified."
return None
grpNode = pm.createNode("transform", n="{0}_{1}".format(targetNode.name(),suffix))
pm.delete(pm.parentConstraint(targetNode, grpNode, mo=False))
grpNode.setParent(targetNode.getParent())
targetNode.setParent(grpNode)
return grpNode
示例13
def create(cls, name):
"""
Create a new Metanode.
:param string name: The name for the created node.
:return: Metanode class wrapping the newly created node.
"""
network_node = pm.createNode(NODE_TYPE)
network_node.rename(name)
for coreAttrName, coreAttrArgs in cls.attr_core().iteritems():
value = coreAttrArgs.pop('value')
network_node.addAttr(coreAttrName, **coreAttrArgs)
network_node.attr(coreAttrName).set(value)
network_node.attr(coreAttrName).setLocked(True)
for coreAttrName, coreAttrArgs in cls.attr_class().iteritems():
network_node.addAttr(coreAttrName, **coreAttrArgs)
return cls(network_node)
示例14
def get(create=True):
'''
Returns the shared shape if it exists and makes it if it doesn't if create=True (default).
'''
obj = core.findNode.mainGroup()
if not obj:
return None
shape = find(obj)
if shape:
return shape
if create:
return _makeSharedShape(obj, 'sharedShape', 'sharedShape')
else:
return None
'''
shape = cmds.createNode( 'nurbsCurve', p=obj.longName() )
cmds.addAttr( shape, ln='sharedShape', at='message' )
cmds.rename( shape, 'sharedShape' )
return obj.longName() + '|sharedShape'
'''
示例15
def getConditionNode(plug, level):
'''
'''
conditions = PyNode(plug).listConnections(type='condition', p=True, d=True, s=False)
for condition in conditions:
if condition.attrName() == 'ft' and condition.node().secondTerm.get() == level:
return condition.node()
condition = createNode('condition', n=plug.split('.')[1] + '_%i' % level)
condition.secondTerm.set(level)
condition.operation.set(3)
connectAttr( plug, condition.firstTerm, f=True )
condition.colorIfTrue.set(1, 1, 1)
condition.colorIfFalse.set(0, 0, 0)
return condition
示例16
def getBaseGrp(self, sAttrName, sGrpName):
nGrpNode = None
try:
nGrpNode = self.masterGrp.getAttr(sAttrName)
except pymel.MayaAttributeError:
try:
nGrpNode = pymel.PyNode(sGrpName)
except pymel.MayaNodeError:
nGrpNode = pymel.createNode("transform", name=sGrpName)
finally:
#Since there is no connection between the master and the node found, create the connection
self.masterGrp.addAttr(sAttrName, attributeType='message')
nGrpNode.message.connect(self.masterGrp.attr(sAttrName))
return nGrpNode
示例17
def _adjust_firstKey(self, iTime, vRestT, vRestRot):
"""
Adjust the offset of the first constraint key in the system to prevent a snap when we move keys
"""
pymel.setCurrentTime(iTime)
aWeight = self.nSwConst.getWeightAliasList()
for i, w in enumerate(aWeight):
if w.get() == 1:
iParentIdx = self._get_adjusted_index(i)
# Create a node as a fake parent to have an easiest way to extract the matrix
nTempDriven = pymel.createNode("transform")
nTempDriven.setTranslation(vRestT, space="world")
nTempDriven.setRotation(vRestRot, space="world")
vTrans = self._get_tm_offset(self.aDrivers[iParentIdx], _nDriven=nTempDriven, _type="t")
vRot = self._get_tm_offset(self.aDrivers[iParentIdx], _nDriven=nTempDriven, _type="r")
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateX.set(vTrans[0])
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateY.set(vTrans[1])
self.nSwConst.target[iParentIdx].targetOffsetTranslate.targetOffsetTranslateZ.set(vTrans[2])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateX.set(vRot[0])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateY.set(vRot[1])
self.nSwConst.target[iParentIdx].targetOffsetRotate.targetOffsetRotateZ.set(vRot[2])
pymel.setKeyframe(self.nSwConst.target[iParentIdx].targetOffsetTranslate, t=iTime, ott="step")
pymel.setKeyframe(self.nSwConst.target[iParentIdx].targetOffsetRotate, t=iTime, ott="step")
pymel.keyTangent(self.nSwConst.target[iParentIdx].targetOffsetTranslate, t=iTime,
ott="step") # Force step
pymel.keyTangent(self.nSwConst.target[iParentIdx].targetOffsetRotate, t=iTime, ott="step") # Force step
pymel.delete(nTempDriven)
示例18
def createLoc(self, sName, nParent):
nTran = pymel.createNode("transform", n=sName, p=nParent)
pymel.createNode("locator", n= (sName + "Shape"), p=nTran)
return nTran
示例19
def export_network(_data, **kwargs):
log.debug('CreateNetwork {0}'.format(_data))
# We'll deal with two additional attributes, '_network' and '_uid'.
# Thoses two attributes allow us to find the network from the value and vice-versa.
# Note that since the '_uid' refer to the current python context, it's value could be erroned when calling import_network.
# However the change of collisions are extremely improbable so checking the type of the python variable is sufficient.
# Please feel free to provide a better design if any if possible.
# Optimisation: Use existing network if already present in scene
if hasattr(_data, '_network') and libPymel.is_valid_PyNode(_data._network):
network = _data._network
else:
# Automaticly name network whenever possible
if hasattr(_data, '__getNetworkName__') and _data.__getNetworkName__ is None:
networkName = _data.__class__.__name__
else:
networkName = _data.__getNetworkName__() if hasattr(_data, '__getNetworkName__') else _data.__class__.__name__
_data._network = networkName
network = pymel.createNode('network', name=networkName)
# Ensure the network have the current python id stored
if not network.hasAttr('_uid'):
pymel.addAttr(network, longName='_uid', niceName='_uid', at='long') # todo: validate attributeType
# network._uid.set(id(_data))
# Convert _pData to basic data dictionary (recursive for now)
dicData = core._export_basicData(_data, _bRecursive=False, **kwargs)
assert(isinstance(dicData, dict))
fnNet = network.__apimfn__()
for key, val in dicData.items():
if val is not None:
if key == '_class' or key[0] != '_': # Attributes starting with '_' are protected or private
_addAttr(fnNet, key, val)
return network
# todo: add an optimisation to prevent recreating the python variable if it already exist.
示例20
def curvecns_op(crv, inputs=[]):
for i, item in enumerate(inputs):
node = pm.createNode("decomposeMatrix")
pm.connectAttr(item + ".worldMatrix[0]", node + ".inputMatrix")
pm.connectAttr(node + ".outputTranslate",
crv + ".controlPoints[%s]" % i)
return node
示例21
def pathCns(obj, curve, cnsType=False, u=0, tangent=False):
"""
Apply a path constraint or curve constraint.
Arguments:
obj (dagNode): Constrained object.
curve (Nurbscurve): Constraining Curve.
cnsType (int): 0 for Path Constraint, 1 for Curve
Constraint (Parametric).
u (float): Position of the object on the curve (from 0 to 100 for path
constraint, from 0 to 1 for Curve cns).
tangent (bool): Keep tangent orientation option.
Returns:
pyNode: The newly created constraint.
"""
node = pm.PyNode(pm.createNode("motionPath"))
node.setAttr("uValue", u)
node.setAttr("fractionMode", not cnsType)
node.setAttr("follow", tangent)
pm.connectAttr(curve.attr("worldSpace"), node.attr("geometryPath"))
pm.connectAttr(node.attr("allCoordinates"), obj.attr("translate"))
pm.connectAttr(node.attr("rotate"), obj.attr("rotate"))
pm.connectAttr(node.attr("rotateOrder"), obj.attr("rotateOrder"))
pm.connectAttr(node.attr("message"), obj.attr("specifiedManipLocation"))
return node
# TODO: review function to make wupObject optional
示例22
def gear_spring_op(in_obj, goal=False):
"""Apply mGear spring node.
Arguments:
in_obj (dagNode): Constrained object.
goal (dagNode): By default is False.
Returns:
pyNode: Newly created node
"""
if not goal:
goal = in_obj
node = pm.createNode("mgear_springNode")
pm.connectAttr("time1.outTime", node + ".time")
dm_node = pm.createNode("decomposeMatrix")
pm.connectAttr(goal + ".parentMatrix", dm_node + ".inputMatrix")
pm.connectAttr(dm_node + ".outputTranslate", node + ".goal")
cm_node = pm.createNode("composeMatrix")
pm.connectAttr(node + ".output", cm_node + ".inputTranslate")
mm_node = pm.createNode("mgear_mulMatrix")
pm.connectAttr(cm_node + ".outputMatrix", mm_node + ".matrixA")
pm.connectAttr(in_obj + ".parentInverseMatrix", mm_node + ".matrixB")
dm_node2 = pm.createNode("decomposeMatrix")
pm.connectAttr(mm_node + ".output", dm_node2 + ".inputMatrix")
pm.connectAttr(dm_node2 + ".outputTranslate", in_obj + ".translate")
pm.setAttr(node + ".stiffness", 0.5)
pm.setAttr(node + ".damping", 0.5)
return node
示例23
def gear_mulmatrix_op(mA, mB, target=False, transform='srt'):
"""Create mGear multiply Matrix node.
Note:
This node have same functionality as the default Maya matrix
multiplication.
Arguments:
mA (matrix): input matrix A.
mB (matrix): input matrix B.
target (dagNode): object target to apply the transformation
transform (str): if target is True. out transform to SRT valid
value s r t
Returns:
pyNode: Newly created mGear_multMatrix node
"""
node = pm.createNode("mgear_mulMatrix")
for m, mi in zip([mA, mB], ['matrixA', 'matrixB']):
if isinstance(m, datatypes.Matrix):
pm.setAttr(node.attr(mi), m)
else:
pm.connectAttr(m, node.attr(mi))
if target:
dm_node = pm.createNode("decomposeMatrix")
pm.connectAttr(node + ".output", dm_node + ".inputMatrix")
if 't' in transform:
pm.connectAttr(dm_node + ".outputTranslate",
target.attr("translate"), f=True)
if 'r' in transform:
pm.connectAttr(dm_node + ".outputRotate",
target.attr("rotate"), f=True)
if 's' in transform:
pm.connectAttr(dm_node + ".outputScale",
target.attr("scale"), f=True)
return node
示例24
def gear_spinePointAtOpWM(cns, startobj, endobj, blend=.5, axis="-Z"):
"""
Apply a SpinePointAt operator using world matrix
Arguments:
cns Constraint: The constraint to apply the operator on (must be a
curve, path or direction constraint).
startobj (dagNode): Start Reference.
endobj (dagNode): End Reference.
blend (float): Blend influence value from 0 to 1.
axis (str): Axis direction.
Returns:
pyNode: The newly created operator.
"""
node = pm.createNode("mgear_spinePointAt")
# Inputs
pm.setAttr(node + ".blend", blend)
pm.setAttr(node + ".axe", ["X", "Y", "Z", "-X", "-Y", "-Z"].index(axis))
dem_node1 = pm.createNode("decomposeMatrix")
dem_node2 = pm.createNode("decomposeMatrix")
pm.connectAttr(startobj + ".worldMatrix", dem_node1 + ".inputMatrix")
pm.connectAttr(endobj + ".worldMatrix", dem_node2 + ".inputMatrix")
pm.connectAttr(dem_node1 + ".outputRotate", node + ".rotA")
pm.connectAttr(dem_node2 + ".outputRotate", node + ".rotB")
# Outputs
pm.setAttr(cns + ".worldUpType", 3)
pm.connectAttr(node + ".pointAt", cns + ".worldUpVector")
return node
示例25
def gear_rollsplinekine_op(out, controlers=[], u=.5, subdiv=10):
"""Apply a sn_rollsplinekine_op operator
Arguments:
out (dagNode): onstrained Object.
controlers (list of dagNodes): Objects that will act as controler of
the bezier curve. Objects must have a parent that will be used as
an input for the operator.
u (float): Position of the object on the bezier curve (from 0 to 1).
subdiv (int): spline subdivision precision.
Returns:
pyNode: The newly created operator.
"""
node = pm.createNode("mgear_rollSplineKine")
# Inputs
pm.setAttr(node + ".u", u)
pm.setAttr(node + ".subdiv", subdiv)
dm_node = pm.createNode("decomposeMatrix")
pm.connectAttr(node + ".output", dm_node + ".inputMatrix")
pm.connectAttr(dm_node + ".outputTranslate", out + ".translate")
pm.connectAttr(dm_node + ".outputRotate", out + ".rotate")
# connectAttr(dm_node+".outputScale", out+".scale")
pm.connectAttr(out + ".parentMatrix", node + ".outputParent")
for i, obj in enumerate(controlers):
pm.connectAttr(obj + ".parentMatrix", node + ".ctlParent[%s]" % i)
pm.connectAttr(obj + ".worldMatrix", node + ".inputs[%s]" % i)
pm.connectAttr(obj + ".rx", node + ".inputsRoll[%s]" % i)
return node
示例26
def findLenghtFromParam(crv, param):
"""
Find lengtht from a curve parameter
Arguments:
param (float): The parameter to get the legth
crv (curve): The source curve.
Returns:
float: Curve uLength
Example:
.. code-block:: python
oParam, oLength = cur.getCurveParamAtPosition(upRope, cv)
uLength = cur.findLenghtFromParam(upRope, oParam)
u = uLength / oLength
"""
node = pm.createNode("arcLengthDimension")
pm.connectAttr(crv.getShape().attr("worldSpace[0]"),
node.attr("nurbsGeometry"))
node.attr("uParamValue").set(param)
uLength = node.attr("arcLength").get()
pm.delete(node.getParent())
return uLength
# ========================================
示例27
def createDistNode(objA, objB, output=None):
"""Create and connect a distance node.
Arguments:
objA (dagNode): The dagNode A.
objB (dagNode): The dagNode B.
output (attr): Output attribute.
Returns:
pyNode: the newly created node.
>>> distA_node = nod.createDistNode(self.tws0_loc, self.tws1_loc)
"""
node = pm.createNode("distanceBetween")
dm_nodeA = pm.createNode("decomposeMatrix")
dm_nodeB = pm.createNode("decomposeMatrix")
pm.connectAttr(objA + ".worldMatrix", dm_nodeA + ".inputMatrix")
pm.connectAttr(objB + ".worldMatrix", dm_nodeB + ".inputMatrix")
pm.connectAttr(dm_nodeA + ".outputTranslate", node + ".point1")
pm.connectAttr(dm_nodeB + ".outputTranslate", node + ".point2")
if output:
pm.connectAttr(node + ".distance", output)
return node
示例28
def createAddNode(inputA, inputB):
"""Create and connect a addition node.
Arguments:
inputA (attr or float): The attribute input A
inputB (attr or float): The attribute input B
Returns:
pyNode: the newly created node.
>>> add_node = nod.createAddNode(self.roundness_att, .001)
"""
node = pm.createNode("addDoubleLinear")
if (isinstance(inputA, str)
or isinstance(inputA, unicode)
or isinstance(inputA, pm.Attribute)):
pm.connectAttr(inputA, node + ".input1")
else:
pm.setAttr(node + ".input1", inputA)
if (isinstance(inputB, str)
or isinstance(inputB, unicode)
or isinstance(inputB, pm.Attribute)):
pm.connectAttr(inputB, node + ".input2")
else:
pm.setAttr(node + ".input2", inputB)
return node
# TODO: update using plusMinusAverage node
示例29
def createSubNode(inputA, inputB):
"""Create and connect a subtraction node.
Arguments:
inputA (attr or float): The attribute input A
inputB (attr or float): The attribute input B
Returns:
pyNode: the newly created node.
>>> sub_nod = nod.createSubNode(self.roll_att, angle_outputs[i-1])
"""
node = pm.createNode("addDoubleLinear")
if (isinstance(inputA, str)
or isinstance(inputA, unicode)
or isinstance(inputA, pm.Attribute)):
pm.connectAttr(inputA, node + ".input1")
else:
pm.setAttr(node + ".input1", inputA)
if (isinstance(inputB, str)
or isinstance(inputB, unicode)
or isinstance(inputB, pm.Attribute)):
neg_node = pm.createNode("multiplyDivide")
pm.connectAttr(inputB, neg_node + ".input1X")
pm.setAttr(neg_node + ".input2X", -1)
pm.connectAttr(neg_node + ".outputX", node + ".input2")
else:
pm.setAttr(node + ".input2", -inputB)
return node
示例30
def createDivNode(inputA, inputB, output=None):
"""Create and connect a Divide node.
Arguments:
inputA (attr, float or list of float): The attribute input A
inputB (attr, float or list of float): The attribute input B
output (attr or list of attr): The attribute to connect the
output.
Returns:
pyNode: the newly created node.
Example:
.. code-block:: python
# Classic Maya style creation and connection = 4 lines
div1_node = pm.createNode("multiplyDivide")
div1_node.setAttr("operation", 2)
div1_node.setAttr("input1X", 1)
pm.connectAttr(self.rig.global_ctl+".sx",
div1_node+".input2X")
# mGear style = 1 line
div1_node = nod.createDivNode(1.0,
self.rig.global_ctl+".sx")
"""
return createMulDivNode(inputA, inputB, 2, output)