Python maya.cmds.parent() Examples

The following are 30 code examples of maya.cmds.parent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .
Example #1
Source File: create.py    From maya-spline-ik with GNU General Public License v3.0 7 votes vote down vote up
def __createControl(self, cls, shape, clr, i=None, suffix=""):
        # create root control
        offset, ctrl = control.createControlShape(
            "{0}{1}".format(self.name, suffix),
            shape,
            clr,
            i
        )
        
        # position control
        pos = cluster.getClusterPosition(cls)
        cmds.setAttr("{0}.translate".format(offset), *pos)

        # parent cluster
        cmds.parent(cls, ctrl)

        return offset, ctrl
        
    # ------------------------------------------------------------------------ 
Example #2
Source File: mayasceneobject.py    From cross3d with MIT License 6 votes vote down vote up
def __init__(self, scene, nativeObject):
		""" MayaSceneObject's should always have the shape node stored in _nativePointer
		MayaSceneObject's should have the transform node stored in _nativeTransform
		A transform can have multiple shape nodes, as children, but a shape node can only
		have a single transform as its parent. If you init this class with a transform node
		it will automaticly convert the native pointer to the first shape node. If you init
		this class with a shape node it will use that shape node as the native pointer.
		
		TODO: When we want to add support for swaping shape nodes they should be implemented
		as self.setTransform(SceneObject). This will update the _nativeTransform for self and
		prevent needing to create a new SceneObject.
		"""
		# Make sure the nativeObject is a OpenMaya.MObject, and that its a shape node.
		mObj = self._asMOBject(nativeObject)
		with ExceptionRouter():
			nativeObject = self._getShapeNode(mObj)
		super(MayaSceneObject, self).__init__(scene, nativeObject)
		# store the transform node so we can access it later
		self._nativeTransform = self._getTransformNode(mObj)
	
	#--------------------------------------------------------------------------------
	#							cross3d private methods
	#-------------------------------------------------------------------------------- 
Example #3
Source File: common.py    From cmt with MIT License 6 votes vote down vote up
def opm_parent_constraint(
    driver, driven, maintain_offset=False, freeze=True, segment_scale_compensate=True
):
    """Create a parent constraint effect with offsetParentMatrix.

    :param driver: Target transforms
    :param driven: Transform to drive
    :param maintain_offset: True to maintain offset
    :param freeze: True to 0 out the local xforms
    :param segment_scale_compensate: True to remove the resulting scale and shear
    """
    opm_constraint(
        driver,
        driven,
        maintain_offset=maintain_offset,
        freeze=freeze,
        segment_scale_compensate=segment_scale_compensate,
    ) 
Example #4
Source File: common.py    From cmt with MIT License 6 votes vote down vote up
def align(node, target, axis, world_up):
    """Align an axis of one node to another using offsetParentMatrix.

    :param node: Node to align
    :param target: Node to align to
    :param axis: Local axis to match
    :param world_up: World up axis
    """
    axis = OpenMaya.MVector(axis)
    world_up = OpenMaya.MVector(world_up)
    tm = OpenMaya.MMatrix(cmds.getAttr("{}.worldMatrix[0]".format(target)))
    world_axis = axis * tm
    world_z = world_axis ^ world_up
    world_up = world_z ^ world_axis
    t = cmds.xform(node, q=True, ws=True, t=True)
    x = list(world_axis) + [0.0]
    y = list(world_up) + [0.0]
    z = list(world_z) + [0.0]
    t = [t[0], t[1], t[2], 1.0]
    m = OpenMaya.MMatrix(*[x + y + z + t])
    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        p = OpenMaya.MMatrix(cmds.getAttr("{}.worldInverseMatrix[0]".format(parent[0])))
        m *= p
    cmds.setAttr("{}.offsetParentMatrix".format(node), list(m), type="matrix") 
Example #5
Source File: common.py    From cmt with MIT License 6 votes vote down vote up
def local_offset(node):
    """Get the local matrix relative to the node's parent.

    This takes in to account the offsetParentMatrix

    :param node: Node name
    :return: MMatrix
    """
    offset = OpenMaya.MMatrix(cmds.getAttr("{}.worldMatrix[0]".format(node)))
    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        pinv = OpenMaya.MMatrix(
            cmds.getAttr("{}.worldInverseMatrix[0]".format(parent[0]))
        )
        offset *= pinv
    return offset 
Example #6
Source File: common.py    From cmt with MIT License 6 votes vote down vote up
def opm_point_constraint(driver, driven, maintain_offset=False, freeze=True):
    """Create a parent constraint effect with offsetParentMatrix.

    :param driver: Target transforms
    :param driven: Transform to drive
    :param maintain_offset: True to maintain offset
    :param freeze: True to 0 out the local xforms
    """
    opm_constraint(
        driver,
        driven,
        maintain_offset=maintain_offset,
        freeze=freeze,
        use_rotate=False,
        use_scale=False,
        use_shear=False,
    ) 
Example #7
Source File: dpAutoRig.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def info(self, title, description, text, align, width, height, *args):
        """ Create a window showing the text info with the description about any module.
        """
        # declaring variables:
        self.info_title       = title
        self.info_description = description
        self.info_text        = text
        self.info_winWidth    = width
        self.info_winHeight   = height
        self.info_align       = align
        # creating Info Window:
        if cmds.window('dpInfoWindow', query=True, exists=True):
            cmds.deleteUI('dpInfoWindow', window=True)
        dpInfoWin = cmds.window('dpInfoWindow', title='dpAutoRig - v'+DPAR_VERSION+' - '+self.langDic[self.langName]['i013_info']+' - '+self.langDic[self.langName][self.info_title], iconName='dpInfo', widthHeight=(self.info_winWidth, self.info_winHeight), menuBar=False, sizeable=True, minimizeButton=False, maximizeButton=False)
        # creating text layout:
        infoColumnLayout = cmds.columnLayout('infoColumnLayout', adjustableColumn=True, columnOffset=['both', 20], parent=dpInfoWin)
        cmds.separator(style='none', height=10, parent=infoColumnLayout)
        infoLayout = cmds.scrollLayout('infoLayout', parent=infoColumnLayout)
        if self.info_description:
            infoDesc = cmds.text(self.langDic[self.langName][self.info_description], align=self.info_align, parent=infoLayout)
        if self.info_text:
            infoText = cmds.text(self.info_text, align=self.info_align, parent=infoLayout)
        # call Info Window:
        cmds.showWindow(dpInfoWin) 
Example #8
Source File: dpAutoRig.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def donateWin(self, *args):
        """ Simple window with links to donate in order to support this free and openSource code via PayPal.
        """
        # declaring variables:
        self.donate_title       = 'dpAutoRig - v'+DPAR_VERSION+' - '+self.langDic[self.langName]['i167_donate']
        self.donate_description = self.langDic[self.langName]['i168_donateDesc']
        self.donate_winWidth    = 305
        self.donate_winHeight   = 300
        self.donate_align       = "center"
        # creating Donate Window:
        if cmds.window('dpDonateWindow', query=True, exists=True):
            cmds.deleteUI('dpDonateWindow', window=True)
        dpDonateWin = cmds.window('dpDonateWindow', title=self.donate_title, iconName='dpInfo', widthHeight=(self.donate_winWidth, self.donate_winHeight), menuBar=False, sizeable=True, minimizeButton=False, maximizeButton=False)
        # creating text layout:
        donateColumnLayout = cmds.columnLayout('donateColumnLayout', adjustableColumn=True, columnOffset=['both', 20], rowSpacing=5, parent=dpDonateWin)
        cmds.separator(style='none', height=10, parent=donateColumnLayout)
        infoDesc = cmds.text(self.donate_description, align=self.donate_align, parent=donateColumnLayout)
        cmds.separator(style='none', height=10, parent=donateColumnLayout)
        brPaypalButton = cmds.button('brlPaypalButton', label=self.langDic[self.langName]['i167_donate']+" - R$ - Real", align=self.donate_align, command=partial(utils.visitWebSite, DONATE+"BRL"), parent=donateColumnLayout)
        #usdPaypalButton = cmds.button('usdPaypalButton', label=self.langDic[self.langName]['i167_donate']+" - USD - Dollar", align=self.donate_align, command=partial(utils.visitWebSite, DONATE+"USD"), parent=donateColumnLayout)
        # call Donate Window:
        cmds.showWindow(dpDonateWin) 
Example #9
Source File: orientjoints.py    From cmt with MIT License 6 votes vote down vote up
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)
        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]
            joint = cmds.rename(joint, orig_joint)
        _reparent_children(joint, children)

    if joints:
        cmds.select(joints) 
Example #10
Source File: common.py    From cmt with MIT License 6 votes vote down vote up
def create(self, hierarchy=None, parent=None):
        if hierarchy is None:
            hierarchy = self.hierarchy
        for name, children in hierarchy.items():
            node = "{}{}{}".format(self.prefix, name, self.suffix)
            setattr(self, name, node)
            func = _create_parent_method(node)
            setattr(self, "parent_to_{}".format(name), func)
            if not cmds.objExists(node):
                node = cmds.createNode("transform", name=node)
            if parent:
                current_parent = cmds.listRelatives(node, parent=True, path=True)
                if current_parent:
                    current_parent = current_parent[0]
                if current_parent != parent:
                    cmds.parent(node, parent)
            lock_and_hide(node, attributes=self.lock_and_hide)
            if children:
                self.create(children, node) 
Example #11
Source File: skeleton.py    From cmt with MIT License 6 votes vote down vote up
def mirror(joint, search_for, replace_with):
    joints = [joint] + (cmds.listRelatives(joint, ad=True, path=True) or [])
    for joint in joints:
        mirrored_joint = joint.replace(search_for, replace_with)
        if cmds.objExists(mirrored_joint):
            translate = list(cmds.getAttr("{0}.t".format(joint))[0])
            parent = cmds.listRelatives(joint, parent=True, path=True)
            if parent and search_for not in parent[0]:
                translate[2] *= -1.0
            else:
                translate = [x * -1.0 for x in translate]
            cmds.setAttr("{0}.t".format(mirrored_joint), *translate)

            rotate = cmds.getAttr("{0}.r".format(joint))[0]
            cmds.setAttr("{0}.r".format(mirrored_joint), *rotate)

            scale = cmds.getAttr("{0}.s".format(joint))[0]
            cmds.setAttr("{0}.s".format(mirrored_joint), *scale) 
Example #12
Source File: skeleton.py    From cmt with MIT License 6 votes vote down vote up
def create(data_list):
    """Create the transform hierarchy.

    :param data_list: The list of transform/joint data generated from dumps.
    """
    for data in data_list:
        node = data["name"]
        if not cmds.objExists(node):
            node = cmds.createNode(data["nodeType"], name=node)
        parent = data["parent"]
        if parent and cmds.objExists(parent):
            cmds.parent(node, parent)
        for attr in ATTRIBUTES:
            attribute = "{}.{}".format(node, attr)
            if not cmds.objExists(attribute):
                continue
            value = data[attr]
            if isinstance(value, string_types):
                cmds.setAttr(attribute, value, type="string")
            elif isinstance(value, list):
                cmds.setAttr(attribute, *value)
            else:
                cmds.setAttr(attribute, value) 
Example #13
Source File: skeleton.py    From cmt with MIT License 6 votes vote down vote up
def get_joint_data(node):
    """Get the serializable data of a node.

    :param node: Joint or transform name.
    :return: Data dictionary.
    """
    node_type = cmds.nodeType(node)
    shapes = cmds.listRelatives(node, children=True, shapes=True)
    if node_type not in ["joint", "transform"] or (shapes and node_type == "transform"):
        # Skip nodes that are not joints or transforms or if there are shapes below.
        return None

    parent = cmds.listRelatives(node, parent=True)
    parent = parent[0] if parent else None
    joint_data = {"nodeType": node_type, "name": node, "parent": parent}
    for attr in ATTRIBUTES:
        attribute = "{}.{}".format(node, attr)
        if not cmds.objExists(attribute):
            continue
        value = cmds.getAttr(attribute)
        if isinstance(value, list):
            value = list(value[0])
        joint_data[attr] = value
    return joint_data 
Example #14
Source File: transformstack.py    From cmt with MIT License 6 votes vote down vote up
def get_stack(node):
    """Get the transforms in the transform stack

    :param node: Stack leaf transform
    :return: List of transforms
    """
    stack = [node]
    parent = cmds.listRelatives(node, parent=True, path=True)
    if parent:
        parent = parent[0]
    while _is_transform_stack_node(parent):
        stack.insert(0, parent)
        parent = cmds.listRelatives(parent, parent=True, path=True)
        if parent:
            parent = parent[0]
    return stack 
Example #15
Source File: dpUtils.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def clearNodeGrp(nodeGrpName='dpAR_GuideMirror_Grp', attrFind='guideBaseMirror', unparent=False):
    """ Check if there is any node with the attribute attrFind in the nodeGrpName and then unparent its children and delete it.
    """
    if cmds.objExists(nodeGrpName):
        foundChildrenList = []
        childrenList = cmds.listRelatives(nodeGrpName, children=True, type="transform")
        if childrenList:
            for child in childrenList:
                if cmds.objExists(child+"."+attrFind) and cmds.getAttr(child+"."+attrFind) == 1:
                    foundChildrenList.append(child)
        if len(foundChildrenList) != 0:
            if unparent:
                for item in foundChildrenList:
                    cmds.parent(item, world=True)
                cmds.delete(nodeGrpName)
        else:
            cmds.delete(nodeGrpName) 
Example #16
Source File: test_skeleton.py    From cmt with MIT License 6 votes vote down vote up
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)

        cmds.joint(j1, e=True, oj="xyz", secondaryAxisOrient="yup", ch=True, zso=True)
        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")
        ] 
Example #17
Source File: dpUtils.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def zeroOutJoints(jntList=None):
    """ Duplicate the joints, parent as zeroOut.
        Returns the father joints (zeroOuted).
        Deprecated = using zeroOut function insted.
    """
    resultList = []
    zeroOutJntSuffix = "_Jzt"
    if jntList:
        for jnt in jntList:
            if cmds.objExists(jnt):
                jxtName = jnt.replace("_Jnt", "").replace("_Jxt", "")
                if not zeroOutJntSuffix in jxtName:
                    jxtName += zeroOutJntSuffix
                dup = cmds.duplicate(jnt, name=jxtName)[0]
                deleteChildren(dup)
                clearDpArAttr([dup])
                cmds.parent(jnt, dup)
                resultList.append(dup)
    return resultList 
Example #18
Source File: dpLayoutClass.py    From dpAutoRigSystem with GNU General Public License v2.0 6 votes vote down vote up
def colorizeModuleUI(self, colorIndex, *args):
        """ Show a little window to choose the color of the button and the override the guide.
        """
        # verify integrity of the guideModule:
        if self.verifyGuideModuleIntegrity():
            # creating colorIndex Window:
            if cmds.window('dpColorIndexWindow', query=True, exists=True):
                cmds.deleteUI('dpColorIndexWindow', window=True)
            colorIndex_winWidth  = 160
            colorIndex_winHeight = 80
            self.dpColorIndexWin = cmds.window('dpColorIndexWindow', title='Color Index', iconName='dpColorIndex', widthHeight=(colorIndex_winWidth, colorIndex_winHeight), menuBar=False, sizeable=False, minimizeButton=False, maximizeButton=False, menuBarVisible=False, titleBar=True)
            # creating layout:
            colorIndexLayout = cmds.gridLayout('colorIndexLayout', numberOfColumns=8, cellWidthHeight=(20,20))
            # creating buttons:
            for colorIndex, colorValues in enumerate(self.colorList):
                cmds.button('indexColor_'+str(colorIndex)+'_BT', label=str(colorIndex), backgroundColor=(colorValues[0], colorValues[1], colorValues[2]), command=partial(self.setColorModule, colorIndex), parent=colorIndexLayout)
            # call colorIndex Window:
            cmds.showWindow(self.dpColorIndexWin) 
Example #19
Source File: mayasceneobject.py    From cross3d with MIT License 6 votes vote down vote up
def _nativeModel(self):
		"""
			\remarks	looks up the native model for this object
			\sa			model, setModel, _setNativeModel
			\return		<variant> nativeObject || None
		"""
		parent = self.parent()
		while parent is not None:
			if isinstance(parent, api.SceneModel):
				return parent.nativePointer()

			parent = parent.parent()

		# namespace = self._namespace(self._nativePointer)['namespace']
		# if namespace:
		# 	return self._scene._findNativeObject(name=namespace)
		
		return None 
Example #20
Source File: mayasceneobject.py    From cross3d with MIT License 6 votes vote down vote up
def _nativeChildren(self, recursive=False, wildcard='', type='', parent='', childrenCollector=[]):
		"""
			\remarks	looks up the native children for this object
			\param		recursive         <bool>
			\param		parent		      <variant> nativeObject(used for recursive searches when necessary)
			\param		childrenCollector <list> (used for recursive searches when necessary)
			\sa			children
			\return		<list> [ <variant> nativeObject, .. ]
		"""
		if type:
			cross3d.logger.debug('type not implemented yet.')
		if parent:
			cross3d.logger.debug('parent not implemented yet.')
		if childrenCollector:
			cross3d.logger.debug('childrenCollector not implemented yet.')
		# Convert the wildcard to a regular expression so the generator doesn't have to create the
		# regex over and over
		regex=None
		if wildcard:
			expression = application._wildcardToRegex(wildcard)
			regex = re.compile(expression, flags=re.I)
		return self._mObjChildren(self._nativeTransform, recursive=recursive, regex=regex) 
Example #21
Source File: leg.py    From cmt with MIT License 6 votes vote down vote up
def create(
        self,
        ik_control,
        pole_vector=None,
        global_scale_attr=None,
        pivots=None,
        scale_stretch=True,
        parent=None,
    ):
        if not cmds.objExists(self.group):
            self.group = cmds.createNode("transform", name=self.group)

        self.__create_ik(
            ik_control, pole_vector, global_scale_attr, pivots, scale_stretch, parent
        )
        self.__create_fk() 
Example #22
Source File: twoboneik.py    From cmt with MIT License 5 votes vote down vote up
def __init__(self, start_joint, end_joint, name):
        self.config_control = None
        self.ik_handle = None
        self.start_joint = start_joint
        self.mid_joint = cmds.listRelatives(end_joint, parent=True, path=True)[0]
        self.end_joint = end_joint
        self.name = name 
Example #23
Source File: mayasceneobject.py    From cross3d with MIT License 5 votes vote down vote up
def name(self):
		""" Return the full name of this object, including parent structure """
		return self._mObjName(self._nativeTransform, False) 
Example #24
Source File: mayasceneobject.py    From cross3d with MIT License 5 votes vote down vote up
def _findNativeChild(self, name, recursive=False, parent=None):
		for child in self._nativeChildren(recursive=recursive, wildcard=name, parent=parent):
			return child 
Example #25
Source File: common.py    From cmt with MIT License 5 votes vote down vote up
def duplicate_chain(start, end, prefix="", suffix="", search_for="", replace_with=""):
    """Duplicates the transform chain starting at start and ending at end.

    :param start: The start transform.
    :param end: The end transform.
    :param prefix: Prefix to add to the new chain.
    :param suffix: Suffix to add to the new chain.
    :param search_for: Search for token
    :param replace_with: Replace token
    :return: A list of the duplicated joints, a list of the original joints that were
    duplicated.
    """
    joint = end
    joints = []
    original_joints = []
    while joint:
        name = "{0}{1}{2}".format(prefix, joint, suffix)
        if search_for or replace_with:
            name = name.replace(search_for, replace_with)
        original_joints.append(joint)
        duplicate_joint = cmds.duplicate(joint, name=name, parentOnly=True)[0]
        if joints:
            cmds.parent(joints[-1], duplicate_joint)
        joints.append(duplicate_joint)
        if joint == start:
            break
        joint = cmds.listRelatives(joint, parent=True, path=True)
        if joint:
            joint = joint[0]
        else:
            raise RuntimeError("{0} is not a descendant of {1}".format(end, start))
    joints.reverse()
    original_joints.reverse()
    return joints, original_joints 
Example #26
Source File: control.py    From cmt with MIT License 5 votes vote down vote up
def create(self, transform=None, as_controller=True):
        """Create a curve.

        :param transform: Name of the transform to create the curve shape under.
            If the transform does not exist, it will be created.
        :param as_controller: True to mark the curve transform as a controller.
        :return: The transform of the new curve shapes.
        """
        transform = transform or self.transform
        if not cmds.objExists(transform):
            transform = cmds.createNode("transform", name=transform)
        periodic = self.form == 2
        points = self._get_transformed_points()
        points = points + points[: self.degree] if periodic else points
        curve = cmds.curve(degree=self.degree, p=points, per=periodic, k=self.knots)
        shape = shortcuts.get_shape(curve)
        if self.color is not None:
            cmds.setAttr("{}.overrideEnabled".format(shape), True)
            if isinstance(self.color, int):
                cmds.setAttr("{}.overrideColor".format(shape), self.color)
            else:
                cmds.setAttr("{}.overrideRGBColors".format(shape), True)
                cmds.setAttr("{}.overrideColorRGB".format(shape), *self.color)
        cmds.parent(shape, transform, r=True, s=True)
        shape = cmds.rename(shape, "{}Shape".format(transform))
        cmds.delete(curve)
        if as_controller:
            cmds.controller(transform)
        logger.info("Created curve {} for transform {}".format(shape, transform))
        return transform 
Example #27
Source File: mayasceneobject.py    From cross3d with MIT License 5 votes vote down vote up
def setParent(self, parent):
		"""Sets the parent for this object to the inputed item
		
		:param parent: :class:`cross3d.SceneObject` or None
		"""
		# set the model in particular
		if (parent and parent.isObjectType(ObjectType.Model)):
			return self._setNativeModel(parent.nativePointer())

		nativeParent = None
		if (parent):
			# NOTE: !!!!!! passing the native transform not the nativePointer
			nativeParent = parent._nativeTransform
		return self._setNativeParent(nativeParent) 
Example #28
Source File: main.py    From ssds with MIT License 5 votes vote down vote up
def bindToSkin(meshPaths, skinIndex, skinWeight,
              skinJnts, numMaxInfluences):
    asl = om.MSelectionList()
    asl.clear()
    jntNames = [sj.name for sj in skinJnts]
    for sj in skinJnts:
        m = om.MMatrix(sj.bindPose.tolist())
        m = om.MTransformationMatrix(m)
        om.MFnTransform(sj.path).setTransformation(m)
        asl.add(sj.path)
    offset = 0
    for meshPath in meshPaths:
        mesh = om.MFnMesh(meshPath)
        sl = om.MSelectionList(asl)
        sl.add(meshPath)
        om.MGlobal.setActiveSelectionList(sl)
        meshName = om.MFnDagNode(mesh.parent(0)).name()
        skinName = cmds.skinCluster(maximumInfluences = numMaxInfluences,
                                    name = meshName + 'Cluster',
                                    toSelectedBones = True)[0]
        skinObj = om.MGlobal.getSelectionListByName(skinName).getDependNode(0)
        skin = oma.MFnSkinCluster(skinObj)
        vertexIndices = om.MIntArray(mesh.numVertices, 0)
        for i in xrange(mesh.numVertices):
            vertexIndices[i] = i
        singleIndexedComp = om.MFnSingleIndexedComponent()
        vertexComp = singleIndexedComp.create(om.MFn.kMeshVertComponent)
        singleIndexedComp.addElements(vertexIndices)
        infDags = skin.influenceObjects()
        numInfDags = len(infDags)
        infIndices = om.MIntArray(numInfDags, 0)
        for i in xrange(numInfDags):
            infIndices[i] = i
        weights = om.MDoubleArray(mesh.numVertices * numInfDags, 0)
        for v in xrange(mesh.numVertices):
            for j, w in zip(skinIndex[offset + v], skinWeight[offset + v]):
                if j >= 0:
                    weights[v * numInfDags + j] = w
        skin.setWeights(meshPath, vertexComp, infIndices, weights)
        offset += mesh.numVertices 
        skin.findPlug('deformUserNormals', True).setBool(False) 
Example #29
Source File: main.py    From ssds with MIT License 5 votes vote down vote up
def cloneMeshs(meshPaths):
    cloneMeshPaths = []
    cloneGroup = cmds.group(empty = True, world = True, name = 'ssdsResult')
    cloneGroupSL = om.MGlobal.getSelectionListByName(cloneGroup)
    cloneGroupFn = om.MFnTransform(cloneGroupSL.getDagPath(0))
    for path in meshPaths:
        mesh = om.MFnMesh(path)
        meshName = om.MFnDagNode(mesh.parent(0)).name()
        cloneMeshName = 'ssds:' + meshName
        sl = om.MSelectionList();
        sl.clear()
        sl.add(path)
        om.MGlobal.setActiveSelectionList(sl)
        cmds.duplicate(returnRootsOnly = True, name = cloneMeshName, renameChildren = True)
        cmds.parent(cloneMeshName, cloneGroup)
        cmds.setAttr(cloneMeshName + '.inheritsTransform', False)
        cloneMeshSL = om.MGlobal.getSelectionListByName(cloneMeshName)
        cloneMeshPath = cloneMeshSL.getDagPath(0)
        cloneMeshPath.extendToShape()
        cloneMeshPaths.append(cloneMeshPath)
    return cloneMeshPaths, cloneGroup 
Example #30
Source File: mayasceneobject.py    From cross3d with MIT License 5 votes vote down vote up
def _setNativeParent(self, nativeParent):
		""" sets the native parent for this object
			\sa			parent, setParent, _nativeParent
			\param		<variant> nativeObject || None
			\return		<bool> success
		"""
		if nativeParent:
			# Making sure the object is not already child of the new parent. Otherwise Maya throw an error.
			parents = cmds.listRelatives(self._mObjName(self._nativeTransform), parent=1, fullPath=True)
			if parents and parents[0] == self._mObjName(nativeParent):
				return True
			cmds.parent(self._mObjName(self._nativeTransform), self._mObjName(nativeParent))
			return True
		return False