Esempio n. 1
1
def keyFullRotation (pObjectName, pStartTime, pEndTime, pTargetAttribute):
    
     cmds.cutKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute)
     cmds.setKeyframe (pObjectName, time = pStartTime, attribute=pTargetAttribute, value=0)
     cmds.setKeyframe (pObjectName, time = pEndTime, attribute=pTargetAttribute, value=360)
     cmds.selectKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True)
     cmds.keyTangent (inTangentType='linear', outTangentType='linear')
Esempio n. 2
1
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTangentAttribute):
            
    # Enable key on selected objects
    cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute)
            
    # Set keyframes
    cmds.setKeyframe(pObjectName, time=pStartTime, attribute=pTangentAttribute, value=0)
    cmds.setKeyframe(pObjectName, time=pEndTime, attribute=pTangentAttribute, value=360)
    
    # Set linear tangent
    cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTangentAttribute)
    cmds.keyTangent(inTangentType='linear', outTangentType='linear')
def keyFullRotation(pObjectName, pStartTime, pEndTime, pTargetAttribute):
    #The keys are deleted
    cmds.cutKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)

    #Define new keys for the animations (rotation in the axis Y). 
    cmds.setKeyframe(pObjectName, time= pStartTime, attribute=pTargetAttribute, value = 0)
    
    cmds.setKeyframe(pObjectName,time=pEndTime, attribute=pTargetAttribute, value = 360)

    #In order to mantain a constant rate of rotation with linear tangents
    cmds.selectKey(pObjectName, time=(pStartTime, pEndTime), attribute=pTargetAttribute)
    cmds.keyTangent( inTangentType='linear', outTangentType='linear')
Esempio n. 4
0
 def TrimKeys(self, extraArg=None):
     selection = Cmds.ls(selection=True)
     if not len(selection) == 1 or not Cmds.nodeType(selection) == 'joint':
         self.MessageBox('Please select (only) the topmost joint of the skeletal system', 'Trim keys pre-requisite error')
         return
         
     trimStart = int(Cmds.textField(self.startFrameTextBox, q=True, text=True))
     trimEnd = int(Cmds.textField(self.endFrameTextBox, q=True, text=True))
     
     if trimStart < 0:
         self.MessageBox('Trim can start only from 0. Please ensure start frame is valid.', 'Trim keys pre-requisite error')
         
     trimRegions = [0] * (trimEnd + 1)
     for animation in self.sequencer.Animations.values():
         trimRegions[animation.StartFrame:animation.EndFrame + 1] = [1] * (animation.EndFrame - animation.StartFrame + 1)
     
     i = 0
     while i < len(trimRegions):
         tStart = FindIndexOf(trimRegions, 0, i, trimEnd)
         tEnd = FindIndexOf(trimRegions, 1, tStart, trimEnd) - 1
         
         if tEnd < tStart:
             break
         
         Cmds.cutKey(selection, animation='keysOrObjects', option='keys', clear=True, hierarchy='below', time=(tStart,tEnd))
         
         i = tEnd + 1
         i = i + 1
         
     self.MessageBox('Trim complete!')
Esempio n. 5
0
def keyCopyObjects( fromList, toList, start, end ):
    
    for i in range( len( fromList ) ):
        fromCtl = fromList[i]
        toCtl = toList[i]
        
        targetMtx = cmds.getAttr( fromCtl+'.m' )
        mirrorMtx = getMirrorMatrix_local( targetMtx )
        
        listAttr = cmds.listAttr( fromCtl, k=1 )
        if not listAttr: continue
        for attr in listAttr:
            times = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), tc=1 )
            if not times: continue
            
            values = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), vc=1 )
            keyLocks = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), lock=1 )
            inAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), ia=1 )
            outAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), oa=1 )
    
            cmds.cutKey( toCtl+'.'+attr, t=(start+0.01, end-0.01) )
            for i in range( len( times ) ):
                if attr.find( 'translate' ) != -1:
                    value = -values[i]
                    ia = -inAngles[i]
                    oa = -outAngles[i]
                else:
                    value = values[i]
                    ia = inAngles[i]
                    oa = outAngles[i]
                cmds.setKeyframe( toCtl+'.'+attr, t=times[i], v=value )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=0 )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), ia=ia )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), oa=oa )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=keyLocks[i] )
Esempio n. 6
0
def keyCopyObjectOnce( target, start, end ):
    
    otherTarget = ''
    if target in CtlInfo.leftCtls:
        otherTarget = target.replace( '_L1_', '_R1_' )
    elif target in CtlInfo.rightCtls:
        otherTarget = target.replace( '_R1_', '_L1_' )
    if not otherTarget: return None
    
    attrs = cmds.listAttr( target, k=1 )

    for attr in attrs:
        times = cmds.keyframe( target+'.'+attr, q=1, t=(start,end), tc=1 )
        if not times: continue
        
        values = cmds.keyframe( target+'.'+attr, q=1, t=(start,end), vc=1 )
        keyLocks = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), lock=1 )
        inAngles = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), ia=1 )
        outAngles = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), oa=1 )

        cmds.cutKey( otherTarget+'.'+attr, t=(start+0.01, end-0.01) )
        
        for i in range( len( times ) ):
            value = values[i]
            ia = inAngles[i]
            oa = outAngles[i]
            cmds.setKeyframe( otherTarget+'.'+attr, t=times[i], v=value )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), lock=0 )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), ia=ia )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), oa=oa )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), lock=keyLocks[i] )
def delete_page():
    """ Delete an existing page.

    Cuts the key from the flipbook_LOC so that it is no longer set.

    :returns:  None.
    :raises: None.
    """
    # Get the current frame that we're on:
    current_frame = cmds.currentTime(query=True)

    # We're going to have to delete the group first and foremost:
    page_name = "page_%04d" % (current_frame)
    expression_name = "page_%04d_visibility_EXP" % (current_frame)
    if cmds.objExists(expression_name):
        cmds.delete(expression_name)
    if cmds.objExists(page_name):
        cmds.delete(page_name)

    # Then we need to delete the key from the master node:
    cmds.cutKey("flipbook_LOC",
                attribute="pagesToDisplay",
                time=(current_frame, current_frame),
                option="keys",
                clear=True)

    # Now that that's done, we *could* set the current frame to the last keyed
    # page?...maybe.
    return
Esempio n. 8
0
def deleteSubFrameKeys(selectionOption=1):
    
    keySel = _getKeySelection(selectionOption)
    for curve, times in zip(keySel.curves, keySel.times):
        cutTimes = [x for x in times if x % 1 != 0 and -9999 < x < 9999]
        if cutTimes:
            mc.cutKey(curve, time=utl.castToTime(cutTimes))
def CutSelKeys():
    # coding=1251
    
    import maya.cmds as cmds
    
    selectedCtrls = cmds.ls(sl = True)
    cmds.cutKey(selectedCtrls)           
	def OnKeyChange( self, *args ):
		checks  = [ cmds.checkBox( self.cXKey, query = True, value = True ), cmds.checkBox( self.cYKey, query = True, value = True ), cmds.checkBox( self.cZKey, query = True, value = True ) ]
		attribs = [ ".translateX", ".translateY", ".translateZ" ]
		
		# ... se quieren cambios? ...
		sequence  = next( ( seq for seq in self.SequenceInfo if seq.GetNode() == self.ActiveNode ), None )
		frameInfo = sequence.GetFrameInfo( self.ActiveManip.GetFrame() )
		
		# ...
		refreshCurve = False
		frame        = self.ActiveManip.GetFrame() + self.StartFrame
		
		for i in range( 0, 3 ):
			if ( checks[ i ] != frameInfo.HasTranslationKeyAxis( i ) ):
				if ( checks[ i ] ): # ... se crea la key ...
					cmds.setKeyframe( self.ActiveNode + attribs[ i ], insert = True, time = ( frame, frame ) )
					frameInfo.SetTranslationKey( i )
				else: # ... se borra la key ...
					#cmds.selectKey( self.ActiveNode + attribs[ i ], add = True, keyframe = True, time = ( frame, frame ) )
					cmds.cutKey( self.ActiveNode + attribs[ i ], time = ( frame, frame ), option = "keys" )
					frameInfo.RemoveTranslationKey( i )
					
				refreshCurve = True
				
		# ...
		if ( refreshCurve ):
			self.CreateCurve()
Esempio n. 11
0
    def applyAttrData(self, attrData):
        
        firstStep       = 0
        totalSteps      = len(attrData)
        estimatedTime   = None
        status          = "aTools Animation Crash Recovery - Step 2/3 - Applying attributes data..."
        startChrono     = None
                        
        for thisStep, loopData in enumerate(attrData):
            if cmds.progressBar(G.progBar, query=True, isCancelled=True ):  return
            startChrono = utilMod.chronoStart(startChrono, firstStep, thisStep, totalSteps, estimatedTime, status)

            objAttr = loopData["object"]
            value   = loopData["value"]["value"]
            
            if not cmds.objExists(objAttr):                     continue            
            if not cmds.getAttr(objAttr, settable=True):        continue 
            if cmds.getAttr(objAttr, lock=True):                continue 
            if cmds.getAttr(objAttr, type=True) == "string":    continue
            
            cmds.cutKey(objAttr)
            
            
            if type(value) is list: #translate, rotate, scale
                value = value[0]
                cmds.setAttr(objAttr, value[0],value[1],value[2], clamp=True)
            else: #translatex, translatey, etc           
                cmds.setAttr(objAttr, value, clamp=True)
            
            
            estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep, totalSteps)
Esempio n. 12
0
    def doEditPivotDriver(self, *args):

        newValue = mc.floatSliderButtonGrp(self.floatSlider, query=True, value=True)
        try:
            mc.deleteUI(self.pivotDriverWindow)
        except:
            pass

        currentValue = mc.getAttr(self.pivotDriver)
        if newValue == currentValue:
            return

        oldRP = mc.getAttr(self.node+'.rotatePivot')[0]
        mc.setAttr(self.pivotDriver, newValue)
        newRP = mc.getAttr(self.node+'.rotatePivot')[0]
        mc.setAttr(self.pivotDriver, currentValue)

        parentPosition = mc.group(em=True)
        offsetPosition = mc.group(em=True)
        offsetPosition = mc.parent(offsetPosition, parentPosition)[0]
        mc.setAttr(offsetPosition+'.translate', newRP[0]-oldRP[0], newRP[1]-oldRP[1], newRP[2]-oldRP[2])

        mc.delete(mc.parentConstraint(self.node, parentPosition))

        utl.matchBake(source=[self.node], destination=[parentPosition], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False)

        mc.cutKey(self.pivotDriver)
        mc.setAttr(self.pivotDriver, newValue)
        mc.refresh()
        utl.matchBake(source=[offsetPosition], destination=[self.node], bakeOnOnes=True, maintainOffset=False, preserveTangentWeight=False, rotate=False)

        mc.delete(parentPosition)
Esempio n. 13
0
def keyCopyObjectOnce( target, start, end ):
    
    otherTarget = ''
    if target in CtlInfo.leftCtls:
        otherTarget = target.replace( 'L_', 'R_' )
    elif target in CtlInfo.rightCtls:
        otherTarget = target.replace( 'R_', 'L_' )
    if not otherTarget: return None
    
    isTransMirror = False
    isZRotMirror    = False
    for transMirrorName in CtlInfo.xTransMirrorTargetNames:
        if target.find( transMirrorName ) != -1:
            isTransMirror = True
    for zRotMirror in CtlInfo.zRotMirrorTargetNames:
        if target.find( zRotMirror ) != -1 and target.find( 'wing_big4_CTL' ) == -1:
            isZRotMirror = True
    
    attrs = cmds.listAttr( target, k=1 )

    for attr in attrs:
        times = cmds.keyframe( target+'.'+attr, q=1, t=(start,end), tc=1 )
        if not times: continue
        
        values = cmds.keyframe( target+'.'+attr, q=1, t=(start,end), vc=1 )
        keyLocks = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), lock=1 )
        inAngles = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), ia=1 )
        outAngles = cmds.keyTangent( target+'.'+attr, q=1, t=(start,end), oa=1 )

        cmds.cutKey( otherTarget+'.'+attr, t=(start+0.01, end-0.01) )
        
        for i in range( len( times ) ):
            if attr.find( 'scale' ) != -1:
                value = values[i]
                ia = inAngles[i]
                oa = outAngles[i]
            elif attr.find( 'translate' ) != -1:
                if isTransMirror and attr[-1] in ['Y','Z']:
                    value = values[i]
                    ia = inAngles[i]
                    oa = outAngles[i]
                else:
                    value = -values[i]
                    ia = -inAngles[i]
                    oa = -outAngles[i]
            else:
                if isZRotMirror and attr[-1] in [ 'X', 'Y' ]:
                    value = -values[i]
                    ia = -inAngles[i]
                    oa = -outAngles[i]
                else:
                    value = values[i]
                    ia = inAngles[i]
                    oa = outAngles[i]
            cmds.setKeyframe( otherTarget+'.'+attr, t=times[i], v=value )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), lock=0 )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), ia=ia )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), oa=oa )
            cmds.keyTangent( otherTarget+'.'+attr, e=1, t=(times[i],times[i]), lock=keyLocks[i] )
Esempio n. 14
0
def distributeKeys(step=3.0, destructive=True, forceWholeFrames=True):
    '''
    operates on selected curves
    '''
    s = GraphSelection()
    sel = cmds.ls(sl=1, fl=True)
    rng = fr.Get()
    if s.crvs:
        # gather info
        autoK = cmds.autoKeyframe(q=True, state=True)
        frames = getKeyedFrames(s.crvs)
        # process start/end of loop
        framesNew = []
        if rng.selection:
            for f in frames:
                if f >= rng.keyStart and f <= rng.keyEnd:
                    framesNew.append(f)
            frames = framesNew
        #
        cut = []
        # print frames
        if forceWholeFrames:
            framesOrig = frames
            frames = [round(frame) for frame in frames]
            framesPartial = list(set(framesOrig) - set(frames))
            cut = [frame for frame in framesPartial]
            # print cut, '______cut'
        lastFrame = frames[len(frames) - 1]
        count = frames[0]
        i = frames[0]
        # turn off autokey
        cmds.autoKeyframe(state=False)
        framesNew = []
        # process keys
        while i < lastFrame:
            if i == count:
                cmds.setKeyframe(s.crvs, i=True, t=count)
                framesNew.append(count)
                count = count + step
            else:
                if i in frames:
                    cut.append(i)
            i = i + 1
        # remove keys is destructive
        if destructive:
            framesDel = sorted(list(set(frames) - set(framesNew)))
            for frame in framesDel:
                cut.append(frame)
            # print framesOrig, '________orig'
            # print framesNew, '________new'
            # print cut, '_________cut'
            if cut:
                for frame in cut:
                    if frame >= rng.keyStart and frame <= rng.keyEnd:
                        cmds.cutKey(sel, clear=1, time=(frame, frame))
        # restore autokey
        cmds.autoKeyframe(state=autoK)
    else:
        message('Select one or more anima curves', maya=1)
Esempio n. 15
0
def cutBefore() :

    ''' cut the keys from 0 to current '''

    cur = m.currentTime(q=True)
    start = m.playbackOptions(q=True, min=True)
    sel = m.ls(sl=True)
    for i in sel: m.cutKey(i, time=(0, cur))
Esempio n. 16
0
def cutAfter() :

    ''' cut the keys from current to end on selected '''

    cur = m.currentTime(q=True)
    end = m.playbackOptions(q=True, max=True)
    sel = m.ls(sl=True)
    for i in sel: m.cutKey(i, time=(cur, end))
Esempio n. 17
0
def deleteDummyKey(objects=None):

    objs = filterNoneObjects(objects)

    if not objs:
        objs = getObjsSel()
    if len(objs) > 0:
        cmds.cutKey(objs, time=(-50000, -50000), clear=True)
Esempio n. 18
0
def assign( source, target, rangemode, replacemode ) :

    ''' Assign a marker, copying from source to destination 
    
    :param source: the source marker to copy data from
    :param target: the target marker to paste data on to
    :param replacemode: 'swap' or 'extract'
    :param rangemode: sett getSourceRange

    '''

    print "Assign: %s ---> %s  Modes:  %s/%s" % (source, target, rangemode, replacemode )

    if not m.objExists( target ) :
        print "renaming: " + source + " as " + target
        m.rename( source, target) 
        return True


    if rangemode == 'gap' :

        # fill the gap in the target using keys from the source

        s = curve.currentSegmentOrGap( target, datarate.nodeRate(source) )
        if s is None or s[0] != 'gap' :
            print "Skipping: " + str(source) + " (not currently in a gap)"
            return

        # values of surrounding keyframes
        sourceIn, sourceOut = s[1]
	# contract range
	sourceIn = sourceIn + 0.5
	sourceOut = sourceOut - 0.5

    else :

        sourceIn, sourceOut = getSourceRange( source, rangemode )
	# expand to 
	sourceIn = sourceIn - 0.5
	sourceOut = sourceOut + 0.5

    print "In: %f  Out: %f" % (sourceIn, sourceOut)
 
    if replacemode == 'swap' :       
        keyTools.swap( (source,target), sourceIn, sourceOut )

    if replacemode == 'extract' :
        # copy the segment over, any clashing keys on the marker will be removed as unlabelled
        keyTools.extractRange( target, sourceIn, sourceOut )
        m.cutKey( source, t = ( sourceIn, sourceOut ) )
        m.pasteKey( target, option='replace' )


    keyTools.setActiveKeys( source, delete=True )
    keyTools.setActiveKeys( target )
    #m.select(target)

    m.dgdirty(a=True)
Esempio n. 19
0
 def deleteKey(self,*a,**kw):
     """ Select the seted objects """        
     if self.setList:
         mc.select(self.setList)
         mc.cutKey(*a,**kw)
         return True
     
     guiFactory.warning("'%s' has no data"%(self.nameShort))  
     return False   
Esempio n. 20
0
def scaleConstraint(master, slave, mo=False, force=False, attrList=['sx', 'sy', 'sz']):
    """
    Create a scale constraint between the specified master and slave transforms.
    Only constrains open, settable channels.
    @param master: Constraint master transform.
    @type master: str
    @param slave: Constraint slave transform.
    @type slave: str
    @param mo: Maintain constraint offset
    @type mo: bool
    @param force: Force constraint by deleteing scale channel keys. Use with caution!
    @type force: bool
    @param attrList: List of transform attributes to constrain.
    @type attrList: list
    """
    # ==========
    # - Checks -
    # ==========

    # Check Master
    if not cmds.objExists(master):
        raise Exception('Constraint master "' + master + '" does not exist!')
    if not glTools.utils.transform.isTransform(master):
        raise Exception('Constraint master "' + master + '" is not a valid transform!')

    # Check Slave
    if not cmds.objExists(slave):
        raise Exception('Constraint slave "' + slave + '" does not exist!')
    if not glTools.utils.transform.isTransform(slave):
        raise Exception('Constraint slave "' + slave + '" is not a valid transform!')

    # Check Settable Channels
    sk = []
    if not 'sx' in attrList or not cmds.getAttr(slave + '.sx', se=True): sk.append('x')
    if not 'sy' in attrList or not cmds.getAttr(slave + '.sy', se=True): sk.append('y')
    if not 'sz' in attrList or not cmds.getAttr(slave + '.sz', se=True): sk.append('z')
    if not sk: st = 'none'

    # Check All
    if len(sk) == 3:
        print('All scale channels locked! Unable to add constraint')
        return None

    # =====================
    # - Create Constraint -
    # =====================

    if force: cmds.cutKey(slave, at=attrList)

    constraint = ''
    try:
        constraint = cmds.scaleConstraint(master, slave, sk=sk, mo=mo)[0]
    except Exception, e:
        # raise Exception('Error creating constraint from "'+master+'" to "'+slave+'"! Exception msg: '+str(e))
        print('Error creating constraint from "' + master + '" to "' + slave + '"! Exception msg: ' + str(e))
        constraint = None
Esempio n. 21
0
def copyAnimation(source=None, destination=None, pasteMethod='replace', offset=0, start=None, end=None, layer=None):
    '''
    Actually do the copy and paste from one node to another. If start and end frame is specified,
    set a temporary key before copying, and delete it afterward.
    '''
    
    if layer:
        mc.select(destination)
        mc.animLayer(layer, edit=True, addSelectedObjects=True)
        
        #we want to make sure rotation values are within 360 degrees, so we don't get flipping when blending layers.
        utl.minimizeRotationCurves(source)
        utl.minimizeRotationCurves(destination)
    
    if pasteMethod=='replaceCompletely' or not start or not end:
        mc.copyKey(source)
        if layer:
            mc.animLayer(layer, edit=True, selected=True)
        mc.pasteKey(destination, option=pasteMethod, timeOffset=offset)
    else:
        
        #need to do this per animation curve, unfortunately, to make sure we're not adding or removing too many keys
        animCurves = mc.keyframe(source, query=True, name=True)
        if not animCurves:
            return
        
        #story cut keytimes as 2 separate lists means we only have to run 2 cutkey commands, rather than looping through each
        cutStart = list()
        cutEnd = list()
        for curve in animCurves:
        
            #does it have keyframes on the start and end frames?
            startKey = mc.keyframe(curve, time=(start,), query=True, timeChange=True)
            endKey = mc.keyframe(curve, time=(end,), query=True, timeChange=True)

            #if it doesn't set a temporary key for start and end
            #and store the curve name in the appropriate list
            if not startKey:
                mc.setKeyframe(curve, time=(start,), insert=True)
                cutStart.append(curve)
            if not endKey: 
                mc.setKeyframe(curve, time=(end,), insert=True)
                cutEnd.append(curve)
            
        mc.copyKey(source, time=(start,end))
        if layer:
            for each in mc.ls(type='animLayer'):
                mc.animLayer(each, edit=True, selected=False, preferred=False)
            mc.animLayer(layer, edit=True, selected=True, preferred=True)
        mc.pasteKey(destination, option=pasteMethod, time=(start,end), copies=1, connect=0, timeOffset=offset)

        #if we set temporary source keys, delete them now
        if cutStart:
            mc.cutKey(cutStart, time=(start,))
        if cutEnd:
            mc.cutKey(cutEnd, time=(end,))
Esempio n. 22
0
def keyCopyObjects( fromList, toList, start, end ):
    
    for i in range( len( fromList ) ):
        fromCtl = fromList[i]
        toCtl   = toList[i]
        
        isTransMirror = False
        isZRotMirror    = False
        for transMirrorName in CtlInfo.xTransMirrorTargetNames:
            if fromCtl.find( transMirrorName ) != -1:
                isTransMirror = True
        for zRotMirror in CtlInfo.zRotMirrorTargetNames:
            if fromCtl.find( zRotMirror ) != -1 and fromCtl.find( 'wing_big4_CTL' ) == -1:
                isZRotMirror = True
        
        listAttr = cmds.listAttr( fromCtl, k=1 )
        if not listAttr: continue
        for attr in listAttr:
            times = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), tc=1 )
            if not times: continue
            
            values = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), vc=1 )
            keyLocks = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), lock=1 )
            inAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), ia=1 )
            outAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), oa=1 )
    
            cmds.cutKey( toCtl+'.'+attr, t=(start+0.01, end-0.01) )
            for i in range( len( times ) ):
                if attr.find( 'scale' ) != -1:
                    value = values[i]
                    ia = inAngles[i]
                    oa = outAngles[i]
                elif attr.find( 'translate' ) != -1:
                    if isTransMirror and attr[-1] == ['Y','Z']:
                        value = values[i]
                        ia = inAngles[i]
                        oa = outAngles[i]
                    else:
                        value = -values[i]
                        ia = -inAngles[i]
                        oa = -outAngles[i]
                else:
                    if isZRotMirror and attr[-1] in [ 'X', 'Y' ]:
                        value = -values[i]
                        ia = -inAngles[i]
                        oa = -outAngles[i]
                    else:
                        value = values[i]
                        ia = inAngles[i]
                        oa = outAngles[i]
                cmds.setKeyframe( toCtl+'.'+attr, t=times[i], v=value )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=0 )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), ia=ia )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), oa=oa )
                cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=keyLocks[i] )
Esempio n. 23
0
def _applyBakedAnimation(obj):
    '''Connetti l'animazione del bake locator all'oggetto.'''

    # se il locator non e' stato creato (niente da bakare) esci
    locatorName = obj + _locSfx
    locList = cmds.ls(locatorName)
    if not locList:
        return
    loc = locList[0]

    # se esiste cancella il nodo rigidBody e il solver
    try:
        rb = _getRigidBody(obj)
        if rb:
            solver = cmds.listConnections(rb + '.generalForce', s=False)[0]
            cmds.delete(rb)
            # se il rigid solver non e' usato cancellalo
            if not cmds.listConnections(solver + '.generalForce', d=False):
                cmds.delete(solver)
    # se il nodo rigidBody e' referenziato allora disconnetti solamente i choice dagli attributi dell'oggetto
    except:
        for choice in cmds.listConnections(obj, d=False, s=True, t='choice'):
            cmds.disconnectAttr(choice + '.output', cmds.listConnections(choice + '.output', p=True)[0])

    # cancella eventuali chiavi nel nodo di trasformazione dell'oggetto
    cmds.cutKey(obj, at=['t', 'r'])

    # trova le curve d'animazione del locator
    animCurves = cmds.listConnections(loc, d=False, type='animCurve')

    # rinominale
    for animCurve in animCurves:
        undIdx = animCurve.rindex('_')
        cmds.rename(animCurve, '%s%s' % (obj, animCurve[undIdx:]))

    # connetti le curve d'animazione all'oggetto
    attrs = cmds.listAttr([obj + '.t', obj + '.r'], u=True, s=True)
    if not attrs:
        return

    for attr in attrs:
        curve = '%s_%s' % (obj, attr)
        curveNameAttr = '%s.output' % curve
        cmds.connectAttr(curveNameAttr, '%s.%s' % (obj, attr))

        # remove namespace from anim curve
        if ':' in curve:
            cmds.rename(curve, curve[curve.index(':')+1:])

    # pulisci le curve
    sys.stdout.write('Optimizing translation and rotation keys...\n')
    _cleanCurves(['%s.%s' % (obj, s) for s in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']])

    # cancella il locator
    cmds.delete(loc)
Esempio n. 24
0
def _applyBakedAnimation(obj):
	'' 'Connect bake the animation of the locator object.'''
	
	# If the locator is not 'created (nothing to Bakare) exit
	locatorName = obj + _locSfx
	locExists = cmds.ls(locatorName)
	if not locExists:
		return
	
	# If this exists deletes the node rigidBody and the solver
	try:
		rb = _getRigidBody(obj)
		if rb:
			solver = cmds.listConnections(rb + '.generalForce', s=False)[0]
			cmds.delete(rb)
			# If a non-rigid solver and 'delete used
			if not cmds.listConnections(solver + '.generalForce', d=False):
				cmds.delete(solver)
	# If the node rigidBody and 'referenced only then disconnect the choice by the attributes of the object
	except:
		for choice in cmds.listConnections(obj, d=False, s=True, t='choice'):
			cmds.disconnectAttr(choice + '.output', cmds.listConnections(choice + '.output', p=True)[0])
	
	# Delete any keys in the node object's transformation
	cmds.cutKey(obj, at=['t', 'r'])
	
	# Find the animation curves of the locator
	animCurves = cmds.listConnections(locatorName, d=False, type='animCurve')
	
	#running euler filter on curves
	cmds.filterCurve(animCurves)
	
	# rinominale
	for crv in animCurves:

		newName=obj+'_'+crv.split('_')[-1]
		cmds.rename(crv,newName)
	
	# Connect the animation curves of the object
	attrs = cmds.listAttr([obj + '.t', obj + '.r'], u=True, s=True)
	
	if not attrs:
		return
	
	for attr in attrs:
		curveNameAttr = '%s_%s.output' % (obj, attr)
		cmds.connectAttr(curveNameAttr, '%s.%s' % (obj, attr))
	
	# pulisci le curve
	sys.stdout.write('Optimizing translation and rotation keys...\n')
	_cleanCurves(['%s.%s' % (obj, s) for s in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']])
	
	# cancella il locator
	cmds.delete(locatorName)
Esempio n. 25
0
 def Delect(self):                     
     min = cmds.intField('min',q=1,value=1)
     max = cmds.intField('max',q=1,value=1)
     a = int(max)
     b = int(min)
     print b
     print a
     if a<=b:
         print cmds.error(' The minimum value is greater than the maximum value')
     else:             
         for i in range(a):        
             if b<i<a:
                 cmds.cutKey('polyAverageVertex'+str(i))          
def delAnimIndex( val, tsl ):
	'''
	Function that deletes an index number of the animation curve from the selected attribute
	'''
	
	# call the getAnimCurve function and assign result to curveName
	curveName = getAnimCurve( tsl )
	
	# deletes the desired index of animation curve
	cmds.cutKey( curveName, index=(val,val) ) 
	
	# call the popAnimMenu function to rebuild the popupMenu
	popAnimMenu( tsl )
Esempio n. 27
0
def cutAndFill() :

    ''' cut the selected keys out and linear fill the gap '''

    try :
        item = getItem()
    except ValueError as e :
        print "Unable to cut and fill: " + str(e)
        return

    times = m.keyframe(item, q=True, sl=True)
    m.cutKey(item, time=(min(times), max(times)))
    (start, end) = findCurrentGap(item, min(times))
    fillGapLinear(item, start=start, end=end)
Esempio n. 28
0
def _cleanCurves(animCurves):
    '''Pulisce le curve rimuovendo le chiavi superflue.'''

    tol = 0.0001
    for c in animCurves:
        keyCount = cmds.keyframe(c, query=True, keyframeCount=True)
        if keyCount == 0:
            continue
        # cancella le chiavi superflue intermedie
        if keyCount > 2:
            times = cmds.keyframe(c, query=True, index=(0, keyCount-1), timeChange=True)
            values = cmds.keyframe(c, query=True, index=(0, keyCount-1), valueChange=True)
            inTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), inAngle=True)
            outTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), outAngle=True)
            for i in range(1, keyCount-1):
                if math.fabs(values[i]-values[i-1]) < tol and math.fabs(values[i+1]-values[i]) < tol and math.fabs(inTan[i]-outTan[i-1]) < tol and math.fabs(inTan[i+1]-outTan[i]) < tol:
                    cmds.cutKey(c, time=(times[i], times[i]))

        # ricalcola il numero di chiavi e pulisce le chiavi agli estremi
        keyCount = cmds.keyframe(c, query=True, keyframeCount=True)
        times = cmds.keyframe(c, query=True, index=(0, keyCount-1), timeChange=True)
        values = cmds.keyframe(c, query=True, index=(0, keyCount-1), valueChange=True)
        inTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), inAngle=True)
        outTan = cmds.keyTangent(c, query=True, index=(0, keyCount-1), outAngle=True)
        # piu' di due key rimanenti
        if keyCount > 2:
            if math.fabs(values[1]-values[0]) < tol and math.fabs(inTan[1]-outTan[0]) < tol:
                cmds.cutKey(c, time=(times[0], times[0]))
            if math.fabs(values[-1]-values[-2]) < tol and math.fabs(inTan[-1]-outTan[-2]) < tol:
                cmds.cutKey(c, time=(times[-1], times[-1]))
        # uno o due key rimanenti
        elif keyCount == 1 or (math.fabs(values[1]-values[0]) < tol and math.fabs(inTan[1]-outTan[0]) < tol):
            val = cmds.getAttr(c)       # debuggato
            cmds.cutKey(c)
            cmds.setAttr(c, val)
Esempio n. 29
0
def deleteRedundantKeys(selectionOption=1):
    
    keySel = _getKeySelection(selectionOption)
    for curve, values in zip(keySel.curves, keySel.values):
        groups = [list(g) for k, g in itertools.groupby(values)]
        i = -1
        cutIndex = list()
        for group in groups:
            gsize = len(group)
            if gsize > 2:
                cutIndex.extend(range(i+2,i+gsize))
            i+=gsize
        if cutIndex:
            mc.cutKey(curve, index=utl.castToTime(cutIndex))
Esempio n. 30
0
def _resetRigidBody(obj):
    '''Cancella le chiavi messe al rigid body.'''

    rb = _getRigidBody(obj)
    if rb:
        # cancella le chiavi attivo-passivo
        cmds.cutKey(rb, cl=True, at='act')
        cmds.setAttr(rb + '.act', 1)
        # cancella le chiavi di posizione per lo stato passivo
        try:
            choices = cmds.listConnections(obj, d=False, s=True, t='choice')
            animCurves = [cmds.listConnections(s + '.input[1]', d=False, s=True)[0] for s in choices]
            cmds.delete(animCurves)
        except:
            pass
Esempio n. 31
0
def createRig(
    upperVertexList,
    lowerVertexList,
    prefix='L_',
    rigPartName='EyeLid',
    rigScale=1.0,
    eyeJoint='',
    numCtrl=5,
):

    if numCtrl < 3:
        cmds.error('numCtrl must bigger than 3!')
        return
    cmds.select(cl=1)
    # create eyeLid Module
    eyeLidRigModule = module.Module(prefix=prefix, rigPartName=rigPartName)

    # create upper eyelid Module
    upperLidRigModule = module.Module(prefix=prefix,
                                      rigPartName='upper_' + rigPartName)

    #####################
    # Upper Eyelid Part #
    #####################

    # create eyelid joint for each vertex
    upperEyeLidJointList = lib.vertex2Joints(vertexList=upperVertexList,
                                             prefix=prefix,
                                             rigPartName='upper_' +
                                             rigPartName,
                                             radius=0.05)

    # connect attr
    for joint in upperEyeLidJointList:
        if cmds.attributeQuery('slaveJoint', node=joint, exists=1):
            cmds.connectAttr(upperLidRigModule.topGrp + '.slaveJoint',
                             joint + '.slaveJoint',
                             f=1)

    # create eyelid parent joint for each eyelid joint
    upperEyeLidParentJntList = []
    for i in upperEyeLidJointList:
        cmds.select(cl=1)

        parentJoint = cmds.joint(n=i + '_Parent', radius=0.05)

        cmds.delete(cmds.pointConstraint(eyeJoint, parentJoint, mo=0))

        cmds.delete(
            cmds.aimConstraint(i,
                               parentJoint,
                               aimVector=(1, 0, 0),
                               upVector=(0, -1, 0),
                               worldUpType='scene',
                               weight=1,
                               offset=(0, 0, 0),
                               mo=0))
        cmds.parent(i, parentJoint)

        cmds.joint(i, e=1, oj='none', ch=1, zso=1)

        cmds.makeIdentity(parentJoint, apply=1, t=1, r=1, s=1)

        upperEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

    upperEyelidLocList = []
    # create locator for each eyelid joint
    for i in upperEyeLidParentJntList:

        cmds.select(cl=1)

        eyelidJoint = cmds.listRelatives(i, c=1, type='joint', shapes=0)[0]

        ikHandle = cmds.ikHandle(n=eyelidJoint + '_IK',
                                 sj=i,
                                 ee=eyelidJoint,
                                 sol='ikSCsolver')

        eyelidLoc = cmds.spaceLocator(n=eyelidJoint + '_LOC')[0]

        cmds.delete(cmds.parentConstraint(eyelidJoint, eyelidLoc, mo=0))

        cmds.select(cl=1)

        cmds.setAttr(ikHandle[0] + '.v', 0)
        LOCShape = cmds.listRelatives(eyelidLoc, p=0, c=1, s=1)[0]
        cmds.setAttr(LOCShape + '.localScaleX', 0.1)
        cmds.setAttr(LOCShape + '.localScaleY', 0.1)
        cmds.setAttr(LOCShape + '.localScaleZ', 0.1)

        cmds.parent(ikHandle[0], eyelidLoc)

        upperEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

    # create high definition curve
    lowerPosList = []
    for i in upperEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        lowerPosList.append(tuple(pos))

    upperKList = []
    for i in xrange(len(lowerPosList)):
        upperKList.append(i)

    upperHighDefCurve = cmds.curve(n=prefix + 'upper_' + rigPartName +
                                   '_HD_Crv',
                                   p=lowerPosList,
                                   k=upperKList,
                                   d=1)
    upperLowDefCurve = cmds.duplicate(upperHighDefCurve,
                                      n=prefix + 'lower_' + rigPartName +
                                      '_LD_Crv')

    upperHighDefCurveShape = cmds.listRelatives(upperHighDefCurve,
                                                p=0,
                                                c=0,
                                                s=1,
                                                path=1)[0]
    cmds.select(cl=1)

    # make each locator attach to the curve

    for i in upperEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        uParam = lib.getUParam(pos, upperHighDefCurveShape)

        PCI = cmds.createNode('pointOnCurveInfo',
                              n=name.removeSuffix(i) + '_PCI')

        cmds.connectAttr(upperHighDefCurveShape + '.worldSpace',
                         PCI + '.inputCurve',
                         f=1)

        cmds.setAttr(PCI + '.parameter', uParam)

        cmds.connectAttr(PCI + '.position', i + '.t')

        cmds.select(cl=1)

    # make HD curve deformed by LD curve
    upperLowDefCurve = cmds.rebuildCurve(upperLowDefCurve,
                                         ch=0,
                                         rpo=1,
                                         rt=0,
                                         end=1,
                                         kr=0,
                                         kcp=0,
                                         kep=1,
                                         kt=0,
                                         s=3,
                                         d=3)
    cmds.select(cl=1)

    upperWireDefomer = cmds.wire(upperHighDefCurve,
                                 gw=0,
                                 en=1,
                                 ce=0,
                                 li=0,
                                 w=upperLowDefCurve)
    upperWireTransNode = cmds.listConnections(upperWireDefomer[0] +
                                              '.baseWire[0]',
                                              source=1,
                                              destination=0)

    cmds.select(cl=1)

    # create control joint and controls for the LD curve
    upperControlJointList = []

    eachADD = 1.0 / (numCtrl - 1)

    for i in xrange(numCtrl):
        newJnt = cmds.joint(n=prefix + 'upper_' + rigPartName + '_CtrlJnt_' +
                            str(i),
                            radius=0.1)
        cmds.select(cl=1)
        motionPath = cmds.pathAnimation(upperLowDefCurve,
                                        newJnt,
                                        n=prefix + rigPartName + '_MP_' +
                                        str(i),
                                        fractionMode=1,
                                        follow=1,
                                        followAxis='x',
                                        upAxis='z',
                                        worldUpType='scene',
                                        inverseUp=0,
                                        inverseFront=0,
                                        bank=0)

        cmds.cutKey(motionPath + '.u', time=())

        cmds.setAttr(motionPath + '.uValue', eachADD * float(i))

        for attr in ['t', 'r']:
            for axis in ['x', 'y', 'z']:
                cmds.delete(newJnt + '.%s%s' % (attr, axis), icn=1)

        cmds.delete(motionPath)
        cmds.select(cl=1)

        upperControlJointList.append(newJnt)

        cmds.setAttr(newJnt + '.r', 0, 0, 0)
        cmds.select(cl=1)

    # bind LD curve by control joint
    cmds.skinCluster(upperControlJointList[:], upperLowDefCurve)
    cmds.select(cl=1)

    upperJntCtrlGrpList = []
    for i in xrange(len(upperControlJointList)):
        ctrl = control.Control(prefix=upperControlJointList[i],
                               rigPartName='',
                               scale=rigScale,
                               shape='circleY',
                               translateTo=upperControlJointList[i],
                               rotateTo=upperControlJointList[i])

        cmds.pointConstraint(ctrl.C, upperControlJointList[i], mo=0)
        cmds.orientConstraint(ctrl.C, upperControlJointList[i], mo=0)

        upperJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

    # clean hierarchy
    upperParentJntGrp = cmds.group(n=prefix + 'upper_' + rigPartName +
                                   '_skinJnt_Grp',
                                   em=1)
    upperLocGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_LOC_Grp',
                             em=1)
    upperCurveGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_Crv_Grp',
                               em=1)
    upperCtrlJntGrp = cmds.group(n=prefix + 'upper_' + rigPartName +
                                 '_ctrlJnt_Grp',
                                 em=1)
    upperCtrlGrp = cmds.group(n=prefix + 'upper_' + rigPartName + '_CtrlGrp',
                              em=1)

    for i in upperEyeLidParentJntList:
        cmds.parent(i, upperParentJntGrp)

    for i in upperEyelidLocList:
        cmds.parent(i, upperLocGrp)

    cmds.parent(upperLowDefCurve, upperCurveGrp)
    cmds.parent(upperHighDefCurve, upperCurveGrp)
    cmds.parent(upperWireTransNode, upperCurveGrp)

    for i in upperControlJointList:
        cmds.parent(i, upperCtrlJntGrp)

    for i in upperJntCtrlGrpList:
        cmds.parent(i, upperCtrlGrp)

    cmds.setAttr(upperLocGrp + '.v', 0)
    cmds.setAttr(upperCurveGrp + '.v', 0)
    cmds.setAttr(upperCtrlJntGrp + '.v', 0)

    cmds.parent(upperParentJntGrp, upperLidRigModule.topGrp)
    cmds.parent(upperLocGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCurveGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCtrlJntGrp, upperLidRigModule.topGrp)
    cmds.parent(upperCtrlGrp, upperLidRigModule.topGrp)

    ###################################################################################################################

    #####################
    # Lower Eyelid Part #
    #####################

    # create lower eyelid Module
    lowerLidRigModule = module.Module(prefix=prefix,
                                      rigPartName='lower_' + rigPartName)

    # create eyelid joint for each vertex
    lowerEyeLidJointList = lib.vertex2Joints(vertexList=lowerVertexList,
                                             prefix=prefix,
                                             rigPartName='lower_' +
                                             rigPartName,
                                             radius=0.05)

    # connect attr
    for joint in lowerEyeLidJointList:
        if cmds.attributeQuery('slaveJoint', node=joint, exists=1):
            cmds.connectAttr(lowerLidRigModule.topGrp + '.slaveJoint',
                             joint + '.slaveJoint',
                             f=1)

    # create eyelid parent joint for each eyelid joint
    lowerEyeLidParentJntList = []
    for i in lowerEyeLidJointList:
        cmds.select(cl=1)

        parentJoint = cmds.joint(n=i + '_Parent', radius=0.05)

        cmds.delete(cmds.pointConstraint(eyeJoint, parentJoint, mo=0))

        cmds.delete(
            cmds.aimConstraint(i,
                               parentJoint,
                               aimVector=(1, 0, 0),
                               upVector=(0, -1, 0),
                               worldUpType='scene',
                               weight=1,
                               offset=(0, 0, 0),
                               mo=0))
        cmds.parent(i, parentJoint)

        cmds.joint(i, e=1, oj='none', ch=1, zso=1)

        cmds.makeIdentity(parentJoint, apply=1, t=1, r=1, s=1)

        lowerEyeLidParentJntList.append(parentJoint)

    cmds.select(cl=1)

    lowerEyelidLocList = []
    # create locator for each eyelid joint
    for i in lowerEyeLidParentJntList:
        cmds.select(cl=1)

        eyelidJoint = cmds.listRelatives(i, c=1, type='joint', shapes=0)[0]

        ikHandle = cmds.ikHandle(n=eyelidJoint + '_IK',
                                 sj=i,
                                 ee=eyelidJoint,
                                 sol='ikSCsolver')

        eyelidLoc = cmds.spaceLocator(n=eyelidJoint + '_LOC')[0]

        cmds.delete(cmds.parentConstraint(eyelidJoint, eyelidLoc, mo=0))

        cmds.select(cl=1)

        cmds.setAttr(ikHandle[0] + '.v', 0)
        LOCShape = cmds.listRelatives(eyelidLoc, p=0, c=1, s=1)[0]
        cmds.setAttr(LOCShape + '.localScaleX', 0.1)
        cmds.setAttr(LOCShape + '.localScaleY', 0.1)
        cmds.setAttr(LOCShape + '.localScaleZ', 0.1)

        cmds.parent(ikHandle[0], eyelidLoc)

        lowerEyelidLocList.append(eyelidLoc)

    cmds.select(cl=1)

    # create high definition curve
    lowerPosList = []
    for i in lowerEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        lowerPosList.append(tuple(pos))

    lowerKList = []
    for i in xrange(len(lowerPosList)):
        lowerKList.append(i)

    lowerHighDefCurve = cmds.curve(n=prefix + 'lower_' + rigPartName +
                                   '_HD_Crv',
                                   p=lowerPosList,
                                   k=lowerKList,
                                   d=1)
    lowerLowDefCurve = cmds.duplicate(lowerHighDefCurve,
                                      n=prefix + 'lower_' + rigPartName +
                                      '_LD_Crv')

    lowerHighDefCurveShape = cmds.listRelatives(lowerHighDefCurve,
                                                p=0,
                                                c=0,
                                                s=1,
                                                path=1)[0]
    cmds.select(cl=1)

    # make each locator attach to the curve

    for i in lowerEyelidLocList:
        pos = cmds.xform(i, q=1, ws=1, t=1)
        uParam = lib.getUParam(pos, lowerHighDefCurveShape)

        PCI = cmds.createNode('pointOnCurveInfo',
                              n=name.removeSuffix(i) + '_PCI')

        cmds.connectAttr(lowerHighDefCurveShape + '.worldSpace',
                         PCI + '.inputCurve',
                         f=1)

        cmds.setAttr(PCI + '.parameter', uParam)

        cmds.connectAttr(PCI + '.position', i + '.t')

        cmds.select(cl=1)

    # make HD curve deformed by LD curve
    lowerLowDefCurve = cmds.rebuildCurve(lowerLowDefCurve,
                                         ch=0,
                                         rpo=1,
                                         rt=0,
                                         end=1,
                                         kr=0,
                                         kcp=0,
                                         kep=1,
                                         kt=0,
                                         s=3,
                                         d=3)
    cmds.select(cl=1)

    lowerWireDefomer = cmds.wire(lowerHighDefCurve,
                                 gw=0,
                                 en=1,
                                 ce=0,
                                 li=0,
                                 w=lowerLowDefCurve)
    lowerWireTransNode = cmds.listConnections(lowerWireDefomer[0] +
                                              '.baseWire[0]',
                                              source=1,
                                              destination=0)

    cmds.select(cl=1)

    # create control joint and controls for the LD curve
    lowerControlJointList = []

    eachADD = 1.0 / (numCtrl - 1)

    for i in xrange(numCtrl - 2):
        newJnt = cmds.joint(n=prefix + 'lower_' + rigPartName + '_CtrlJnt_' +
                            str(i + 1),
                            radius=0.1)
        cmds.select(cl=1)
        motionPath = cmds.pathAnimation(lowerLowDefCurve,
                                        newJnt,
                                        n=prefix + rigPartName + '_MP_' +
                                        str(i + 1),
                                        fractionMode=1,
                                        follow=1,
                                        followAxis='x',
                                        upAxis='z',
                                        worldUpType='scene',
                                        inverseUp=0,
                                        inverseFront=0,
                                        bank=0)

        cmds.cutKey(motionPath + '.u', time=())

        cmds.setAttr(motionPath + '.uValue', eachADD * float(i + 1))

        for attr in ['t', 'r']:
            for axis in ['x', 'y', 'z']:
                cmds.delete(newJnt + '.%s%s' % (attr, axis), icn=1)

        cmds.delete(motionPath)
        cmds.select(cl=1)

        lowerControlJointList.append(newJnt)

        cmds.setAttr(newJnt + '.r', 0, 0, 0)
        cmds.select(cl=1)

    lowerControlJointList.insert(0, upperControlJointList[0])
    lowerControlJointList.append(upperControlJointList[-1])

    # bind LD curve by control joint
    cmds.skinCluster(lowerControlJointList[:], lowerLowDefCurve)
    cmds.select(cl=1)

    lowerJntCtrlGrpList = []
    for i in xrange(len(lowerControlJointList[1:-1])):
        ctrl = control.Control(prefix=lowerControlJointList[i + 1],
                               rigPartName='',
                               scale=rigScale,
                               shape='circleY',
                               translateTo=lowerControlJointList[i + 1],
                               rotateTo=lowerControlJointList[i + 1])

        cmds.pointConstraint(ctrl.C, lowerControlJointList[i + 1], mo=0)
        cmds.orientConstraint(ctrl.C, lowerControlJointList[i + 1], mo=0)

        lowerJntCtrlGrpList.append(ctrl.Off)

    cmds.select(cl=1)

    # clean hierarchy
    lowerParentJntGrp = cmds.group(n=prefix + 'lower_' + rigPartName +
                                   '_skinJnt_Grp',
                                   em=1)
    lowerLocGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_LOC_Grp',
                             em=1)
    lowerCurveGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_Crv_Grp',
                               em=1)
    lowerCtrlJntGrp = cmds.group(n=prefix + 'lower_' + rigPartName +
                                 '_ctrlJnt_Grp',
                                 em=1)
    lowerCtrlGrp = cmds.group(n=prefix + 'lower_' + rigPartName + '_CtrlGrp',
                              em=1)

    for i in lowerEyeLidParentJntList:
        cmds.parent(i, lowerParentJntGrp)

    for i in lowerEyelidLocList:
        cmds.parent(i, lowerLocGrp)

    cmds.parent(lowerLowDefCurve, lowerCurveGrp)
    cmds.parent(lowerHighDefCurve, lowerCurveGrp)
    cmds.parent(lowerWireTransNode, lowerCurveGrp)

    for i in lowerControlJointList:
        cmds.parent(i, lowerCtrlJntGrp)

    for i in lowerJntCtrlGrpList:
        cmds.parent(i, lowerCtrlGrp)

    cmds.setAttr(lowerLocGrp + '.v', 0)
    cmds.setAttr(lowerCurveGrp + '.v', 0)
    cmds.setAttr(lowerCtrlJntGrp + '.v', 0)

    cmds.parent(lowerParentJntGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerLocGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCurveGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCtrlJntGrp, lowerLidRigModule.topGrp)
    cmds.parent(lowerCtrlGrp, lowerLidRigModule.topGrp)

    # final
    cmds.parent(upperLidRigModule.topGrp, eyeLidRigModule.topGrp)
    cmds.parent(lowerLidRigModule.topGrp, eyeLidRigModule.topGrp)

    cmds.select(cl=1)
Esempio n. 32
0
import maya.cmds as cmds

my_guy = 'polySurface21'

#Select my guy
cmds.select(my_guy, r=True)

#clear animation
start_time = cmds.playbackOptions(query=True, minTime=True)
end_time = cmds.playbackOptions(query=True, maxTime=True)

cmds.cutKey(time=(start_time, end_time))

#Rotate
cmds.rotate(0.0, 90.0, 0.0, r=True, os=True)

#Scale
cmds.scale(1.1, 1.1, 1.1, r=True)

#Translate
cmds.move(0, 3.0, 0.0, r=True)

#Move camera
cmds.orbit('persp', ha=90)

inc = end_time / 5

#Animated Part
for i in range(0, 6):
    my_time = (end_time / 5) * i
    my_rotation = (360 / 5) * i
Esempio n. 33
0
def armIkToFk(rigNS, side, bakeWrist=True, start=None, end=None, sampleBy=1):
    """
    Bake IK arm animation to FK controls
    @param rigNS: IK/FK toggle attribute
    @type rigNS: str
    @param side: Arm side ("lf" or "rt")
    @type side: str
    @param bakeWrist: Bake wrist animation
    @type bakeWrist: bool
    @param start: Transfer animation start frame
    @type start: int or None
    @param end: Transfer animation end frame
    @type end: int or None
    @param sampleBy: Bake animation by N frames
    @type sampleBy: int
    """
    # ==========
    # - Checks -
    # ==========

    # Get Start/End
    if start == None: start = cmds.playbackOptions(q=True, min=True)
    if end == None: end = cmds.playbackOptions(q=True, max=True)

    # Get IK/FK Joints
    ikJntList = [
        rigNS + ':' + side + '_arm_ik' + i + '_jnt' for i in ['A', 'B']
    ]
    fkJntList = [
        rigNS + ':' + side + '_arm_fk' + i + '_jnt' for i in ['A', 'B']
    ]

    # =====================
    # - Bake IK Limb Anim -
    # =====================

    # Set Arm to IK mode
    cmds.setAttr(rigNS + ':config.' + side + 'ArmIkFkBlend', 0)  # IK

    # Bake Wrist to Locator
    wristLoc = None
    wristJnt = rigNS + ':' + side + '_handA_jnt'
    if bakeWrist:
        wristLoc = glTools.anim.utils.bakeAnimToLocator(
            obj=wristJnt,
            start=start,
            end=end,
            sampleBy=sampleBy,
            simulation=True,
            attrList=['rx', 'ry', 'rz'])

    # Duplicate FK Joints and Constrain to IK
    fkDupList = []
    fkOriList = []
    for i in range(2):
        fkDupList.append(cmds.duplicate(fkJntList[i], po=True)[0])
        fkOriList.append(cmds.orientConstraint(ikJntList[i], fkDupList[-1])[0])

    # =============================
    # - Transfer Baked Anim to FK -
    # =============================

    cmds.refresh(suspend=True)
    for i in range(2):
        cmds.bakeResults(fkDupList[i],
                         t=(start, end),
                         at=['rx', 'ry', 'rz'],
                         simulation=True,
                         preserveOutsideKeys=True,
                         sampleBy=sampleBy)
        cmds.cutKey(fkDupList[i], at=['rx', 'ry', 'rz'], t=(start, end))
        cmds.pasteKey(fkJntList[i],
                      at=['rx', 'ry', 'rz'],
                      t=(start, end),
                      option='replace')
    cmds.refresh(suspend=False)

    # Delete Duplicate Joints and Constraints
    if fkOriList:
        try:
            cmds.delete(fkOriList)
        except Exception, e:
            print('Error deleting nodes ' + str(fkOriList) +
                  '! Exception Msg: ' + str(e))
Esempio n. 34
0
def setKey(deleteSubFrames=False,
           insert=False,
           selectedChannels=False,
           visibleInGraphEditor=False,
           keyKeyed=False,
           keyShapes=False):
    '''
    The main function arguments:
    
        deleteSubFrames:        Delete sub-frame keys surrounding the current frame
        insert:                 Insert key (preserve tangents)
        selectedChannels:       Only key channels that are selected in the Channel Box
        visibleInGraphEditor:   Only key curves visible in Graph Editor
        keyKeyed:               Only set keys on channels that are already keyed
        keyShapes:              Set keyframes on shapes as well as transforms
    '''

    sel = mc.ls(sl=True)
    if not sel:
        return

    channels = list()

    doInsert = False

    if selectedChannels:
        chanBoxChan = utl.getSelectedChannels()
        if chanBoxChan:
            for obj in sel:
                for attr in chanBoxChan:
                    #shapes don't work here? because the channel doesn't exist on the selected object.
                    if mc.attributeQuery(attr, node=obj, exists=True):
                        channels.append('.'.join((obj, attr)))

    if channels:
        #this is an interface thing, I like to deselect channels if channels were selected
        utl.deselectChannels()

    if visibleInGraphEditor and not channels:
        #then visible in graph editor

        #first check if graph editor open
        if 'graphEditor1' in mc.getPanel(visiblePanels=True):
            graphVis = mc.selectionConnection('graphEditor1FromOutliner',
                                              query=True,
                                              obj=True)
            if graphVis:
                curves = mc.keyframe(graphVis, query=True, name=True)
                if curves:
                    for c in curves:
                        chan = utl.getChannelFromAnimCurve(c)
                        if chan:
                            channels.append(chan)
                    if channels:
                        doInsert = insert

    if keyKeyed and not channels:
        #otherwise try keyed channels.
        curves = mc.keyframe(sel, query=True, name=True)
        if curves:
            for c in curves:
                chan = utl.getChannelFromAnimCurve(c)
                if chan:
                    channels.append(chan)
            if channels:
                doInsert = insert

    if not channels:
        #otherwise just all the selected nodes, flatten the keyable channels.
        for each in sel:
            if doInsert != insert and mc.keyframe(each, query=True, eval=True):
                #if there's keyframe values, we can can still insert
                doInsert = insert

            attrs = mc.listAttr(each, keyable=True, settable=True)
            if attrs:
                channels.extend(['.'.join((each, attr)) for attr in attrs])

    if not channels:
        OpenMaya.MGlobal.displayWarning('No channels specified.')
        return

    #if the user has middle-mouse dragged, we don't want to insert
    #test this by comparing the current attribute value with the evaluated animation curve
    #also check if there's n
    if doInsert:
        for each in channels:
            curveValue = mc.keyframe(each, query=True, eval=True)
            if not curveValue:
                doInsert = False
                break
            if round(mc.getAttr(each), 3) != round(curveValue[0], 3):
                doInsert = False
                break

    #this is a special arg, which creates keys on the attributes determined so far
    mc.setKeyframe(channels, insert=doInsert, shape=keyShapes)

    #remove nearby sub-frames
    #this breaks at higher frame ranges because maya doesn't keep enough digits
    #this value is also different for different frame rates
    time = mc.currentTime(query=True)
    if deleteSubFrames and time % 1 == 0 and -9999 < time < 9999:
        #the distance that keys can be is independent of frame rate, so we have to convert based on the frame rate.
        tol = getFrameRate() / 6000.0
        mc.cutKey(channels, time=(time + tol, time + 0.5))
        mc.cutKey(channels, time=(time - 0.5, time - tol))
Esempio n. 35
0
def keyClearAll(keyTimeMax):
    cmds.cutKey('Hand_Left', time=(0, 800))
    cmds.cutKey('Hand_Right', time=(0, 800))
    cmds.cutKey('Hips', time=(0, 800))
    cmds.cutKey('Iris_Left', time=(0, 800))
    cmds.cutKey('Iris_Right', time=(0, 800))
    cmds.cutKey('Animation_Camera', time=(0, 800))
Esempio n. 36
0
#File:      torus.py
#Author:    Mariana Avalos
#Date:      22/03/2019
#Description: Python code that makes animation of a torus movement

import maya.cmds as cmds
import math

objs = cmds.ls(selection=True)  #lista de los objetos en escena
cmds.cutKey(objs)
obj = objs[0]

r = 4
R = 8
frames = 500

if (R <= r):
    r = 2
    R = 10
if frames <= 0:
    frames = 80

xPos = 0
yPos = 0
frame = 0
freq = R * 4  # the torus will make R * 4 revolutions
for i in range(0, frames):
    frame = i
    xPos = math.cos(math.radians(360.0 / frames * i)) * (
        R + r * math.cos(math.radians(freq * (360.0 / frames * i))))
    zPos = math.sin(math.radians(360.0 / frames * i)) * (
Esempio n. 37
0
def unParentToWorld(objs,
                    withChild=False,
                    parentChild=True,
                    save=False,
                    disconnect=True,
                    relatedObjs=[]):
    attrs = [
        "tx", "ty", "tz", "rx", "ry", "rz", "sx", "sy", "sz", "t", "r", "s"
    ]
    saveList = [{}, {}]

    #-------------------------------------------------------------------------------
    # save the uid
    #-------------------------------------------------------------------------------
    if relatedObjs:
        uRelatedObjs = cmds.ls(relatedObjs, uid=1)
    uObjs = cmds.ls(objs, uid=1)

    #-------------------------------------------------------------------------------
    # clear connection before unparent
    #-------------------------------------------------------------------------------
    if save:
        for obj in objs:
            locked_attrs = []
            for attr in attrs:
                attr_name = "%s.%s" % (obj, attr)

                #unlock locked transformtions
                if cmds.getAttr(attr_name, l=1):
                    locked_attrs.append(attr)
                    cmds.setAttr(attr_name, l=0)

                #delete transformtions'key
                cmds.cutKey(attr_name, cl=1, t=(), f=())

                if disconnect:
                    #disconnect transformtions
                    connect_s = cmds.listConnections(attr_name, d=0, s=1, p=1)
                    if connect_s:
                        connect_s = connect_s[0]
                        cmds.disconnectAttr(connect_s, attr_name)

            if locked_attrs:
                saveList[1].update({cmds.ls(item, uid=1)[0]: locked_attrs})

            #unlimit transformtions
            cmds.transformLimits(obj,
                                 etx=(0, 0),
                                 ety=(0, 0),
                                 etz=(0, 0),
                                 erx=(0, 0),
                                 ery=(0, 0),
                                 erz=(0, 0),
                                 esx=(0, 0),
                                 esy=(0, 0),
                                 esz=(0, 0))

            items = [obj]
            if not withChild:
                children = getChl(obj, type='transform')
                if children: items.extend(children)

            for item in items:
                prt = getPrt(item)
                if prt:
                    saveList[0].update(
                        {cmds.ls(item, uid=1)[0]: cmds.ls(prt, uid=1)[0]})

    #-------------------------------------------------------------------------------
    # parent chrldren to the world or to origin parent
    #-------------------------------------------------------------------------------
    if not withChild:
        for obj in objs:
            prt = getPrt(obj)
            children = getChl(obj, type='transform')
            if children:
                for child in children:
                    if prt and parentChild:
                        cmds.parent(child, prt)
                    else:
                        cmds.parent(child, w=1)

    #update name
    objs = cmds.ls(uObjs, l=1)

    #-------------------------------------------------------------------------------
    # unparent to the world
    #-------------------------------------------------------------------------------
    for obj in objs:
        prt = getPrt(obj)
        if prt:
            cmds.parent(obj, w=1)

    #load from uid
    objs = cmds.ls(uObjs, l=1)
    if save and relatedObjs:
        relatedObjs = cmds.ls(uRelatedObjs, l=1)
        return relatedObjs, saveList
    if not save and relatedObjs:
        relatedObjs = cmds.ls(uRelatedObjs, l=1)
        return relatedObjs
    if save and not relatedObjs:
        return objs, saveList
    else:
        return objs
Esempio n. 38
0
def setSDK( sdk, keyList, preInfinity=False, postInfinity=False, insert=False):
    '''
    This will set the data on the setDrivenKeyframe. Most of this information is gathered
    using the data.

    :param keyList: Array containing the key information for each key.
    :type keyList: list | tuple

    :param preInfinity: Whether postInfinity is on the curve for the sdk
    :type preInfinity: bool

    :param postInfinity: Whether preInfinity is on the curve for the sdk
    :type postInfinity: bool

    :param insert: If insert is True then insert into existing sdk, otherwise replace it
    :type insert: bool
    '''
    # if we're replacing the sdk and a name isn't provided, use the name of the existing sdk
    if not mc.objExists(sdk):
        raise RuntimeError("{} doesn't exist in the current Maya session.".format())

    # Get the driver and driven
    driver = getSDKdriver(sdk)
    driven = getSDKdriven(sdk)

    if not insert:
        # create the key frame at a rediculous number to preserve the animCurve node.
        mc.setKeyframe(sdk, insert=True, float=1000001)
        mc.cutKey(sdk,f=(-100000,100000), clear=True)

    # Create keys 
    for keyData in keyList:
       mc.setDrivenKeyframe(driven, cd=driver, dv=keyData['dv'], v=keyData['v'])

    # cut the key at a ridiculous number
    mc.cutKey(sdk,f=(1000001,1000001), clear=True)

    if preInfinity:
        mc.setAttr('{}.preInfinity'.format(sdk), preInfinity)

    if postInfinity:
        mc.setAttr('{}.postInfinity'.format(sdk), postInfinity)

    # then loop to set tangents.  this doesn't work if done in the same loop that the keys are created

    for i, keyData in enumerate(keyList):
        args=keyData.copy()
        args.pop('dv', None)
        args.pop('v', None)
        
        # Make sure the absolute value is set on the curve
        mc.keyframe(sdk,index=(i,i),absolute=True, valueChange= keyData['v'])

        if args:
            # weighted tangets must be applied separately or else other args are ignored
            if keyData.has_key('wt'):
                mc.keyTangent(sdk, f=(keyData['dv'], keyData['dv']), wt=keyData['wt'])
                args.pop('wt', None)
            # if the tangents aren't set to fixed we will take them out and not apply them.
            # reson for this is that if you apply tangents they will automatically be set to fixed.
            if args['itt']!='fixed':
                args.pop('ia', None)
            if args['ott']!='fixed':
                args.pop('oa', None)

            args = rigrepo.libs.common.convertDictKeys(args)
            mc.keyTangent(sdk, f=(keyData['dv'], keyData['dv']), **args)

    return sdk
Esempio n. 39
0
def create(target,
           slaveList,
           slaveAimUp=None,
           weightList=None,
           bakeAnim=False,
           bakeStartEnd=[None, None],
           offsetAnim=None,
           offset=(0, 0, 0),
           cleanup=False):
    '''
	Create a lookAt constraint setup based in the input arguments
	@param target: LookAt target transform.
	@type target: str
	@param slaveList: LookAt slave transform list.
	@type slaveList: list
	@param slaveAimUp: List of slave lookAt aim and up vectors. [(aim,up),('z',x),...]
	@type slaveAimUp: list
	@param weightList: LookAt weight list. If None, use default weight list (evenly distributed).
	@type weightList: list
	@param bakeAnim: Bake lookAt animation to controls.
	@type bakeAnim: bool
	@param bakeStartEnd: Tuple containing start and end frame value.
	@type bakeStartEnd: tuple
	@param offsetAnim: Offset baked lookAt animation.
	@type offsetAnim: float or None
	@param offset: Constraint offset.
	@type offset: tuple
	'''
    # ==========
    # - Checks -
    # ==========

    # Target
    if not glTools.utils.transform.isTransform(target):
        raise Exception(
            'LookAt target "' + target +
            '" is not a valid transform! Unable to create lookAt setup...')

    # Slave List
    if not slaveList:
        raise Exception(
            'Invalid lookAt slave list! Unable to create lookAt setup...')

    # Weight List
    if not weightList:
        print(
            'Invalid lookAt weight list! Generating default lookAt weight list...'
        )
        weightList = range(0, 101, 100.0 / len(slaveList))[1:]
    if len(weightList) != len(slaveList):
        print(
            'Invalid lookAt weight list! Generating default lookAt weight list...'
        )
        weightList = range(0, 101, 100.0 / len(slaveList))[1:]

    # Slave Aim/Up Vectors
    if not slaveAimUp:
        print(
            'Invalid lookAt slave aim/up vector values! Using default lookAt vectors (aim="z",up="y")...'
        )
        slaveAimUp = [('z', 'y') for slave in slaveList]
    if len(slaveAimUp) != len(slaveList):
        print(
            'Invalid lookAt slave aim/up vector values! Using default lookAt vectors (aim="z",up="y")...'
        )
        slaveAimUp = [('z', 'y') for slave in slaveList]

    # ===========
    # - Look At -
    # ===========

    slaveReferenceList = []
    slaveLookAtList = []
    slaveLookAt_aimList = []
    slaveLookAt_orientList = []

    slaveBakeList = []

    for i in range(len(slaveList)):

        # Check Slave Object
        if not mc.objExists(slaveList[i]):
            print('Slave object "' + slaveList[i] + '" not found! Skipping...')
            continue

        # Get Slave Short Name
        slaveSN = slaveList[i].split(':')[0]

        # Duplicate Slave to get Reference and LookAt Targets
        slaveReference = mc.duplicate(slaveList[i],
                                      po=True,
                                      n=slaveSN + '_reference')[0]
        slaveLookAt = mc.duplicate(slaveList[i],
                                   po=True,
                                   n=slaveSN + '_lookAt')[0]

        # Transfer Anim to Reference
        slaveKeys = mc.copyKey(slaveList[i])
        if slaveKeys: mc.pasteKey(slaveReference)

        # Delete Slave Rotation Anim
        mc.cutKey(slaveList[i], at=['rx', 'ry', 'rz'])

        # Create Slave LookAt
        slaveLookAt_aim = glTools.tools.constraint.aimConstraint(
            target=target,
            slave=slaveLookAt,
            aim=slaveAimUp[i][0],
            up=slaveAimUp[i][1],
            worldUpType='scene',
            offset=offset,
            mo=False)[0]

        # Weighted Orient Constraint
        slaveLookAt_orient = mc.orientConstraint([slaveReference, slaveLookAt],
                                                 slaveList[i],
                                                 mo=False)[0]
        slaveLookAt_targets = glTools.utils.constraint.targetAliasList(
            slaveLookAt_orient)

        # Set Constraint Target Weights
        mc.setAttr(slaveLookAt_orient + '.' + slaveLookAt_targets[0],
                   1.0 - (weightList[i] * 0.01))
        mc.setAttr(slaveLookAt_orient + '.' + slaveLookAt_targets[1],
                   weightList[i] * 0.01)
        mc.setAttr(slaveLookAt_orient + '.interpType', 2)  # Shortest

        # Add Message Connections
        mc.addAttr(slaveList[i], ln='lookAtTarget', at='message')
        mc.addAttr(slaveList[i], ln='lookAtAnmSrc', at='message')
        mc.connectAttr(slaveLookAt + '.message',
                       slaveList[i] + '.lookAtTarget',
                       f=True)
        mc.connectAttr(slaveReference + '.message',
                       slaveList[i] + '.lookAtAnmSrc',
                       f=True)

        # Append Lists
        slaveReferenceList.append(slaveReference)
        slaveLookAtList.append(slaveLookAt)
        slaveLookAt_aimList.append(slaveLookAt_aim)
        slaveLookAt_orientList.append(slaveLookAt_orient)

        slaveBakeList.append(slaveList[i])

    # =============
    # - Bake Anim -
    # =============

    if bakeAnim:

        # Get Bake Range
        start = bakeStartEnd[0]
        end = bakeStartEnd[1]
        if start == None: start = mc.playbackOptions(q=True, min=True)
        if end == None: end = mc.playbackOptions(q=True, max=True)

        # Bake Results
        mc.refresh(suspend=True)
        #for slave in slaveBakeList:
        mc.bakeResults(slaveBakeList,
                       t=(start, end),
                       at=['rx', 'ry', 'rz'],
                       simulation=True)
        mc.refresh(suspend=False)

        # Post Bake Cleanup
        if cleanup:
            try:
                mc.delete(slaveLookAt_orientList)
            except:
                pass
            try:
                mc.delete(slaveLookAt_aimList)
            except:
                pass
            try:
                mc.delete(slaveReferenceList)
            except:
                pass
            try:
                mc.delete(slaveLookAtList)
            except:
                pass

    # ====================
    # - Bake Anim Offset -
    # ====================

    if offsetAnim != None:

        # For Each Slave Object
        for slave in slaveList:

            # Check Slave Object
            if not mc.objExists(slave):
                print('Slave object "' + slave + '" not found! Skipping...')
                continue

            # Offset Rotate Channels
            for r in ['rx', 'ry', 'rz']:
                mc.keyframe(slave + '.' + r,
                            e=True,
                            relative=True,
                            timeChange=offsetAnim)

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

    return slaveList
Esempio n. 40
0
               
dofList = [u'rotateX',
           u'rotateY',
           u'rotateZ',
           u'translateX',
           u'translateY',
           u'translateZ']
           
attrList = [u'rotate', u'translate']

tMin = 0
tMax = 1100

mc.select( clear=True )
selectJoints(controlList)
mc.cutKey(time=(tMin, tMax), attribute='rotate')
mc.cutKey(time=(tMin, tMax), attribute='translate')

folderNum = 2
folderPath = '/Users/flemone/Documents/maya/projects/COMP755/data/pose{}/'.format(folderNum)
pathList = glob.glob(os.path.join(folderPath, '*'))
split_ids = []
for path in pathList:
    split_id = os.path.basename(path)
    split_id = split_id.split('_')[1][:6]
    split_id = split_id if split_id != '' else '0'
    split_ids.append(int(split_id))

order = np.argsort(split_ids)
pathList = [pathList[idx] for idx in order]
Esempio n. 41
0
    def sampleNewCurvesFromOld(self, *args):

        minTime = cmds.intField("startTime", query=True, value=True)
        maxTime = cmds.intField("endTime", query=True, value=True)

        faceStr1 = self.OTHER_FACE_IDS % 1
        faceStr2 = self.OTHER_FACE_IDS % 2
        faceStr3 = self.OTHER_FACE_IDS % 3

        strongest = self.getNextStrongestShape()

        # ranIntensity = random.uniform(-0.5, 0.7)
        ranIntensity2 = random.uniform(-0.5, 0.7)
        ranTime = random.randint(-20, 20)
        print "ranIntensity: %f, ranTime: %i" % (ranIntensity2, ranTime)

        for group, vals in self.newShapes.iteritems():

            for shape in vals:

                nSId = shape[0].find(':')
                if nSId != -1:
                    out1 = shape[0][:nSId] + str(1) + shape[0][nSId:]
                    out2 = shape[0][:nSId] + str(2) + shape[0][nSId:]
                    out3 = shape[0][:nSId] + str(3) + shape[0][nSId:]

                else:
                    out1 = faceStr1 + shape[0]
                    out2 = faceStr2 + shape[0]
                    out3 = faceStr3 + shape[0]

                ranGauss = random.gauss(ranIntensity2, 0.5)
                print "ranGauss: %f" % (ranGauss)

                cmds.copyKey(strongest, time=(minTime, maxTime),
                             option="keys")  # or keys?
                cmds.pasteKey(out1,
                              time=(minTime, maxTime),
                              valueOffset=0.0,
                              option="replace")
                cmds.pasteKey(out2,
                              time=(minTime, maxTime),
                              valueOffset=ranGauss,
                              option="replace")
                #ranTime2 = random.gauss(ranTime,3)
                cmds.pasteKey(out3,
                              time=(minTime, maxTime),
                              timeOffset=ranTime,
                              option="replace")
                if ranTime >= 0:
                    cmds.cutKey(out3,
                                time=(minTime, minTime + ranTime),
                                option="keys")
                    cmds.cutKey(out3,
                                time=(maxTime, maxTime + ranTime),
                                option="keys")
                else:
                    cmds.cutKey(out3,
                                time=(minTime + ranTime, minTime),
                                option="keys")
                    cmds.cutKey(out3,
                                time=(maxTime + ranTime, maxTime),
                                option="keys")
                #cmds.pasteKey(shape[0], time=(minTime, maxTime), option="replace")

        self.createAltGUI(strongest, ranIntensity2, ranTime)
Esempio n. 42
0
def destroy():
    '''Cancella i parent constraint.'''

    sel, ctrls = _getCtrlsFromSelection(PARENT_HANDLE_SUFFIX)

    # se non ho selezionato nessun controllo provvisto di ph esci
    if not ctrls:
        raise Exception, 'No valid objects selected'

    # chiedi se fare bake o no
    result = cmds.confirmDialog(
        title='Destroy constraints',
        message=
        'The constraints will be deleted.\nDo you want to revert to previous state or bake and keep animation?',
        button=['Revert', 'Bake', 'Cancel'],
        defaultButton='Revert',
        cancelButton='Cancel',
        dismissString='Cancel')
    if result == 'Cancel':
        return
    bake = result == 'Bake'

    for ctrl in ctrls:
        # nome del constrain
        constrName = _getParentConstraint(ctrl)

        temp = cmds.ls(_getSnapGroup(ctrl))
        ## se il gruppo snap esiste
        if temp:
            temp = cmds.ls(constrName)
            ## se il parent constr esiste (lo snap group puo' esistere anche senza parent constr... vedi la feature Create parent groups)
            if temp:
                # se necessario crea il locator e fai il bake
                if bake:
                    _bakeObj(ctrl)
                targetList = cmds.parentConstraint(constrName, q=True, tl=True)
                # azzera tutti i target e cancella il constraint
                for i in range(len(targetList)):
                    cmds.setAttr('%s.w%d' % (constrName, i), 0.0)
                cmds.delete(constrName)

            # cancella le chiavi del controllo snap
            cmds.cutKey(_getSnapGroup(ctrl), at=['translate', 'rotate'])
            # ripristino gli attributi del controllo snap a 0
            [
                cmds.setAttr('%s.%s' % (_getSnapGroup(ctrl), s), 0.0)
                for s in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']
            ]

            # se possibile (cioe' se non referenziato) parento l'oggetto al genitore originario
            try:
                ctrlParent = cmds.pickWalk(_getParentHandle(ctrl), d='up')[0]
                if ctrlParent == _getParentHandle(ctrl):
                    cmds.parent(ctrl, r=True, w=True)
                else:
                    cmds.parent([ctrl, ctrlParent], r=True)
                # cancello il parent handle
                cmds.delete(_getParentHandle(ctrl))
            except:
                pass

            # resetta il rigid body
            _resetRigidBody(ctrl)
            if bake:
                _applyBakedAnimation(ctrl)

            # aggiorna la timeline window
            pmScriptJobCmd(ctrl)

    # seleziona i controlli
    cmds.select(ctrls)

    # output
    sys.stdout.write(' '.join(ctrls) + ' constraints destroyed\n')
Esempio n. 43
0
    def prepareForExportFBX(self, path, startFrame, endFrame, *args):
        sys.__stdout__.write("Preparing the File...\n")

        #get the characters in the scene
        characters = self.getCharacters()

        #get rotation interp
        options = cmds.optionVar(list=True)
        for op in options:
            if op == "rotationInterpolationDefault":
                interp = cmds.optionVar(q=op)
        cmds.optionVar(iv=("rotationInterpolationDefault", 3))

        #Loop through each character in the scene, and export the fbx for that character
        cmds.progressBar(self.widgets["currentFileProgressBar"],
                         edit=True,
                         progress=40)

        #create increment ammount for progress bar
        increment = 50 / len(characters)
        step = increment / 5

        #NEW: If use anim sequence info, get that info now
        if cmds.checkBox(self.widgets["useSequenceInfo"], q=True,
                         v=True) == True:
            if cmds.objExists("ExportAnimationSettings"):
                sys.__stdout__.write("Using file anim sequence data" + "\n")
                sequeneces = cmds.listAttr("ExportAnimationSettings",
                                           string="sequence*")

                for seq in sequeneces:
                    #get data
                    data = cmds.getAttr("ExportAnimationSettings." + seq)
                    dataList = data.split("::")
                    name = dataList[0]
                    start = dataList[1]
                    end = dataList[2]
                    fps = dataList[3]
                    interp = dataList[4]
                    sys.__stdout__.write("Export Sequence ------------->: " +
                                         str(name) + "\n")

                    try:
                        exportCharacter = dataList[5]
                    except:
                        if len(characters) > 1:
                            characterString = ""
                            for char in characters:
                                characterString += str(char) + " or "
                            result = cmds.promptDialog(
                                title='No Character Data Found',
                                message='Enter Name: ' + characterString,
                                button=['OK', 'Cancel'],
                                defaultButton='OK',
                                cancelButton='Cancel',
                                dismissString='Cancel')

                            if result == 'OK':
                                exportCharacter = cmds.promptDialog(query=True,
                                                                    text=True)
                        else:
                            exportCharacter = characters[0]

                    if interp == "Independent Euler Angle":
                        interp = 1

                    if interp == "Synchronized Euler Angle":
                        interp = 2

                    if interp == "Quaternion Slerp":
                        interp = 3

                    if cmds.checkBox(self.widgets["optionalPathCB"],
                                     q=True,
                                     v=True):
                        customPath = cmds.textField(
                            self.widgets["ExportPathtextField"],
                            q=True,
                            text=True)
                        filename = os.path.basename(name)
                        exportPath = os.path.join(customPath, filename)
                    else:
                        #directory = os.path.dirname(path)
                        #filename = os.path.basename(name)
                        #exportPath = os.path.join(directory, filename)
                        exportPath = name

                    sys.__stdout__.write("             Final Export Path: " +
                                         exportPath + "\n")
                    pre_text = "--- Final Export Path: "
                    self.logger.info(pre_text + exportPath, title=None)
                    if os.path.exists(exportPath):
                        self.logger.warning("OVERWRITTEN: " + exportPath,
                                            title=None)
                        self._fbx_overwrites.append(exportPath)
                    if exportPath in self._fbx_files:
                        self.logger.error("DUPLICATE!!!: " + exportPath,
                                          title=None)
                        self._duplicates.append(exportPath)
                    self._fbx_files.append(exportPath)

                    startFrame = int(start)
                    endFrame = int(end)

                    cmds.playbackOptions(min=startFrame,
                                         animationStartTime=startFrame)
                    cmds.playbackOptions(max=endFrame,
                                         animationEndTime=endFrame)
                    sys.__stdout__.write("Start Frame: " + str(startFrame) +
                                         "\n")
                    sys.__stdout__.write("End Frame:   " + str(endFrame) +
                                         "\n")

                    #custom attrs to export
                    import json

                    if not cmds.objExists("ExportAnimationSettings.settings"):
                        cmds.addAttr("ExportAnimationSettings",
                                     ln="settings",
                                     dt="string")
                        jsonString = json.dumps(
                            [False, False, False, "null", "null"])
                        cmds.setAttr("ExportAnimationSettings.settings",
                                     jsonString,
                                     type="string")

                    settings = json.loads(
                        cmds.getAttr("ExportAnimationSettings.settings"))

                    #get blendshapes
                    #sys.__stdout__.write("    get blendshapes..." + "\n")
                    cmds.progressBar(self.widgets["currentFileProgressBar"],
                                     edit=True,
                                     step=step)

                    self.getBlendshapes(step, exportCharacter, startFrame,
                                        endFrame)

                    #duplicate the skeleton
                    self.dupeAndBake(step, exportCharacter, startFrame,
                                     endFrame, settings[2], settings[4])

                    cmds.select("root", hi=True)
                    skeletonvis = cmds.ls(sl=True)
                    cmds.cutKey(cl=True, at="v")
                    for jnt in skeletonvis:
                        cmds.setAttr(jnt + ".v", 1)

                    self.exportFBX(exportPath, interp)

        else:
            for character in characters:
                sys.__stdout__.write("Export Character ------------->: " +
                                     str(character) + "\n")
                #add character suffix to fbx path file
                exportPath = path.rpartition(".fbx")[0]
                exportPath = exportPath + "_" + character + ".fbx"

                #get blendshapes
                #sys.__stdout__.write("    get blendshapes..." + "\n")
                cmds.progressBar(self.widgets["currentFileProgressBar"],
                                 edit=True,
                                 step=step)
                self.getBlendshapes(step, character, startFrame, endFrame)

                #duplicate the skeleton
                self.dupeAndBake(step, character, startFrame, endFrame)

                sys.__stdout__.write("Start Frame: " + str(startFrame) + "\n")
                sys.__stdout__.write("End Frame:   " + str(endFrame) + "\n")

                #check remove root animation checkbox. if true, delete keys off of root and zero out
                removeRoot = cmds.checkBox(self.widgets["removeRoot"],
                                           q=True,
                                           v=True)
                if removeRoot:
                    cmds.select("root")
                    cmds.cutKey()
                    for attr in ["tx", "ty", "tz", "rx", "ry", "rz"]:
                        cmds.setAttr("root." + attr, 0)
                self.logger.info(exportPath, title=None)
                if os.path.exists(exportPath):
                    self.logger.warning("OVERWRITTEN: " + exportPath,
                                        title=None)
                    self._fbx_overwrites.append(exportPath)
                if exportPath in self._fbx_files:
                    self.logger.error("DUPLICATE!: " + exportPath, title=None)
                    self._duplicates.append(exportPath)
                self._fbx_files.append(exportPath)
                self.exportFBX(exportPath, interp)
Esempio n. 44
0
    def apply(self, mapping, **kwargs):
        '''
		valid kwargs are:
		mult                [1.0]   apply a mutiplier when applying curve values
		additive			[False]
		clear				[True]
		'''
        beginningWeightedTanState = cmd.keyTangent(q=True, g=True, wt=True)

        ### gather options...
        additive = kwargs.get(self.kOPT_ADDITIVE,
                              self.kOPT_DEFAULTS[self.kOPT_ADDITIVE])
        worldAdditive = kwargs.get(
            self.kOPT_ADDITIVE_WORLD,
            self.kOPT_DEFAULTS[self.kOPT_ADDITIVE_WORLD])
        clear = kwargs.get(self.kOPT_CLEAR,
                           self.kOPT_DEFAULTS[self.kOPT_CLEAR])
        mult = kwargs.get(self.kMULT, self.kOPT_DEFAULTS[self.kMULT])
        timeOffset = kwargs.get(self.kOPT_OFFSET, self.offset)

        #if worldAdditive is turned on, then additive is implied
        if worldAdditive:
            additive = worldAdditive

        #determine the time range to clear
        clearStart = timeOffset
        clearEnd = clearStart + self.range

        for obj, tgtObj in mapping.iteritems():
            if not tgtObj:
                continue

            try:
                attrDict = self[obj]
            except KeyError:
                continue

            for attr, (weightedTangents, keyList) in attrDict.iteritems():
                attrpath = '%s.%s' % (tgtObj, attr)
                try:
                    if not cmd.getAttr(attrpath, settable=True):
                        continue
                except TypeError:
                    continue
                except RuntimeError:
                    print obj, tgtObj, attrpath
                    raise

                #do the clear...  maya doesn't complain if we try to do a cutKey on an attrpath with no
                #animation - and this is good to do before we determine whether the attrpath has a curve or not...
                if clear:
                    cmd.cutKey(attrpath, t=(clearStart, clearEnd), cl=True)

                #is there an anim curve on the target attrpath already?
                curveExists = cmd.keyframe(attrpath, index=(0, ),
                                           q=True) is not None

                preValue = 0
                if additive:
                    if worldAdditive:
                        isWorld = True

                        #if the control has space switching setup, see if its value is set to "world" - if its not, we're don't treat the control's animation as additive
                        try:
                            isWorld = cmd.getAttr('%s.parent' % obj,
                                                  asString=True) == 'world'
                        except TypeError:
                            pass

                        #only treat translation as additive
                        if isWorld and attr.startswith('translate'):
                            preValue = cmd.getAttr(attrpath)
                    else:
                        preValue = cmd.getAttr(attrpath)

                for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList:
                    value *= mult
                    value += preValue
                    if time is None:
                        #in this case the attr value was just a pose...
                        cmd.setAttr(attrpath, value)
                    else:
                        time += timeOffset
                        cmd.setKeyframe(attrpath, t=(time, ), v=value)
                        if weightedTangents:
                            #this needs to be done as two separate commands - because setting the tangent types in the same cmd as setting tangent weights can result
                            #in the tangent types being ignored (for the case of stepped mainly, but subtle weirdness with flat happens too)
                            cmd.keyTangent(attrpath,
                                           t=(time, ),
                                           ix=ix,
                                           iy=iy,
                                           ox=ox,
                                           oy=oy,
                                           l=isLocked,
                                           wl=isWeighted)
                            cmd.keyTangent(attrpath,
                                           t=(time, ),
                                           itt=itt,
                                           ott=ott)
                        else:
                            cmd.keyTangent(attrpath,
                                           t=(time, ),
                                           ix=ix,
                                           iy=iy,
                                           ox=ox,
                                           oy=oy)
Esempio n. 45
0
def main():

    sel = mc.ls(sl=True)

    if not sel:
        raise RuntimeError('Please select an object.')

    if [
            x for x in sel
            if not mc.attributeQuery('translate', exists=True, node=x)
    ]:
        raise RuntimeError(
            'Only works on transform nodes, please adjust your selection.')

    frameRate = utl.getFrameRate()
    timeFactor = 1.0 / frameRate

    unit = mc.currentUnit(query=True, linear=True)

    #default is meters
    distFactor = 1

    if unit == 'mm':
        distFactor = 1000
    elif unit == 'cm':
        distFactor = 100
    elif unit == 'km':
        distFactor = 0.001
    elif unit == 'in':
        distFactor = 39.3701
    elif unit == 'ft':
        distFactor = 3.28084
    elif unit == 'yd':
        distFactor = 1.09361
    elif unit == 'mi':
        distFactor = 0.000621371

    g = 9.8 * distFactor

    start, end = utl.frameRange()
    start = int(start)
    end = int(end)

    mc.currentTime(start)

    for each in sel:

        mc.setKeyframe(each + '.translate')
        startTrans = mc.getAttr(each + '.translate')[0]
        prevTrans = [
            mc.keyframe(each,
                        query=True,
                        attribute=x,
                        eval=True,
                        time=(start - 1, ))[0] for x in ('tx', 'ty', 'tz')
        ]

        xInit = startTrans[0] - prevTrans[0]
        yInit = startTrans[1] - prevTrans[1]
        zInit = startTrans[2] - prevTrans[2]

        mc.cutKey(each, attribute='translate', time=(start + 0.1, end + 0.5))
        mc.setKeyframe(each,
                       attribute='translateX',
                       time=start + 1,
                       value=startTrans[0] + xInit)
        mc.setKeyframe(each,
                       attribute='translateZ',
                       time=start + 1,
                       value=startTrans[2] + zInit)
        mc.setKeyframe(each,
                       attribute='translateX',
                       time=end - 1,
                       value=startTrans[0] + (xInit * (end - start - 1)))
        mc.setKeyframe(each,
                       attribute='translateZ',
                       time=end - 1,
                       value=startTrans[2] + (zInit * (end - start - 1)))
        mc.setKeyframe(each,
                       attribute='translateX',
                       time=end,
                       value=startTrans[0] + (xInit * (end - start)))
        mc.setKeyframe(each,
                       attribute='translateZ',
                       time=end,
                       value=startTrans[2] + (zInit * (end - start)))

        for i, f in enumerate(range(start, end + 1)):
            t = i * timeFactor
            y = startTrans[1] + (i * yInit) - (g * t * t) / 2

            mc.setKeyframe(each, attribute='translateY', time=f, value=y)
Esempio n. 46
0
    def Create(self):
        
        #main layout with tabs
        self.form = cmds.formLayout()
        self.tabs = cmds.tabLayout(innerMarginWidth=5, innerMarginHeight=5)
        cmds.formLayout( self.form, edit=True, attachForm=((self.tabs, 'top', 0), (self.tabs, 'left', 0), (self.tabs, 'bottom', 0), (self.tabs, 'right', 0)) )
        
        #modelling tab
        self.child1 = cmds.rowColumnLayout(parent = self.tabs, numberOfColumns=1)
        
        #duplicate and scatter
        self.dupScatFrame = cmds.frameLayout(parent = self.child1, label = "Duplicate and Scatter", collapsable = True, collapse = True)
        self.dupScatRC = cmds.rowColumnLayout(parent = self.dupScatFrame, numberOfColumns = 3)

        cmds.text(parent = self.dupScatRC, label = "X range")
        self.xMinField = cmds.floatField(parent = self.dupScatRC, value = -10)
        self.xMaxField = cmds.floatField(parent = self.dupScatRC, value = 10)
        cmds.text(parent = self.dupScatRC, label = "Y range")
        self.yMinField = cmds.floatField(parent = self.dupScatRC, value = -10)
        self.yMaxField = cmds.floatField(parent = self.dupScatRC, value = 10)
        cmds.text(parent = self.dupScatRC, label = "Z range")
        self.zMinField = cmds.floatField(parent = self.dupScatRC, value = -10)
        self.zMaxField = cmds.floatField(parent = self.dupScatRC, value = 10)
        cmds.text(parent = self.dupScatRC, label = "Number of Duplicates")
        self.dupNumField = cmds.intField(parent = self.dupScatRC, value = 10)

        self.dupScatCol = cmds.columnLayout(parent = self.dupScatFrame)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.dupScatFrame, label = "Duplicate", command = lambda : self.DupAndScatter(cmds.intField(self.dupNumField, q = 1, v = 1), cmds.floatField(self.xMinField , q = 1, v = 1), cmds.floatField(self.xMaxField , q = 1, v = 1), cmds.floatField(self.yMinField , q = 1, v = 1), cmds.floatField(self.yMaxField , q = 1, v = 1), cmds.floatField(self.zMinField , q = 1, v = 1), cmds.floatField(self.zMaxField , q = 1, v = 1)))
        
        #rigging tab
        self.child2 = cmds.rowColumnLayout(parent = self.tabs, numberOfColumns=1)
        
        #locator creator
        self.createLocatorFrame = cmds.frameLayout(parent = self.child2, label = "Create Locators", collapsable = True, collapse = True)
        self.createLocatorRC = cmds.rowColumnLayout(parent = self.createLocatorFrame, numberOfColumns = 2)
        cmds.text(parent = self.createLocatorRC, label = "Type")
        self.createLocatorMenu = cmds.optionMenu(parent = self.createLocatorRC)
        cmds.menuItem(parent = self.createLocatorMenu, label = "Center of Objects")
        cmds.menuItem(parent = self.createLocatorMenu, label = "Center of Components")
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.createLocatorFrame, label = "Create Locator", command = lambda : self.CreateLocator(cmds.optionMenu(self.createLocatorMenu, q = True, v = True)))

        cmds.separator(parent = self.child2, style = "double")

        #joint creator
        self.createJointFrame = cmds.frameLayout(parent = self.child2, label = "Create Joints", collapsable = True, collapse = True)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.createJointFrame, label = "Create Joints", command = lambda : self.CreateJoints())

        cmds.separator(parent = self.child2, style = "double")
        
        #joint orient
        self.jointOrientFrame = cmds.frameLayout(parent = self.child2, label = "Orient Joints", collapsable = True, collapse = True)
        
        self.primaryAxisRC = cmds.radioButtonGrp(parent = self.jointOrientFrame, label = "Primary Axis:", ad3 = 1, cw3 = [20, 20, 20], labelArray3 = ["X", "Y", "Z"], numberOfRadioButtons = 3, select = 1)

        self.secondaryAxisRC = cmds.radioButtonGrp(parent = self.jointOrientFrame,  label = "Secondary Axis:", ad3 = 1, cw3 = [20, 20, 20], labelArray3 = ["X", "Y", "Z"], numberOfRadioButtons = 3, select = 3)

        self.SAORC = cmds.radioButtonGrp(parent = self.jointOrientFrame, label = "Secondary Axis World Orientation", ad3 = 1, cw3 = [20, 20, 20], labelArray3 = ["X", "Y", "Z"], numberOfRadioButtons = 3, select = 1)
        
        self.upOrDown = cmds.optionMenu(parent = self.jointOrientFrame)
        cmds.menuItem(parent = self.upOrDown, label = "+")
        cmds.menuItem(parent = self.upOrDown, label = "-")
        
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.jointOrientFrame, label = "Orient Joints", command = lambda : self.OrientJoints(self.QueryRadioButtonGrp(self.primaryAxisRC), self.QueryRadioButtonGrp(self.secondaryAxisRC), self.QueryRadioButtonGrp(self.SAORC), cmds.optionMenu(self.upOrDown, q = 1, value = 1), True, True, True))
        
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.jointOrientFrame, label = "Freeze Rotations", command = lambda : self.FreezeRotation())
        
        cmds.separator(parent = self.child2, style = "double")
        
        #ik solvers
        self.ikSolversFrame = cmds.frameLayout(parent = self.child2, label = "IK Solvers", collapsable = True, collapse = True)
        cmds.text(parent = self.ikSolversFrame, label = "Spline IK")
        self.splineSelectHierarchyCB = cmds.checkBox(parent = self.ikSolversFrame, label = "Select Hierarchy")
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.ikSolversFrame, label = "Create Spline IK", command = lambda : self.SplineIK(cmds.checkBox(self.splineSelectHierarchyCB, query = 1, value = 1)))
        
        cmds.separator(parent = self.child2, style = "double")

        #control creator
        self.createControlFrame = cmds.frameLayout(parent = self.child2, label = "Create Controls", collapsable = True, collapse = True)
        self.createControlRC = cmds.rowColumnLayout(parent = self.createControlFrame, numberOfColumns=2)
        self.createControlGrid = cmds.gridLayout(parent = self.createControlFrame, numberOfColumns = 8)
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 0, 0), command = lambda x: self.SetColor(1) )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.75, 0.75, 0.75), command = lambda x: self.SetColor(2) )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.5, 0.5, 0.5), command = lambda x: self.SetColor(3) )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (.8, 0, 0.2), command = lambda x: self.SetColor(4)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 0, .4), command = lambda x: self.SetColor(5)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 0, 1), command = lambda x: self.SetColor(6)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, .3, 0), command = lambda x: self.SetColor(7)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.2, 0, 0.3), command = lambda x: self.SetColor(8)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (.8, 0, .8), command = lambda x: self.SetColor(9)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.6, 0.3, 0.2), command = lambda x: self.SetColor(10)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.25, 0.13, 0.13), command = lambda x: self.SetColor(11)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.7, .2, 0), command = lambda x: self.SetColor(12)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (1, 0, 0), command = lambda x: self.SetColor(13)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 1, 0), command = lambda x: self.SetColor(14)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 0.3, 0.6), command = lambda x: self.SetColor(15)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (1, 1, 1), command = lambda x: self.SetColor(16)  )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (1, 1, 0), command = lambda x: self.SetColor(17)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 1, 1), command = lambda x: self.SetColor(18)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 1, .8), command = lambda x: self.SetColor(19)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (1, .7, .7), command = lambda x: self.SetColor(20)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.9, .7, .5), command = lambda x: self.SetColor(21)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (1, 1, 0.4), command = lambda x: self.SetColor(22)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0, 0.7, .4), command = lambda x: self.SetColor(23)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (.6, .4, .2), command = lambda x: self.SetColor(24)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (.63, .63, .17), command = lambda x: self.SetColor(25)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.4, 0.6, 0.2), command = lambda x: self.SetColor(26)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.2, 0.63, 0.35), command = lambda x: self.SetColor(27)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.18, 0.63, 0.63), command = lambda x: self.SetColor(28)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.18, 0.4, 0.63), command = lambda x: self.SetColor(29)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.43, 0.18, 0.63), command = lambda x: self.SetColor(30)   )
        cmds.button( label = "", parent = self.createControlGrid, backgroundColor = (0.63, 0.18, 0.4), command = lambda x: self.SetColor(31)   )
        cmds.text(parent = self.createControlRC, label = "Control Type")
        self.createControlOptnMenu = cmds.optionMenu(parent = self.createControlRC)
        cmds.menuItem(parent = self.createControlOptnMenu, label = "")
        cmds.menuItem(parent = self.createControlOptnMenu, label = "Circle")
        cmds.menuItem(parent = self.createControlOptnMenu, label = "Square")
        cmds.menuItem(parent = self.createControlOptnMenu, label = "Flower")
        cmds.text(parent = self.createControlRC, label = "Constrain to Joint")
        self.createControlCheckbox = cmds.checkBox(parent = self.createControlRC, value = False, label = "")
        cmds.text(parent = self.createControlRC, label = "Color Joints")
        self.colorJointsCheckbox = cmds.checkBox(parent = self.createControlRC, value = False, label = "")
        cmds.text(parent = self.createControlRC, label = "Rotate 90 Y")
        self.rotateYCheckbox = cmds.checkBox(parent = self.createControlRC, value = False, label = "")
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.createControlFrame, label = "Create Controls", command = lambda : self.CreateControl(cmds.optionMenu(self.createControlOptnMenu, q = True, v = True), self.colorIndex, cmds.checkBox(self.createControlCheckbox, q= True, v = True), cmds.checkBox(self.colorJointsCheckbox, q= True, v = True), cmds.checkBox(self.rotateYCheckbox, q= True, v = True)))
        cmds.text(parent = self.createControlRC, label = "Control Color:")
        
        cmds.separator(parent = self.child2, style = "double")

        # constraints
        self.constraintsFrame = cmds.frameLayout(parent = self.child2, label = "Constraints", collapsable = True, collapse = True)

        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.constraintsFrame, label = "Parent-Scale Constraint", command = lambda : self.ParentScaleConstraint())
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.constraintsFrame, label = "Split Parent Constrain", command = lambda : self.SplitParentConstrain())
        
        cmds.separator(parent = self.child2, style = "double")

        #RK system tools
        self.rkFrame = cmds.frameLayout(parent = self.child2, label = "IKFK System", collapsable = True, collapse = True)
        
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.rkFrame, label = "Create IK FK Chains", command = lambda : self.CreateIKFKJoints())
        
        self.scrollList = cmds.textScrollList(parent = self.rkFrame)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.rkFrame, label = "Add", command = lambda : self.AddToTextScrollList(self.scrollList))
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.rkFrame, label = "Create Transform Control Attributes", command = lambda : self.CreateIKFKAttributes(self.QueryTextScrollList(self.scrollList)), ann = "Select your Transform control to run this command. Will create an IKFK attribute for two arms and two legs")

        self.rkRC1 = cmds.rowColumnLayout(parent = self.rkFrame, numberOfColumns=2)
        cmds.text(parent = self.rkRC1, label = "Attribute Number", ann = "Check the order of the user-created attributes on Transform control to get this number")
        self.rkAttrNum1 = cmds.intField(parent = self.rkRC1, value = 1)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.rkFrame, label = "Key IKFK Switch", command = lambda : self.RKConstraintSetDrivenKey(self.QueryTextScrollList(self.scrollList), cmds.intField(self.rkAttrNum1, q = 1, v = 1)), ann  = "Select your Transform control first, then select the parent constraints on your RK joint chain for one joint system (ie for the left arm)")

        self.rkRC2 = cmds.rowColumnLayout(parent = self.rkFrame, numberOfColumns=2)
        cmds.text(parent = self.rkRC2, label = "Attribute Number", ann = "Check the order of the user-created attributes on Transform control to get this number")
        self.rkAttrNum2 = cmds.intField(parent = self.rkRC2, value = 1)
        cmds.text(parent = self.rkRC2, label = "Control Type")
        self.rkOptnMenu = cmds.optionMenu(parent = self.rkRC2)
        cmds.menuItem(parent = self.rkOptnMenu, label = "FK")
        cmds.menuItem(parent = self.rkOptnMenu, label = "IK")
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.rkFrame, label = "Key Control Visibility", command = lambda : self.RKCtrlSetDrivenKey(self.QueryTextScrollList(self.scrollList), cmds.intField(self.rkAttrNum2, q = 1, v = 1), cmds.optionMenu(self.rkOptnMenu, q = 1, v = 1)) , ann = "Select Transform control first, then select the controls for one joint system (ie the left arm IK controls)")
        
        cmds.separator(parent = self.child2, style = "double")

        #skinning animator
        self.skinAnimFrame = cmds.frameLayout(parent = self.child2, label = "Skinning Auto Animator", collapsable = True, collapse = True)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.skinAnimFrame, label = "Animate", command = lambda : self.SkinningAnim())
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.skinAnimFrame, label = "Clear Keys", command = lambda : cmds.cutKey())

        
        
        #utility tab
        self.child3 = cmds.rowColumnLayout(parent = self.tabs, numberOfColumns=1)

        #renamer
        self.renamerFrame = cmds.frameLayout(parent = self.child3, label = "Renamer", collapsable = True, collapse = True)
        self.renamerRC = cmds.rowColumnLayout(parent = self.renamerFrame, numberOfColumns = 2)

        cmds.text(parent = self.renamerRC, label = "Name")
        self.nameField = cmds.textField(parent = self.renamerRC, text = "name")
        cmds.text(parent = self.renamerRC, label = "Number Padding")
        self.numPadField = cmds.textField(parent = self.renamerRC, text = "00")
        cmds.text(parent = self.renamerRC, label = "Number")
        self.numField = cmds.intField(parent = self.renamerRC, value = 1)
        cmds.text(parent = self.renamerRC, label = "Suffix")
        self.suffixField = cmds.textField(parent = self.renamerRC, text = "suffix")

        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.renamerFrame, label = "Rename and Number", command = lambda : self.RenameAndNumber(cmds.textField(self.nameField, q = 1, text = 1), cmds.textField(self.numPadField, q = 1, text = 1), cmds.intField(self.numField, q = 1, v = 1), cmds.textField(self.suffixField, q = 1, text = 1)))

        #filter selection
        self.filselFrame = cmds.frameLayout(parent = self.child3, label = "Filter Selection", collapsable = True, collapse = True)
        self.filselRC = cmds.rowColumnLayout(parent = self.filselFrame, numberOfColumns = 2)
        cmds.text(parent = self.filselRC, label = "Select Hierarchy")
        self.filselCheckbox = cmds.checkBox(parent = self.filselRC, value = True, label = "")
        cmds.text(parent = self.filselRC, label = "Node Type")
        self.filselText = cmds.textField(parent = self.filselRC)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.filselFrame, label = "Filter Selection", command = lambda : self.FilterSelection(cmds.checkBox(self.filselCheckbox, q = 1, v = 1), cmds.textField(self.filselText, q = 1, text = 1)))

        #randomize selection
        self.randSelFrame = cmds.frameLayout(parent = self.child3, label = "Randomize Selection", collapsable = True, collapse = True)
        self.randSelRC = cmds.rowColumnLayout(parent = self.randSelFrame, numberOfColumns = 2)

        cmds.text(parent = self.randSelRC, label = "Percent of Selection")
        self.percentSelField = cmds.floatField(parent = self.randSelRC, value = 50)
        cmds.iconTextButton(style = "textOnly", rpt = 1, parent = self.randSelFrame, label = "Randomize", command = lambda : self.RandomizeSelection(cmds.floatField(self.percentSelField, q = 1, v = 1)))
        
        #set up tab layout
        cmds.tabLayout( self.tabs, edit=True, tabLabel=((self.child1, 'Modelling'), (self.child2, 'Rigging'), (self.child3, 'Utility')) )
# entry point
#----------------------------------------

print "---- Start grenadeAnimate.py ----\n"

# get objects
selection = cmds.ls(orderedSelection=True, type='transform')
if len(selection) < 3:
    print "Select three objects: grenade, particle and enemy."
    sys.exit()

object1Name = selection[0]
object2Name = selection[1]
object3Name = selection[2]

cmds.cutKey(object1Name)
cmds.cutKey(object1Name, s=True, at='v')

# set first key at 0 frame
timeFrame = 0
coordX = cmds.getAttr('%s.tx' % (object1Name))
coordY = cmds.getAttr('%s.ty' % (object1Name))
cmds.setKeyframe(object1Name,
                 t=timeFrame,
                 at='tx',
                 v=coordX,
                 itt='linear',
                 ott='linear')
cmds.setKeyframe(object1Name,
                 t=timeFrame,
                 at='ty',
Esempio n. 48
0
def disableTurn(obj, *args):
    cmds.cutKey(obj, at='rotateY', option='keys', cl=True)
    cmds.setAttr('%s.rotateY' % obj, 0)
Esempio n. 49
0
 def deleteKeys(self):
     for i in range(441):
         cmds.cutKey('bend' + str(i + 1), time=(0, 200), at='curvature', option="keys")
Esempio n. 50
0
    def autoTranfer(self, arg):
        self.listSel = mc.ls(selection=True)

        if not mc.objExists('ARLoc_Grp'):
            mc.group(em=True, name='ARLoc_Grp')
        self.bakeLoc = []
        self.delPar = []
        self.delScale = []
        self.selList = []
        for self.sel in self.listSel:
            self.locName = self.sel + "_loc"
            self.loc = mc.spaceLocator(p=(0, 0, 0), name=self.locName)
            self.parentLoc = mc.parentConstraint(self.sel,
                                                 self.loc,
                                                 maintainOffset=False)
            self.scaleLoc = mc.scaleConstraint(self.sel,
                                               self.loc,
                                               maintainOffset=False)  #
            self.bakeLoc.append(self.loc[0])  #because loc is list
            self.delPar.append(self.parentLoc[0])  #because delPar is list
            self.selList.append(self.sel)
            #mc.bakeResults(self.loc,simulation=True,time = (self.timeSliderMin,self.timeSliderMax))
            #mc.delete(self.parentLoc)
            #mc.cutKey(self.sel, option='keys')
            #self.parentCon = mc.parentConstraint(self.loc,self.sel,maintainOffset = True)
            #self.scaleCon = mc.scaleConstraint(self.loc,self.sel,maintainOffset = True)
            #mc.parent(self.loc,'ARLoc_Grp')
            #mc.cutKey(self.loc,time=((self.timeSliderMin+1), (self.timeSliderMax-1)), option='keys')

        print self.delPar
        self.animNodes = mc.ls(type='animCurve')
        self.firstKey = mc.findKeyframe(self.animNodes, which='first')
        self.lastKey = mc.findKeyframe(self.animNodes, which='last')

        if self.firstKey < 101:
            self.firstKey = 101

        # isolate viewport for faster baking
        mayaTools.isolateObj(True)

        # bake locator
        mc.bakeResults(self.bakeLoc,
                       simulation=True,
                       time=(self.firstKey, self.lastKey))

        # restore viewport back
        mayaTools.isolateObj(False)

        mc.delete(self.delPar)
        mc.delete(self.delScale)
        mc.cutKey(self.selList, option='keys')
        #return
        for self.sel in self.listSel:
            self.locName = self.sel + "_loc"
            #mc.cutKey(self.sel, option='keys')
            self.parentCon = mc.parentConstraint(self.locName,
                                                 self.sel,
                                                 maintainOffset=False)  #True
            self.scaleCon = mc.scaleConstraint(self.locName,
                                               self.sel,
                                               maintainOffset=False)
            mc.parent(self.locName, 'ARLoc_Grp')
            for shotSq in mc.sequenceManager(listShots=True):
                self.currentShotStart = mc.shot(shotSq, q=True, st=True)
                self.currentShotEnd = mc.shot(shotSq, q=True, et=True)

                mc.cutKey(self.locName,
                          time=((self.currentShotStart + 1),
                                (self.currentShotEnd - 1)),
                          option='keys')
Esempio n. 51
0
def ReductKeyFunction():
    cmds.commandEcho(ln=False)

    #define UI information
    channelCheck = getChannelCheck()
    channelBox_attrs = channelBoxList(channelCheck)
    appliedChannels = appliedChannelList(channelCheck)
    [start, end] = defineTimeRange()

    #create objLists
    objLists = cmds.ls(sl=True)

    if cmds.checkBox('LockSelectedKey', q=True, value=True) == True:
        #create L_KeyNameLists
        L_KeyNameLists = cmds.keyframe(q=True, n=True)
        [L_Name, L_keyTimes, L_keyValues, L_keyOutTangents,
         L_keyTangentTypes] = lockedKeyframe(L_KeyNameLists)
    else:
        L_Name = []
        L_keyTimes = []
        L_keyValues = []
        L_keyOutTangents = []
        L_keyTangentTypes = []

    #undo
    cmds.undoInfo(openChunk=True)

    for obj in objLists:
        #define channels
        [keyable_channels,
         channels] = common(obj, channelCheck, channelBox_attrs,
                            appliedChannels, start, end)

        if len(channels) != 0:
            for channel in channels:
                #get key information
                key_times = cmds.keyframe('{0}.{1}'.format(obj, channel),
                                          q=True,
                                          t=(start, end),
                                          timeChange=True)
                key_values = cmds.keyframe('{0}.{1}'.format(obj, channel),
                                           q=True,
                                           t=(start, end),
                                           valueChange=True)
                key_numbers = cmds.keyframe('{0}.{1}'.format(obj, channel),
                                            q=True,
                                            t=(start, end),
                                            iv=True)
                key_outTangents = cmds.keyTangent('{0}.{1}'.format(
                    obj, channel),
                                                  q=True,
                                                  t=(start, end),
                                                  outAngle=True)
                key_tangentTypes = cmds.keyTangent('{0}.{1}'.format(
                    obj, channel),
                                                   q=True,
                                                   t=(start, end),
                                                   ott=True)

                #fixed keyTangent
                fixed_index = fixedKey(key_tangentTypes, key_numbers)
                if len(fixed_index) != 0:
                    cmds.keyTangent('{0}.{1}'.format(obj, channel),
                                    e=True,
                                    index=fixed_index,
                                    itt='fixed',
                                    ott='fixed')
                else:
                    continue

                if len(key_outTangents) == 1:
                    continue
                else:
                    reduct_index = getReduct_index(key_outTangents, key_values,
                                                   key_numbers, key_times)

                if len(reduct_index) != 0:
                    cmds.cutKey(obj,
                                at=channel,
                                clear=True,
                                index=reduct_index)
                else:
                    continue
        else:
            continue

    if cmds.checkBox('LockSelectedKey', q=True, value=True) == True:
        if len(L_Name) != 0:
            for (i, L_name) in enumerate(L_Name):
                L_Times = L_keyTimes[i]
                L_values = L_keyValues[i]
                L_OutTangents = L_keyOutTangents[i]
                L_TangentTypes = L_keyTangentTypes[i]

                for (j, L_Time) in enumerate(L_Times):
                    cmds.setKeyframe(L_name,
                                     t=(L_Time, L_Time),
                                     value=L_values[j])
                    cmds.keyTangent(L_name,
                                    e=True,
                                    time=(L_Time, L_Time),
                                    ia=L_OutTangents[j],
                                    oa=L_OutTangents[j],
                                    itt=L_TangentTypes[j],
                                    ott=L_TangentTypes[j])

    cmds.undoInfo(closeChunk=True)
Esempio n. 52
0
def shotSplitter_process(*args):

    start_time = time.time()

    #get info

    textFile = cmds.textField("shotSplitterTextFile", q=True, text=True)

    audioFile = cmds.textField("shotSplitterAudioFile", q=True, text=True)

    #fbxFile = cmds.textField("shotSplitterFBXFile", q = True, text = True)

    output = cmds.textField("shotSplitterOutput", q=True, text=True)

    mel.eval('trace "Getting Data from text file..." ;')

    #get shot data from the text file

    shotInfo = shotSplitter_getShotData(textFile)

    #import in the audio file

    #if audioFile != "":

    #mel.eval('trace "Importing audio..." ;')

    #cmds.file(audioFile, i = True, type = "audio")

    ##offset audio 300 frames

    #firstShot = shotInfo[0]

    #offsetValue = firstShot[1]

    #audioFileName = audioFile.rpartition("/")[2].partition(".")[0]

    #cmds.setAttr(audioFileName + ".offset", offsetValue)

    #import in the fbx file and set it up

    #mel.eval('trace "Setting up matinee FBX file..." ;')

    cmds.unloadPlugin("fbxmaya.mll")

    cmds.loadPlugin("fbxmaya.mll")

    shotSplitter_setupFBXFile()

    #snap the characters to their spots and orient everything correctly

    #mel.eval('trace "Snapping Characters..." ;')

    #shotSplitter_setupCharacters()

    #save out individual shot files

    mel.eval('trace "Saving out master file..." ;')

    masterFile = shotSplitter_SaveMaster()

    i = 0

    sceneFrameEnd = shotSplitter_findSceneFrameRange()

    for shot in shotInfo:

        shotNum = shot[0]

        mel.eval('trace "Creating shot %s" ;' % str(shotNum))

        shotFrameStart = shot[1]

        try:

            shotFrameEnd = shotInfo[i + 1][1]

        except IndexError:

            print "Last shot. Using Scene Frame Range"

            shotFrameEnd = sceneFrameEnd

        shotCamera = shot[2]

        shotName = shot[3]

        #set frame range, set camera, save out shot

        cmds.playbackOptions(min=shotFrameStart,
                             max=shotFrameEnd,
                             ast=shotFrameStart,
                             aet=shotFrameEnd)

        if cmds.objExists(shotCamera):

            cameraName = cmds.listRelatives(shotCamera, children=True)[0]

            #debug print

            print(cameraName)

            #if shake is in the name

            #select the non shake camera

            if 'Shake' in cameraName:

                print('changing name')

                cameraName = cameraName.partition('_Shake')[0]

            #debug print

            print('changing the camera name to ' + cameraName)

            newCamName = cmds.rename(cameraName, "SHOT_CAM")

            #lock the camera

            cmds.setAttr(newCamName + ".tx", lock=True)

            cmds.setAttr(newCamName + ".ty", lock=True)

            cmds.setAttr(newCamName + ".tz", lock=True)

            cmds.setAttr(newCamName + ".rx", lock=True)

            cmds.setAttr(newCamName + ".ry", lock=True)

            cmds.setAttr(newCamName + ".rz", lock=True)

            cmds.setAttr(newCamName + ".sx", lock=True)

            cmds.setAttr(newCamName + ".sy", lock=True)

            cmds.setAttr(newCamName + ".sz", lock=True)

        #This will get replaced when the new text file info is in

        f = open(textFile, "r")

        lines = f.readlines()

        f.close()

        #find the cine name

        cineFullName = lines[1]

        cineName = cineFullName.partition(": ")[2]

        cineName = cineName.rstrip("\r\n")

        #chop off excess keys

        cmds.select(all=True)

        try:

            cmds.cutKey(option="keys", time=(0, shotFrameStart - 30))

            cmds.cutKey(option="keys", time=(shotFrameEnd + 30, 120000))

        except:

            pass

        #save out the shot

        if shotName.find("<Unknown>") == -1:

            newFileName = (output + "/" + cineName + "_" + shotName + ".mb")

            cmds.file(rename=newFileName)

            shotFile = cmds.file(save=True, type='mayaBinary', force=True)

            #rename the shot cam back

            if cmds.objExists(shotCamera):

                cmds.rename(newCamName, cameraName)

        #iterate i

        i = i + 1

        #open up the master file

        cmds.file(masterFile, open=True, force=True, prompt=False)

    elapsed_time = time.time() - start_time

    timeInMins = str((elapsed_time / 60))[0:4]

    minutes = str(timeInMins).partition(".")[0]

    seconds = str(timeInMins).rpartition(".")[2]

    seconds = ("." + seconds)

    seconds = float(seconds) * 60

    seconds = str(seconds)[0:2]

    finalTime = "Total Time: " + minutes + " minutes and " + seconds + " seconds"

    result = cmds.confirmDialog(
        title="Shot Splits Complete",
        message="Yay! Your shots have been generated! Total time: " + minutes +
        " minutes and " + seconds + " seconds",
        button=["Close"],
        cancelButton="Close",
        dismissString="Close")
Esempio n. 53
0
def BakeFunction():
    cmds.commandEcho(ln=False)

    #define UI information
    channelCheck = getChannelCheck()
    channelBox_attrs = channelBoxList(channelCheck)
    appliedChannels = appliedChannelList(channelCheck)
    [start, end] = defineTimeRange()
    b_sample = cmds.floatField('bakeSample', q=True, value=True)

    #create objLists
    objLists = cmds.ls(sl=True)

    #undo
    cmds.undoInfo(openChunk=True)

    bake_channels = bake_channel(channelCheck, channelBox_attrs,
                                 appliedChannels)

    if cmds.checkBox('Euler', q=True, value=True) == True:
        if cmds.checkBox('Sim', q=True, value=True) == True:
            cmds.bakeResults(objLists,
                             at=bake_channels,
                             simulation=True,
                             t=(start, end),
                             sb=b_sample,
                             pok=True)
            cmds.setKeyframe(objLists, t=(-10000, -10000))
            cmds.setKeyframe(objLists, t=(-10001, -10001), value=0)
            cmds.filterCurve(objLists)
            cmds.cutKey(obj, at=bake_channels, t=(-10001, -10000))
        else:
            cmds.bakeResults(objLists,
                             at=bake_channels,
                             t=(start, end),
                             sb=b_sample,
                             pok=True)
            cmds.setKeyframe(objLists, t=(-10000, -10000))
            cmds.setKeyframe(objLists, t=(-10001, -10001), value=0)
            cmds.filterCurve(objLists)
            cmds.cutKey(objLists, at=bake_channels, t=(-10001, -10000))
    else:
        if cmds.checkBox('Sim', q=True, value=True) == True:
            cmds.bakeResults(objLists,
                             at=bake_channels,
                             simulation=True,
                             t=(start, end),
                             sb=b_sample,
                             pok=True)
        else:
            cmds.bakeResults(objLists,
                             at=bake_channels,
                             t=(start, end),
                             sb=b_sample,
                             pok=True)
    if cmds.checkBox('POK', q=True, value=True) == False:
        cmds.cutKey(objLists,
                    at=bake_channels,
                    clear=True,
                    t=(-100000, start - 1))
        cmds.cutKey(objLists,
                    at=bake_channels,
                    clear=True,
                    t=(end + 1, 100000))
    else:
        pass

    cmds.undoInfo(closeChunk=True)
Esempio n. 54
0
def _fixThis(ctrl, timeRange):
    '''Fixa lo snap per questo controllo.'''

    constrName = _getParentConstraint(ctrl)
    # fixa il timerange corrente
    if timeRange:
        currentFrame = cmds.currentTime(q=True)
        allKeyTimes = list(
            set(
                cmds.keyframe(constrName,
                              q=True,
                              time=(cmds.playbackOptions(q=True, min=True),
                                    cmds.playbackOptions(q=True, max=True)),
                              timeChange=True)))
        allKeyTimes.sort()
        for t in allKeyTimes:
            cmds.currentTime(t)
            _fixThis(ctrl, False)
        # ritorna al frame di prima
        cmds.currentTime(currentFrame)
    # fixa solo il frame corrente
    else:
        # se sono al primo frame o non ci sono keyframe in questo frame esci
        firstFrame = cmds.playbackOptions(q=True, ast=True)
        currentFrame = cmds.currentTime(q=True)
        if currentFrame == firstFrame or cmds.keyframe(
                constrName,
                q=True,
                time=(currentFrame, currentFrame),
                timeChange=True) == None:
            sys.stdout.write('Nothing to fix at frame %d\n' % currentFrame)
            return

        # target attivo
        activeTarget = _getActiveAttachTarget(constrName)

        # elimina le chiavi
        selectConstraintNodes(ctrl)
        cmds.cutKey(t=(currentFrame, currentFrame))

        # se rigid body rivaluta dal primo frame
        if _getRigidBody(ctrl):
            # dummy locator (faccio il bake su di lui e lo cancello)
            tempLoc = cmds.spaceLocator()[0]
            cmds.hide(tempLoc)
            # mi permette di riprodurre la simulazione dal primo frame fino a quello corrente
            cmds.bakeResults(tempLoc,
                             at=['t'],
                             sm=True,
                             t=(firstFrame, currentFrame),
                             dic=True,
                             pok=True)
            cmds.delete(tempLoc)

        # rifai il parent (detach o attach)
        if not activeTarget:
            cmds.select(ctrl)
            detach()
        else:
            cmds.select([ctrl, activeTarget])
            attach()

        sys.stdout.write('Snap fixed at frame %d\n' % currentFrame)
Esempio n. 55
0
def smartSnapKeys():

    getCurves = animMod.getAnimCurves()
    animCurves = getCurves[0]

    if not animCurves or len(animCurves) == 0: return

    getFrom = getCurves[1]
    keyTimes = animMod.getTarget("keyTimes", animCurves, getFrom)
    keysSel = animMod.getTarget("keysSel", animCurves, getFrom)
    hasDecimalKeys = False

    for loopKey in utilMod.mergeLists(keysSel):
        if loopKey != round(loopKey) > 0:
            hasDecimalKeys = True
            break

    if not hasDecimalKeys: return

    keyTangentsType = animMod.getTarget("keyTangentsType", animCurves, getFrom)
    firstStep = 0
    totalSteps = len(animCurves)
    estimatedTime = None
    status = "aTools - Smart Snap Curves..."
    startChrono = None
    utilMod.startProgressBar(status)

    for thisStep, loopCurve in enumerate(animCurves):

        startChrono = utilMod.chronoStart(startChrono, firstStep, thisStep,
                                          totalSteps, estimatedTime, status)

        if None in [keyTimes[thisStep], keysSel[thisStep]]: continue

        stepKeys = [
            loopKey for nn, loopKey in enumerate(keyTimes[thisStep])
            if loopKey != round(loopKey) and loopKey in keysSel[thisStep]
            and keyTangentsType[thisStep][nn][1] == "step"
        ]
        linearKeys = [
            loopKey for nn, loopKey in enumerate(keyTimes[thisStep])
            if loopKey != round(loopKey) and loopKey in keysSel[thisStep]
            and keyTangentsType[thisStep][nn][1] == "linear"
        ]
        decimalKeys = [
            loopKey for nn, loopKey in enumerate(keyTimes[thisStep])
            if loopKey != round(loopKey) and loopKey in keysSel[thisStep]
            and loopKey not in stepKeys + linearKeys
        ]

        for loopKey in stepKeys:
            cmds.snapKey(loopCurve, time=(loopKey, loopKey))
        for loopKey in linearKeys:
            cmds.snapKey(loopCurve, time=(loopKey, loopKey))

        if len(decimalKeys) == 0: continue

        if not getFrom:
            if cmds.keyframe(query=True, selected=True) != None:
                getFrom = "graphEditor"

        #inLinearKeys    = [round(loopKey) for nn, loopKey in enumerate(keyTimes[thisStep]) if keyTangentsType[thisStep][nn][0] == "linear"]
        #outLinearKeys   = [round(loopKey) for nn, loopKey in enumerate(keyTimes[thisStep]) if keyTangentsType[thisStep][nn][1] == "linear"]
        createKeys = list(set([round(loopKey) for loopKey in decimalKeys]))
        selectKeys = []

        #print "inlinearKeys", inLinearKeys, outLinearKeys

        if getFrom == "graphEditor":
            selectKeys = list(
                set([
                    round(loopKey) for loopKey in keysSel[thisStep]
                    if round(loopKey) in createKeys
                ]))

        for loopKey in createKeys:
            cmds.setKeyframe(loopCurve, time=(loopKey, loopKey), insert=True)
        for loopKey in selectKeys:
            cmds.selectKey(loopCurve, addTo=True, time=(loopKey, loopKey))
        for loopKey in decimalKeys:
            cmds.cutKey(loopCurve, time=(loopKey, loopKey))
        #for loopKey in outLinearKeys:   cmds.keyTangent(loopCurve, edit=True, time=(loopKey, loopKey), outTangentType="linear")
        #for loopKey in inLinearKeys:    cmds.keyTangent(loopCurve, edit=True, time=(loopKey, loopKey), inTangentType="linear")

        estimatedTime = utilMod.chronoEnd(startChrono, firstStep, thisStep,
                                          totalSteps)

    utilMod.setProgressBar(endProgress=True)
Esempio n. 56
0
def _cleanCurves(animCurves):
    '''Pulisce le curve rimuovendo le chiavi superflue.'''

    tol = 0.0001
    for c in animCurves:
        keyCount = cmds.keyframe(c, query=True, keyframeCount=True)
        if keyCount == 0:
            continue
        # cancella le chiavi superflue intermedie
        if keyCount > 2:
            times = cmds.keyframe(c,
                                  query=True,
                                  index=(0, keyCount - 1),
                                  timeChange=True)
            values = cmds.keyframe(c,
                                   query=True,
                                   index=(0, keyCount - 1),
                                   valueChange=True)
            inTan = cmds.keyTangent(c,
                                    query=True,
                                    index=(0, keyCount - 1),
                                    inAngle=True)
            outTan = cmds.keyTangent(c,
                                     query=True,
                                     index=(0, keyCount - 1),
                                     outAngle=True)
            for i in range(1, keyCount - 1):
                if math.fabs(values[i] - values[i - 1]) < tol and math.fabs(
                        values[i + 1] - values[i]) < tol and math.fabs(
                            inTan[i] - outTan[i - 1]) < tol and math.fabs(
                                inTan[i + 1] - outTan[i]) < tol:
                    cmds.cutKey(c, time=(times[i], times[i]))

        # ricalcola il numero di chiavi e pulisce le chiavi agli estremi
        keyCount = cmds.keyframe(c, query=True, keyframeCount=True)
        times = cmds.keyframe(c,
                              query=True,
                              index=(0, keyCount - 1),
                              timeChange=True)
        values = cmds.keyframe(c,
                               query=True,
                               index=(0, keyCount - 1),
                               valueChange=True)
        inTan = cmds.keyTangent(c,
                                query=True,
                                index=(0, keyCount - 1),
                                inAngle=True)
        outTan = cmds.keyTangent(c,
                                 query=True,
                                 index=(0, keyCount - 1),
                                 outAngle=True)
        # piu' di due key rimanenti
        if keyCount > 2:
            if math.fabs(values[1] - values[0]) < tol and math.fabs(
                    inTan[1] - outTan[0]) < tol:
                cmds.cutKey(c, time=(times[0], times[0]))
            if math.fabs(values[-1] - values[-2]) < tol and math.fabs(
                    inTan[-1] - outTan[-2]) < tol:
                cmds.cutKey(c, time=(times[-1], times[-1]))
        # uno o due key rimanenti
        elif keyCount == 1 or (math.fabs(values[1] - values[0]) < tol
                               and math.fabs(inTan[1] - outTan[0]) < tol):
            val = cmds.getAttr(c)  # debuggato
            cmds.cutKey(c)
            cmds.setAttr(c, val)
Esempio n. 57
0
    global_ctl = ''
    for i in controllers:
        if 'global_C0_ctl' in i:
            global_ctl = i
    print '\t\tFound %d controllers' % len(controllers)
    print '\t\tFound global controller %s' % global_ctl

    curves = cmds.listConnections(controllers, type='animCurve')
    print '\t\tFound %d animation curves' % len(curves)

    print '\t\tSetting key on first frame...'
    cmds.currentTime(frame_s)
    cmds.setKeyframe()

    print '\t\tRemoving all keys before start.'
    cmds.cutKey(time=(-9999, frame_s - 1))

    print '\t\tRemoving all keys after end.'
    cmds.cutKey(time=(frame_e + 1, 100000))

    print '\t\tSetting hold keys...'
    cmds.currentTime(frame_s - 1)
    cmds.setKeyframe()
    cmds.currentTime(frame_e + 1)
    cmds.setKeyframe()

    print '\t\tSetting hold key...'
    cmds.currentTime(frame_s - 20)
    # UPDATE SHIT ###################################################
    # update for switching from IK to FK on the arms, to stop
    # intersections for use in sim export.
Esempio n. 58
0
"""
Ryan Huber
Must have object selected.
Deletes History, Freezes transforms, removes all keyframes.
Option checkbox UI coming soon.
"""
#imports
import maya.cmds as cmds
import logging

#variables
Selection = cmds.ls(sl=True) 
#window_name = "controlsWindow"

    cmds.delete(Selection, constructionHistory=True)
    cmds.cutKey(Selection, clear=True)
    cmds.makeIdentity(Selection, apply=True, t=1, r=1, s=1, n=0)

"""
#replace existing window
if cmds.window(window_name, q=True, exists=True):
    cmds.deleteUI(window_name)
#definitions
def DH(useDH):
    cmds.delete(constructionHistory=True)

#commands
cmds.delete(Selection, constructionHistory=True)
cmds.cutKey(Selection, clear=True)
cmds.makeIdentity(Selection, apply=True, t=1, r=1, s=1, n=0)
Esempio n. 59
0
def main():
    ####################################################################
    #初期設定
    ####################################################################
    In = cmds.playbackOptions(q=True,min=True)
    Out = cmds.playbackOptions(q=True,max=True)
    oSel = cmds.ls(sl=True,tr=True)
    oSel_str = map(str,oSel)
    oSel_Joint = ",".join(oSel_str)
    oSel_Array = oSel_Joint.split(",")
    bakeSet = []
    deleteSet = []
    Finsel = []

    if len(oSel)>0:
        for i in oSel_Array:
            Artr_Check = cmds.attributeQuery('TargetModel', node=i, exists=1)
            if Artr_Check ==False:
    			posX_Flag = int("0")
    			posY_Flag = int("0")
    			posZ_Flag = int("0")
    			rotX_Flag = int("0")
    			rotY_Flag = int("0")
    			rotZ_Flag = int("0")
    			sclX_Flag = int("0")
    			sclY_Flag = int("0")
    			sclZ_Flag = int("0")

    			posX = cmds.selectKey(i,at="translateX")
    			posY = cmds.selectKey(i,at="translateY")
    			posZ = cmds.selectKey(i,at="translateZ")

    			rotX = cmds.selectKey(i,at="rotateX")
    			rotY = cmds.selectKey(i,at="rotateY")
    			rotZ = cmds.selectKey(i,at="rotateZ")

    			sclX = cmds.selectKey(i,at="scaleX")
    			sclY = cmds.selectKey(i,at="scaleY")
    			sclZ = cmds.selectKey(i,at="scaleZ")

    	####################################################################
    	#アトリビュート確認
    	####################################################################
    			posX_Flag += Flag_Check(posX,posX_Flag)
    			posY_Flag += Flag_Check(posY,posY_Flag)
    			posZ_Flag += Flag_Check(posZ,posZ_Flag)
    			rotX_Flag += Flag_Check(rotX,rotX_Flag)
    			rotY_Flag += Flag_Check(rotY,rotY_Flag)
    			rotZ_Flag += Flag_Check(rotZ,rotZ_Flag)
    			sclX_Flag += Flag_Check(sclX,sclX_Flag)
    			sclY_Flag += Flag_Check(sclY,sclY_Flag)
    			sclZ_Flag += Flag_Check(sclZ,sclZ_Flag)
    			Rename_Point = 0
    			Rename_Orient = 0
    			Rename_Scale = 0

    	####################################################################
    	#選択にコンスト
    	####################################################################
    			if posX_Flag+posY_Flag+posZ_Flag+rotX_Flag+rotY_Flag+rotZ_Flag+sclX_Flag+sclY_Flag+sclZ_Flag == 0:
    				makeWindow(i)
    			else:
    				Sel_FullPath = Path(i)
    				Sel_Long = Sel_FullPath.fullPathName()
    				Cone = cmds.curve(d = 1, p = [[-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 12.236166355956469], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, 8.721448300231371], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [11.80981745916246, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [8.2950984497630458, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, -11.763830783020582], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, -8.2491136809698009], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, 12.628153763637824, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, 8.721448300231371], [-12.190180633488907, -11.371846236362176, 0.23616730963078481], [-0.19018254083754044, -11.371846236362176, 0.23616730963078481], [-8.6754635314381261, -11.371846236362176, 8.721448300231371]])
    				cmds.addAttr(Cone,sn="TM", ln="TargetModel", dt="string" )
    				cmds.setAttr(Cone+'.TargetModel',Sel_Long,type='string')
    				if posX_Flag+posY_Flag+posZ_Flag > 2:
    					Point_Const = cmds.pointConstraint(i,Cone)
    					Rename_Point = 1
    				if rotX_Flag+rotY_Flag+rotZ_Flag > 2:
    					Orient_Const = cmds.orientConstraint(i,Cone)
    					Rename_Orient = 1
    				if sclX_Flag+sclY_Flag+sclZ_Flag > 2:
    					Scale_Const = cmds.scaleConstraint(i,Cone)
    					Rename_Scale = 1

    				Name_Set = ''
    				if Rename_Scale ==1:
    					Name_Set = Name_Set + 'S'
    				if Rename_Orient ==1:
    					Name_Set = Name_Set + 'R'
    				if Rename_Point ==1:
    					Name_Set = Name_Set + 'T'
    				ReName = cmds.rename(Cone,"Global_"+i+"_"+Name_Set)
    				At_list = []
    	####################################################################
    	#ベイク設定
    	####################################################################
    				Bake_list = Channel_Check(ReName,posX,rotX,sclX,At_list)
    				Connections = cmds.listRelatives(ReName,c=True,typ="constraint")
    	####################################################################
    	#ベイク関数
    	####################################################################
    				RunBake(Bake_list,In,Out,Connections)
    	####################################################################
    	#再コンスト
    	####################################################################
    				if Rename_Scale == 1 :
    					cmds.cutKey( i, attribute='scaleX', option="keys" )
    					cmds.cutKey( i, attribute='scaleY', option="keys" )
    					cmds.cutKey( i, attribute='scaleZ', option="keys" )
    					cmds.scaleConstraint(ReName,i)
    				if Rename_Orient == 1 :
    					cmds.orientConstraint(ReName,i)
    				if Rename_Point == 1 :
    					cmds.pointConstraint(ReName,i)
    				Sel_Pos = cmds.xform(i,worldSpace=True,q=True,translation=True)
    				cmds.xform(ReName, translation=Sel_Pos,worldSpace=True,absolute=True )
    				cmds.setAttr(ReName+".overrideEnabled",1)
    				cmds.setAttr(ReName+".overrideColor",6)
    				Finsel.append(ReName)
            else:
                target = cmds.getAttr ( '%s.TargetModel' % i )
                bakeSet.append(target)
                deleteSet.append(i)
        ###########################################################
        #グローバルを一括ペースト
        ###########################################################
        if len(bakeSet)>0:
            At_list = []
            for i in bakeSet:
                posX = cmds.selectKey(i,at="translateX")
                posY = cmds.selectKey(i,at="translateY")
                posZ = cmds.selectKey(i,at="translateZ")
                rotX = cmds.selectKey(i,at="rotateX")
                rotY = cmds.selectKey(i,at="rotateY")
                rotZ = cmds.selectKey(i,at="rotateZ")
                sclX = cmds.selectKey(i,at="scaleX")
                sclY = cmds.selectKey(i,at="scaleY")
                sclZ = cmds.selectKey(i,at="scaleZ")
                Bake_list = Channel_Check(i,posX,rotX,sclX,At_list)
            #Bakeしてワールドコントローラーを削除
            RunBake(Bake_list,In,Out,deleteSet)


    else:
    	cmds.confirmDialog(message = u'1つ以上選択して実行して下さい。',b= u'~終了~')
    if len(Finsel)>0:
        cmds.select(Finsel)
    def finishBake(self):
        if self._bakedLoc and not self.debug:
            mc.delete(self._bakedLoc.mNode)
            self._bakedLoc = None

        mc.cutKey(self.obj.mNode, at=['tx', 'ty', 'tz'], clear=True)