def parentWithZeroes(self):
     oSel = pm.ls(sl=True)
     objs = oSel[:] ## copy list oSel so I can change objs list but leave oSel alone
     par = objs.pop(-1)
     for child in objs:
         childZero = child.getParent()
         pm.parent( childZero, par )
Пример #2
0
    def fixXforms(self):
        ## Get the first selected object
        objs = pm.ls(selection=True)
        
        for obj in objs:
            pm.parent( obj, world=True )

        for obj in objs:        
            ## Unparent the object
            
            ## Move the pivot to the origin
            pm.move ( obj.scalePivot , [0,0,0] )
            pm.move ( obj.rotatePivot , [0,0,0] )
            ## Freeze transforms
            pm.makeIdentity(
                obj,
                apply = True,
                normal = 0,
                preserveNormals = True
            )
            ## Note that the options for makeIdentity were simply
            ## from the Mel script history or freeze transform
            
            ## Delete the history
            pm.delete (ch = True )        
Пример #3
0
 def mirrorSelection(self):
     #try:
         nobjs = pm.instance()
         gr = pm.group(em=True, n = "Mirrored")
         for nobj in nobjs:
             pm.parent( nobj, gr )  ### **** Fix this later to use pymel
         pm.scale( gr, -1,1,1 )
 def reparent(self, clean=False):
     for c in self.oXformChildren:
         pm.parent( c, self.obj )
     if self.oParent!=None:
         pm.parent( self.obj, self.oParent )
     if clean==True:
         self.clean()
Пример #5
0
def createController(object):
    # object = pma.ls(sl=True)
    pivotObj = pma.xform(object, query=True, t=True, worldSpace=True)
    edges = pma.filterExpand(pma.polyListComponentConversion(te=1), sm=32,
                             ex=1)  # convert edges to curve ancd create one object
    for edge in edges:
        vtx = pma.ls(pma.polyListComponentConversion(edge, fe=1, tv=1), fl=1)
        p1 = pma.pointPosition(vtx[0])
        p2 = pma.pointPosition(vtx[1])
        curves = pma.curve(n="line_ctrl_curve", d=1, p=(p1, p2))

    ctrl = pma.curve(n="bool_ctrl", d=1, ws=True, p=pivotObj)
    pma.xform(centerPivots=True)
    for curveEdge in pma.ls("line_ctrl*"):
        pma.parent(curveEdge, ctrl, s=1, r=1)
        pma.rename(curveEdge, "shapeunused")

    transforms = pma.ls(type='transform')
    deleteList = []
    for tran in transforms:
        if pma.nodeType(tran) == 'transform':
            children = pma.listRelatives(tran, c=True)
            if children is None:
                # print '%s, has no childred' %(tran)
                deleteList.append(tran)

    if not deleteList:
        pma.delete(deleteList)
    return ctrl
 def place_objects(self, **kwargs):
     interval = kwargs.get("skip", 0)
     if not self.loop:
         pm.displayError("no Loops received")
         return None
     if interval > len(self.loop):
         pm.displayError(
             "Skipping value larger than number of edges present")
         return self.FAIL
     jnt_lst = []
     index = 0
     max_len = len(self.loop)
     while index < max_len:
         pos = CustomScripts.midPos(selected_items=self.loop[index])
         jnt_lst.append(pm.joint(position=pos))
         if len(jnt_lst) > 1:
             pm.parent(jnt_lst[-1], jnt_lst[-2])
             pm.joint(jnt_lst[-2],
                      edit=True,
                      orientJoint='xyz',
                      secondaryAxisOrient='yup',
                      zeroScaleOrient=True)
         index += interval + 1
     pm.select(jnt_lst[-2], jnt_lst[-1])
     CustomScripts.CopyJntOri()
     return jnt_lst
Пример #7
0
 def addChild(self, obj):
     pm.parent(obj.node.getTransform().name(), self.node.getTransform().name())
     conn = self._addNode(self.children, obj)
     parent = obj.addParent(self)
     pm.mel.eval("connectAttr " + self.node.name()+ '.' + conn + ' ' +
             obj.node.name() + '.' + parent)
     return conn
    def rotateOnXToMatchZ( self, obj, target ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
    
        helperZ = pm.createNode('transform')
        helperX = pm.createNode('transform')

        ## get helperZ,
        ## parent helperZ to target
        pm.parent( helperZ, target)    
        ##  zero helperZ, except +tz
        helperZ.translate.set( [0,0,16] )
        ######################### pm.duplicate( helperZ )  ## just to visualize debug
        ## parent helperZ to obj
        pm.parent( helperZ, obj )
        ## zero helperZ tx
        helperZ.tx.set( 0 )    
        ## make another helperX
        ## parent helperX to obj
        pm.parent( helperX, obj )
        ## move helperX only +tz, zero all else
        helperX.translate.set( [1,0,0] )
        ## unparent helper and helperX
        pm.parent( helperX, world=True )
        pm.parent( helperZ, world=True )
        ## should probably zero everything out that we can here
        obj.jointOrient.set( 0,0,0 )
        obj.rotateAxis.set( 0,0,0 )
        con = pm.aimConstraint( helperX, obj,
            worldUpType='object',
            worldUpObject=helperZ,
            aimVector=[1,0,0],
            upVector=[0,0,1],
        )
        pm.delete( con )   
        pm.delete( [helperX, helperZ] )
 def autoOrientTipJoint(self,obj):
     ## this currently assumes that tip has no children
     par = obj.getParent()
     pm.parent( obj )
     obj.rotate.set( [0,0,0] )
     obj.jointOrient.set( [0,0,0] )
     obj.rotateAxis.set( [0,0,0] )
     con = pm.orientConstraint( par, obj )
     pm.delete( con )
Пример #10
0
def parentChain():
    """
        Parent objects one under another in selected order,
        with first selection at top
    """
    sel = pm.ls(selection=True)
    count = len(sel)
    for index in range(count - 1):
        pm.parent(sel[index + 1], sel[index])
    return None
 def chainParent(self):
     objs = pm.ls(selection=True)
     for i,obj in enumerate(objs):
         try:
             if i==0:
                 continue
             child = objs[i-1]
             pm.parent( child, obj )
         except:
             print(traceback.format_exc() )
 def parentToIntendedParent( self, obj, doUnparenting=True ):
     parAttr = self.getParentAttr() ## returns None if doesn't exists
     ## only continue if has intended parent attr
     if not parAttr is None:
         par = self.getIntendedParent( obj )
         if not par is None:
             pm.parent( obj, par )
         ## only unparent because of clear intended
         # parent if doUnparenting is True
         elif doUnparenting:
             pm.parent( obj, w=True)
Пример #13
0
 def create_joint(self, **kwargs):
     crv = kwargs.get("crv_node", "")
     if isinstance(crv, list):
         crv = pm.PyNode(crv[0])
     crv = pm.PyNode(crv)
     shp = crv.getShape()
     pm.select(clear=True)
     ctr = pm.joint()
     pm.parent(shp, ctr, relative=True, shape=True)
     pm.delete(crv)
     return ctr
 def chainParentWithZeroes(self):
     objs = pm.ls(selection=True)
     for i,obj in enumerate(objs):
         try:
             if i==0:
                 continue
             ## if this current obj is to be parent
             ## the zero to be child is the parent of last in list
             child = objs[i-1].getParent( )
             pm.parent( child, obj )
         except:
             print(traceback.format_exc() )
Пример #15
0
 def create_zero_group(self, **kwargs):
     ctr = kwargs.get("ctr", None)
     from_name = kwargs.get("from_nm", "")
     z_name = kwargs.get("zero_nm", "")
     if not z_name:
         z_name = "_ZeroNode"
     node_nm = str(ctr) + z_name
     grp_nd = pm.group(name="null", empty=True)
     if from_name:
         if str(ctr).find(from_name) > -1:
             node_nm = str(ctr).replace(from_name, z_name)
     self.set_control_position(cur_obj=ctr, ctr=grp_nd)
     pm.parent(ctr, grp_nd)
     pm.rename(grp_nd, node_nm)
     return None
Пример #16
0
def pivotToZeroDeleteHistoryAndFreezeTransformsInWorldSpace():

    original_selection = pm.ls(selection=True)
    objs = original_selection[:]

    for obj in objs:
        try:
            previous_parent = obj.getParent()
            pm.parent(obj, world=True)
            pm.move(obj.scalePivot, [0, 0, 0])
            pm.move(obj.rotatePivot, [0, 0, 0])
            pm.makeIdentity(obj, apply=True, normal=0, preserveNormals=True)
            pm.delete(ch=True)
            pm.parent(obj, previous_parent)
        except:
            print(traceback.format_exc())
Пример #17
0
 def makeScripterNode(self):
     node = pm.createNode('mmmmScripterNodeV001v')
     originalName = node.name()
     node.rename(originalName + 'Shape')
     t = node.getParent()
     t.rename(originalName)
     node.rename(t.name() + 'Shape')
     c = pm.createNode('transform')
     c.rename('computationEnforcer')
     d = pm.createNode('plusMinusAverage')
     d.rename('dependency__plug_all_dependencies_into_1D_inputs_00')
     d.output1D >> node.dependency
     pm.parent(c, t)
     node.output >> c.translateX
     pm.select(t)
     return [t, node, c]
Пример #18
0
 def makeScripterNode( self ):
     node = pm.createNode('mmmmScripterNodeV001v')
     originalName = node.name()
     node.rename( originalName + 'Shape' )
     t = node.getParent()
     t.rename( originalName )
     node.rename( t.name()+'Shape' )
     c = pm.createNode('transform')
     c.rename( 'computationEnforcer' )
     d = pm.createNode('plusMinusAverage')
     d.rename( 'dependency__plug_all_dependencies_into_1D_inputs_00' )
     d.output1D >> node.dependency
     pm.parent( c, t )
     node.output >> c.translateX
     pm.select(t)
     return [t,node,c]
Пример #19
0
def pivotToZeroDeleteHistoryAndFreezeTransformsInWorldSpace():

    original_selection = pm.ls(selection = True)
    objs = original_selection[:]

    for obj in objs:
        try:
            previous_parent = obj.getParent()
            pm.parent( obj, world=True )                
            pm.move ( obj.scalePivot , [0,0,0] )
            pm.move ( obj.rotatePivot , [0,0,0] )
            pm.makeIdentity (obj, apply = True, normal = 0, preserveNormals = True )
            pm.delete (ch = True )
            pm.parent( obj, previous_parent )                
        except:
            print( traceback.format_exc()     )
Пример #20
0
 def makePoleVector(self, constrain=True):
     iks = pm.ls(selection = True )
     originalSelection = iks
     locators = []        
     for ik in iks:
         loc = pm.spaceLocator()
         pm.rename( loc, 'poleVectorTarget' )
         pm.parent( loc, ik )
         ik.poleVectorX >> loc.translateX
         ik.poleVectorY >> loc.translateY
         ik.poleVectorZ >> loc.translateZ
         loc.translateX.disconnect()
         loc.translateY.disconnect()
         loc.translateZ.disconnect()
         pm.parent( loc, world=True )
         if constrain==True:
             pm.poleVectorConstraint( loc, ik, weight=1 )
Пример #21
0
    def makeAndParentUcx(self):
        originalSelection = pm.ls(selection=True)
        ## Only attempt to export directly from transform nodes!
        objs = pm.ls( selection=True, transforms=True )
        
        parentObj = objs.pop( )
        
        for i, obj in enumerate(objs):
            newName = 'UCX_' + parentObj.name() + '_' + str(i).zfill(2)
            pm.parent( obj, parentObj )
            obj.rename( newName )
            
            s = obj.getShape()
            s.overrideEnabled.set(True)
            s.overrideShading.set(False)
        
Пример #22
0
    def moveUpInHierarchy(cls):

        origSel = pm.ls(selection=True)

        for obj in origSel:
            par = None
            gpar = None

            par = obj.getParent()

            if par is not None:
                gpar = par.getParent()

                if gpar is None:
                    pm.parent(obj, world=True)

                else:
                    pm.parent(obj, gpar)
Пример #23
0
        import maya.cmds as cmds
        
        cmds.file( rename = filename_w_fullpath )
        if ext=='mb':
            cmds.file( save=True, type='mayaBinary' )
        else:
            cmds.file( save=True, type='mayaAscii' )

    @classmethod
    def moveUpInHierarchy( cls ):

        origSel = pm.ls(selection=True)
        
        for obj in origSel:
            par = None
            gpar = None
            
Пример #24
0
def ckAddFidget():
    """
        ckAddFidget( )

        description: this function collects the selected attribute and adds it
          to the list of data that fidget will work with

        inputs: None

        outputs: None

        CK - this would be a great place to add data to a persistent node in the
        maya file(working)
    """

    # fist we are collecting the selected attribute
    atribSel = pm.mel.eval('selectedChannelBoxAttributes();')
    # then we get the object said attribute belongs to
    slectItm = pm.ls( selection = True )
    # the two are added together so we can work with the information
    # inside the maya context
    newAttr =  slectItm.pop() + '.' + atribSel.pop()

    # this is a test to ensure that we are in fact getting some kind of data from
    # the attribute
    newVal = pm.getAttr( newAttr )
    print newVal

    pm.select( clear = True )
    # given that has worked  we will add the data to the lists
    ckAddToList( "ckFidget_GRP.ckFidgetList", newAttr)
    ckAddToList( "ckFidget_GRP.ckFidgetSav", newVal)
    pm.group(name = str(newAttr+"_SAV0" ))
    pm.addAttr( longName="fdgSave", dataType="string", keyable=False)
    newAttr = newAttr.split(".")
    pm.setAttr( str(newAttr[0]+"_"+newAttr[1]+"_SAV0.fdgSave"), str(newVal))
    pm.select( "ckFidget_GRP")
    pm.parent( str(newAttr[0]+"_"+newAttr[1]+"_SAV0") )
    pm.select( clear = True )
    pm.select(newAttr[0])
    # now issue the call to rebuild the interface
    ckFidgetWin()
Пример #25
0
    def go(self):            
        ## Get a list of the selected objects in maya
        sel = pm.ls(selection=True)
            ## in mel:   ls -sl

        ## Get the last object selected by
        ## popping it out of the list
        target = sel.pop(-1)

        for obj in sel:
            obj.rename(  'UCX_' + target.name() + '_00'  )  ## rename based on the target's name
            pm.parent( obj, target ) ## parent this object to the target


        ## Freeze transforms
        pm.makeIdentity( target, apply=True  )
        ## Select target and all its children
        pm.select( target, hierarchy=True )
        ## Delete history
        pm.delete( constructionHistory=True )
Пример #26
0
def immediateParent(**kwargs):
    """
        Insert an immediate parent node to the selected object with
        the selected object position as reference to parent
    """
    group_name = kwargs.get("name", "null")
    sel_obj = pm.ls(selection=True)
    if not sel_obj:
        pm.group(name=group_name)
        return None
    for obj in sel_obj:
        parent_node = pm.listRelatives(obj, parent=True)
        pm.select(clear=True)
        group_name = str(obj) + "_Znode"
        null = pm.group(name=group_name)
        pm.parentConstraint(obj, null, maintainOffset=False, name="temp_const")
        pm.delete("temp_const")
        if parent_node:
            pm.parent(null, parent_node)
        pm.parent(obj, null)
    return None
    def makeCamPlaneForDrawing(self):
        drawPlaneGroup = pm.createNode( "transform" );
    
        size = 1024
        planeList = pm.polyPlane( w=size,h=size, sx=1,sy=1, n="drawPlane", axis=[0,0,1] )  #print( planeList )
        planeXform = planeList[0]

        planeShape = planeXform.getShape()
        planeShape.overrideEnabled.set(1)
        planeShape.overrideShading.set(0)
        
        locatorXform = pm.spaceLocator(n="drawPlaneLocator")
        locatorShape = locatorXform.getShape()
        locatorShape.localScale.set( [128,128,128] )

        camList = pm.camera( name="drawPlaneCam" )  #print( camList )
        camXform = camList[0]
        camXform.tz.set(256)        
        
        pm.parent( planeXform, locatorXform )
        pm.parent( locatorXform, drawPlaneGroup )
        pm.parent( camXform, drawPlaneGroup )
        
        pm.orientConstraint( camXform, planeXform, ) ##aimVector=[0,1,0], upVector=[0,0,1] )
        
        ## Look through cam
        pm.select( camXform )
        panel = pm.getPanel( withFocus=True )        
        pm.mel.eval( "lookThroughSelected 0 " + panel +";")
        
        pm.makeLive( planeXform )
Пример #28
0
    def updateInfo(self):
        s = self

        self.updateScriptNames()
        candidates = pm.ls(s.scriptFullName + "*")

        if len(candidates) > 1:
            try:
                foundObjs = pm.ls(s.scriptFullName)
                assert (len(foundObjs) == 1)
                candidates[0] = foundObjs[0]
            except:
                print(
                    'Major problem found: you should have exactly one object'
                    'with that script name in your scene. Please double check'
                    ' your naming.')
        elif len(candidates) == 0:
            originalSelection = pm.ls(
                selection=True)  ## store selection to get it back later
            self.node = pm.createNode('transform',
                                      n=s.scriptFullName)  ## type, n=name
            try:
                scriptsParent = pm.ls('scripts*')[0]
            except:
                scriptsParent = pm.createNode('transform', n='scripts')
            pm.parent(self.node, scriptsParent)
            pm.select(originalSelection)  ## restore selection

        else:
            self.node = candidates[0]

        try:
            getattr(self.node, self.attrName)
        except:
            try:
                self.node.addAttr(self.attrName, dt='string')
                print('An attribute named "' + self.attrName +
                      '" was added to ' + self.node.name())
            except:
                print("Couldn't add attribute. Continuing anyway...")
Пример #29
0
def createTwistJointToSelectedChild():
    objs = pm.ls(selection=True)

    ## Make an empty list to store joints in
    newJoints = []

    for obj in objs:
        pm.select( clear=True )
        child = obj
        parentJnt = obj.getParent()
        jnt = pm.joint(position=[0,0,0])


        pc = pm.pointConstraint( [parentJnt, child] , jnt )
        oc = pm.orientConstraint( parentJnt, jnt )
        pm.delete( pc )
        pm.delete( oc )
        pm.parent( jnt, parentJnt )
        ## Put out new joint in the list!
        newJoints.append( jnt )
 def unparent( self ):
     obj=self.obj
     try:
         oParent = obj.getParent()
     except:
         oParent = None
         
     oChildren = obj.getChildren()
     oXformChildren = []
     
     for i,c in enumerate(oChildren):
         tcheck = pymel.core.nodetypes.Transform
         jcheck = pymel.core.nodetypes.Joint
         if type(c)==tcheck or type(c)==jcheck:
             oXformChildren.append( c )
             
     for c in oXformChildren:
         pm.parent( c, world=True )
     if oParent!=None:
         pm.parent( obj, world=True )
         
     self.oParent = oParent
     self.oXformChildren = oXformChildren
Пример #31
0
    def updateScriptNames(self):
        self.scriptPrefix = self.scriptPrefixTextField.getText()
        self.scriptName = self.scriptNameTextField.getText()
        self.scriptFullName = self.scriptPrefix + self.scriptName
                                
    def updateInfo(self):
        s = self
       
        self.updateScriptNames()
        candidates = pm.ls( s.scriptFullName + "*" )
        
        if len(candidates)>1:
            try:
                foundObjs = pm.ls( s.scriptFullName )
                assert(  len(foundObjs)==1  )
                candidates[0]=foundObjs[0]
            except:
                print( 'Major problem found: you should have exactly one object'
                    'with that script name in your scene. Please double check'
                    ' your naming.'
                )
        elif len(candidates)==0:
            originalSelection = pm.ls(selection=True)  ## store selection to get it back later
            self.node = pm.createNode( 'transform', n=s.scriptFullName )   ## type, n=name
            try:
                scriptsParent = pm.ls( 'scripts*' )[0]
            except:
                scriptsParent = pm.createNode( 'transform', n='scripts' )
            pm.parent( self.node, scriptsParent )
            pm.select( originalSelection)  ## restore selection
            
        else:
            self.node = candidates[0]
            
        try:
            getattr(self.node, self.attrName)
    def fixJointComplexXforms( self, obj ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
        
        unrepar = Unreparenter( obj )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        tmp = pm.createNode('joint')
        cons = [
            pm.pointConstraint( obj, tmp ),
            pm.orientConstraint( obj, tmp ),
            pm.scaleConstraint( obj, tmp )
        ]
        pm.delete( cons )
        
        helperZ = pm.createNode('transform')
        helperX = pm.createNode('transform')
        pm.parent( helperX, tmp )
        pm.parent( helperZ, tmp )
        
        helperX.translate.set( [1,0,0] )    
        helperZ.translate.set( [0,0,1] )    

        obj.jointOrient.set( 0,0,0 )
        obj.rotateAxis.set( 0,0,0 )
        con = pm.aimConstraint( helperX, obj,
            worldUpType='object',
            worldUpObject=helperZ,
            aimVector=[1,0,0],
            upVector=[0,0,1],
        )
        pm.delete( con )   
        pm.delete( [helperX, helperZ] )
        
        pm.delete( tmp )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        unrepar.reparent( )
Пример #33
0
def dupXformNoChildren( obj ):
    ## takes only a single object
    assert type(obj) == pymel.core.nodetypes.Transform
    print( obj )
    
    dupShapesFinal = []
    tempDuplicatedXforms = []
    
    for s in obj.getShapes():
    
        s = obj.getShape()

        ## we need a temporary xform to move the shape to
        tempXform = pm.createNode('transform')
        pm.parent( s, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        dups = pm.duplicate( s )
        tempDuplicatedXform = dups[0]
        tempDuplicatedXforms.append( tempDuplicatedXform )
        
        dupShapesFinal.append( tempDuplicatedXform.getShape() )
    
        ## Now put the original xform back where we got it from!
        pm.parent( s, obj, shape=True, relative=True )
        pm.delete( tempXform )
        
        ## Now we should be back where we started, except with a new
        ## duplicated shape node at the origin, with a indentity
        ## xform node
        
    ## Now that we have duplicates of all the shapes,
    ## we need a duplicated xform node
    dupList = pm.duplicate( obj, parentOnly=True, returnRootsOnly=True )
    dupXform = dupList[0]
    ## Now parent all the duplicated shapes to the duplicated xform
    for s in dupShapesFinal:
        pm.parent( s, dupXform, shape=True, relative=True )
        
        
    ## We have to delete tempInplaceXform later, because we need it for a bit
    pm.delete( tempDuplicatedXforms )
def match_ctrl(jnt, ctrl):
    control_name = ctrl.name(long=None)
    control_shape = ctrl.getShape()

    transform = pm.group(parent=jnt, empty=True)
    transform.zeroTransformPivots()
    pm.parent(transform, world=True)

    pm.parent(control_shape, transform, absolute=True, shape=True)

    new_trans = pm.listRelatives(control_shape, parent=True)

    pm.makeIdentity(new_trans, s=True, r=True, t=True, apply=True)

    pm.parent(control_shape, transform, relative=True, shape=True)

    pm.delete(new_trans, ctrl)

    transform.rename(control_name)

    pm.delete(transform, constructionHistory=True)
Пример #35
0
def duplicateShape( shape, selectDup=False ):

        '''
        Duplicates the shape node, does not by default select the result.
        Takes as an argument a single pymel shape node.
        '''

        oSel = pm.ls(selection=True)
        
        ## we need a temporary xform to move the shape to
        originalParent = shape.getParent()
        tempXform = pm.createNode('transform')
        pm.parent( shape, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        ## it's guaranteed to be a simple one xform
        ## hierarchy because we started from the new xform we created
        dups = pm.duplicate( shape )
        tempDuplicatedXform = dups[0]
        dupShape = tempDuplicatedXform.getShape()
        
    
        ## Now put the original xform back where we got it from!
        ## also parent new duplicated shape back to original xform
        pm.parent( shape, originalParent, shape=True, relative=True )
        pm.parent( dupShape, originalParent, shape=True, relative=True )
        ## Clean up the temporary xforms that were used
        pm.delete( tempXform )
        pm.delete( tempDuplicatedXform )
        
        ## restore selection and return result
        if selectDup==False:
            pm.select( oSel )
        return dupShape
    def makeAnimCtrlAndZero(self, doConnectPosSlave=True, doConnectRotSlave=True):
        ctrls = []
        objs = pm.ls(selection=True)
        for obj in objs:
            
            ## really, you have to find the first occurance of the numbered name
            ## that didn't exist in the scene as either a zero or a control
            goodNumber = None
            iter = 0
            while goodNumber == None   and   iter < 99:
                iter+=1
                if iter==0:
                    foundZ = pm.ls( obj.name() + "_zero" )
                    foundC = pm.ls( obj.name() + "_ctrl" )
                    if len(foundZ)==0  and  len( foundC )==0:
                        goodNumber = 0
                else:
                    foundZ = pm.ls( obj.name() + str(iter) + "_zero" )  ## could use .zfill(2)
                    foundC = pm.ls( obj.name() + str(iter) + "_ctrl" )
                    if len(foundZ)==0  and  len( foundC )==0:
                        goodNumber = iter
        
            if goodNumber == 0:
                basename = obj.name()
            else:
                basename = obj.name() + str(goodNumber)
            
            
            try:
                jointRadius=obj.radius.get()
            except:
                print( traceback.format_exc()  )
                jointRadius=16
            
            radiusToUse = self.ctrlSizeFloatField.getValue()
            if radiusToUse <= 0.0:
                radiusToUse = 8*jointRadius
            ctrlList = pm.circle(normal=[1,0,0], radius=radiusToUse, ch=False)
            #ctrlCircle = ctrlList[1]
            ctrl = ctrlList[0]
            pm.rename( ctrl, basename + "_ctrl" )
            pCon = pm.pointConstraint(
               obj, ctrl
            )
            oCon = pm.orientConstraint(
               obj, ctrl
            )
            ## beware, pymel returns constraints back directly, not in list
            pm.delete( [pCon, oCon] ) ## delte constraints  
        
            zeroList = pm.duplicate( ctrl )
            zero = zeroList[0]
            
            pm.rename( zero, basename + "_zero")
        
        
                
                
        
            pm.delete( zero.getShape() )
            
            pm.parent( ctrl, zero )
            #pCon = pm.pointConstraint( ctrl, obj )
            #oCon = pm.orientConstraint( ctrl, obj ) 

            pm.addAttr( ctrl, ln='posSlave', at='message' )
            pm.addAttr( ctrl, ln='rotSlave', at='message' )
            if doConnectPosSlave==True:
                obj.message >> ctrl.posSlave
            if doConnectRotSlave==True:
                obj.message >> ctrl.rotSlave
                
            ctrls.append( ctrl )
            
        pm.select( ctrls )
Пример #37
0
import pymel.all as pm

objs = pm.ls(selection=True)

## Make an empty list to store joints in
newJoints = []

for obj in objs:
    pm.select( clear=True )
    jnt = pm.joint(position=[0,0,0])
    children = obj.getChildren()
    child = children[0]

    pc = pm.pointConstraint( [obj, child] , jnt )
    oc = pm.orientConstraint( obj, jnt )
    pm.delete( pc )
    pm.delete( oc )
    pm.parent( jnt, obj )
    ## Put out new joint in the list!
    newJoints.append( jnt )

pm.select( newJoints )
Пример #38
0
    def createRivet(self):
        """
        Create one rivet for each selected vertex
        """
        selObjs = pm.ls(selection=True)
        if not selObjs:
            ## Nothing is selected, so print out warning and raise error        
            print( self.emsgPleaseSelect )
            return
            #raise Exception, self.emsgPleaseSelect
        self.originalSel = selObjs  #### Store this step of of the selection in case we want it again later

        uvs = []
        
                
        uvs.extend( pm.polyListComponentConversion( selObjs, tuv=True )  ) #### Change this to the full version
              
        #uvs.extend( [uv for uv in selObjs if '.uv' in uv] )  #### This is a very good list comprehension, perhaps expand it though
            ## the extend method of a list adds all items from another given list to the list

        uvsFromNurbs = []
        for i in selObjs:
            if pm.objectType( i ) == 'nurbsSurface' :
                uvs.append( i )

        
        ##  select our new, smaller/filtered uvs       
        pm.select( uvs )
        uvs = pm.ls( flatten = True, selection = True )  ## The flatten command returns each component individually in the list, rather than using strings that specify ranges of selections.  It takes more RAM but is often much more suitable to work with.

        ## Create a group so that we can organize the rivets  -  **** Note that this should be improved with the MmmmTools upcoming unique naming system
        if not pm.objExists('_follicle_grp'):    #### This line and the next should eventually be improved to not use a hardcoded name
            group = pm.group( em = True, w=True, n='_follicle_grp' )    #### **** Totally recreate this line, use a variable name or at least a unique one
        else:
            group = pm.PyNode('_follicle_grp')
            
        rivets = []
        
        pm.select( selObjs )

        failCount = 0

        ## Give an error msg if the user didn't use the script on a compatible selection
        if not uvs:
            failCount += 1
            print( self.emsgPleaseSelect )

        ## Everything is good, proceed to investigate and create rivets
        for uv in uvs:
                ## The commented out print line are simple useful for debugging
                print pm.objectType( uv )                
                
                objShapeName, index = tuple( uv.split( '.', 1 )  )
                obj = pm.PyNode( objShapeName )
                loc = pm.createNode( 'locator' )
                tr = getT( loc ) 
                #print( "Transform was: " + tr )
                hair = pm.createNode( 'follicle', parent = tr )
                pm.parent( tr, group )  ####  This line sucks because it's using a f*****g stupid name again
                rivets.append( tr )
                
                ## Poly mesh handler
                if pm.objectType( obj ) == 'mesh':
                    obj.outMesh >> hair.inputMesh
                    uvPos = pm.polyEditUV( uv, query=True )
                ## Nurbs surface handler
                elif pm.objectType( obj ) == 'nurbsSurface':
                    obj.local >> hair.inputSurface
                    ## The index is a messy string, so we need to pull uv data out of it
                    uvTuple = ( index.strip('.uv[]').split('][')  )
                    ## We need to create the tuple as floats, because we got it as strings
                    uvPos = (    float(uvTuple[0]), float(uvTuple[1])     )
                    #uvPos = ( uvTuple[0], uv[1] )#index.strip('.uv[]').split('][')

                    ## Handle conditions where the uvs aren't normalized, this may not be required often
                    maxU = float(  obj.maxValueU.get()     )
                    maxV = float(  obj.maxValueV.get()     )
                    uvPos = (    uvPos[0]/maxU,  uvPos[1]/maxV   )
                ## Handle other cases, where this script can't do anything useful
                else:
                    print( obj + ' with uv: ' + uv + \
                        '   was incompatible, it much be either polygons or Nurbs' )
                    failCount += 1                        
                    continue
                    
                u, v = uvPos                    

                ## Make the hair follow the model, both by parenting, and by keeping its translate and rotate matched
                obj.worldMatrix >> hair.inputWorldMatrix
                hair.outTranslate >> tr.translate
                hair.outRotate >> tr.rotate   ## Note:  The hair has no outScale
                
                ## Set the u and v parameters of the hair so that it sticks to the correct place on the model
                hair.parameterU.set( u )
                hair.parameterV.set( v )
                
                ## Put the rivet into a group so we can select it afterwards
                self.lastRivetsCreated.append( loc )
           
        ## Select all the new rivets we created
        pm.select( self.lastRivetsCreated, replace=True )
        if failCount:
            print( str(failCount) + """ rivets failed to be created. Most likely because the selection was not correct. Try selecting vertices on a nurbs surface or a polygon mesh and running the script again. """)
        else:
            print( self.msgSucess )
        return       
import pymel.all as pm

objs = pm.ls(selection=True)

## Make an empty list to store joints in
newJoints = []

for obj in objs:
    pm.select( clear=True )
    child = obj
    parentJnt = obj.getParent()
    jnt = pm.joint(position=[0,0,0])


    pc = pm.pointConstraint( [parentJnt, child] , jnt )
    oc = pm.orientConstraint( parentJnt, jnt )
    pm.delete( pc )
    pm.delete( oc )
    pm.parent( jnt, parentJnt )
    ## Put out new joint in the list!
    newJoints.append( jnt )

pm.select( newJoints )
ik = selection[0]
 ## get the first things in 
 ## the list of selected objects


## get a locator by name
#loc = pm.PyNode('locator1')
loc = pm.spaceLocator()


## the locator first get's parented to
## the ik handle, just so it's in the right
## coordsys
## parenting order is (slave, master)
## or  (child, parent)
pm.parent( loc, ik )


## now we need to put the locator
## at the one exact "magic"
## place where the pole vector
## is for the ik handle
## it's magic, because it's the only
## place that won't "pop" out of the pose
##
## connect the ik's poleVector attribute
## to the locators translation
## which is a way of recording the data
ik.poleVector >> loc.translate
##
## now that's it is in the right
Пример #41
0
def treadAtPoints(**kwargs):
    #get inputs
    tread_name = kwargs.get("tr_name", "Tread")
    crv = kwargs.get("path_crv", None)
    crv = str(pm.duplicate(crv, name=str(tread_name) + "PathCrv")[0])
    pm.xform(crv, centerPivots=True)
    #obtain curve length
    full_length = pm.arclen(crv)
    paramVal = []
    uVal = []
    # get param value on the curve at each position selected (locators)
    sel_obj = pm.ls(selection=True)
    for obj in sel_obj:
        pos = pm.xform(obj, query=True, translation=True, worldSpace=True)
        param = getuParamVal(pos, crv)
        paramVal.append(param)
    crv_shp = pm.listRelatives(crv, shapes=True)[0]
    # create arc length dimension tool
    arcLen = pm.arcLengthDimension(crv_shp + ".u[0]")
    # for each param value obtained set the arc length tool attribute and
    # store the length of curve at that param value
    # normalize the curve to obtain the motion path U value at each position
    for val in paramVal:
        pm.setAttr(str(arcLen) + ".uParamValue", val)
        len_at_pos = pm.getAttr(str(arcLen) + ".arcLength")
        uVal.append(len_at_pos / full_length)
    pm.delete(arcLen)
    mthPthLst = []
    jntLst = []
    # create joints, assign motion path and set U value obtained
    for u in uVal:
        pm.select(clear=True)
        jnt = pm.joint()
        jntLst.append(jnt)
        pathanim = pm.pathAnimation(jnt,
                                    curve=crv,
                                    fractionMode=True,
                                    follow=True,
                                    followAxis="x",
                                    worldUpType="vector",
                                    worldUpVector=(0, 1, 0))
        mthPthLst.append(pathanim)
        pm.setAttr(str(pathanim) + ".uValue", u)
        pm.disconnectAttr(str(pathanim) + ".u")
        # create up locator at mid point of all joints
    #loc_pos = midPos(selected_items = jntLst)
    #loc_pos = pm.xform(crv, query=True, translation=True, worldSpace=True)
    loc_pos = midPosVec(objects=jntLst)
    loc = pm.spaceLocator()
    pm.xform(loc, translation=loc_pos, worldSpace=True)
    for mtPth in mthPthLst:
        pm.pathAnimation(mtPth,
                         edit=True,
                         worldUpType="object",
                         worldUpObject=loc)
    # create control curve, add run and speed attributes
    control_crv = pm.circle(name=tread_name + "CTRL",
                            normalX=1,
                            normalY=0,
                            normalZ=0)
    pm.xform(control_crv, translation=loc_pos)
    pm.select(clear=True)
    pm.addAttr(control_crv,
               longName="run",
               attributeType="float",
               keyable=True)
    pm.addAttr(control_crv,
               longName="speed",
               attributeType="float",
               keyable=True,
               minValue=0.0,
               defaultValue=0.5)
    # group the tread setup
    pm.parent(crv, control_crv)
    pm.parent(loc, control_crv)
    pm.select(clear=True)
    gp = pm.group(name=tread_name + "GP")
    pm.select(clear=True)
    jnt_gp = pm.group(jntLst, name=tread_name + "JNTGP")
    pm.xform(gp, translation=loc_pos)
    pm.parent(control_crv, gp)
    pm.parent(jnt_gp, gp)
    createTreadExpression(mtnPth=mthPthLst,
                          runAttr=str(control_crv[0]) + ".run",
                          speedAttr=str(control_crv[0]) + ".speed",
                          exp_nm=tread_name)
    return None


#treadAtPoints(pathCrv = "nurbsCircle1", tr_name = "testTread")