def reverseSelected(self,*args):
		selected = cmds.ls( sl=True )
		reverseSelected = cmds.ls( sl=True )

		parentResult = cmds.listRelatives( selected[0], parent=True )

		if parentResult is not None:
			parent = parentResult[0]
			children = cmds.listRelatives( parent, children=True, pa=True )

			reverseSelected.reverse()
			reverseIndex = 0

			numberOfSelected = len(selected)

			for item in children:
				if reverseIndex < numberOfSelected and item == selected[reverseIndex]:
					cmds.reorder( reverseSelected[reverseIndex], back=True )
					reverseIndex = reverseIndex+1
				else:
					cmds.reorder( item, back=True )

			cmds.select( reverseSelected )
		else:
			cmds.warning( 'Selected objects are parented to the World, they need to be children of a transform' )
Ejemplo n.º 2
0
def bake_pivot():
    """
    Bake modified manipulator pivot onto object.
    """
    s = mampy.ordered_selection(tr=True, l=True)
    dag = s.pop(len(s) - 1)
    out_idx = get_outliner_index(dag)
    parent = dag.get_parent()

    # Get manipulator information
    pos = cmds.manipMoveContext('Move', q=True, p=True)
    rot = cmds.manipMoveContext('Move', q=True, oa=True)
    rot = tuple(math.degrees(i) for i in rot)

    # Create dummpy parent
    space_locator = cmds.spaceLocator(name='bake_dummy_loc', p=pos)[0]
    cmds.xform(space_locator, cp=True)
    cmds.xform(space_locator, rotation=rot, ws=True)

    dag.set_parent(space_locator)
    cmds.makeIdentity(dag.name, rotate=True, translate=True, apply=True)

    dag.set_parent(parent)
    cmds.delete(space_locator)
    cmds.reorder(dag.name, f=True); cmds.reorder(dag.name, r=out_idx)
    cmds.select(list(s), r=True); cmds.select(dag.name, add=True)
	def reverseGroupChildren(self,*args):
		selected = cmds.ls( sl=True )
		for group in selected:
			children = cmds.listRelatives( group, children=True, pa=True )
			children.reverse()
			for item in children:
				cmds.reorder( item, back=True )
Ejemplo n.º 4
0
def dag_sort(objList=None):
    """    
    Dag sort children under their parent
    
    """
    _str_func = 'dag_sort'
    if not objList:
        objList = mc.ls(sl=1)
    else:
        objList = VALID.mNodeStringList(objList)
    log.info("|{0}| >> ObjList: {1} ".format(_str_func, objList))

    d_p = {}
    l_p = []
    l_world = []

    for o in objList:
        p = TRANS.parent_get(o)
        if not p:
            l_world.append(o)
        elif p not in l_p:
            l = TRANS.children_get(p) or []
            l.sort()
            l.reverse()
            for c in l:
                try:
                    mc.reorder(c, front=True)
                except Exception, err:
                    print err
Ejemplo n.º 5
0
    def testReorderRelative(self):
        ''' Reorder (a.k.a move) objects relative to their siblings.
           For relative moves, both positive and negative numbers may be specified.
        '''
        cylinderPath = ufe.PathString.path(
            "|Primitives_usd|Primitives_usdShape,/Xform1/Cylinder1")
        cylinderItem = ufe.Hierarchy.createItem(cylinderPath)

        # start by getting the children from the parent node ( Xform1 )
        hier = ufe.Hierarchy.hierarchy(cylinderItem)
        childrenList = ufe.Hierarchy.hierarchy(hier.parent()).children()

        # get Cylinder1 position ( index ) before the move
        index = childrenList.index(cylinderItem)
        self.assertEqual(index, 3)

        # move Cylinder1 forward ( + ) by 3
        cmds.reorder("|Primitives_usd|Primitives_usdShape,/Xform1/Cylinder1",
                     r=3)

        # check Cylinder1 position ( index ) after the move
        self.assertEqual(findIndex(cylinderItem), 6)

        # move Cylinder1 backward ( - ) by 3
        cmds.reorder("|Primitives_usd|Primitives_usdShape,/Xform1/Cylinder1",
                     r=-3)

        # check Cylinder1 position ( index ) after the move
        self.assertEqual(findIndex(cylinderItem), 3)
Ejemplo n.º 6
0
def do_modifyAdvancedSkeletonTopHierarchy(rig):
    """Merges MasterBodyCog and AdvSkeleton rig hierarchies"""

    master_ctl = dragonfly.modules.name_from_uuid(str(rig['master']))
    master_offset_ctl = dragonfly.modules.get_metatype(
        dragonfly.meta_types.MTYPE_MASTER_OFFSET)[0]
    body_ctl = dragonfly.modules.name_from_uuid(str(rig['body']))
    cog_ctl = rig['cog']
    root_jnt = dragonfly.modules.get_metatype(
        dragonfly.meta_types.MTYPE_ROOT)[0]

    # Modify Main to master
    if cmds.objExists(master_ctl):
        cmds.parent('Main', master_ctl)

    # Body ctl mod
    if cmds.objExists(body_ctl):
        cmds.parent('cn_body_buf', 'Main')
        cmds.parentConstraint(body_ctl, 'RootExtraX_M', mo=True)
        #cmds.delete('RootExtraX_MShape')

    # Cog mod
    if cmds.objExists(cog_ctl):
        cmds.parentConstraint(cog_ctl, 'RootX_M', mo=True)

    # Master Offset ctl mod, renames and modifies "Main" node from AS rig
    if master_offset_ctl:
        if cmds.objExists(master_offset_ctl):
            cmds.delete(master_offset_ctl)

    if cmds.objExists('Main'):
        master_offset_ctl_name = master_offset_ctl.split('|')[-1]
        master_offset_ctl = cmds.rename('Main', master_offset_ctl_name)
        cmds.reorder(master_offset_ctl, relative=-1)
        setColor(master_offset_ctl, YELLOW_AS)
        cmds.setAttr('{}Shape.overrideEnabled'.format(master_offset_ctl), 0)

    # Designate masterOffset metatype to the new renamed Main control
    dragonfly.modules.add_metatype(master_offset_ctl,
                                   dragonfly.meta_types.MTYPE_MASTER_OFFSET)
    cmds.setAttr('{}.v'.format(master_offset_ctl), k=False, l=True)
    cmds.delete(cmds.listRelatives('RootX_M', shapes=True))

    # Connect the globalScale from the master ctl to the master_offset_ctl
    for attr in ['sx', 'sy', 'sz']:
        cmds.setAttr('{}.{}'.format(master_ctl, attr), k=False, lock=False)
        cmds.connectAttr('{}.globalScale'.format(master_ctl),
                         '{}.{}'.format(master_ctl, attr))
        cmds.setAttr('{}.{}'.format(master_offset_ctl, attr),
                     k=False,
                     lock=True)
        cmds.setAttr('{}.{}'.format(master_ctl, attr), k=False, lock=True)

    # Constrain root_jnt to trajectory
    if dragonfly.modules.get_metatype(dragonfly.meta_types.MTYPE_TRAJECTORY):
        traj_ctl = dragonfly.modules.get_metatype(
            dragonfly.meta_types.MTYPE_TRAJECTORY)[0]
        cmds.parentConstraint(traj_ctl, root_jnt, mo=True)
    else:
        cmds.parentConstraint(master_ctl, root_jnt, mo=True)
Ejemplo n.º 7
0
def renameShapes(verbose=True):
    """
    Rename previously referenced shape nodes.
    @param verbose: Print progress messages
    @type verbose: bool
    """
    # List all scene transforms
    xformList = cmds.ls(type='transform')

    # Iterate over transforms
    for xform in xformList:

        # Get Xform Short Name
        xformSN = xform.split('|')[-1]

        # List all shapes
        allShapeList = cmds.listRelatives(xform, s=True, pa=True)
        if not allShapeList: continue

        # List all non-intermediate shape children
        shapeList = cmds.listRelatives(xform, s=True, ni=True, pa=True)
        if not shapeList: continue

        # List all intermediate shapes
        if len(allShapeList) == len(shapeList): continue
        intShapeList = list(set(allShapeList) - set(shapeList))

        # Check shape naming
        for shape in shapeList:

            # Get Shape Short Name
            shapeSN = shape.split('|')[-1]

            # Check for ShapeDeformed naming
            if shapeSN.endswith('Deformed'):

                # Find input shape
                try:
                    inputShape = glTools.utils.shape.findInputShape(shape)
                except:
                    inputShape = glTools.utils.shape.findInputShape2(shape)

                # Get InputShape Short Name
                inputShapeSN = inputShape.split('|')[-1]

                # Check Input Shape
                if inputShapeSN != shapeSN:
                    # Rename input shape
                    if verbose:
                        print('Renaming: ' + inputShapeSN + ' -> ' + xformSN +
                              'IntermediateShape')
                    inputShape = cmds.rename(inputShape,
                                             xformSN + 'IntermediateShape')

                # Rename current shape
                if verbose:
                    print('Renaming: ' + shapeSN + ' -> ' + xformSN + 'Shape')
                shape = cmds.rename(shape, xformSN + 'Shape')
                cmds.reorder(shape, f=True)
Ejemplo n.º 8
0
def orderCamsFirst():
    '''
    makes sure the default cameras are first in scene hierarchy
    '''
    assemblies = m.ls(assemblies=True, long=True)
    if assemblies[0] != "|persp":
        for cam in ["|side", "|front", "|top", "|persp"]:
            m.reorder(cam, front=True)
Ejemplo n.º 9
0
def renameShapes(verbose=True):
    """
    Rename previously referenced shape nodes.
    @param verbose: Print progress messages
    @type verbose: bool
    """
    # List all scene transforms
    xformList = cmds.ls(type='transform')

    # Iterate over transforms
    for xform in xformList:

        # Get Xform Short Name
        xformSN = xform.split('|')[-1]

        # List all shapes
        allShapeList = cmds.listRelatives(xform, s=True, pa=True)
        if not allShapeList: continue

        # List all non-intermediate shape children
        shapeList = cmds.listRelatives(xform, s=True, ni=True, pa=True)
        if not shapeList: continue

        # List all intermediate shapes
        if len(allShapeList) == len(shapeList): continue
        intShapeList = list(set(allShapeList) - set(shapeList))

        # Check shape naming
        for shape in shapeList:

            # Get Shape Short Name
            shapeSN = shape.split('|')[-1]

            # Check for ShapeDeformed naming
            if shapeSN.endswith('Deformed'):

                # Find input shape
                try:
                    inputShape = glTools.utils.shape.findInputShape(shape)
                except:
                    inputShape = glTools.utils.shape.findInputShape2(shape)

                # Get InputShape Short Name
                inputShapeSN = inputShape.split('|')[-1]

                # Check Input Shape
                if inputShapeSN != shapeSN:
                    # Rename input shape
                    if verbose: print('Renaming: ' + inputShapeSN + ' -> ' + xformSN + 'IntermediateShape')
                    inputShape = cmds.rename(inputShape, xformSN + 'IntermediateShape')

                # Rename current shape
                if verbose: print('Renaming: ' + shapeSN + ' -> ' + xformSN + 'Shape')
                shape = cmds.rename(shape, xformSN + 'Shape')
                cmds.reorder(shape, f=True)
Ejemplo n.º 10
0
    def controlShape(
        self, transform, controlType, translate=(0, 0, 0), rotate=(0, 0, 0), scale=1, colour=-1, text="", orient=True
    ):
        """
		Add control shape to an existing transform.
		@param transform: Transform to add controlshape to.
		@type transform: str
		@param controlType: Type of control to build.
		@type controlType: str
		@param translate: Translational offset for control curve.
		@type translate: list or tuple
		@param rotate: Rotational offset for control curve.
		@type rotate: list or tuple
		@param scale: Scale offset for control curve.
		@type scale: list or tuple
		@param colour: The colour of the control curve.
		@type colour: int
		@param text: Text value for "text" type control curve.
		@type text: str
		@param orient: Orient control to transform.
		@type orient: bool
		"""
        # Create Control
        if controlType == "text":
            control = self.create(controlType, "temp_control_transform", text=text)
        else:
            control = self.create(controlType, "temp_control_transform")
        controlShapeList = mc.listRelatives(control, s=True)

        # Match Control
        if not orient:
            mc.setAttr(control + ".rotate", rotate[0], rotate[1], rotate[2])
        mc.delete(mc.pointConstraint(transform, control))
        mc.parent(control, transform)
        mc.setAttr(control + ".translate", translate[0], translate[1], translate[2])
        if orient:
            mc.setAttr(control + ".rotate", rotate[0], rotate[1], rotate[2])
        mc.setAttr(control + ".scale", scale, scale, scale)
        mc.makeIdentity(control, apply=True, t=1, r=1, s=1, n=0)

        # Parent Control Shape
        for i in range(len(controlShapeList)):
            controlShapeList[i] = mc.parent(controlShapeList[i], transform, r=True, s=True)[0]
            controlShapeList[i] = mc.rename(controlShapeList[i], transform + "Shape" + str(i + 1))
            mc.reorder(controlShapeList[i], b=True)

            # Delete temp transform
        mc.delete(control)

        # Colour Control
        self.colourControl(transform, colour)

        # Return result
        return controlShapeList
Ejemplo n.º 11
0
    def skin_duo_drivers(self):
        """
        Creates a pair of driver joints at either end of your ribbon
        """
        btDriver = self.driverJoints[0]
        tpDriver = self.driverJoints[1]
        ribbon = self.ribbon
        crv = self.lenCurves[0]
        cvrows = self.spans + 3
        frac = 1.0 / self.spans
        thrdFrac = .333 * frac

        # Freeze transformation of the base driver joint
        mc.makeIdentity(btDriver, a=True)

        # Apply skincluster to ribbon and lenCrv
        scRib = mc.skinCluster(btDriver, tpDriver, ribbon,
                               n="{}_sc".format(ribbon))[0]
        scCrv = mc.skinCluster(btDriver, tpDriver, crv,
                               n="{}_sc".format(crv))[0]
        for i in range(cvrows):
            if i == 0:
                btwt = 1
                tpwt = 0
            elif i == 1:
                btwt = 1 - thrdFrac
                tpwt = thrdFrac
            elif i == cvrows - 2:
                btwt = thrdFrac
                tpwt = 1 - thrdFrac
            elif i == cvrows - 1:
                btwt = 0
                tpwt = 1
            else:
                btwt = 1 - ((i - 1) * frac)
                tpwt = (i - 1) * frac
            # Set the weighting of the CVs based on the number of CV rows
            mc.skinPercent(scRib, "{}.cv[{}][0:3]".format(
                ribbon, i), tv=[(btDriver, btwt), (tpDriver, tpwt)])
            mc.skinPercent(scCrv, "{}.cv[{}]".format(
                crv, i), tv=[(btDriver, btwt), (tpDriver, tpwt)])

        # turn off ribbon's inherit transform to prevent double transforms
        mc.setAttr("{}.inheritsTransform".format(ribbon), 0)
        # turn off curve's inherit transform to prevent double transforms
        mc.setAttr("{}.inheritsTransform".format(crv), 0)

        # Group your driver joints and parent it to your rig group
        driverGrp = mc.createNode(
            "transform", n="{}_driver_jnt_grp".format(self.name))
        mc.parent(tpDriver, driverGrp)
        mc.parent(btDriver, driverGrp)
        mc.parent(driverGrp, "{}_rig".format(self.name))
        mc.reorder(driverGrp, r=-1)
Ejemplo n.º 12
0
    def anchorCurve(self, control, anchor, template=True, selectable=False):
        """
		Create an anchor curve for the specified control.
		@param control: The control object to create an anchor curve for.
		@type control: str
		@param anchor: The transform that the anchor curve will be attached to for.
		@type anchor: str
		@param template: Set the anchor curve override type to template
		@type template: bool
		"""
        # Check control
        if not mc.objExists(control):
            raise Exception('Control "' + control + '" does not exist!')
        if not mc.objExists(anchor):
            raise Exception('Anchor transform "' + anchor + '" does not exist!')

            # Create curve shape
        crv = mc.curve(p=[(0, 0, 0), (0, 1, 0)], k=[0, 1], d=1, n=control + "Anchor")
        crvShape = mc.listRelatives(crv, s=True, pa=True)
        if not crvShape:
            raise Exception('Unable to determine shape for curve "' + crv + '"!')

            # Create Curve Locators
        crvLoc = glTools.utils.curve.locatorCurve(crv, locatorScale=0.0, local=True, prefix=control)
        mc.parent(crvLoc, control)
        mc.setAttr(crvLoc[0] + ".t", 0, 0, 0)
        mc.setAttr(crvLoc[1] + ".t", 0, 0, 0)
        mc.setAttr(crvLoc[0] + ".v", 0)
        mc.setAttr(crvLoc[1] + ".v", 0)

        # Rename and Parent curve shape
        crvShape = mc.parent(crvShape[0], control, r=True, s=True)[0]
        crvShape = mc.rename(crvShape, control + "Shape0")
        mc.reorder(crvShape, b=True)

        # Colour Curve Shape - Light Grey
        mc.setAttr(crvShape + ".overrideEnabled", 1)
        mc.setAttr(crvShape + ".overrideColor", 3)  # Light Grey

        # Delete Original Curve Transform
        mc.delete(crv)

        # Connect to anchor
        mc.pointConstraint(anchor, crvLoc[1])

        # Template
        if template:
            glTools.utils.base.displayOverride(crvShape, overrideEnable=1, overrideDisplay=1)

        # Set channel states
        glTools.utils.channelState.ChannelState().setFlags([2, 2, 2, 2, 2, 2, 2, 2, 2, 1], crvLoc)

        # Return result
        return crvShape
Ejemplo n.º 13
0
def reorder_outliner(objects=None):
    """Reorders the outliner based of selection.
        @PARAMS:
            objects: list, list of dag objects.
    """
    selection = cmds.ls(sl=True)
    if objects:
        selection = objects
    selection = sorted(selection, key=lambda s: s.lower())
    for dag_obj in selection:
        cmds.reorder(dag_obj, b=True)
Ejemplo n.º 14
0
def createIntermediate(shape):
    """
	Create and connect an intermediate shape for the specified geoemtry shape
	@param shape: Shape or create intermediate shape for
	@type shape: str
	"""
    # Check Shape
    if not mc.objExists(shape):
        raise Exception('Object "' + shape + '" does not exist!!')

    # Check Geometry Type
    geoType = mc.objectType(shape)
    if geoType == "transform":
        shapes = getShapes(shape, intermediates=False)
        if not shapes:
            raise Exception('Object "' + shape + '" has no valid shapes!!')
        shape = shapes[0]
        geoType = mc.objectType(shape)

    geoDict = {"mesh": ("outMesh", "inMesh"), "nurbsSurface": ("local", "create"), "nurbsCurve": ("local", "create")}
    if not geoDict.has_key(geoType):
        raise Exception("Invalid shape type (" + geoType + ') for "' + shape + '"!!')

    # Get transform
    transform = str(mc.listRelatives(shape, p=True)[0])

    # Rename current shape as intermediate
    shapeOrig = mc.rename(shape, shape + "Orig")
    """
	ind = 1
	shapeOrig = shape.replace('Shape','ShapeOrig')
	while(mc.objExists(shapeOrig)):
		shapeOrig =  shape.replace('Shape','ShapeOrig'+ind)
		ind += 1
	shapeOrig = mc.rename(shape,shape.replace('Shape','ShapeOrig'))
	"""
    # Create new shape
    shape = mc.createNode(geoType, n=shape, p=transform)
    mc.reorder(shape, f=True)

    # Connect shapes
    mc.connectAttr(shapeOrig + "." + geoDict[geoType][0], shape + "." + geoDict[geoType][1], f=True)

    # Set shapeOrig as intermediate
    mc.setAttr(shapeOrig + ".intermediateObject", 1)

    # Connect to existing shader
    shader = mc.listConnections(shapeOrig, type="shadingEngine")
    if shader:
        mc.sets(shapeOrig, rm=shader[0])
        mc.sets(shape, fe=shader[0])

        # Return result
    return shapeOrig
    def testRootNodeReordering(self):
        """
        Tests that root-level Maya nodes can still be reordered when the
        pxrHdImagingShape is present.

        At one time, the pxrHdImagingShape and its transform were being locked,
        which ended up preventing other root-level nodes from being reordered.
        """
        cmds.polyCube(n='testNode1')
        cmds.polyCube(n='testNode2')
        cmds.reorder('testNode1', back=True)
        cmds.reorder('testNode2', front=True)
Ejemplo n.º 16
0
def createIntermediate(shape):
	'''
	Create and connect an intermediate shape for the specified geoemtry shape
	@param shape: Shape or create intermediate shape for
	@type shape: str
	'''
	# Check Shape
	if not mc.objExists(shape): raise Exception('Object "'+shape+'" does not exist!!')
	
	# Check Geometry Type
	geoType = mc.objectType(shape)
	if geoType == 'transform':
		shapes = getShapes(shape,intermediates=False)
		if not shapes: raise Exception('Object "'+shape+'" has no valid shapes!!')
		shape = shapes[0]
		geoType = mc.objectType(shape)
		
	geoDict = {'mesh':('outMesh','inMesh'),'nurbsSurface':('local','create'),'nurbsCurve':('local','create')}
	if not geoDict.has_key(geoType): raise Exception('Invalid shape type ('+geoType+') for "'+shape+'"!!')
	
	# Get transform
	transform = str(mc.listRelatives(shape,p=True)[0])
	
	# Rename current shape as intermediate
	shapeOrig = mc.rename(shape,shape+'Orig')
	'''
	ind = 1
	shapeOrig = shape.replace('Shape','ShapeOrig')
	while(mc.objExists(shapeOrig)):
		shapeOrig =  shape.replace('Shape','ShapeOrig'+ind)
		ind += 1
	shapeOrig = mc.rename(shape,shape.replace('Shape','ShapeOrig'))
	'''
	# Create new shape
	shape = mc.createNode(geoType,n=shape,p=transform)
	mc.reorder(shape,f=True)
	
	# Connect shapes
	mc.connectAttr(shapeOrig+'.'+geoDict[geoType][0],shape+'.'+geoDict[geoType][1],f=True)
	
	# Set shapeOrig as intermediate
	mc.setAttr(shapeOrig+'.intermediateObject',1)
	
	# Connect to existing shader
	shader = mc.listConnections(shapeOrig,type='shadingEngine')
	if shader:
		mc.sets(shapeOrig,rm=shader[0])
		mc.sets(shape,fe=shader[0])
	
	# Return result
	return shapeOrig
Ejemplo n.º 17
0
def offset_joint_hierarchy(joints):
    """
    Offsets a hierarchy of joints with SRT groups, detaching the visible bones
    """
    # Add the new ensureArray function from the os wrapper when added to github
    # Also consider option to just select hierarchy parent to run
    for jnt in joints:
        jnt_parent = nUtil.get_parent(jnt)
        ofs = create_offset(suffix='OFS', input_object=jnt)
        create_offset(suffix='SRT', input_object=jnt)
        if jnt_parent:
            # parent to the above srt offset then clean the hierarchy children order
            cmds.parent(ofs, jnt_parent + '_SRT')
            cmds.reorder(ofs, front=True)
Ejemplo n.º 18
0
    def clean_up_object(new):
        """
        Cleans up after `polyUnite` / `polySeparate`
        """
        if not new.get_parent() == parent:
            new.set_parent(parent)

        cmds.reorder(str(new), f=True)
        cmds.reorder(str(new), r=outliner_index)
        new.transform.set_pivot(pivot)

        new.attr['rotate'] = list(transforms.rotate)
        new.attr['scale'] = list(transforms.scale)
        return cmds.rename(str(new), name.split('|')[-1])
Ejemplo n.º 19
0
def parentShape(child=None, parent=None, maintainOffset=True):
    '''
    Parent a child shape node to a parent transform. The child node can be a shape,
    or a transform which has any number of shapes.
    '''

    if not child or not parent:
        sel = mc.ls(sl=True)
        if sel and len(sel) > 1:
            child = sel[:-1]
            parent = sel[-1]
        else:
            OpenMaya.MGlobal.displayWarning('Please make a selection.')
            return

    parentNodeType = mc.nodeType(parent)
    if not parentNodeType in ('transform', 'joint', 'ikHandle'):
        OpenMaya.MGlobal.displayWarning('Parent must be a transform node.')
        return

    if not isinstance(child, (list, tuple)):
        child = [child]

    newChild = unparentShape(child)

    shapes = list()
    for each in newChild:
        thisChild = mc.parent(each, parent)[0]
        mc.makeIdentity(thisChild, apply=True)

        for s in mc.listRelatives(thisChild,
                                  shapes=True,
                                  noIntermediate=True,
                                  path=True):
            shape = mc.parent(s, parent, shape=True, relative=True)[0]
            #move to bottom
            mc.reorder(shape, back=True)

            #rename
            parentName = mc.ls(parent, shortNames=True)[0]
            shapes.append(mc.rename(shape, parentName + 'Shape#'))

    mc.delete(newChild)

    for each in child:
        if not mc.listRelatives(each):
            #if it doesn't have any kids, delete it
            mc.delete(each)

    return shapes
Ejemplo n.º 20
0
def sortObj(objs):
    '''\n
    Sort objects alphabetically and reposition in hierarchy.
    Objects must be under the same parent.
    '''
    # convert list to string objects
    i = 0
    for item in objs:
        objs[i] = str(item)
        i = i + 1
    # sort string objects
    objs.sort(key=str.lower)
    #reorder in scene
    for item in objs:
        cmds.reorder(item, b=True)
Ejemplo n.º 21
0
    def Activity_CreateAll():
        selection = maya_cmds.ls(selection=True)

        if not maya_cmds.objExists('ToolSeq_Cameras'):
            maya_cmds.group(empty=True, name='ToolSeq_Cameras')
            maya_cmds.hide('ToolSeq_Cameras')
            maya_cmds.reorder('ToolSeq_Cameras', front=True)
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Perspective', 'persp')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Top', 'top')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Bottom', 'bottom')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Front', 'front')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Back', 'back')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Left', 'left')
        ToolSeq_Cameras.Activity_CreateCamera('Camera_Right', 'right')

        maya_cmds.select(selection)
Ejemplo n.º 22
0
def parentShape(child=None, parent=None, maintainOffset=True):
    '''
    Parent a child shape node to a parent transform. The child node can be a shape,
    or a transform which has any number of shapes.
    '''
    
    if not child or not parent:
        sel = mc.ls(sl=True)
        if sel and len(sel) > 1:
            child = sel[:-1]
            parent = sel[-1]
        else:
            OpenMaya.MGlobal.displayWarning('Please make a selection.')
            return
    
    parentNodeType = mc.nodeType(parent)
    if not parentNodeType in ('transform', 'joint', 'ikHandle'):
        OpenMaya.MGlobal.displayWarning('Parent must be a transform node.')
        return
    
    if not isinstance(child, (list, tuple)):
        child = [child]
    
    newChild = unparentShape(child)
    
    shapes = list()
    for each in newChild:
        thisChild = mc.parent(each, parent)[0]
        mc.makeIdentity(thisChild, apply=True)
    
        for s in mc.listRelatives(thisChild, shapes=True, noIntermediate=True, path=True):
            shape = mc.parent(s, parent, shape=True, relative=True)[0]
            #move to bottom
            mc.reorder(shape, back=True)
            
            #rename
            parentName = mc.ls(parent, shortNames=True)[0]
            shapes.append(mc.rename(shape, parentName+'Shape#'))

    mc.delete(newChild)
    
    for each in child:
        if not mc.listRelatives(each):
            #if it doesn't have any kids, delete it
            mc.delete(each)
        
    return shapes
Ejemplo n.º 23
0
def addCtrlShape(lCtrls, sCtrlShape, bVis = True, dCtrlShapeInfo = None, bTop = False):
	'''
	add a shape node to a list of controls

	lCtrls: a list of transform nodes need to add the shape node
	sCtrlShape: shape node name
	bVis: shape node's visibility, True/False
	dCtrlShapeInfo: a dictionary contain all the shape node's shape information
	bTop: either the shape node will be on top of other shape nodes nor not, True/False
	'''
	if not cmds.objExists(sCtrlShape):
		if dCtrlShapeInfo:
			lCtrlPnts = dCtrlShapeInfo['lCtrlPnts']
			lKnots = dCtrlShapeInfo['lKnots']
			iDegree = dCtrlShapeInfo['iDegree']
			bPeriodic = dCtrlShapeInfo['bPeriodic']
			bOverride = dCtrlShapeInfo['bOverride']
			iOverrideType = dCtrlShapeInfo['iOverrideType']
			iColor = dCtrlShapeInfo['iColor']
		else:
			lCtrlPnts = [[0,0,0], [1,0,0]]
			lKnots = [0,1]
			iDegree = 1
			bPeriodic = False
			bOverride = False
			iOverrideType = 0
			iColor = 0
		sCrv = cmds.curve(p=lCtrlPnts, k=lKnots, d=iDegree, per = bPeriodic)
		sCrvShape = getCtrlShape(sCrv)
		cmds.rename(sCrvShape, sCtrlShape)
		cmds.setAttr('%s.overrideEnabled' %sCtrlShape, bOverride)
		cmds.setAttr('%s.overrideDisplayType' %sCtrlShape, iOverrideType)
		cmds.setAttr('%s.overrideColor' %sCtrlShape, iColor)
	else:
		sCrv = None

	if not bVis:
		cmds.setAttr('%s.v' %sCtrlShape, lock = False)
		cmds.setAttr('%s.v' %sCtrlShape, 0)
		cmds.setAttr('%s.v' %sCtrlShape, lock = True)
	for sCtrl in lCtrls:
		cmds.parent(sCtrlShape, sCtrl, add = True, s = True)
	if bTop:
		cmds.reorder(sCtrlShape, f = True)
	if sCrv:
		cmds.delete(sCrv)
Ejemplo n.º 24
0
    def testProxyShapeBoundingBox(self):
        mayaFile = os.path.abspath('ProxyShape.ma')
        cmds.file(mayaFile, open=True, force=True)

        # Verify that the proxy shape read something from the USD file.
        bboxSize = cmds.getAttr('Cube_usd.boundingBoxSize')[0]
        self.assertEqual(bboxSize, (1.0, 1.0, 1.0))

        # The VP2 render delegate doesn't use additional proxy shape
        if not Tf.GetEnvSetting('VP2_RENDER_DELEGATE_PROXY'):
            # The proxy shape is imaged by the pxrHdImagingShape, which should be
            # created by the proxy shape's postConstructor() method. Make sure the
            # pxrHdImagingShape (and its parent transform) exist.
            hdImagingTransformPath = '|HdImaging'
            hdImagingShapePath = '%s|HdImagingShape' % hdImagingTransformPath

            self.assertTrue(cmds.objExists(hdImagingTransformPath))
            self.assertEqual(cmds.nodeType(hdImagingTransformPath),
                             'transform')

            self.assertTrue(cmds.objExists(hdImagingShapePath))
            self.assertEqual(cmds.nodeType(hdImagingShapePath),
                             'pxrHdImagingShape')

            self.assertNotEqual(cmds.ls(hdImagingTransformPath, uuid=True),
                                cmds.ls(hdImagingShapePath, uuid=True))

        # The pxrHdImagingShape and its parent transform are set so that they
        # do not write to the Maya scene file and are not exported by
        # usdExport, so do a test export and make sure that's the case.
        usdFilePath = os.path.abspath('ProxyShapeExportTest.usda')
        cmds.usdExport(file=usdFilePath)

        usdStage = Usd.Stage.Open(usdFilePath)
        prim = usdStage.GetPrimAtPath('/HdImaging')
        self.assertFalse(prim)
        prim = usdStage.GetPrimAtPath('/HdImaging/HdImagingShape')
        self.assertFalse(prim)

        # Make sure that we can reorder root nodes in the scene with the
        # pxrHdImagingShape present.
        cmds.polyCube(n="testNode1")
        cmds.polyCube(n="testNode2")
        cmds.reorder("testNode1", back=True)
        cmds.reorder("testNode2", front=True)
Ejemplo n.º 25
0
    def Activity_CreateCamera(cameraName, cameraDirection):
        if maya_cmds.objExists(cameraName):
            return

        if cameraDirection in ['persp', 'top', 'front', 'left']:
            maya_cmds.duplicate(cameraDirection.replace('left', 'side'),
                                name=cameraName)
        elif cameraDirection == 'bottom':
            maya_cmds.duplicate('top', name=cameraName)
            maya_cmds.setAttr(cameraName + '.rotateX', 90)
        elif cameraDirection == 'back':
            maya_cmds.duplicate('front', name=cameraName)
            maya_cmds.setAttr(cameraName + '.rotateY', 180)
        elif cameraDirection == 'right':
            maya_cmds.duplicate('side', name=cameraName)
            maya_cmds.setAttr(cameraName + '.rotateY', -90)
        maya_cmds.hide(cameraName)
        maya_cmds.parent(cameraName, 'ToolSeq_Cameras')
        maya_cmds.reorder(cameraName, back=True)
Ejemplo n.º 26
0
    def testFrontBackRelative(self):
        '''
            Reorder (a.k.a move) to front and back of the sibling list
        '''
        cylinderPath = ufe.PathString.path(
            "|Primitives_usd|Primitives_usdShape,/Xform1/Cylinder1")
        cylinderItem = ufe.Hierarchy.createItem(cylinderPath)

        # make Cylinder1 the first sibling ( front )
        cmds.reorder(ufe.PathString.string(cylinderPath), front=True)

        # check Cylinder1 position ( index ) after the move
        self.assertEqual(findIndex(cylinderItem), 0)

        # make Cylinder1 the last sibling ( back )
        cmds.reorder(ufe.PathString.string(cylinderPath), back=True)

        # check Cylinder1 position ( index ) after the move
        self.assertEqual(findIndex(cylinderItem), 7)
    def testProxyShapeBoundingBox(self):
        mayaFile = os.path.abspath('ProxyShape.ma')
        cmds.file(mayaFile, open=True, force=True)

        # Verify that the proxy shape read something from the USD file.
        bboxSize = cmds.getAttr('Cube_usd.boundingBoxSize')[0]
        self.assertEqual(bboxSize, (1.0, 1.0, 1.0))

        # The proxy shape is imaged by the pxrHdImagingShape, which should be
        # created by the proxy shape's postConstructor() method. Make sure the
        # pxrHdImagingShape (and its parent transform) exist.
        hdImagingTransformPath = '|HdImaging'
        hdImagingShapePath = '%s|HdImagingShape' % hdImagingTransformPath

        self.assertTrue(cmds.objExists(hdImagingTransformPath))
        self.assertEqual(cmds.nodeType(hdImagingTransformPath), 'transform')

        self.assertTrue(cmds.objExists(hdImagingShapePath))
        self.assertEqual(cmds.nodeType(hdImagingShapePath), 'pxrHdImagingShape')

        self.assertNotEqual(
                cmds.ls(hdImagingTransformPath, uuid=True),
                cmds.ls(hdImagingShapePath, uuid=True))

        # The pxrHdImagingShape and its parent transform are set so that they
        # do not write to the Maya scene file and are not exported by
        # usdExport, so do a test export and make sure that's the case.
        usdFilePath = os.path.abspath('ProxyShapeExportTest.usda')
        cmds.usdExport(file=usdFilePath)

        usdStage = Usd.Stage.Open(usdFilePath)
        prim = usdStage.GetPrimAtPath('/HdImaging')
        self.assertFalse(prim)
        prim = usdStage.GetPrimAtPath('/HdImaging/HdImagingShape')
        self.assertFalse(prim)

        # Make sure that we can reorder root nodes in the scene with the
        # pxrHdImagingShape present.
        cmds.polyCube(n="testNode1")
        cmds.polyCube(n="testNode2")
        cmds.reorder("testNode1", back=True)
        cmds.reorder("testNode2", front=True)
Ejemplo n.º 28
0
    def mk_driver_joints(self):
        """
        Create the joints that will drive your ribbon
        """
        for i in range(self.driverJointNum):
            # Define rotation order based on riibbon's primary axis
            if self.primaryAxis == "X":
                ro = "xyz"
            elif self.primaryAxis == "Y":
                ro = "yzx"
            else:
                ro = "zxy"

            if i == 0:
                jnt = mc.joint(n="{}_base_driver_jnt".format(
                    self.name), rad=3, roo=ro)
            elif i == self.driverJointNum - 1:
                jnt = mc.joint(n="{}_tip_driver_jnt".format(
                    self.name), rad=3, roo=ro)
                mc.setAttr("{}.translate{}".format(
                    jnt, self.primaryAxis), mc.arclen(self.proxieCrv) / (self.driverJointNum - 1))
            elif i == 1 and self.driverJointNum == 3:
                jnt = mc.joint(n="{}_mid_driver_jnt".format(
                    self.name), rad=3, roo=ro)
                mc.setAttr("{}.translate{}".format(
                    jnt, self.primaryAxis), mc.arclen(self.proxieCrv) / (self.driverJointNum - 1))
            else:
                jnt = mc.joint(
                    n="{}_mid{}_driver_jnt".format(self.name, str(i).zfill(2)), rad=3, roo=ro)
                mc.setAttr("{}.translate{}".format(jnt, self.primaryAxis), mc.arclen(
                    self.proxieCrv) / (self.driverJointNum - 1))

            self.driverJoints.append(jnt)

        # Group your driver joints and parent it to your rig group
        driverGrp = mc.createNode(
            "transform", n="{}_driver_jnt_grp".format(self.name))
        mc.parent(self.driverJoints[0], driverGrp)
        mc.parent(driverGrp, "{}{}".format(self.name, RIG))
        mc.reorder(driverGrp, r=-1)

        return self.driverJoints
Ejemplo n.º 29
0
    def assignCollision(self, *args):
        """
        Assigns collision mesh to mesh
        """
        if not self._hasSelection():
            return
        selection = cmds.ls(sl=True)
        cmds.select(cl=True)
        renderMeshName = self._checkRenderMeshName(selection.pop())
        renderMeshGroup = self.createMainGroup(renderMeshName)
        collisionGroup = '%s_Collision' % renderMeshName
        if not cmds.objExists(collisionGroup):
            cmds.group(name=collisionGroup, empty=True, parent=renderMeshGroup)

        #Checks for collisions inside collisionGroup
        initCollisions = []
        newCollisions = selection
        groupRelatives = cmds.listRelatives(collisionGroup)
        if groupRelatives:
            #Validate if all are proper collision names per object
            for relative in groupRelatives:
                if any(
                        relative.startswith(collisionType + renderMeshName)
                        for collisionType in ['UBX_', 'USP_', 'UCP_', 'UCX_']):
                    initCollisions.append(relative)
                    if relative in newCollisions:
                        newCollisions.remove(relative)
                else:
                    if relative not in newCollisions:
                        newCollisions.append(relative)

        #Insure intial collisions are in correct index order
        initCollisions.sort(key=lambda x: x[-2:])
        for i, collision in enumerate(initCollisions):
            cmds.reorder(collision, front=True)
            cmds.reorder(collision, r=i)
            correctNaming = collision[:-2] + '%02d' % i
            if collision != correctNaming:
                cmds.rename(collision, correctNaming)

        #Add new collision meshes and renames
        numCollisions = len(initCollisions)
        for i, newCollision in enumerate(newCollisions):
            collisionName = self._findCollisionType(
                newCollision) + renderMeshName + '_%02d' % (i + numCollisions)
            cmds.rename(newCollision, collisionName)
            if (cmds.listRelatives(collisionName, parent=True) !=
                    collisionGroup):
                cmds.parent(collisionName, collisionGroup)
            cmds.reorder(collisionName, front=True)
            cmds.reorder(collisionName, r=i + numCollisions)
        cmds.select(cl=True)
	def sortSelected(self,type='asc'):
		selected = cmds.ls( sl=True )
		selectedDictionary = {}
		for item in selected:
			key = item.split('|')[-1]
			selectedDictionary[key] = item

		selectedKeys = selectedDictionary.keys()
		if type == 'asc':
			selectedKeys.sort()
		elif type == 'desc':
			selectedKeys.sort(reverse=True)
		else:
			return None

		sortSelected = []
		for key in selectedKeys:
			sortSelected.append(selectedDictionary[key])

		parentResult = cmds.listRelatives( selected[0], parent=True )

		if parentResult is not None:
			parent = parentResult[0]
			children = cmds.listRelatives( parent, children=True, pa=True )
			sortIndex = 0

			currentIndexex = []
			for index,item in enumerate(children):
				if item in selected:
					currentIndexex.append(index)
					sortIndex = sortIndex+1

			for index, currentIndex in enumerate(currentIndexex):
				children[currentIndex] = sortSelected[index]

			for item in children:
				cmds.reorder( item, back=True )

			cmds.select( sortSelected )
		else:
			cmds.warning( 'Selected objects are parented to the World, they need to be children of a transform' )
Ejemplo n.º 31
0
def createNodeFromEmbedInfo(embed_info, node_type=None):
    """create or update position of an embed node

    Args:
        embed_info (dict): point position in space
        node_type (str, optional): if none, default to joint. maya data type

    Returns:
        list: of created nodes
    """
    if not node_type:
        node_type = "joint"
    created_nodes = []
    for name, position in embed_info["joints"].items():
        if not cmds.objExists(name):
            name = cmds.createNode(node_type, name=name)
        cmds.xform(name, worldSpace=True, translation=position)
        created_nodes.append(name)
    for point in DEFAULT_BIPED_POINTS:
        cmds.reorder(point, back=True)
    return created_nodes
Ejemplo n.º 32
0
    def setCtlLayering(self):
        "【スイッチ】"
        cmds.parent(SwitchCtlList[0], "All_Ctl")
        "【ルート】"
        cmds.parent(RootCtlList[2], "All_Ctl")
        cmds.reorder(RootCtlList[0], f=True)
        "【スウィング】"
        cmds.parent(SwingCtlList[0], "All_Ctl")
        #cmds.reorder(self.SwingCtl,f=True)
        "【頭】"
        cmds.parent(NeckCtlList[0], "All_Ctl")
        cmds.parent(HeadCtlList[0], "All_Ctl")
        "【背骨】"
        cmds.parent(SpineCtlList[0], "All_Ctl")
        "【腕】"
        cmds.parent(LArmCtlList[0], self.GP3Name[1])
        cmds.parent(RArmCtlList[0], self.GP3Name[1])
        cmds.parent(LArmCtlList[1], "All_Ctl")
        cmds.parent(RArmCtlList[1], "All_Ctl")

        print "result setup.",
Ejemplo n.º 33
0
def reorderShapes():
    """
    """
    # Start Timer
    timer = cmds.timerX()

    print('Reordering Constraints Nodes (push constraints to end of child list)')
    constraintList = cmds.ls(type='constraint')
    if constraintList: cmds.reorder(constraintList, b=True)

    # Print Timed Result
    print('# Clean Rig: Reorder Constraints - ' + str(cmds.timerX(st=timer)))

    # Start Timer
    timer = cmds.timerX()

    print('Reordering Shape Nodes (push shapes to end of child list)')
    shapeList = cmds.ls(type=['mesh', 'nurbsCurve', 'nurbsCurve'])
    if shapeList: cmds.reorder(shapeList, b=True)

    # Print Timed Result
    print('# Clean Rig: Reorder Shapes - ' + str(cmds.timerX(st=timer)))
Ejemplo n.º 34
0
def dagSort(objectList=[]):
    """
    Sort the list of DAG objects in the hierarchy
    @param objectList: List of DAG object to sort. If empty, use current selection.
    @type objectList: list
    """
    # Check Object List
    if not objectList:
        objectList = cmds.ls(sl=1)
        objectList = cmds.listRelatives(objectList, ad=True)
        objectList = cmds.ls(objectList, transforms=True)

    # Sort Object List
    objectList.sort()
    objectList.reverse()

    # Reorder Objects
    for i in objectList:
        cmds.reorder(i, f=True)

    # Return Result
    return objectList
Ejemplo n.º 35
0
def dagSort(objectList=[]):
	'''
	Sort the list of DAG objects in the hierarchy
	@param objectList: List of DAG object to sort. If empty, use current selection.
	@type objectList: list
	'''
	# Check Object List
	if not objectList:
		objectList = mc.ls(sl=1)
		objectList = mc.listRelatives(objectList,ad=True)
		objectList = mc.ls(objectList,transforms=True)

	# Sort Object List
	objectList.sort()
	objectList.reverse()

	# Reorder Objects
	for i in objectList:
		mc.reorder(i,f=True)

	# Return Result
	return objectList
Ejemplo n.º 36
0
def reorderShapes():
    """
    """
    # Start Timer
    timer = cmds.timerX()

    print(
        'Reordering Constraints Nodes (push constraints to end of child list)')
    constraintList = cmds.ls(type='constraint')
    if constraintList: cmds.reorder(constraintList, b=True)

    # Print Timed Result
    print('# Clean Rig: Reorder Constraints - ' + str(cmds.timerX(st=timer)))

    # Start Timer
    timer = cmds.timerX()

    print('Reordering Shape Nodes (push shapes to end of child list)')
    shapeList = cmds.ls(type=['mesh', 'nurbsCurve', 'nurbsCurve'])
    if shapeList: cmds.reorder(shapeList, b=True)

    # Print Timed Result
    print('# Clean Rig: Reorder Shapes - ' + str(cmds.timerX(st=timer)))
	def groupChildren(self,type='asc'):
		groups = cmds.ls( sl=True )
		for group in groups:
			groupChildren = cmds.listRelatives(group, children=True, pa=True)

			childrenDictionary = {}
			for item in groupChildren:
				key = item.split('|')[-1]
				childrenDictionary[key] = item

			childrenKeys = childrenDictionary.keys()
			if type == 'asc':
				childrenKeys.sort()
			elif type == 'desc':
				childrenKeys.sort(reverse=True)
			else:
				return None

			sortChildren = []
			for key in childrenKeys:
				sortChildren.append(childrenDictionary[key])

			for item in sortChildren:
				cmds.reorder( item, back=True )
Ejemplo n.º 38
0
    def testUndoRedo(self):
        ''' 
            Undo/Redo reorder command
        '''
        # create multiple item
        capsulePath = ufe.PathString.path(
            "|Primitives_usd|Primitives_usdShape,/Xform1/Capsule1")
        capsuleItem = ufe.Hierarchy.createItem(capsulePath)

        conePath = ufe.PathString.path(
            "|Primitives_usd|Primitives_usdShape,/Xform1/Cone1")
        coneItem = ufe.Hierarchy.createItem(conePath)

        cubePath = ufe.PathString.path(
            "|Primitives_usd|Primitives_usdShape,/Xform1/Cube1")
        cubeItem = ufe.Hierarchy.createItem(cubePath)

        # move items forward ( + )
        cmds.reorder(ufe.PathString.string(capsulePath), r=3)
        cmds.reorder(ufe.PathString.string(conePath), r=3)
        cmds.reorder(ufe.PathString.string(cubePath), r=3)

        # check positions
        self.assertEqual(findIndex(capsuleItem), 1)
        self.assertEqual(findIndex(coneItem), 2)
        self.assertEqual(findIndex(cubeItem), 3)

        # undo
        for _ in range(3):
            cmds.undo()

        # check positions
        self.assertEqual(findIndex(capsuleItem), 0)
        self.assertEqual(findIndex(coneItem), 1)
        self.assertEqual(findIndex(cubeItem), 2)

        # redo
        for _ in range(3):
            cmds.redo()

        # check positions
        self.assertEqual(findIndex(capsuleItem), 1)
        self.assertEqual(findIndex(coneItem), 2)
        self.assertEqual(findIndex(cubeItem), 3)
Ejemplo n.º 39
0
    def comRenReorder(self, _=False):
        self.comRenList = cmds.ls(sl=True)

        sorted(self.comRenList)
        for i in reversed(self.comRenList):
            cmds.reorder(i, front=True)
Ejemplo n.º 40
0
def setOrder(obj, nr):
    '''
    just to have this inline to use in conjunction with the getOrder function
    '''
    m.reorder(obj, front=True)
    m.reorder(obj, relative=nr)
Ejemplo n.º 41
0
def createIntermediate(shape):
	'''
	Create and connect an intermediate shape for the specified geoemtry shape
	@param shape: Shape or create intermediate shape for
	@type shape: str
	'''
	# ==========
	# - Checks -
	# ==========
	
	# Check Shape
	if not mc.objExists(shape):
		raise Exception('Object "'+shape+'" does not exist!!')
	
	# Check Geometry Type
	geoType = mc.objectType(shape)
	if geoType == 'transform':
		shapes = getShapes(shape,intermediates=False)
		if not shapes: raise Exception('Object "'+shape+'" has no valid shapes!!')
		shape = shapes[0]
		geoType = mc.objectType(shape)
	
	# Check In/Out Attributes
	geoDict = {'mesh':('outMesh','inMesh'),'nurbsSurface':('local','create'),'nurbsCurve':('local','create')}
	if not geoDict.has_key(geoType): raise Exception('Invalid shape type ('+geoType+') for "'+shape+'"!!')
	
	# =============================
	# - Create Intermediate Shape -
	# =============================
	
	# Get Shape Node from Transform
	transform = str(mc.listRelatives(shape,p=True)[0])
	
	# Rename Current Shape as Intermediate
	shapeOrig = mc.rename(shape,shape+'Orig')
	
	# Create New Shape
	shape = mc.createNode(geoType,n=shape,p=transform)
	mc.connectAttr(shapeOrig+'.'+geoDict[geoType][0],shape+'.'+geoDict[geoType][1],f=True)
	mc.setAttr(shapeOrig+'.intermediateObject',1)
	mc.reorder(shape,f=True)
	
	# Connect Shader
	shader = mc.listConnections(shapeOrig,type='shadingEngine')
	if shader:
		mc.sets(shapeOrig,rm=shader[0])
		mc.sets(shape,fe=shader[0])
	
	# Update Outgoing Connections
	outConn = mc.listConnections(shapeOrig,s=False,d=True,p=True,c=True)
	for i in range(0,len(outConn),2):
		# Check Connection Destination
		dst = outConn[i+1]
		if shape in dst: continue
		# Check Connection Source
		src = outConn[i].replace(shapeOrig,shape)
		if mc.objExists(src):
			print('New source connection: '+src)
		else:
			print('Source connection "'+src+'" does not exist! Skipping...')
			continue
		# Update Connection
		mc.connectAttr(src,dst,f=True)
	
	# =================
	# - Return Result -
	# =================
	
	return shapeOrig
Ejemplo n.º 42
0
def projectToSurface(surface,
                     targetSurface,
                     direction='u',
                     keepOriginal=False,
                     prefix=''):
    """
    Project the edit points of the specified nurbs surface to another nurbs or polygon object
    @param surface: Surface to project
    @type surface: str
    @param targetSurface: Surface to project onto
    @type targetSurface: str
    @param direction: Surface direction to extract isoparm curves from
    @type direction: str
    @param keepOriginal: Create new surface or replace original
    @type keepOriginal: bool
    @param prefix: Name prefix for all created nodes
    @type prefix: str
    """
    # Check surface
    if not cmds.objExists(surface):
        raise Exception('Surface "' + surface + '" does not exist!!')
    if not isSurface(surface):
        raise Exception('Object "' + surface +
                        '" is not a valid nurbs surface!!')

    # Check target surface
    if not cmds.objExists(targetSurface):
        raise Exception('Target surface "' + targetSurface +
                        '" does not exist!!')

    # Check prefix
    if not prefix: prefix = glTools.utils.stringUtils.stripSuffix(surface)

    # Check direction
    direction = direction.upper()
    if (direction != 'U') and (direction != 'V'):
        raise Exception(
            'Invalid surface direction specified! Must specify either "u" or "v"!!'
        )

    # Get surface information
    spans = cmds.getAttr(surface + '.spans' + direction)
    minVal = cmds.getAttr(surface + '.minValue' + direction)
    maxVal = cmds.getAttr(surface + '.maxValue' + direction)

    # Create main surface group
    mainGrp = cmds.createNode('transform', n=prefix + '_grp')

    # Extract curves
    curveList = []
    curveGrpList = []
    curveLocList = []
    geocmdsonstraintList = []
    spanInc = (maxVal - minVal) / spans
    for i in range(spans + 1):
        # Curve prefix
        strInd = glTools.utils.stringUtils.stringIndex(i, 2)
        crvPrefix = prefix + '_crv' + strInd
        # Create curve group
        curveGrp = crvPrefix + '_grp'
        curveGrp = cmds.createNode('transform', n=curveGrp)
        curveGrp = cmds.parent(curveGrp, mainGrp)[0]
        curveGrpList.append(curveGrp)
        # Get surface curve
        srfCurveName = crvPrefix + '_crv'
        srfCurve = cmds.duplicateCurve(surface + '.' + direction.lower() +
                                       '[' + str(i * spanInc) + ']',
                                       ch=0,
                                       rn=0,
                                       local=0,
                                       n=srfCurveName)
        srfCurve = cmds.parent(srfCurve[0], curveGrp)[0]
        curveList.append(srfCurve)
        # Generate curve locators
        curveLocatorList = glTools.utils.curve.locatorEpCurve(
            srfCurve, locatorScale=0.05, prefix=crvPrefix)
        curveLocatorList = cmds.parent(curveLocatorList, curveGrp)
        curveLocList.append(curveLocatorList)
        # Create geometry constraints
        for loc in curveLocatorList:
            geocmdsonstraint = crvPrefix + '_geometryConstraint'
            geocmdsonstraint = cmds.geometryConstraint(targetSurface,
                                                       loc,
                                                       n=geocmdsonstraint)
            geocmdsonstraintList.append(geocmdsonstraint[0])
        # Center group pivot
        cmds.xform(curveGrp, cp=True)

    # Delete original surface
    surfaceName = prefix + '_surface'
    if not keepOriginal:
        surfaceName = surface
        cmds.delete(surface)

    # Loft new surface
    surfaceLoft = cmds.loft(curveList,
                            ch=1,
                            u=1,
                            c=0,
                            ar=1,
                            d=3,
                            ss=1,
                            rn=0,
                            po=0,
                            rsn=True)
    surface = cmds.rename(surfaceLoft[0], surface)
    surface = cmds.parent(surface, mainGrp)[0]
    cmds.reorder(surface, f=True)
    loft = cmds.rename(surfaceLoft[1], prefix + '_loft')

    # Return result
    return [
        surface, loft, curveList, curveGrpList, curveLocList,
        geocmdsonstraintList
    ]
Ejemplo n.º 43
0
def FKAutoRig():
    #Closes windows
    if cmds.window("Rig1", q=True, ex=True):
        cmds.deleteUI("Rig1")
    if cmds.window("Rig2", q=True, ex=True):
        cmds.deleteUI("Rig2")
    #Error handeling
    if cmds.nodeType(cmds.ls(sl=True)) == None:
        message = "You must have a joint in your selection."
        cmds.warning(message)
        makeGUI2(message)
        return
    elif cmds.nodeType(cmds.ls(sl=True)) != "joint":
        message = "You must select the top joint of the chain you wish to a control rig for."
        cmds.warning(message)
        makeGUI2(message)
        return
    else:

        #Original Joint List
        #Also fills the list with everything below the selection
        cmds.SelectHierarchy()
        OJL = cmds.ls(sl=True)
        #FK Joint List
        FKJL = []
        IKJL = []
        count = 0
        FKHndleRatio = .5
        IKHndleRatio = 1
        anklIndex = 2  #assumes the third joint will be the ankle
        #Extra variables to make scaling the tool easier
        skipLastJoint = False
        addConstraints = True

        #Create IK/FK switch Controller
        cmds.circle(name="IK_FK_Switch", nr=(0, 1, 0), c=(0, 0, 0), r=1)
        cmds.color(rgb=(0, 1, 1))
        cmds.pointConstraint(str(OJL[0]), "IK_FK_Switch")
        cmds.delete("IK_FK_Switch_pointConstraint1")
        cmds.makeIdentity("IK_FK_Switch",
                          apply=True,
                          t=True,
                          r=True,
                          s=True,
                          n=False,
                          pn=True)
        cmds.move(5, 0, 0)
        #Lock channels
        cmds.setAttr("IK_FK_Switch.sx",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        cmds.setAttr("IK_FK_Switch.sy",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        cmds.setAttr("IK_FK_Switch.sz",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        cmds.setAttr("IK_FK_Switch.rx",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        cmds.setAttr("IK_FK_Switch.ry",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        cmds.setAttr("IK_FK_Switch.rz",
                     channelBox=False,
                     lock=True,
                     keyable=False)
        #Add IK and FK attributes
        cmds.addAttr(ln="Streatch_Tolerance", at="float",
                     dv=0)  #AddStreatchy Offset
        cmds.setAttr("IK_FK_Switch.Streatch_Tolerance",
                     channelBox=True,
                     l=False)
        cmds.setAttr("IK_FK_Switch.Streatch_Tolerance", k=True)
        cmds.addAttr(ln="IK", at="float", min=0, max=1, dv=0)  #AddIK
        cmds.setAttr("IK_FK_Switch.IK", channelBox=True, l=False)
        cmds.setAttr("IK_FK_Switch.IK", k=True)
        cmds.addAttr(ln="FK", at="float", min=0, max=1, dv=1)  #AddFK
        cmds.setAttr("IK_FK_Switch.FK", channelBox=True, l=False)
        cmds.setAttr("IK_FK_Switch.FK", k=True)

        #Creates new FK Skeleton identicle to the original skeleton
        cmds.JointTool()
        for jnt in OJL:
            rad = str(cmds.joint(OJL[count], q=True,
                                 rad=True)).replace("[", "")
            newrad = rad.replace("]", "")
            cmds.joint(p=cmds.xform(jnt, q=True, t=True, ws=True),
                       rad=float(newrad))
            FKJL.append(cmds.ls(sl=True))
            count += 1
        count = 0
        maya.mel.eval("escapeCurrentTool;")

        #Renames, orients and colors the new FK skeleton
        for jnt in FKJL:
            FKJL[count] = cmds.rename(jnt, str(OJL[count] + "_FK_CTRL"))
            cmds.orientConstraint(str(OJL[count]),
                                  str(OJL[count] + "_FK_CTRL"))
            cmds.pointConstraint(str(OJL[count]), str(OJL[count] + "_FK_CTRL"))
            cmds.delete(OJL[count] + "_FK_CTRL_orientConstraint1",
                        OJL[count] + "_FK_CTRL_pointConstraint1")
            cmds.select(OJL[count] + "_FK_CTRL")
            cmds.makeIdentity(apply=True,
                              t=True,
                              r=True,
                              s=True,
                              n=False,
                              pn=True)  #Freze transforms
            cmds.color(rgb=(0, 0, 1))
            #Sets up handles on the new FK skeleton and preps it for use
            if count > 0:
                cmds.setAttr(FKJL[count] + ".tx",
                             channelBox=False,
                             lock=True,
                             keyable=False)
                cmds.setAttr(FKJL[count] + ".ty",
                             channelBox=False,
                             lock=True,
                             keyable=False)
                cmds.setAttr(FKJL[count] + ".tz",
                             channelBox=False,
                             lock=True,
                             keyable=False)
            cmds.setAttr(FKJL[count] + ".sx",
                         channelBox=False,
                         lock=True,
                         keyable=False)
            cmds.setAttr(FKJL[count] + ".sy",
                         channelBox=False,
                         lock=True,
                         keyable=False)
            cmds.setAttr(FKJL[count] + ".sz",
                         channelBox=False,
                         lock=True,
                         keyable=False)
            cmds.setAttr(FKJL[count] + ".radi",
                         channelBox=False,
                         lock=True,
                         keyable=False)
            #Adds Constraints
            if addConstraints == True:
                cmds.orientConstraint(FKJL[count], OJL[count], mo=True)
                if count < 1:
                    cmds.scaleConstraint(FKJL[count], OJL[count], mo=False)
        #Adds Curves
            if count < len(
                    FKJL
            ) - 1 and skipLastJoint == False:  #Skips the final joint as it shouldn't need a controll
                rad = cmds.xform(OJL[count + 1], q=True, t=True,
                                 r=True)[0] * FKHndleRatio
                cmds.circle(name="crv_" + str(count),
                            nr=(1, 0, 0),
                            c=(0, 0, 0),
                            r=rad)
                cmds.select("crv_" + str(count) + "Shape", r=True)
                cmds.select(str(OJL[count] + "_FK_CTRL"), tgl=True)
                cmds.parent(r=True, s=True)
                cmds.select("crv_" + str(count) + "Shape", r=True)
                cmds.rename("FK_" + OJL[count] + "Shape")
                cmds.color(rgb=(0, 0, 1))
                cmds.select("crv_" + str(count), r=True)
                cmds.delete()
                cmds.select(cl=True)
            elif count < len(FKJL) and skipLastJoint == True:
                rad = cmds.xform(OJL[count + 1], q=True, t=True,
                                 r=True)[0] * FKHndleRatio
                cmds.circle(name="crv_" + str(count),
                            nr=(1, 0, 0),
                            c=(0, 0, 0),
                            r=rad)
                cmds.select("crv_" + str(count) + "Shape", r=True)
                cmds.select(str(OJL[count] + "_FK_CTRL"), tgl=True)
                cmds.parent(r=True, s=True)
                cmds.select("crv_" + str(count), r=True)
                cmds.delete()
                cmds.select(cl=True)
            count += 1

#////////// Now working on IK \\\\\\\\\\

#Creates new FK Skeleton identicle to the original skeleton
        count = 0
        cmds.JointTool()
        for jnt in OJL:
            rad = str(cmds.joint(OJL[count], q=True,
                                 rad=True)).replace("[", "")
            newrad = rad.replace("]", "")
            cmds.joint(p=cmds.xform(jnt, q=True, t=True, ws=True),
                       rad=float(newrad))
            IKJL.append(cmds.ls(sl=True))
            count += 1
        count = 0
        maya.mel.eval("escapeCurrentTool;")

        #Creates IK controller
        cmds.spaceLocator(p=cmds.xform(OJL[0], q=True, t=True, ws=True))
        cmds.rename("loc1")
        cmds.pointConstraint(OJL[anklIndex], "loc1")
        locPos = cmds.xform("loc1", q=True, t=True, ws=True)
        IKRad = locPos[0] + locPos[1] + locPos[2]
        IKRad = IKRad * IKHndleRatio
        cmds.delete("loc1")
        cmds.circle(name="Leg_IK_Main_CTRL",
                    nr=(0, 1, 0),
                    c=(0, 0, 0),
                    r=IKRad)
        cmds.color(rgb=(1, 0, 0))
        cmds.pointConstraint(OJL[anklIndex], "Leg_IK_Main_CTRL")
        cmds.delete("Leg_IK_Main_CTRL_pointConstraint1")
        cmds.makeIdentity("Leg_IK_Main_CTRL",
                          apply=True,
                          t=True,
                          r=True,
                          s=True,
                          n=False,
                          pn=True)
        #Renames, orients and colors the new FK skeleton
        for jnt in IKJL:
            IKJL[count] = cmds.rename(jnt, str(OJL[count] + "_IK_CTRL"))
            cmds.orientConstraint(str(OJL[count]),
                                  str(OJL[count] + "_IK_CTRL"))
            cmds.pointConstraint(str(OJL[count]), str(OJL[count] + "_IK_CTRL"))
            cmds.delete(OJL[count] + "_IK_CTRL_orientConstraint1",
                        OJL[count] + "_IK_CTRL_pointConstraint1")
            cmds.select(OJL[count] + "_IK_CTRL")
            cmds.makeIdentity(apply=True,
                              t=True,
                              r=True,
                              s=True,
                              n=False,
                              pn=True)  #Freze transforms
            cmds.color(rgb=(1, 0, 0))
            #Preps IK skeliton for use
            if count > 0:
                cmds.setAttr(IKJL[count] + ".tx",
                             channelBox=False,
                             lock=True,
                             keyable=False)
                cmds.setAttr(IKJL[count] + ".ty",
                             channelBox=False,
                             lock=True,
                             keyable=False)
                cmds.setAttr(IKJL[count] + ".tz",
                             channelBox=False,
                             lock=True,
                             keyable=False)
            #cmds.setAttr(IKJL[count]+".sx", channelBox=False, lock=True, keyable=False)
            #cmds.setAttr(IKJL[count]+".sy", channelBox=False, lock=True, keyable=False)
            #cmds.setAttr(IKJL[count]+".sz", channelBox=False, lock=True, keyable=False)
            cmds.setAttr(IKJL[count] + ".radi",
                         channelBox=False,
                         lock=True,
                         keyable=False)
            #Adds constraints
            if addConstraints == True:
                cmds.orientConstraint(IKJL[count], OJL[count], mo=True)
                cmds.scaleConstraint(IKJL[count], OJL[count], mo=False)
            count += 1

        #Creates IK solver and moves it under IK controller
        cmds.ikHandle(n="IKLeg", sj=IKJL[0], ee=IKJL[anklIndex])
        cmds.parent("IKLeg", "Leg_IK_Main_CTRL")
        cmds.ikHandle(n="IKFoot", sj=IKJL[anklIndex], ee=IKJL[anklIndex + 1])
        cmds.parent("IKFoot", "Leg_IK_Main_CTRL")

        #Outliner cleanup
        #IK
        cmds.group(em=True, name=OJL[0] + "_IK_GRP")
        cmds.parent(str(IKJL[0]), OJL[0] + "_IK_GRP")
        cmds.parent("Leg_IK_Main_CTRL", OJL[0] + "_IK_GRP")
        #FK
        cmds.group(em=True, name=OJL[0] + "_FK_GRP")
        cmds.parent(str(FKJL[0]), OJL[0] + "_FK_GRP")
        #Move switch in outliner
        cmds.reorder("IK_FK_Switch", r=2)
        #Hide Bound Chain
        cmds.setAttr(OJL[0] + ".visibility", 0)

        #Connects constraints to IK_FK_Switch
        count = 0
        for jnt in OJL:
            cmds.connectAttr("IK_FK_Switch.IK",
                             jnt + "_orientConstraint1." + jnt + "_IK_CTRLW1")
            cmds.connectAttr("IK_FK_Switch.FK",
                             jnt + "_orientConstraint1." + jnt + "_FK_CTRLW0")
            if count < 1:
                cmds.connectAttr(
                    "IK_FK_Switch.IK",
                    jnt + "_scaleConstraint1." + jnt + "_IK_CTRLW1")
                cmds.connectAttr(
                    "IK_FK_Switch.FK",
                    jnt + "_scaleConstraint1." + jnt + "_FK_CTRLW0")
            count += 1
        cmds.connectAttr("IK_FK_Switch.FK", OJL[0] + "_FK_GRP.visibility")
        cmds.connectAttr("IK_FK_Switch.IK", OJL[0] + "_IK_GRP.visibility")

        #Creates 1-x relationship in IK/FK switch controller
        cmds.expression(s="IK_FK_Switch.FK = 1-IK_FK_Switch.IK",
                        o="IK_FK_Switch",
                        ae=1,
                        uc="all")
        cmds.setAttr("IK_FK_Switch.FK", k=False, cb=False)

        #Set up Streatchy joints
        cmds.spaceLocator(n=str(OJL[0] + "_LOCATOR"))  #Locator 1
        cmds.pointConstraint(str(IKJL[0]), OJL[0] + "_LOCATOR")
        cmds.spaceLocator(n=str(OJL[anklIndex] + "_LOCATOR"))  #Locator2
        cmds.pointConstraint("Leg_IK_Main_CTRL", OJL[anklIndex] + "_LOCATOR")
        cmds.parent(OJL[0] + "_LOCATOR", OJL[anklIndex] + "_LOCATOR",
                    OJL[0] + "_IK_GRP")

        #Get max offset distance (Streatch Tolerance)
        length1 = cmds.getAttr(OJL[1] + ".translateX")
        length2 = cmds.getAttr(OJL[2] + ".translateX")
        distance = length1 + length2
        distance = distance * 100
        distance = floor(distance)  #Floor to stop snapping.
        distance = distance / 100
        cmds.setAttr("IK_FK_Switch.Streatch_Tolerance", distance)
        cmds.createNode("distanceBetween",
                        n=OJL[0] + "_distanceBetween")  #DistanceBetween
        cmds.connectAttr(OJL[0] + "_LOCATOR.translate",
                         OJL[0] + "_distanceBetween.point1")
        cmds.connectAttr(OJL[anklIndex] + "_LOCATOR.translate",
                         OJL[0] + "_distanceBetween.point2")

        #Create condition logic
        cmds.createNode("condition",
                        n=OJL[0] + "_streatchCondition")  #Create <= Condition
        cmds.setAttr(OJL[0] + "_streatchCondition.operation", 3)
        cmds.connectAttr(OJL[0] + "_distanceBetween.distance",
                         OJL[0] + "_streatchCondition.firstTerm")
        cmds.connectAttr(OJL[0] + "_distanceBetween.distance",
                         OJL[0] + "_streatchCondition.colorIfTrueR")
        cmds.setAttr(OJL[0] + "_streatchCondition.secondTerm", distance)
        cmds.setAttr(OJL[0] + "_streatchCondition.colorIfFalseR", distance)

        #Create streatch fraction
        cmds.createNode("multiplyDivide", n=OJL[0] + "_streatchFraction")
        cmds.connectAttr(OJL[0] + "_streatchCondition.outColorR",
                         OJL[0] + "_streatchFraction.input1X")
        cmds.setAttr(OJL[0] + "_streatchFraction.input2X", distance)
        cmds.setAttr(OJL[0] + "_streatchFraction.operation", 2)

        #Create inverse fraction
        cmds.createNode("multiplyDivide", n=OJL[0] + "_inverseFraction")
        cmds.connectAttr(OJL[0] + "_streatchFraction.outputX",
                         OJL[0] + "_inverseFraction.input2X")
        cmds.setAttr(OJL[0] + "_inverseFraction.input1X", 1)
        cmds.setAttr(OJL[0] + "_inverseFraction.operation", 2)

        #Connect first 2 joints
        count = 0
        while count < anklIndex:
            cmds.connectAttr(OJL[0] + "_streatchFraction.outputX",
                             IKJL[count] + ".scaleX")
            cmds.connectAttr(OJL[0] + "_inverseFraction.outputX",
                             IKJL[count] + ".scaleY")
            cmds.connectAttr(OJL[0] + "_inverseFraction.outputX",
                             IKJL[count] + ".scaleZ")
            count += 1

        print "Now you have an awesome rig!"
Ejemplo n.º 44
0
    def anchorCurve(self, control, anchor, template=True, selectable=False):
        '''
		Create an anchor curve for the specified control.
		@param control: The control object to create an anchor curve for.
		@type control: str
		@param anchor: The transform that the anchor curve will be attached to for.
		@type anchor: str
		@param template: Set the anchor curve override type to template
		@type template: bool
		'''
        # Check control
        if not mc.objExists(control):
            raise Exception('Control "' + control + '" does not exist!')
        if not mc.objExists(anchor):
            raise Exception('Anchor transform "' + anchor +
                            '" does not exist!')

        # Create curve shape
        crv = mc.curve(p=[(0, 0, 0), (0, 1, 0)],
                       k=[0, 1],
                       d=1,
                       n=control + 'Anchor')
        crvShape = mc.listRelatives(crv, s=True, pa=True)
        if not crvShape:
            raise Exception('Unable to determine shape for curve "' + crv +
                            '"!')

        # Create Curve Locators
        crvLoc = glTools.utils.curve.locatorCurve(crv,
                                                  locatorScale=0.0,
                                                  local=True,
                                                  prefix=control)
        mc.parent(crvLoc, control)
        mc.setAttr(crvLoc[0] + '.t', 0, 0, 0)
        mc.setAttr(crvLoc[1] + '.t', 0, 0, 0)
        mc.setAttr(crvLoc[0] + '.v', 0)
        mc.setAttr(crvLoc[1] + '.v', 0)

        # Rename and Parent curve shape
        crvShape = mc.parent(crvShape[0], control, r=True, s=True)[0]
        crvShape = mc.rename(crvShape, control + 'Shape0')
        mc.reorder(crvShape, b=True)

        # Colour Curve Shape - Light Grey
        mc.setAttr(crvShape + '.overrideEnabled', 1)
        mc.setAttr(crvShape + '.overrideColor', 3)  # Light Grey

        # Delete Original Curve Transform
        mc.delete(crv)

        # Connect to anchor
        mc.pointConstraint(anchor, crvLoc[1])

        # Template
        if template:
            glTools.utils.base.displayOverride(crvShape,
                                               overrideEnable=1,
                                               overrideDisplay=1)

        # Set channel states
        glTools.utils.channelState.ChannelState().setFlags(
            [2, 2, 2, 2, 2, 2, 2, 2, 2, 1], crvLoc)

        # Return result
        return crvShape
Ejemplo n.º 45
0
def follicleRivet(surface, baseName=None, U=0.5, V=0.5, attr=False, shape=True, p=None):
    '''
    Create follicle on surface as a rivet hook
    #    return rivet

    Options:
    -baseName (string): base name string used as prefix for all nodes
    -U (float): u placement
    -v (float): v placement
    -attr (bool): add U and V position option attributes to rivet
    -shape (bool): add locator shaped curve to rivet
    -p (node): rivet target parent node

    author: guillaume barlier
    '''
    #    sanity check
    surface, surfaceShp = shapeFunctions.filterShpAndTransform(surface)
    if not (surface and surfaceShp):
        return

    #    define baseName
    if not baseName:
        baseName    =   'rivet'

    #    create follicle
    follicleShp =   cmds.createNode('follicle')
    follicle    =   cmds.listRelatives(follicleShp, p=True)[0]
    cmds.setAttr('%s.inheritsTransform'%follicle, 0)

    cmds.connectAttr('%s.outRotate'%follicleShp, '%s.rotate'%follicle, f=True)
    cmds.connectAttr('%s.outTranslate'%follicleShp, '%s.translate'%follicle, f=True)

    #    set U V
    cmds.setAttr('%s.pu'%follicleShp, U)
    cmds.setAttr('%s.pv'%follicleShp, V)

    #    rename follicle (createNode create the shape)
    follicle    =   cmds.rename(follicle, baseName)
    follicleShp =   cmds.listRelatives(follicle, s=True)[0]

    #    connect surface to follicle
    cmds.connectAttr('%s.worldMatrix[0]'%surfaceShp, '%s.inputWorldMatrix'%follicleShp, f=True)
    if cmds.nodeType(surfaceShp) == 'nurbsSurface':
        cmds.connectAttr('%s.local'%surfaceShp, '%s.inputSurface'%follicleShp, f=True)
    elif cmds.nodeType(surfaceShp) == 'mesh':
        cmds.connectAttr('%s.worldMesh[0]'%surfaceShp, '%s.inputMesh'%follicleShp, f=True)

    #    add curve locator shape
    locatorShp  =   None
    if shape:
        #    rename.hide follicle shape
        follicleShp = cmds.rename(follicleShp, baseName+'FollicleShape')
        cmds.setAttr('%s.v'%follicleShp, 0)

        #    add curve locator shape
        locatorShp  =    handleFunctions.curveLocator(baseName+'CrvLoc', p=follicle, s=True)
        cmds.reorder(locatorShp, front=True )
        controlFunctions.colorShape([locatorShp], 4)

    #    add custom attribute
    if attr:
        attributeFunctions.createSeparator(follicle)
        cmds.addAttr(follicle, ln='parameterU', sn='pu', at='double')
        cmds.setAttr('%s.pu'%follicle, U, k=True)
        cmds.connectAttr('%s.pu'%follicle, '%s.pu'%follicleShp, f=True)

        cmds.addAttr(follicle, ln='parameterV', sn='pv', at='double')
        cmds.setAttr('%s.pv'%follicle, V, k=True)
        cmds.connectAttr('%s.pv'%follicle, '%s.pv'%follicleShp, f=True)

    #    parent rivet
    if p and cmds.objExists(p):
        cmds.parent(follicle, p)

    #    clean and lock
    attributeFunctions.lockAndHideTransforms(follicle)
    attributeFunctions.lockAll(follicleShp)
    cmds.select(cl=True)

    return follicle
Ejemplo n.º 46
0
    def __init__(self, characterName, scale=GLOBAL_SCALE, mesh='', parentJoint='', geoList=[], builder=''):
        # Sanity check
        print('__init__ from "Base" class to build rig folder structure')

        # create "folder structure"
        self.global_group = cmds.group(name=characterName + '_globalSystem_grp', em=True)
        self.components_group = cmds.group(name=characterName + '_components_grp', em=True)
        self.geometry_group = cmds.group(name=characterName + '_geometries_grp', em=True)
        self.rigging_group = cmds.group(name=characterName + '_rigging_grp', em=True)
        self.joints_group = cmds.group(name=characterName + '_joints_grp', em=True)
        self.noXform_group = cmds.group(name=characterName + '_noXform_grp', em=True)
        self.noXformHead_group = cmds.group(name=characterName + '_noXformHead_grp', em=True)
        self.noXformBodybody_group = cmds.group(name=characterName + '_noXformBody_grp', em=True)
        self.facialRig_group = cmds.group(name=characterName + '_facialRig_grp', em=True)
        self.bodyRig_group = cmds.group(name=characterName + '_bodyRig_grp', em=True)

        # parenting I
        cmds.parent(self.components_group, self.global_group)
        cmds.parent(self.geometry_group, self.rigging_group, self.joints_group, self.noXform_group, self.components_group)
        cmds.parent(self.noXformHead_group, self.noXformBodybody_group, self.noXform_group)
        cmds.parent(self.facialRig_group, self.bodyRig_group, self.rigging_group)

        # no xform group set attribute
        cmds.setAttr(self.noXform_group + '.it', False, lock=True)

        reorder = [self.geometry_group, self.joints_group, self.noXform_group, self.rigging_group]
        for grp in reorder:
            cmds.reorder(grp, back=True)

        char_name_attr = 'characterName'
        scene_objectType_attr = 'scene_objectType'

        for att in [char_name_attr, scene_objectType_attr]:
            cmds.addAttr(self.global_group, ln=att, dt='string')

        cmds.setAttr(self.global_group + '.' + char_name_attr, characterName, type='string', lock=True)
        cmds.setAttr(self.global_group + '.' + scene_objectType_attr, SCENE_OBJECT_TYPE, type='string', lock=True)

        # make controls
        global_control_obj = None

        if mesh and cmds.objExists(mesh):
            global_control_obj = control.Control(prefix=characterName + '_global', scale=tools.get_boundingBoxSize(mesh), translateTo=mesh, parent=self.bodyRig_group, lockChannels=['v'])
        else:
            global_control_obj = control.Control(prefix=characterName + '_global', scale=scale * 40, parent=self.bodyRig_group, lockChannels=['v'])

        # add global scale attribute
        cmds.addAttr(global_control_obj.control, ln='globalScale', at='float', k=True, defaultValue=1.0, minValue=0.2)
        for axis in 'xyz':
            cmds.connectAttr(global_control_obj.control + '.globalScale', global_control_obj.control + '.s%s' % axis)

        main_visibility_attr = ['modelVis', 'jointsVis']
        main_display_attr = ['modelDisplay', 'jointsDisplay']
        obj_to_add_attrs = [self.geometry_group, self.joints_group]

        # add rig visibility connections
        for at, obj in zip(main_visibility_attr, obj_to_add_attrs):
            cmds.addAttr(global_control_obj.control, ln=at, at='enum', enumName='off:on', k=True, defaultValue=True)
            cmds.setAttr(global_control_obj.control + '.' + at, cb=True)
            cmds.connectAttr(global_control_obj.control + '.' + at, obj + '.v')

        # add rig display connections
        for at, obj in zip(main_display_attr, obj_to_add_attrs):
            cmds.addAttr(global_control_obj.control, ln=at, at='enum', enumName='normal:template:reference', k=True)
            cmds.setAttr(global_control_obj.control + '.' + at, cb=True)
            cmds.setAttr(obj + '.ove', True)
            cmds.connectAttr(global_control_obj.control + '.' + at, obj + '.ovdt')

        global_control_obj.lockChannels = ['s']
        global_control_obj.lock_control_channels()

        cmds.addAttr(global_control_obj.control, shortName='cntRig', longName='ConnectRig', at='bool', defaultValue=1, k=True)
        cmds.setAttr(global_control_obj.control + '.ConnectRig', cb=True)

        if parentJoint:
            cmds.parent(parentJoint, self.joints_group)

        if geoList:
            cmds.parent(geoList, self.geometry_group)

        if builder:
            cmds.delete(builder)

        ############
        # Public members
        self.global_control_obj = global_control_obj
Ejemplo n.º 47
0
        objList = mc.ls(sl=1)
    else:
        objList = VALID.mNodeStringList(objList)
    log.info("|{0}| >> ObjList: {1} ".format(_str_func, objList))

    d_p = {}
    l_p = []
    l_world = []

    for o in objList:
        p = TRANS.parent_get(o)
        if not p:
            l_world.append(o)
        elif p not in l_p:
            l = TRANS.children_get(p) or []
            l.sort()
            l.reverse()
            for c in l:
                try:
                    mc.reorder(c, front=True)
                except Exception, err:
                    print err

    if l_world:
        l_world.sort()
        for o in l_world:
            try:
                mc.reorder(o, front=True)
            except Exception, err:
                print err
Ejemplo n.º 48
0
def createIntermediate(shape):
    """
    Create and connect an intermediate shape for the specified geoemtry shape
    @param shape: Shape or create intermediate shape for
    @type shape: str
    """
    # ==========
    # - Checks -
    # ==========

    # Check Shape
    if not cmds.objExists(shape):
        raise Exception('Object "' + shape + '" does not exist!!')

    # Check Geometry Type
    geoType = cmds.objectType(shape)
    if geoType == 'transform':
        shapes = getShapes(shape, intermediates=False)
        if not shapes:
            raise Exception('Object "' + shape + '" has no valid shapes!!')
        shape = shapes[0]
        geoType = cmds.objectType(shape)

    # Check In/Out Attributes
    geoDict = {
        'mesh': ('outMesh', 'inMesh'),
        'nurbsSurface': ('local', 'create'),
        'nurbsCurve': ('local', 'create')
    }
    if not geoDict.has_key(geoType):
        raise Exception('Invalid shape type (' + geoType + ') for "' + shape +
                        '"!!')

    # =============================
    # - Create Intermediate Shape -
    # =============================

    # Get Shape Node from Transform
    transform = str(cmds.listRelatives(shape, p=True)[0])

    # Rename Current Shape as Intermediate
    shapeOrig = cmds.rename(shape, shape + 'Orig')

    # Create New Shape
    shape = cmds.createNode(geoType, n=shape, p=transform)
    cmds.connectAttr(shapeOrig + '.' + geoDict[geoType][0],
                     shape + '.' + geoDict[geoType][1],
                     f=True)
    cmds.setAttr(shapeOrig + '.intermediateObject', 1)
    cmds.reorder(shape, f=True)

    # Connect Shader
    shader = cmds.listConnections(shapeOrig, type='shadingEngine')
    if shader:
        cmds.sets(shapeOrig, rm=shader[0])
        cmds.sets(shape, fe=shader[0])

    # Update Outgoing Connections
    outConn = cmds.listConnections(shapeOrig, s=False, d=True, p=True, c=True)
    for i in range(0, len(outConn), 2):
        # Check Connection Destination
        dst = outConn[i + 1]
        if shape in dst: continue
        # Check Connection Source
        src = outConn[i].replace(shapeOrig, shape)
        if cmds.objExists(src):
            print('New source connection: ' + src)
        else:
            print('Source connection "' + src +
                  '" does not exist! Skipping...')
            continue
        # Update Connection
        cmds.connectAttr(src, dst, f=True)

    # =================
    # - Return Result -
    # =================

    return shapeOrig