Esempio n. 1
0
def keys_shift(targets, incr=0.0, rand=0.0, rand_abs=False, round=False):
    """ This script will copy the keyframes from source to targets from selected channel box attributes
    Args:
        targets [pm.nt.Transform]: target transforms to sequentialize
        incr (float): Increment value through selection by x, 0 is no increment
        rand (float): Randomly shift by x, 0 is no shift
        rand_abs (bool): Random range will be absolute and not include negatives
        round (bool): whether or not to round the key shift value to an integer
    Returns (None)
    Example:
        keys_shift(pm.ls(sl=True), rand=5.0, round=True)
    """
    #Determine Selected attributes from channelbox
    attrs = get_cb_sel_attrs()
    x_shift = 0
    for target in targets:
        ast, aet = pm.playbackOptions(q=True, ast=True), pm.playbackOptions(q=True, aet=True)
        rand_val = 0
        if rand:
            rand_val = random.randrange(-rand*(1-rand_abs), rand)
        x_shift += rand_val
        if round:
            x_shift=int(x_shift)
        pm.keyframe(target, edit=True, at=attrs, relative=True, timeChange=x_shift)
        x_shift += incr
Esempio n. 2
0
def duplicateSequence(objects):
	'''duplicates the given objects as groups per frame with properly named objects
	Args:
		objects (list(pm.PyNode)): list of objects to be duplicated every frame
	Returns:
		nothing...yet.
	Usage:
		duplicateSequence(pm.ls(sl=True))
	'''
	for obj in objects:
		topGrp = obj.getParent().name().replace('GRP','ANIM_GRP')
		if pm.objExists(topGrp):
			topGrp = pm.PyNode(topGrp)
		else:
			topGrp = pm.group(em=True,n=topGrp)
		startFrame = pm.playbackOptions(q=True,ast=True)
		endFrame = pm.playbackOptions(q=True,aet=True)
		incr = 1
		grp = pm.group(em=True, n=obj.name().replace('GEO','ANIM_GRP'), p=topGrp)
		i=0
		for frame in range (startFrame, endFrame+1, incr):
			pm.currentTime(frame)
			dup=pm.duplicate(obj, n=obj.name().replace('GEO','%d_GEO'%i))
			dup[0].setParent(grp)
			i+=1
Esempio n. 3
0
    def set_range_from_seq(self):
        """sets the playback range from the sequencer node in the scene
        """
        min_frame = self.sequencer.getAttr('minFrame')
        max_frame = self.sequencer.getAttr('maxFrame')

        pm.playbackOptions(ast=min_frame, aet=max_frame, min=min_frame, max=max_frame)
Esempio n. 4
0
def fixedSeed():
  sel = pm.selected()
  
  animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
  animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
  for attr in sel:
    animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
    animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
    xVal = attr.rotateX.get()
    yVal = attr.rotateY.get()
    zVal = attr.rotateZ.get()
  
    print animStartTime
    print animEndTime
    print xVal
    print yVal
    print zVal
      
    while animStartTime<=animEndTime:
      attr.rotateX.set(xVal+random.uniform(-.1,.1))
      attr.rotateY.set(yVal+random.uniform(-.1,.1))
      attr.rotateZ.set(zVal+random.uniform(-.1,.1))
      pm.setKeyframe(attribute="rotate", time=animStartTime)
      animStartTime+=1
def main():
	prefRun()
	#get all renderable cameras in scene
	allCamShapes = pm.ls( type='camera')

	
	cams = []
	for cam in allCamShapes:
		if pm.getAttr(cam+".renderable"):
			cams.append(pm.listRelatives(cam, p=1))
			
	print cams
		
	
	#Get the current frame range from the timeslider
	startTime = pm.playbackOptions(q=True, min=True )
	endTime = pm.playbackOptions(q=True, max=True )
	
	print "Playblasting Cameras:",
	
	#generate playblast for each renderable cam
	for cam in cams:
		pm.playblast(
			cam, 
			startTime=startTime, 
			endTime=endTime, 
			viewer=0, 
			#filename="X:/Projects/GREY11_ANM71_Rewe_Starzone/GR11A71_Shots/GR11A71_Animatic/Animatic_Maya/data/test"+cam[0])
			)
	
	print "for range: %04d - %04d" % (startTime,endTime)
Esempio n. 6
0
    def _bakeAnim(self, root):
        '''
        Given root:
        - Bake the heirarchy animation data
        - Reset timeline to 1 if wasn't already set to 1
        '''
        print 'Starting: bakeAnim()...'
        # Getting time range from scene
        startFrame = int( pm.playbackOptions(q=1, min=1) )
        endFrame = int( pm.playbackOptions(q=1, max=1) )

        pm.select(root, hi=1, r=1)

        # Set timeline to start at frame 1
        if startFrame != 1:
            if startFrame < 1:
                tChange = (-(startFrame))+1
            elif startFrame > 1:
                tChange = (-(startFrame-1))
        
            pm.keyframe(e=1, time=(startFrame, endFrame), relative=1, timeChange=tChange)
            pm.playbackOptions(e=1, min=1, max=endFrame+tChange )
            
        pm.bakeResults(root, 
                       t=(startFrame, endFrame), 
                       simulation=True, hi='below' )
        
        print 'bakeAnim(): Baked anim onto %s' % root
        print 'bakeAnim(): Range baked: %s - %s' % (startFrame, endFrame) 
        print 'End: bakeAnim()'
Esempio n. 7
0
    def importAnimation(self, speak=0,lib=1):
        print 'Importing Animation'
        rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma')
        pm.openFile(rigFile,f=1)
        if lib:
            importAnimPath = ANIM_LIB_PATH
        else:
            fbxPath = os.path.split(self.fbxFile)[0]
            importAnimPath = fbxPath + '/' + 'animations/'

        animFiles = [f for f in os.listdir(importAnimPath) if f.endswith('.fbx')]
        #self.logger.info('########### Importing animations from library ############')
        for anim in animFiles:
            pm.mel.eval('FBXImportFillTimeline -v 1;')
            cmd = 'FBXImport -f "' + importAnimPath + anim+ '" -caller \"FBXMayaTranslator\" -importFormat \"fbx;v=0\"'
            pm.mel.eval(cmd)
            #self.logger.info('Imported %s ', (importAnimPath + anim))
            #pm.importFile(importAnimPath + anim, type='FBX',mergeNamespacesOnClash=0,rpr=anim.split('.')[0],options = 'v=0;',loadReferenceDepth = 'all')
            start = pm.playbackOptions(q=1,ast=1)
            end = pm.playbackOptions(q=1,aet=1)
            pm.bakeResults( 'shadowJoint',t=(start,end), simulation=True )

            self.saveAnimation(anim.split('.')[0])

            pm.openFile(rigFile,f=1)

        if speak:
            #self.logger.info('Creating speak anims ')
            for anim in speakAnims:
                pm.openFile(rigFile,f=1)
                animationFile = os.path.join(CHARACTERS_PATH,self.name,'animation',anim + '.ma')
                #self.logger.info('%s created',animationFile)
                pm.saveAs(animationFile,f=1)
Esempio n. 8
0
def viewOutHide():
    
    transNodeList = []
    
    startTime = pm.playbackOptions(q=1, min=1)
    endTime = pm.playbackOptions(q=1, max=1)
    
    for x in range(int(startTime), int(endTime + 1)):
        pm.currentTime(x)
        transNodeList += viewObjectList(False)
    
    transNodeListS = set(transNodeList)

    allTransNodeList = set()
    
    for x in pm.ls(type='mesh'):
        allTransNodeList.add(x.getParent().name())

    hideList = allTransNodeList - transNodeListS
    
    for x in hideList:
        try:
            pm.setAttr(x + '.v', 0)
        except:
            pass

    pm.currentTime(startTime)
Esempio n. 9
0
    def writeRetimeFile(viz, pubShot):
        '''
        Write the animated data on the currentTime attribute to a txt file.
        '''
        tmpPath = None
        # Return None if the attribute is not keyed.
        
        if pm.keyframe('%s.currentTime'%viz, query=True, keyframeCount=True):
            # get framelist from pod
            podFile = str(pm.getAttr('%s.podFile'%viz))
            ggcp = GtoGeometryCachePod.fromPodFile(podFile)
            ggcp.startFrame = pm.playbackOptions(q=True, animationStartTime=True)
            ggcp.endFrame = pm.playbackOptions(q=True, animationEndTime=True)
            frameList = ggcp.frameNumberList()
#             offset = float(pm.getAttr('%s.timeOffset'%viz))
#             frameList = [frame + offset for frame in ggcp.frameNumberList()]
            
            # Get curve data
            animCurveData = list()
            for frame in frameList:
                value = pm.keyframe(viz, query=True, time=[frame], attribute='currentTime', eval=True)
                assert len(value) == 1, '%s keyframes found for time %s. One expected.' % (len(value), frame)
                animCurveData.append([frame, value[0]])

            # Write it out to a temp file
            selCharName = str(pm.getAttr('%s.label'%viz))
            if not tmpPath:
                name = '_'.join(['animLib', 'bd', pubShot, selCharName, 'retime.txt'])
                tmpPath = os.path.join(tempfile.gettempdir(), name)
            fh = open(tmpPath, 'w')
            for time, value in animCurveData:
                fh.write('%s %s\n' % (time, value))
            fh.close()
            
        return tmpPath
Esempio n. 10
0
    def exportAnimation(self):
        exportFolder = ASSETS_PATH + 'characters/' + self.name + '_std/animations/'
        exportAnimationsPath = os.path.join(CHARACTERS_PATH ,self.name,'animation')
        animFiles = []
        if os.path.isdir(exportAnimationsPath):
            animFiles = [f for f in sorted(os.listdir(exportAnimationsPath)) if f.endswith('.ma') or f.endswith('.ma') ]
        else:
            pm.warning('No animation files found, aborting!')
            return
        #self.logger.info('########### Exporting animations for OGRE ###########')
        for anim in animFiles:
            animFile = os.path.join(exportAnimationsPath,anim)
            pm.openFile(animFile,f=1)
            start = int(pm.playbackOptions(q=1,ast=1))
            end = int(pm.playbackOptions(q=1,aet=1))
            #ogreExport -all -outDir "P:/mixamo_character/assets/characters/EveBavaria_std/animations/" -skeletonClip "EveBavaria_action_unjured_walk_35" startEnd 0 34 frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose

            cmd = 'ogreExport -all -outDir "'+ exportFolder + '"'
            cmd += ' -skeletonClip "' + anim.split('.')[0] + '"'
            if 'speak' in anim:
                cmd += ' startEnd 0 1' 
            else:
                cmd += ' startEnd ' + str(start) + ' ' + str(end)
            cmd += ' frames sampleByFrames 1 -lu pref -scale 1.00 -skeletonAnims -skelBB -np bindPose'

            pm.mel.eval(cmd)
Esempio n. 11
0
    def copyZoobeAnimations(self,zoobeChar):
        print 'Importing Zoobe Animations'


        if zoobeChar:
            sourceChar = 'source:' + zoobeChar
            fuseChar = self.name

            rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma')

            zoobeCharFolder = os.path.join(ANIM_LIB_PATH,zoobeChar)
            if os.path.isdir(zoobeCharFolder):
                animFiles = [f for f in os.listdir(zoobeCharFolder) if (f.endswith('.ma') or f.endswith('.mb'))]
                animFile = '/home/zoobe/mixamo/testproject/incoming/animLib/violet/violet_angry_action_01.ma'
                #self.copyAnimation(animFile,sourceChar,fuseChar,0,300)

                for anim in animFiles:
                    print animFile
                    animPath = os.path.join(zoobeCharFolder,anim)
                    print animPath 
                    pm.openFile(animPath,f=1)
                    start = pm.playbackOptions(q=1,ast=1)
                    end = pm.playbackOptions(q=1,aet=1)
                    print start, end
                    self.copyAnimation(animPath,sourceChar,fuseChar,start,end)
                    print 'saving animation %s'%anim.split('.')[0]

                    self.saveAnimation(anim.split('.')[0])
            else:
                pm.warning('Did not find %s char folder'%zoobeChar)
Esempio n. 12
0
def aw_copyKeys(source, targets, randomShift=0, increment=0, mo=False):
	'''This script will copy the keyframes from source to targets from selected channel box attributes
	Args:
		source (mayaObject): Source object with animation
		targets (list[mayaObject]): Copy To Targets
		randomShift (int): Randomly shift by x, 0 is no shift
		increment (int): Increment value through selection by x, 0 is no increment
		mo (Boolean): Maintain the Offset or not
	Returns (void): no return
	Example:
		aw_copyKeys(pm.PyNode('pSphere1'), pm.ls(sl=True), randomShift=0, increment=1, mo=True)
	'''
	args=targets
	animSrc=source
	#Determine Selected attributes from channelbox
	pm.language.melGlobals.initVar( 'string', 'gChannelBoxName' )
	attrs = pm.channelBox(pm.language.melGlobals['gChannelBoxName'],q=True,sma=True)
	#Copy Keys from the Graph Editor for main object (deselect other objects before copying)
	if not attrs:
		print 'Nothing selected in channel box, setting copy attributes to default all'
		attrs=['tx','ty','tz','rx','ry','rz','sx','sy','sz','v']
	for arg,i in zip(args, range(len(args))):
		if arg != animSrc:
			for attr in attrs:
				pm.copyKey(animSrc, time = (pm.playbackOptions(q=True,ast=True), pm.playbackOptions(q=True,aet=True)), at=attr,option="curve", hierarchy='none')
				#Paste keys to all objects depending on attributes selected from the channelBox
				offsetCheck = attr in ['tx','ty','tz','rx','ry','rz']
				offsetSeed = ((i+1) * increment) + int(math.floor( random.random() * randomShift))
				pm.pasteKey(arg, option='insert', valueOffset=((offsetCheck * mo) * (arg.attr(attr).get() - animSrc.attr(attr).get())), copies=True, connect=True, at=attr, timeOffset=offsetSeed)
Esempio n. 13
0
def setCamPlaybackRange():
    modelPanel = pm.playblast(activeEditor=True).split('|')[-1]

    activeCam  = pm.PyNode( pm.modelPanel( modelPanel, q=True, camera=True ) )
    startFrame = activeCam.startFrame.get()
    endFrame   = activeCam.endFrame.get()

    pm.playbackOptions(min=endFrame, max=startFrame)
Esempio n. 14
0
	def getTimeRange(self, *args):
		# get time range
		aPlayBackSliderPython = pm.mel.eval('$tmpVar=$gPlayBackSlider')
		timeRange = pm.timeControl( aPlayBackSliderPython, q=True, rangeArray=True )
		if timeRange[1] - timeRange[0] < 2.0:
			timeRange =  [ pm.playbackOptions( q=True, minTime=True), pm.playbackOptions( q=True, maxTime=True) ]
		pm.intField( self.startFrameIntField, e=True, value=timeRange[0] )
		pm.intField( self.endFrameIntField, e=True, value=timeRange[1] )
Esempio n. 15
0
    def get_shot_frame_range(self, shot):
        """returns the shot
        """
        # set start and end frame of time slider

        start_frame = shot.startFrame.get()
        end_frame = shot.endFrame.get()
        pm.playbackOptions(min=start_frame, max=end_frame)
Esempio n. 16
0
def togglePlaybackSpeed():
    """Toggle between Real-time and Every Frame playback"""

    newSpeed = not bool( pm.playbackOptions( playbackSpeed=True, query=True ) )
    pm.playbackOptions( playbackSpeed=newSpeed )

    pm.headsUpDisplay( 'HUDPlaybackSpeed', edit=True )
    print 'Playback Speed: %s' % ( 'Every Frame', 'Real-time' )[newSpeed]
	def set_framesField(self):
		interv_int = self.interv_int.value()
		orbit_int = self.orbit_int.value()
		value = interv_int * orbit_int

		self.frames_int.setValue(value)
		pm.setAttr("defaultRenderGlobals.endFrame", value)
		pm.playbackOptions(maxTime=value, e=True)
Esempio n. 18
0
 def bakeCmd(self):
     sel = pm.ls(sl=1)
     min = pm.playbackOptions(q=1, min=1)
     max = pm.playbackOptions(q=1, max=1)
     m = re.match("BCT_ctrl\d*_Ctrl", sel[0].name())
     if m:
         pm.bakeResults(sel[0], t=(min, max), simulation=True)
     else:
         print "selection is not BCT!!!"
Esempio n. 19
0
 def saveAnimation(self,animFile):
     print 'Saving file'
     start = pm.playbackOptions(q=1,ast=1)
     end = pm.playbackOptions(q=1,aet=1)
     length = int(end - start)
     saveName = animFile.replace('lib',self.name) + '_' + str(length) + '.ma'
     pm.playbackOptions(aet = end-1)
     animationFile = os.path.join(CHARACTERS_PATH,self.name,'animation',saveName)
     pm.saveAs(animationFile,f=1)
Esempio n. 20
0
def bdExportHIKAnim(fromFolder,toFolder,charName,charType):
  animFiles = [f for f in os.listdir(fromFolder) if (f.endswith('.ma') or f.endswith('.mb'))]
  for anim in animFiles:
    animFile = os.path.join(fromFolder,anim)
    pm.openFile(animFile,f=1)
    start = pm.playbackOptions(q=1,min=1)
    end = pm.playbackOptions(q=1,max=1)
    
    
    
Esempio n. 21
0
def getTimelineFrameRange():
    '''
    Return the timeline frame range of the scene
    
    Return :
    startFrame = int
    endFrame = int
    '''
    startFrame = pm.playbackOptions (q=True,minTime =True)
    endFrame = pm.playbackOptions (q=True,maxTime =True)
    return startFrame,endFrame
Esempio n. 22
0
def model_screenshot(selected=True, debug=False, centerCam=False):
	meshes = pm.ls(sl=True)
	cam = pm.camera(n='tempCam')
	hfv=cam[1].getHorizontalFieldOfView()
	vfv=cam[1].getVerticalFieldOfView()
	grp = pm.group(em=True, n='tempCamOffset_GRP')
	
	#Determine the selection
	if selected==False:
		meshes = [mesh.getParent() for mesh in pm.ls(type=pm.nt.Mesh)]
	print meshes
	boundingBox = pm.polyEvaluate(meshes, b=True)
	
	#Determine the positions of the bounding box as variables
	xmin=boundingBox[0][0]
	xmax=boundingBox[0][1]
	ymin=boundingBox[1][0]
	ymax=boundingBox[1][1]
	zmin=boundingBox[2][0]
	zmax=boundingBox[2][1]
	
	#get the midpoints (these are also the object center!)
	zmid=(zmin+zmax)/2
	ymid=(ymin+ymax)/2
	xmid=(xmin+xmax)/2
	
	# Create locators to visualize the bounding box
	locators=[]
	locators.append(pm.spaceLocator(n='xmin',p=[xmin,ymid,zmid]))
	locators.append(pm.spaceLocator(n='xmax',p=[xmax,ymid,zmid]))
	locators.append(pm.spaceLocator(n='ymin',p=[xmid,ymin,zmid]))
	locators.append(pm.spaceLocator(n='ymax',p=[xmid,ymax,zmid]))
	locators.append(pm.spaceLocator(n='zmin',p=[xmid,ymid,zmin]))
	locators.append(pm.spaceLocator(n='zmax',p=[xmid,ymid,zmax]))
	
	#Determine the furthest distance needed from the object
	h_dist=(math.tan(hfv)*abs(xmin-xmax)) + abs(zmin-zmax)
	zh_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax)
	zv_dist=(math.tan(vfv)*abs(zmin-zmax)) + abs(zmin-zmax)
	v_dist=(math.tan(vfv)*abs(ymin-ymax)) + abs(zmin-zmax) #this will never be used, always going to be shortest.
	
	#set the camera distance etc for the bounding box.
	print h_dist,v_dist,zh_dist, zv_dist
	print max(h_dist,v_dist,zh_dist, zv_dist)
	cam[0].translateZ.set(max(h_dist,zh_dist,v_dist,zv_dist))
	cam[0].translateY.set(ymid)
	
	cam[0].setParent(grp)
	if debug:
		pm.delete(locators)
	if centerCam:
		grp.translate.set([zmid,0,xmid])
		pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,ast=True), v=0)
		pm.setKeyframe(grp.rotateY, t=pm.playbackOptions(q=True,aet=True), v=360)
Esempio n. 23
0
    def bake(self):

        minFrame = int(pm.playbackOptions(q=1,min=1))
        maxFrame = int(pm.playbackOptions(q=1,max=1))
        selectSet = pm.ls('*:bake_set*',typ='objectSet')
        if selectSet == []:
            pm.headsUpMessage( '???' )
        else:
            bakeList = []
            for x in selectSet:
                for y in x.flattened():
                    bakeList.append(y)
            pm.bakeResults(bakeList, sm=1, t=(minFrame, maxFrame), sb=1, pok=1, sac=0, bol=0, at=['tx','ty','tz','rx','ry','rz','sx','sy','sz'])
Esempio n. 24
0
def bdCleanKeyframes():
    start = pm.playbackOptions(q=1,ast=1)
    end = pm.playbackOptions(q=1,aet=1)

    sel = pm.ls(sl=1,type='transform')

    for i in range(8,end-10,1):
        if not (i%4):
            print i
            pm.currentTime(i)
            pm.setKeyframe(sel,t=i)
        else:
            pm.cutKey(sel,clear=1,an='objects',iub=0,t=(i,i+1))
Esempio n. 25
0
    def set_frame_range(self, engine, in_frame, out_frame):

        if engine == "tk-maya":
            import pymel.core as pm
            
            # set frame ranges for plackback
            pm.playbackOptions(minTime=in_frame, 
                               maxTime=out_frame,
                               animationStartTime=in_frame,
                               animationEndTime=out_frame)
           
            # set frame ranges for rendering
            defaultRenderGlobals=pm.PyNode('defaultRenderGlobals')
            defaultRenderGlobals.startFrame.set(in_frame)
            defaultRenderGlobals.endFrame.set(out_frame)
           
        elif engine == "tk-nuke":
            import nuke

            # unlock
            locked = nuke.root()["lock_range"].value()
            if locked:
                nuke.root()["lock_range"].setValue(False)
            # set values
            nuke.root()["first_frame"].setValue(in_frame)
            nuke.root()["last_frame"].setValue(out_frame)
            # and lock again
            if locked:
                nuke.root()["lock_range"].setValue(True)

        elif engine == "tk-motionbuilder":
            from pyfbsdk import FBPlayerControl, FBTime

            lPlayer = FBPlayerControl()
            lPlayer.LoopStart = FBTime(0, 0, 0, in_frame)
            lPlayer.LoopStop = FBTime(0, 0, 0, out_frame)

        elif engine == "tk-softimage":
            import win32com
            Application = win32com.client.Dispatch('XSI.Application')

            Application.SetValue("PlayControl.In", in_frame)
            Application.SetValue("PlayControl.Out", out_frame)

        elif engine == "tk-houdini":
            import hou
            hou.playbar.setPlaybackRange(in_frame, out_frame)

        else:
            raise tank.TankError("Don't know how to set current frame range for engine %s!" % engine)
Esempio n. 26
0
    def set_frame_range(self, start_frame=1, end_frame=100,
                        adjust_frame_range=False):
        """sets the start and end frame range
        """
        # set it in the playback
        pm.playbackOptions(ast=start_frame, aet=end_frame)

        if adjust_frame_range:
            pm.playbackOptions(min=start_frame, max=end_frame)

        # set in the render range
        dRG = pm.PyNode('defaultRenderGlobals')
        dRG.setAttr('startFrame', start_frame)
        dRG.setAttr('endFrame', end_frame)
Esempio n. 27
0
    def set_fps(self, fps=25):
        """sets the fps of the environment
        """

        # get the current time, current playback min and max (because maya
        # changes them, try to restore the limits)

        current_time = pm.currentTime(q=1)
        pMin = pm.playbackOptions(q=1, min=1)
        pMax = pm.playbackOptions(q=1, max=1)
        pAst = pm.playbackOptions(q=1, ast=1)
        pAet = pm.playbackOptions(q=1, aet=1)

        # set the time unit, do not change the keyframe times
        # use the timeUnit as it is
        time_unit = u"pal"

        # try to find a timeUnit for the given fps
        # TODO: set it to the closest one
        for key in self.time_to_fps:
            if self.time_to_fps[key] == fps:
                time_unit = key
                break

        pm.currentUnit(t=time_unit, ua=0)
        # to be sure
        pm.optionVar['workingUnitTime'] = time_unit

        # update the playback ranges
        pm.currentTime(current_time)
        pm.playbackOptions(ast=pAst, aet=pAet)
        pm.playbackOptions(min=pMin, max=pMax)
Esempio n. 28
0
    def __init__(self, title, widthHeight, tabs_names, frameLayoutPerTab, collapseStyle=0, descr=''):
        super(Exporter, self).__init__(title, widthHeight, tabs_names, frameLayoutPerTab)
        self.localProject = os.environ[ 'MAYA_PROJECT' ]
        self.localUser=os.environ[ 'USER' ]
        self.path = os.path.join(self.localProject+ "/export/GEO")
        self.scene_name = cmds.file(q=True, sn=True, shn=True).split('.')[0]
        self.folder_path = os.path.join(self.path, 'OBJ', self.localUser, self.scene_name)
        self.type = 'OBJ'
        self.extension = 'obj'
        self.curFr=1001
        # GUI BUILDING #
        self.fl = self.frameLayouts[0][0].columnLayout
        col = pm.columnLayout(p=self.fl, h=self.wh[1]/2)
        flow_1=pm.flowLayout(p=col, w=self.wh[0])
        self.type_om = win.AW_optionMenu(label="File Type",
                                         options=['OBJ','ZBRUSH', 'MUDBOX', 'FBX', 'MB', 'MA', 'ALEMBIC'],
                                         parent=flow_1,
                                         cc=self._updateDirectory)
        self.autoCheck = pm.checkBox(l='Auto-detect Folder', p=flow_1, v=1)
        
        pm.flowLayout(p=col, w=self.wh[0])
        pm.text(l='Directory:')
        self.path_tf=pm.textField(w=self.wh[0]/1.3,cc=self._update_path_tf)
        pm.button(label='Browse',w=80, c=self._browser, bgc=self.col_fls[1])
        
        self.path_tf.setText(self.folder_path)

        flow_3 = pm.flowLayout(w=self.wh[0], p=col)
        self.combined_cb = pm.checkBox(l='Export Per Object', v=1, cc=self._change_combined_cb, p=flow_3)
        pm.text(l='Combined Name:',p=flow_3,w=200)
        self.combined_tf = pm.textField(tx='', p=flow_3,w=300, editable=False)
        
        flow_4 = pm.flowLayout(w=self.wh[0],p=col)
        self.framesCheck = pm.checkBox(l='Frame Range', w=200,p=flow_4, v=0, cc=self._framesCallback)
        self.fr_st = pm.textField(editable=False,w=100,tx=str(int(pm.playbackOptions(ast=True, q=True))),p=flow_4)
        self.fr_end = pm.textField(editable=False,w=100,tx=str(int(pm.playbackOptions(aet=True, q=True))),p=flow_4)
        
        pm.text(l='\n', p=col)
        flow_col = pm.flowLayout(p=col, w=self.wh[0])
        col_1 = pm.columnLayout(p=flow_col, w=self.wh[0]/2)
        col_2 = pm.columnLayout(p=flow_col, w=self.wh[0]/2)
        self.export_btn = pm.button(label='Export', bgc=self.col_fls[4], c=self._export, p=col_1, w=self.wh[0]/4)
        
        flow_5 = pm.flowLayout(w=self.wh[0],p=col_2)
        self.recursiveCheck = pm.checkBox(l='Check all folders inside', v=1, p=flow_5)
        self.list_btn = pm.button(label='List Files in Directory', bgc=self.col_fls[5], c=partial(self._getDirectoryFiles,True), p=flow_5, w=self.wh[0]/4)
        
        self.import_btn = pm.button(label='Import Directory', bgc=self.col_fls[5], c=self._customImport, p=col_2, w=self.wh[0]/2.5)
        pm.text(l='\n',p=col)
        pm.button(label='Swap Namespace with Name', bgc=self.col_fls[6], c=self._swapNamespace, p=col_2,w=self.wh[0]/2.5)
Esempio n. 29
0
    def copyAnimation(self,sourceAnim,sourceChar,fuseChar,start,end):
        rigFile = os.path.join(CHARACTERS_PATH,self.name,'rigging',self.name + '.ma')
        pm.openFile(rigFile,f=1)

        referenceAnim = pm.createReference(sourceAnim,namespace='source')
        pm.playbackOptions(e=1,ast=start,aet=end,min=start,max=end)
        pm.mel.eval('hikSetCurrentCharacter("' + fuseChar + '")')
        #pm.mel.eval('mayaHIKsetStanceInput( "' + fuseChar + '" )')
        #pm.mel.eval('HIKCharacterControlsTool()')
        pm.mel.eval('hikToggleLockDefinition')
        #self.logger.info('Characterized the skeleton')        
        pm.mel.eval('mayaHIKsetCharacterInput( "' + fuseChar + '","' + sourceChar +  '")')
        #pm.mel.eval('HIKCharacterControlsTool()')
        pm.mel.eval('hikBakeCharacter 0')
        referenceAnim.remove()
Esempio n. 30
0
def bdMultiMotionPath(crvPath, objects,interval=2,speed=20):
    numObjects = len(objects)
    startTime = pm.playbackOptions(q=1,minTime=1)
    endTime = pm.playbackOptions(q=1,maxTime=1)
    allMotionPath = []
    for i in range(numObjects):
        #motionPath = pm.pathAnimation(objects[i],c=crvPath,n=objects[i].name() + '_mp',stu = i*interval , etu = i*interval + speed,follow = 1, followAxis = 'x', upAxis = 'y',fractionMode =1)
        pm.currentTime(0)
        motionPath = pm.pathAnimation(objects[i],c=crvPath,n=objects[i].name() + '_mp',follow = 1, followAxis = 'x', upAxis = 'y',fractionMode =1)
        allMotionPath.append(motionPath)
        pm.setAttr(motionPath + '.worldUpType',1)


    bdSetStartMp(allMotionPath)
    startCycleFrame = i*interval + speed + 2
Esempio n. 31
0
def exportPlane(*args):
    # for sel in pm.ls(sl=1,ni=1):
    #     for i in range(pm.polyEvaluate(sel,v=1)):
    #         print (sel.vtx[i].getPosition(space="world"))

    export_dir = pm.fileDialog2(dialogStyle=2,
                                fileMode=3,
                                startingDirectory=os.path.dirname(
                                    pm.sceneName()))
    if not export_dir:
        return
    export_dir = export_dir[0]
    for sel in pm.ls(sl=1, ni=1):
        if not sel.endswith("_follow_plane") or not sel.getParent().endswith(
                "_follow_grp"):
            continue

        shape = sel.getShape()
        vtx_num = pm.polyEvaluate(sel, v=1)
        startTime = pm.playbackOptions(q=1, min=1)
        endTime = pm.playbackOptions(q=1, max=1)

        sel_list = om.MSelectionList()
        sel_list.add(str(sel))
        dagPath = sel_list.getDagPath(0)
        mesh = om.MFnMesh(dagPath)

        # NOTE 如果裁剪区域超过原图范围则限制到原图的边界上
        width = int(vtx_num)
        height = int(endTime - startTime)

        data = {}
        for h in range(height):
            data[h] = {}
            pm.currentTime(startTime + h)
            for w in range(width):
                vtx_pos = sel.vtx[w].getPosition(space="world")
                data[h][w] = vtx_pos.tolist()
                # data[h][w] = pm.pointPosition(sel.vtx[w],w=1).tolist()

        json_path = os.path.join(tempfile.gettempdir(), "pathTracker_EXR.json")
        with open(json_path, 'w') as f:
            json.dump(data, f)

        DIR = os.path.dirname(__file__)
        exr_exe = os.path.join(DIR, "dist", "pathTracker_EXR.exe")

        basename = sel.replace(":", "_")
        exr_path = os.path.join(export_dir, "%s_EXR.exr" % basename)

        # NOTE 执行 exr 输出
        subprocess.call([exr_exe, json_path, exr_path])

        # NOTE 导出 FBX
        SetFbxParameter()
        export_FBX = os.path.join(export_dir,
                                  "%s_FBX.fbx" % basename).replace("\\", "/")
        plane = pm.duplicate(sel)
        pm.parent(plane, w=1)
        pm.select(plane)
        mel.eval('FBXExport -f "' + export_FBX + '" -s')
        pm.delete(plane)

        os.startfile(export_dir)
        pm.confirmDialog(message='输出成功', button=['确定'])
    def _check_frame_range_with_shotgun(self, item):
        """
        Checks whether frame range is in sync with shotgun.

        :param item: Item to process
        :return: True if yes False otherwise
        """
        context = item.context
        entity = context.entity

        # checking entity validity
        if entity:
            frame_range_app = self.parent.engine.apps.get(
                "tk-multi-setframerange")
            if not frame_range_app:
                # return valid for asset/sequence entities
                self.logger.warning(
                    "Unable to find tk-multi-setframerange app. "
                    "Not validating frame range.")
                return True

            sg_entity_type = entity["type"]
            sg_filters = [["id", "is", entity["id"]]]
            in_field = frame_range_app.get_setting("sg_in_frame_field")
            out_field = frame_range_app.get_setting("sg_out_frame_field")
            fields = [in_field, out_field]

            # get the field information from shotgun based on Shot
            # sg_cut_in and sg_cut_out info will be on Shot entity, so skip in case this info is not present
            # or if the sg_head_in or sg_tail_out is empty, skip the check
            data = self.sgtk.shotgun.find_one(sg_entity_type,
                                              filters=sg_filters,
                                              fields=fields)
            if in_field not in data or out_field not in data:
                return True
            elif in_field is None or out_field is None:
                return True

            # Check if playback_start or animation_start is not in sync with shotgun
            # Similarly if animation_start or animation_start is not in sync with shotgun
            playback_start = pm.playbackOptions(q=True, minTime=True)
            playback_end = pm.playbackOptions(q=True, maxTime=True)

            animation_start = pm.playbackOptions(q=True,
                                                 animationStartTime=True)
            animation_end = pm.playbackOptions(q=True, animationEndTime=True)

            if playback_start != data[in_field] or playback_end != data[
                    out_field]:
                self.logger.warning("Frame range not synced with Shotgun.")
                QtGui.QMessageBox.warning(
                    None, "Frame range mismatch!",
                    "WARNING! Frame range not synced with Shotgun.")
                return True

            if animation_start != data[in_field] or animation_end != data[
                    out_field]:
                self.logger.warning("Frame range not synced with Shotgun.")
                QtGui.QMessageBox.warning(
                    None, "Frame range mismatch!",
                    "WARNING! Frame range not synced with Shotgun.")
                return True
            return True
        return True
Esempio n. 33
0
    def process(self, instance):
        self.log.info("Extracting capture..")

        # get scene fps
        fps = instance.data.get("fps") or instance.context.data.get("fps")

        # if start and end frames cannot be determined, get them
        # from Maya timeline
        start = instance.data.get("frameStartFtrack")
        end = instance.data.get("frameEndFtrack")
        if start is None:
            start = cmds.playbackOptions(query=True, animationStartTime=True)
        if end is None:
            end = cmds.playbackOptions(query=True, animationEndTime=True)

        self.log.info("start: {}, end: {}".format(start, end))

        # get cameras
        camera = instance.data['review_camera']
        capture_preset = instance.context.data['presets']['maya']['capture']

        try:
            preset = lib.load_capture_preset(data=capture_preset)
        except Exception:
            preset = {}
        self.log.info('using viewport preset: {}'.format(preset))

        preset['camera'] = camera
        preset['format'] = "image"
        # preset['compression'] = "qt"
        preset['quality'] = 95
        preset['compression'] = "png"
        preset['start_frame'] = start
        preset['end_frame'] = end
        camera_option = preset.get("camera_option", {})
        camera_option["depthOfField"] = cmds.getAttr(
            "{0}.depthOfField".format(camera))

        stagingdir = self.staging_dir(instance)
        filename = "{0}".format(instance.name)
        path = os.path.join(stagingdir, filename)

        self.log.info("Outputting images to %s" % path)

        preset['filename'] = path
        preset['overwrite'] = True

        pm.refresh(f=True)

        refreshFrameInt = int(pm.playbackOptions(q=True, minTime=True))
        pm.currentTime(refreshFrameInt - 1, edit=True)
        pm.currentTime(refreshFrameInt, edit=True)

        with maintained_time():
            filename = preset.get("filename", "%TEMP%")

            # Force viewer to False in call to capture because we have our own
            # viewer opening call to allow a signal to trigger between
            # playblast and viewer
            preset['viewer'] = False

            # Remove panel key since it's internal value to capture_gui
            preset.pop("panel", None)

            path = capture.capture(**preset)
            playblast = self._fix_playblast_output_path(path)

        self.log.info("file list  {}".format(playblast))

        collected_frames = os.listdir(stagingdir)
        collections, remainder = clique.assemble(collected_frames)
        input_path = os.path.join(
            stagingdir, collections[0].format('{head}{padding}{tail}'))
        self.log.info("input {}".format(input_path))

        if "representations" not in instance.data:
            instance.data["representations"] = []

        representation = {
            'name': 'png',
            'ext': 'png',
            'files': collected_frames,
            "stagingDir": stagingdir,
            "frameStart": start,
            "frameEnd": end,
            'fps': fps,
            'preview': True,
            'tags': ['review', 'delete']
        }
        instance.data["representations"].append(representation)
Esempio n. 34
0
import pymel.core as pm

#get selection
currentSelectionNames = pm.ls(selection=True)[0]

#Frame Range set by animator
frameRangeMin = pm.playbackOptions(query=True, minTime=True)
frameRangeMax = pm.playbackOptions(query=True, maxTime=True)

#get all keyable controls
currentSelectKeyable = pm.listAttr(currentSelectionNames, keyable=1)

eachGraphKeyedValues = None

listOfAttributes = []
listOfValues = []
listOfValuesTimes = []

#Go through the selected controllers graph values and times visible within in the channel box and place these in variables which are manageable
for eachAttribute in currentSelectKeyable:

    #Check number of keys on each frame
    numberOfKeys = pm.keyframe(currentSelectionNames + '.' + eachAttribute,
                               time=(frameRangeMin, frameRangeMax),
                               query=True,
                               keyframeCount=True)

    #EachAttributes graphs keyframe values
    eachGraphKeyedValues = pm.keyframe(currentSelectionNames + '.' +
                                       eachAttribute,
                                       time=(frameRangeMin, frameRangeMax),
Esempio n. 35
0
def rnkBipiedAnimation():
    global RNK_BIPIED_MAP
    rigDict = NITROGEN_BIPIED_MAP
    rigDict = ka_pymel.getAsPyNodes(rigDict)
    OOOOOOO = 'rigDict'
    print '%s: ' % OOOOOOO, eval(OOOOOOO), ' ', type(eval(OOOOOOO))
    # CENTER -----------------------------------------
    hip = rigDict.get('hip', None)
    pelvis = rigDict.get('pelvis', None)
    spines = rigDict.get('spines', None)
    necks = rigDict.get('necks', None)
    head = rigDict.get('head', None)

    # LEFT -----------------------------------------
    l_leg = rigDict.get('l_leg', None)
    l_knee = rigDict.get('l_knee', None)
    l_ankle = rigDict.get('l_ankle', None)
    l_footBall = rigDict.get('l_footBall', None)

    l_clavical = rigDict.get('l_clavical', None)
    l_arm = rigDict.get('l_arm', None)
    l_elbow = rigDict.get('l_elbow', None)
    l_wrist = rigDict.get('l_wrist', None)
    l_thumb = rigDict.get('l_thumb', None)
    l_fingers = rigDict.get('l_fingers', None)
    l_metacarpals = rigDict.get('l_metacarpals', None)

    # RIGHT -----------------------------------------
    r_leg = rigDict.get('r_leg', None)
    r_knee = rigDict.get('r_knee', None)
    r_ankle = rigDict.get('r_ankle', None)
    r_footBall = rigDict.get('r_footBall', None)

    r_clavical = rigDict.get('r_clavical', None)
    r_arm = rigDict.get('r_arm', None)
    r_elbow = rigDict.get('r_elbow', None)
    r_wrist = rigDict.get('r_wrist', None)
    r_thumb = rigDict.get('r_thumb', None)
    r_fingers = rigDict.get('r_fingers', None)
    r_metacarpals = rigDict.get('r_metacarpals', None)

    thumbCurlAxis = 'ry'
    flatThumbRotation = [0.0, -45.0, 0.0]

    pymel.currentTime(1)
    allControls = getAllControls_fromRigDict(rigDict)
    #for key in allControls:
    #if allControls[key] == None:
    #pymel.warning('%s has a value of None' % key)

    ka_animation.storeAllControls(allControls)
    ka_animation.deleteAnimationOnAllControls()

    # set A Pose ----------------------------------------------------------------
    ka_animation.keyAllControls()
    pymel.currentTime(0)  # count from zero, but first key is on frame 1

    pymel.select(clear=True)
    # set T Pose ----------------------------------------------------------------
    ka_animation.advanceNFrames(KEY_SPACING * 2)

    tryToXform(l_leg, rotation=[0, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    tryToXform(l_knee, rotation=[0, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_knee, targetTransform=l_knee)

    tryToXform(l_ankle, rotation=[0, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    tryToXform(l_footBall, rotation=[90, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_footBall, targetTransform=l_footBall)

    tryToXform(l_arm, rotation=[-180, 0, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    tryToXform(l_elbow, rotation=[-180, 0, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_elbow, targetTransform=l_elbow)

    tryToXform(l_wrist, rotation=[-180, 0, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    for iA, finger in enumerate(l_fingers):
        for iB, fingerJoint in enumerate(finger):
            tryToXform(l_fingers[iA][iB],
                       rotation=[-90, 0, 0],
                       worldSpace=True)
            ka_transforms.mirrorTransform(r_fingers[iA][iB],
                                          targetTransform=fingerJoint)

    for iA, thumbJoint in enumerate(l_thumb):
        #worldRot = pymel.xform(l_thumb[0], q=True, ws=True, rotation=True)
        if iA != 0:
            #pymel.xform(l_thumb[iA], ws=True, rotation=worldRot)
            ka_transforms.snap(l_thumb[iA], l_thumb[0], r=1)
            ka_transforms.mirrorTransform(r_thumb[iA],
                                          targetTransform=thumbJoint)

    for spine in spines:
        tryToXform(spine, rotation=[0, 0, 0], worldSpace=True)

    for neck in necks:
        tryToXform(neck, rotation=[0, 0, 0], worldSpace=True)

    tryToXform(head, rotation=[0, 0, 0], worldSpace=True)

    ka_animation.storePose('tPose')
    ka_animation.keyAllControls()

    #pymel.error()

    # FINGER CURLS ----------------------------------------------------------------
    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.keyAllControls()

    #pymel.error()

    for iA, finger in enumerate(reversed(l_fingers)):

        # inward curl
        curl = 0
        for iB, fingerJoint in enumerate(finger):
            ka_animation.advanceNFrames(KEY_SPACING / 2)

            tryToXform(l_thumb[0], rotation=flatThumbRotation, worldSpace=True)
            ka_transforms.mirrorTransform(r_thumb[0],
                                          targetTransform=l_thumb[0])

            if iB == 0:
                curl = -75

            elif iB == 1:
                curl = -95

            else:
                curl = -65

            tryToXform(fingerJoint,
                       rotation=[0, 0, curl],
                       worldSpace=True,
                       relative=True)
            ka_transforms.mirrorTransform(r_fingers[iA][iB],
                                          targetTransform=fingerJoint)

            ka_animation.keyAllControls()

        ka_animation.advanceNFrames(KEY_SPACING)
        ka_animation.applyPose('tPose')

        tryToXform(
            l_thumb[0],
            rotation=flatThumbRotation,
            worldSpace=True,
        )
        ka_transforms.mirrorTransform(r_thumb[0], targetTransform=l_thumb[0])

        ka_animation.keyAllControls()

        # upward curl
        curl = 0
        for iB, fingerJoint in enumerate(finger):
            ka_animation.advanceNFrames(KEY_SPACING / 2)

            if iB == 0:
                curl = 40

            elif iB == 1:
                curl = 10

            else:
                curl = 15

            tryToXform(fingerJoint,
                       rotation=[0, 0, curl],
                       worldSpace=True,
                       relative=True)
            ka_transforms.mirrorTransform(r_fingers[iA][iB],
                                          targetTransform=fingerJoint)

            ka_animation.keyAllControls()

        ka_animation.advanceNFrames(KEY_SPACING / 2)
        ka_animation.applyPose('tPose')

        tryToXform(l_thumb[0], rotation=flatThumbRotation, worldSpace=True)
        ka_transforms.mirrorTransform(r_thumb[0], targetTransform=l_thumb[0])

        ka_animation.keyAllControls()

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')

    ka_animation.keyAllControls()

    # THUMB CURLS ----------------------------------------------------------------

    # innerCurl
    for iA, thumbJoint in enumerate(l_thumb):
        if iA == 0:
            #tryToXform(thumbJoint, rotation=[-90, -40, -30], worldSpace=True,)
            #ka_transforms.mirrorTransform(r_thumb[iA], targetTransform=l_thumb[iA])
            pass

        else:
            if iA == 1:
                curl = 60

            else:
                curl = 65

            rot = thumbJoint.attr(thumbCurlAxis).get()
            thumbJoint.attr(thumbCurlAxis).set(rot + curl)
            ka_transforms.mirrorTransform(r_thumb[iA],
                                          targetTransform=l_thumb[iA])

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING / 2)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()

    # outerCurl
    for iA, thumbJoint in enumerate(l_thumb):
        if iA == 0:
            #tryToXform(thumbJoint, rotation=[-45, -45, -40], worldSpace=True)
            pass
        else:
            if iA == 1:
                curl = -20

            else:
                curl = -65

            rot = thumbJoint.attr(thumbCurlAxis).get()
            thumbJoint.attr(thumbCurlAxis).set(rot + curl)
            ka_transforms.mirrorTransform(r_thumb[iA],
                                          targetTransform=l_thumb[iA])

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING / 2)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()

    # HAND CUP ----------------------------------------------------------------
    # metacarpals
    ka_animation.advanceNFrames(KEY_SPACING)
    for iA, metacarpal in enumerate(l_metacarpals):
        if iA == 0:
            rotation = [16, 0, -7]

        else:
            rotation = [-42, 0, -16]

        tryToXform(metacarpal,
                   rotation=[rotation[0], 0, 0],
                   worldSpace=True,
                   relative=True)
        tryToXform(metacarpal,
                   rotation=[0, 0, rotation[2]],
                   worldSpace=True,
                   relative=True)
        #metacarpal.r.set(rotation)
        ka_transforms.mirrorTransform(r_metacarpals[iA],
                                      targetTransform=l_metacarpals[iA])

    # thumb
    for iA, thumbJoint in enumerate(l_thumb):
        if iA == 0:
            tryToXform(thumbJoint, rotation=[-40, 0, -44], worldSpace=True)
            ka_transforms.mirrorTransform(r_thumb[0],
                                          targetTransform=l_thumb[0])

        else:
            if iA == 1:
                curl = 40

            else:
                curl = -57

            rotz = thumbJoint.rz.get()
            rotz = thumbJoint.rz.set(rotz + curl)
            ka_transforms.mirrorTransform(r_thumb[iA],
                                          targetTransform=l_thumb[iA])

    ka_animation.keyAllControls()

    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()

    # HAND SPLAY ----------------------------------------------------------------
    # thumb
    tryToXform(l_thumb[0], rotation=[-95, -63, 7], worldSpace=True)
    ka_transforms.mirrorTransform(r_thumb[0], targetTransform=l_thumb[0])

    for iA, finger in enumerate(l_fingers):
        if iA == 0:
            splay = 21

        elif iA == 1:
            splay = 0

        elif iA == 2:
            splay = -15

        else:
            splay = -30

        for iB, fingerJoint in enumerate(finger):
            if iB == 0:
                ry = fingerJoint.ry.get()
                fingerJoint.ry.set(ry + splay)
                ka_transforms.mirrorTransform(
                    r_fingers[iA][iB], targetTransform=l_fingers[iA][iB])

    for iA, metacarpal in enumerate(l_metacarpals):
        if iA == 0:
            splay = -2

        else:
            splay = -6

        ry = metacarpal.ry.get()
        metacarpal.ry.set(ry + splay)
        ka_transforms.mirrorTransform(r_metacarpals[iA],
                                      targetTransform=l_metacarpals[iA])

    ka_animation.keyAllControls()

    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()

    # WRIST ROTATIONS ----------------------------------------------------------------
    ka_animation.advanceNFrames(KEY_SPACING)

    # forward
    tryToXform(l_wrist, rotation=[-180, -32, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # back
    tryToXform(l_wrist, rotation=[-180, 50, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # up
    tryToXform(l_wrist, rotation=[-180, 0, -268], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # down
    tryToXform(l_wrist, rotation=[-180, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # forward
    tryToXform(l_wrist, rotation=[-180, -32, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # up
    tryToXform(l_wrist, rotation=[-180, 0, -268], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # back
    tryToXform(l_wrist, rotation=[-180, 50, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # down
    tryToXform(l_wrist, rotation=[-180, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # forward
    tryToXform(l_wrist, rotation=[-180, -32, 0], worldSpace=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ARM TWIST ----------------------------------------------------------------

    # twist back
    # wrist
    tryToXform(l_wrist, rotation=[-38, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # arm
    tryToXform(l_arm, rotation=[-38, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # twist forward
    # wrist
    tryToXform(l_wrist, rotation=[90, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_wrist, targetTransform=l_wrist)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # arm
    tryToXform(l_arm, rotation=[38, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ELBOW BEND ----------------------------------------------------------------
    tryToXform(l_elbow, rotation=[0, -135, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_elbow, targetTransform=l_elbow)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ARM ROTATIONS ----------------------------------------------------------------
    # down
    tryToXform(l_arm, rotation=[0, 0, -90], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # forward
    tryToXform(l_arm, rotation=[-90, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # flat
    ka_animation.applyPose('tPose')
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    tryToXform(l_arm, rotation=[0, 0, 90], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # back
    tryToXform(l_arm, rotation=[0, 90, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # down and back
    tryToXform(l_arm, rotation=[-45, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # down
    tryToXform(l_arm, rotation=[-90, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_arm, targetTransform=l_arm)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # SHOULDER ROTATIONS ISOLATED ----------------------------------------------------------------

    # up
    tryToXform(l_clavical, rotation=[0, 0, 35], worldSpace=True, relative=True)

    tryToXform(l_arm, rotation=[90, 0, -0], worldSpace=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # down
    tryToXform(l_clavical,
               rotation=[0, 0, -16],
               worldSpace=True,
               relative=True)

    tryToXform(l_arm, rotation=[90, 0, 0], worldSpace=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # forward
    tryToXform(l_clavical,
               rotation=[0, -60, 0],
               worldSpace=True,
               relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # back
    tryToXform(l_clavical, rotation=[0, 16, 0], worldSpace=True, relative=True)

    tryToXform(l_arm, rotation=[90, 0, 0], worldSpace=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ARM OVER HEAD ----------------------------------------------------------------
    tryToXform(l_clavical, rotation=[0, 0, 35], worldSpace=True, relative=True)

    tryToXform(l_arm, rotation=[0, 0, 105], worldSpace=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ARM CROSSOVER ----------------------------------------------------------------
    tryToXform(l_clavical,
               rotation=[0, -60, 0],
               worldSpace=True,
               relative=True)

    tryToXform(l_arm, rotation=[90, -155, 0], worldSpace=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # HEAD AND NECK ROTATIONS ----------------------------------------------------------------

    # look up
    tryToXform(head, rotation=[45, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        if iA == 0:
            tryToXform(neckJoint,
                       rotation=[20, 0, 0],
                       worldSpace=True,
                       relative=True)
        else:
            tryToXform(neckJoint,
                       rotation=[10, 0, 0],
                       worldSpace=True,
                       relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # look down
    tryToXform(head, rotation=[-35, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        if iA == 0:
            tryToXform(neckJoint,
                       rotation=[-15, 0, 0],
                       worldSpace=True,
                       relative=True)
        else:
            tryToXform(neckJoint,
                       rotation=[-7, 0, 0],
                       worldSpace=True,
                       relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # bend left
    tryToXform(head, rotation=[0, 0, 45], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        if iA == 0:
            tryToXform(neckJoint,
                       rotation=[0, 0, 20],
                       worldSpace=True,
                       relative=True)
        else:
            tryToXform(neckJoint,
                       rotation=[0, 0, 10],
                       worldSpace=True,
                       relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # bend right
    tryToXform(head, rotation=[0, 0, -45], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        if iA == 0:
            tryToXform(neckJoint,
                       rotation=[0, 0, -20],
                       worldSpace=True,
                       relative=True)
        else:
            tryToXform(neckJoint,
                       rotation=[0, 0, -10],
                       worldSpace=True,
                       relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # HEAD AND NECK TWIST ----------------------------------------------------------------
    twist = 105
    numberOfControls = 1 + len(necks)
    twistPerJoint = twist * (1.0 / numberOfControls)

    # twist left
    tryToXform(head,
               rotation=[0, twistPerJoint, 0],
               worldSpace=True,
               relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        tryToXform(neckJoint,
                   rotation=[0, twistPerJoint, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # twist right
    twistPerJoint *= -1

    tryToXform(head,
               rotation=[0, twistPerJoint, 0],
               worldSpace=True,
               relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    for iA, neckJoint in enumerate(reversed(necks)):
        tryToXform(neckJoint,
                   rotation=[0, twistPerJoint, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # SPINE ROTATIONS ----------------------------------------------------------------

    # forward
    for iA, spineJoint in enumerate(reversed(spines)):
        if iA == 0:
            bend = -20
        else:
            bend = -30

        tryToXform(spineJoint,
                   rotation=[bend, 0, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING / 2)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # backward
    for iA, spineJoint in enumerate(reversed(spines)):
        if iA == 0:
            bend = 20
        else:
            bend = 30

        tryToXform(spineJoint,
                   rotation=[bend, 0, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # bend left
    for iA, spineJoint in enumerate(reversed(spines)):
        if iA == 0:
            bend = 20
        else:
            bend = 30

        tryToXform(spineJoint,
                   rotation=[0, 0, bend],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # bend right
    for iA, spineJoint in enumerate(reversed(spines)):
        if iA == 0:
            bend = -20
        else:
            bend = -30

        tryToXform(spineJoint,
                   rotation=[0, 0, bend],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # SPINE TWIST ----------------------------------------------------------------
    twist = 90
    numberOfControls = len(spines)
    twistPerJoint = twist * (1.0 / numberOfControls)

    # left
    for iA, spineJoint in enumerate(reversed(spines)):
        tryToXform(spineJoint,
                   rotation=[0, twistPerJoint, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING / 2)

    tryToXform(l_clavical, rotation=[0, 15, 0], worldSpace=True, relative=True)
    tryToXform(r_clavical, rotation=[0, 30, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    # right
    twistPerJoint *= -1

    for iA, spineJoint in enumerate(reversed(spines)):
        tryToXform(spineJoint,
                   rotation=[0, twistPerJoint, 0],
                   worldSpace=True,
                   relative=True)

        ka_animation.keyAllControls()
        ka_animation.advanceNFrames(KEY_SPACING / 2)

    tryToXform(l_clavical,
               rotation=[0, -30, 0],
               worldSpace=True,
               relative=True)
    tryToXform(r_clavical,
               rotation=[0, -15, 0],
               worldSpace=True,
               relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING / 2)

    ka_animation.advanceNFrames(KEY_SPACING / 2)
    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # PELVIS ----------------------------------------------------------------

    # forwards
    tryToXform(pelvis, rotation=[0, 0, -45], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # backwards
    tryToXform(pelvis, rotation=[0, 0, 30], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # left
    tryToXform(pelvis, rotation=[0, 0, -20], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # right
    tryToXform(pelvis, rotation=[0, 0, 20], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # twist right
    tryToXform(pelvis, rotation=[0, 30, 0], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # twist left
    tryToXform(pelvis, rotation=[0, -30, 0], worldSpace=True, relative=True)
    tryToXform(
        l_leg,
        rotation=[90, 0, -90],
        worldSpace=True,
    )
    tryToXform(
        r_leg,
        rotation=[-90, 0, 90],
        worldSpace=True,
    )

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # TOES ----------------------------------------------------------------
    # up
    tryToXform(l_footBall,
               rotation=[-45, 0, 0],
               worldSpace=True,
               relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # down
    tryToXform(l_footBall, rotation=[30, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # ANKLE ----------------------------------------------------------------
    # up
    tryToXform(l_ankle, rotation=[-15, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # down
    tryToXform(l_ankle, rotation=[60, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # outside
    tryToXform(l_ankle, rotation=[0, 0, -40], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # inside
    tryToXform(l_ankle, rotation=[0, 0, 30], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # KNEE ----------------------------------------------------------------
    tryToXform(l_knee, rotation=[90, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # LEG ROTATION ----------------------------------------------------------------
    # fowards
    tryToXform(l_leg, rotation=[-90, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # backwards
    tryToXform(l_leg, rotation=[90, 0, 0], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # outside
    tryToXform(l_leg, rotation=[0, 0, 30], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # inside
    tryToXform(l_leg, rotation=[0, 0, -65], worldSpace=True, relative=True)
    tryToXform(r_leg, rotation=[0, 0, -65], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # fowards
    tryToXform(l_leg, rotation=[-90, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # outside
    tryToXform(l_leg, rotation=[0, 0, 30], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # backwards
    tryToXform(l_leg, rotation=[90, 0, 0], worldSpace=True, relative=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # inside
    tryToXform(l_leg, rotation=[0, 0, -65], worldSpace=True, relative=True)
    tryToXform(r_leg, rotation=[0, 0, -65], worldSpace=True, relative=True)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # LEG TWIST ----------------------------------------------------------------

    # outside
    # ankle
    tryToXform(l_ankle, rotation=[0, -60, -0], worldSpace=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # leg
    tryToXform(l_leg, rotation=[-10, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # inside
    # ankle
    tryToXform(l_ankle, rotation=[0, -135, -0], worldSpace=True)
    ka_transforms.mirrorTransform(r_ankle, targetTransform=l_ankle)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # leg
    tryToXform(l_leg, rotation=[135, 0, -90], worldSpace=True)
    ka_transforms.mirrorTransform(r_leg, targetTransform=l_leg)

    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    ka_animation.applyPose('tPose')
    ka_animation.keyAllControls()
    ka_animation.advanceNFrames(KEY_SPACING)

    # Finish
    pymel.playbackOptions(min=1, max=pymel.currentTime(query=True) + 50)
    pymel.currentTime(1)
Esempio n. 36
0
    def create_alembic(cls, from_top_node=1):
        """creates alembic cache from selected nodes
        """
        import os
        root_flag = '-root %(node)s'
        mel_command = 'AbcExport -j "-frameRange %(start)s %(end)s -ro ' \
                      '-stripNamespaces -uvWrite -wholeFrameGeo -worldSpace ' \
                      '%(roots)s ' \
                      '-file %(path)s";'

        current_path = pm.workspace.path
        abc_path = os.path.join(current_path, 'cache', 'alembic')
        try:
            os.makedirs(abc_path)
        except OSError:
            pass

        abc_full_path = pm.fileDialog2(startingDirectory=abc_path)

        def find_top_parent(node):
            parents = node.listRelatives(p=1)
            parent = None
            while parents:
                parent = parents[0]
                parents = parent.listRelatives(p=1)
                if parents:
                    parent = parents[0]
                else:
                    return parent
            if not parent:
                return node
            else:
                return parent

        if abc_full_path:
            abc_full_path = abc_full_path[0]  # this is dirty
            abc_full_path = os.path.splitext(abc_full_path)[0] + '.abc'

            # get nodes
            selection = pm.ls(sl=1)
            nodes = []
            for node in selection:
                if from_top_node:
                    node = find_top_parent(node)
                if node not in nodes:
                    nodes.append(node)

            # generate root flags
            roots = []
            for node in nodes:
                roots.append(root_flag % {'node': node.fullPath()})

            roots_as_string = ' '.join(roots)

            start = int(pm.playbackOptions(q=1, minTime=1))
            end = int(pm.playbackOptions(q=1, maxTime=1))
            rendered_mel_command = mel_command % {
                'start': start,
                'end': end,
                'roots': roots_as_string,
                'path': abc_full_path
            }
            pm.mel.eval(rendered_mel_command)
Esempio n. 37
0
    def bake(self):
        buttons = export, create, cancel = '.abc 저장', '씬 안에 생성', '취소'
        option = questionbox(
            parent=self,
            title='출력형태 지정',
            message='베이크할 카메라의 출력 형태를 선택하세요.',
            icon='question',
            button=buttons,
            default=export,
            cancel=cancel,
            dismiss=cancel,
        )
        if option == cancel:
            return

        cam_file = None
        if option == export:
            optionvar = 'camviewmgr_last_exported_path'

            if pm.optionVar(exists=optionvar):
                last_dir = pm.optionVar(query=optionvar)
            else:
                last_dir = ''

            response = QFileDialog.getSaveFileName(
                caption='카메라가 저장될 위치를 지정하세요',
                dir=last_dir,
                filter='Alembic File (*.abc)',
                parent=self,
            )
            if not response[0]:
                return
            cam_file = response[0]
            dirs(os.path.dirname(cam_file))
            pm.optionVar(stringValue=(optionvar, os.path.dirname(cam_file)))

        cam = pm.PyNode(self.currentItem().text())
        if not cam:
            return
        cam_shape = cam.getShape()

        pm.undoInfo(openChunk=True)

        dup_cam = pm.duplicate(cam)[0]
        dup_cam_shape = dup_cam.getShape()

        for child in pm.listRelatives(dup_cam, children=True):
            if child.nodeType() == 'camera':
                continue
            pm.delete(child)

        dup_cam_shape.focalLength.set(lock=False, keyable=True)
        dup_cam_shape.nearClipPlane.set(lock=False, keyable=True)
        dup_cam_shape.farClipPlane.set(lock=False, keyable=True)

        cam_shape.focalLength.connect(dup_cam_shape.focalLength, force=True)
        cam_shape.nearClipPlane.connect(dup_cam_shape.nearClipPlane,
                                        force=True)
        cam_shape.farClipPlane.connect(dup_cam_shape.farClipPlane, force=True)

        for child in pm.listRelatives(dup_cam, children=True):
            if child.nodeType() == 'camera':
                continue
            pm.delete(child)

        for ch in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']:
            attr = dup_cam.attr(ch)
            attr.set(lock=False)

        for attr in dup_cam.listAttr(userDefined=True):
            try:
                attr.set(lock=False)
                pm.deleteAttr(attr)
            except:
                pass

        pm.parent(dup_cam, world=True)
        pm.rename(dup_cam, cam.name() + '_baked')
        constraint = pm.parentConstraint(cam, dup_cam)
        st = pm.playbackOptions(query=True, minTime=True - 2)
        ed = pm.playbackOptions(query=True, maxTime=True + 2)
        pm.bakeResults(
            [dup_cam, dup_cam_shape],
            shape=True,
            simulation=True,
            time=(st, ed),
        )
        pm.delete(constraint)

        pm.undoInfo(closeChunk=True)

        if cam_file:
            pm.rename(dup_cam, cam.name())
            pm.select(dup_cam, replace=True)
            pm.delete(pm.ls(type='unknown'))
            pm.mel.eval(
                'AbcExport -j "-frameRange {} {} -noNormals -eulerFilter -dataFormat ogawa -root {} -file {}"'
                .format(st, ed, dup_cam.name(), cam_file))
            if option != create:
                pm.delete(dup_cam)
Esempio n. 38
0
 def getCurrentTimeSlider(self):
     endFrame = pm.playbackOptions(q=True, maxTime=True)
     return int(endFrame)
Esempio n. 39
0
import pymel.core as pm
import os
import errno

#load plugin
if not pm.pluginInfo('AbcExport', query=True, loaded=True):
    pm.loadPlugin('AbcExport')

#selection
selection = pm.ls(sl=True)
if not selection:
    raise ValueError('Cannot save empty selection.')
previouse_selection = selection

#get frame range
fstart = pm.playbackOptions(query=True, minTime=True)
fend = pm.playbackOptions(query=True, maxTime=True)
fcurrent = pm.currentTime()
step = 1

# Ensure target folder exists
target = (u'F:\local_WIP\pythonAbcExport')
try:
    os.makedirs(target)
except OSError as error:
    if error.errno != errno.EEXIST:
        raise

#build filepath
cache_path = os.path.join(target, 'cache.abc')
Esempio n. 40
0
def main():
    cmds.loadPlugin("AbcExport.mll")
    # get the top one
    objs = pm.ls(sl=True)
    if not objs:
        return pm.inViewMessage(smg="select object first",
                                pos="midCenterTop",
                                bkc=0x00FF1010,
                                fade=True)
    pm.select(clear=True)
    for obj in objs:
        parent_node = pm.listRelatives(obj,
                                       children=True,
                                       fullPath=True,
                                       allParents=True)
        if parent_node:
            final = get_top(obj)[0]
        else:
            final = obj
        # judge the selection is ref or not
        ref_jud = pm.referenceQuery("%s" % final, isNodeReferenced=True)

        if ref_jud:
            file_path = pm.referenceQuery("%s" % final, filename=True)
            print file_path
            name_space = pm.referenceQuery("%s" % final, namespace=True)
            print name_space

            pm.mel.eval('file -importReference "%s"' % file_path)
            # remove the namespace
            pm.mel.eval('namespace -mv "%s" ":" -force' % name_space)
            # trying to get the shape group(filter of the curve and rig)
        pm.select(final, add=True)

    #deal with the samename node after import the reference readonly
    obj_list = cmds.ls(sl=True, long=True, dag=True)
    obj_list.sort(key=len, reverse=True)
    renamedict = {}
    namelist = []
    for obj in obj_list:
        obj_name = obj.split("|")[-1]
        print obj_name
        if not namelist.count(obj_name):
            namelist.append(obj_name)
            renamedict[obj_name] = [obj]
        else:
            renamedict[obj_name].append(obj)

    for name in namelist:
        paths = renamedict[name]
        paths.sort(key=len, reverse=True)
        if len(paths) == 1:
            continue
        print name, paths
        index = 1
        for path in paths:
            new_name = "%s_%s" % (name, index)
            index += 1
            cmds.rename(path, new_name)

    # pm.select(clear=True)
    # pm.select(final, add=True)
    objs = pm.ls(sl=True, long=True)

    geo_list = []
    for obj in objs:
        print obj
        geo = None
        children = pm.listRelatives(obj, children=True, fullPath=True)
        for child in children:
            print pm.objectType(child)
            if "geo" in child.name() or "Geo" in child.name():
                geo = child
                geo_list.append(geo)
                break
            else:
                geo = None
        if not geo:
            if len(children) == 1 and pm.objectType(children) == "mesh":
                geo = obj
                geo_list.append(geo)
                continue
            else:
                for child in children:
                    if get_next(child):
                        geo = child
                        geo_list.append(geo)

    pm.select(clear=True)
    pm.select(geo_list, add=True)
    print(666666666666666666666666666666666666666666666666666)
    # use the current filepath as the clue to query the destination

    current_path = pm.mel.eval("file -q -sn")
    filename = os.path.basename(current_path)
    abc_name = os.path.splitext(filename)[0] + ".abc"

    rp_code = os.path.dirname(current_path).split("/")[-1]

    dirname = os.path.join(
        os.path.dirname(current_path)[:-len(rp_code)], "abc")

    abc_name = os.path.normpath(os.path.join(dirname, abc_name))

    sel_frameRange = str(pm.playbackOptions(q=True, minTime=True) -
                         10) + " " + str(
                             pm.playbackOptions(q=True, maxTime=True) + 10)

    root_geo = ""
    for obj in geo_list:
        root_geo += "-root %s " % obj

    print root_geo
    pm.AbcExport(
        j="-frameRange {frameRange} -uvWrite -worldSpace -writeVisibility -dataFormat hdf {file} -file {path}"
        .format(frameRange=sel_frameRange, file=root_geo, path=abc_name))
Esempio n. 41
0
	def getTimeSliderMinMax(self):
		"""doc"""
		start = int(pm.playbackOptions(q= 1, min= 1))
		end = int(pm.playbackOptions(q= 1, max= 1)) + 1
		return start, end
Esempio n. 42
0
 def anim_range(self):
     start_time = pm.playbackOptions(q=True, min=True)
     end_time = pm.playbackOptions(q=True, max=True)
     return [start_time, end_time]
Esempio n. 43
0
 def get_playback_info(self):
     return (int(pm.playbackOptions(q=1, min=1)),
             int(pm.playbackOptions(q=1, max=1)))
Esempio n. 44
0
 def test_EntityPerFrame(self):
     '''
     Test the conversion to single visibility switched nodes
     '''
     pCore.playbackOptions(min=1, max=50)
     tag=mTag.GetExportTagFromSelected(pCore.PyNode('pCube1'))[0]
     tag=tag.ConvertTagType('EntityPerFrame')
     data=tag._ProcessBaseTagFilter()
     
     #Test that the new nodes have the TimeLine Data cast over to them
     firstTenResults=['%s,on:%0.2f,off:%0.2f' % (node.name(),node.TimelineStart.get(),node.TimelineEnd.get()) for node in sorted(data)[:10]]
     assert firstTenResults==['EntityPerFrame_1,on:1.00,off:2.00',
                              'EntityPerFrame_10,on:10.00,off:11.00',
                              'EntityPerFrame_11,on:11.00,off:12.00',
                              'EntityPerFrame_12,on:12.00,off:13.00',
                              'EntityPerFrame_13,on:13.00,off:14.00',
                              'EntityPerFrame_14,on:14.00,off:15.00',
                              'EntityPerFrame_15,on:15.00,off:16.00',
                              'EntityPerFrame_16,on:16.00,off:17.00',
                              'EntityPerFrame_17,on:17.00,off:18.00',
                              'EntityPerFrame_18,on:18.00,off:19.00']
     
     expected=['EntityPerFrame_1',
              'EntityPerFrame_10',
              'EntityPerFrame_11',
              'EntityPerFrame_12',
              'EntityPerFrame_13',
              'EntityPerFrame_14',
              'EntityPerFrame_15',
              'EntityPerFrame_16',
              'EntityPerFrame_17',
              'EntityPerFrame_18',
              'EntityPerFrame_19',
              'EntityPerFrame_2',
              'EntityPerFrame_20',
              'EntityPerFrame_21',
              'EntityPerFrame_22',
              'EntityPerFrame_23',
              'EntityPerFrame_24',
              'EntityPerFrame_25',
              'EntityPerFrame_26',
              'EntityPerFrame_27',
              'EntityPerFrame_28',
              'EntityPerFrame_29',
              'EntityPerFrame_3',
              'EntityPerFrame_30',
              'EntityPerFrame_31',
              'EntityPerFrame_32',
              'EntityPerFrame_33',
              'EntityPerFrame_34',
              'EntityPerFrame_35',
              'EntityPerFrame_36',
              'EntityPerFrame_37',
              'EntityPerFrame_38',
              'EntityPerFrame_39',
              'EntityPerFrame_4',
              'EntityPerFrame_40',
              'EntityPerFrame_41',
              'EntityPerFrame_42',
              'EntityPerFrame_43',
              'EntityPerFrame_44',
              'EntityPerFrame_45',
              'EntityPerFrame_46',
              'EntityPerFrame_47',
              'EntityPerFrame_48',
              'EntityPerFrame_49',
              'EntityPerFrame_5',
              'EntityPerFrame_50',
              'EntityPerFrame_6',
              'EntityPerFrame_7',
              'EntityPerFrame_8',
              'EntityPerFrame_9'] 
     
     assert [n.name() for n in sorted(data)]==expected
     toClean=['EntityPerFrame']
     toClean.extend(expected)
     assert sorted(pCore.melGlobals['NodesToDeleteOnCleanUp'])==toClean
     
     #test the Cleanup calls
     tag._CleanupProcessedTagFilter()
     assert not pCore.melGlobals['NodesToDeleteOnCleanUp']
     assert not [n for n in data if pCore.PyNode(n).exists()]
Esempio n. 45
0
 def test_ProgressiveMorphFilter(self):
     '''
     Test the convertion of the deformerData to linear blendshape
     '''
     pCore.playbackOptions(min=1, max=50)
     tag=mTag.GetExportTagFromSelected(pCore.PyNode('pCube1'))[0]
     data=tag._ProcessBaseTagFilter()
     
     #Note the actual Tagged Node is NOT passed into the filtered nodes!
     assert data==['pCube1_progressive']
     
     #Test the generated Progressive network
     node=data[0]
     shape=node.getShape()
     shape.listHistory(type='mesh')
     blendshape=shape.listHistory(type='blendShape')[0]
     assert blendshape.name()=='blendShape1'
     assert blendshape.getTarget()==['Progressive_1',
                              'Progressive_2',
                              'Progressive_3',
                              'Progressive_4',
                              'Progressive_5',
                              'Progressive_6',
                              'Progressive_7',
                              'Progressive_8',
                              'Progressive_9',
                              'Progressive_10',
                              'Progressive_11',
                              'Progressive_12',
                              'Progressive_13',
                              'Progressive_14',
                              'Progressive_15',
                              'Progressive_16',
                              'Progressive_17',
                              'Progressive_18',
                              'Progressive_19',
                              'Progressive_20',
                              'Progressive_21',
                              'Progressive_22',
                              'Progressive_23',
                              'Progressive_24',
                              'Progressive_25',
                              'Progressive_26',
                              'Progressive_27',
                              'Progressive_28',
                              'Progressive_29',
                              'Progressive_30',
                              'Progressive_31',
                              'Progressive_32',
                              'Progressive_33',
                              'Progressive_34',
                              'Progressive_35',
                              'Progressive_36',
                              'Progressive_37',
                              'Progressive_38',
                              'Progressive_39',
                              'Progressive_40',
                              'Progressive_41',
                              'Progressive_42',
                              'Progressive_43',
                              'Progressive_44',
                              'Progressive_45',
                              'Progressive_46',
                              'Progressive_47',
                              'Progressive_48',
                              'Progressive_49',
                              'Progressive_50']
Esempio n. 46
0
 def apply_scene_range(self):
     self.set_job_value('start_frame', int(pm.playbackOptions(minTime=True, query=True)))
     self.set_job_value('end_frame', int(pm.playbackOptions(maxTime=True, query=True)))
Esempio n. 47
0
#coding=gbk
import maya.cmds as cmds
import pymel.core as pmel
import maya.mel as mel
from functools import partial

#获取当前时间轴起始结束帧
st_frame_time = pmel.playbackOptions(q=1,ast=1)
et_frame_time = pmel.playbackOptions(q=1,aet=1)
#创建aov类型
rs_aov_Type = ["Ambient Occlusion",
                "Background",
                "Bump Normals",
                "Caustics",
                "Caustics Raw",
                "Depth",
                "Diffuse Filter",
                "Diffuse Lighting",
                "Diffuse Lighting Raw",
                "Emission",
                "Global Illumination",
                "Global Illumination Raw",
                "Matte",
                "Motion Vectors",
                "Normals",
                "ObjectID",
                "Object-Space Bump Normals",
                "Object-Space Positions",
                "Puzzle Matte",
                "Reflections",
                "Reflections Filter",
Esempio n. 48
0
def CreateCloth():
    #TwClothSolverIOPaperBlockout
    #----------------------------------
    #----------------------------------

    #Get Pasing Parameters:
    subx = pm.intSliderGrp(GlobalVars["SubX"], q=True, value=True)
    suby = pm.intSliderGrp(GlobalVars["SubY"], q=True, value=True)
    grav = pm.floatSliderGrp(GlobalVars["GraV"], q=True, value=True)
    wind_x = pm.floatSliderGrp(GlobalVars["Wind_X"], q=True, value=True)
    wind_y = pm.floatSliderGrp(GlobalVars["Wind_Y"], q=True, value=True)
    wind_z = pm.floatSliderGrp(GlobalVars["Wind_Z"], q=True, value=True)
    noise = pm.floatSliderGrp(GlobalVars["Noise"], q=True, value=True)

    #create inputGeo
    #----------------------------------
    #inputGeo
    inputGeoTrans = pm.polyPlane(sx=subx, sy=suby, w=10, h=10, ch=False)[0]
    inputGeoShape = inputGeoTrans.getShape()
    #transformPlane
    inputGeoTrans.translateY.set(5)
    inputGeoTrans.visibility.set(0)
    pm.select(cl=True)
    #pm.select(inputGeoTrans, r = True)
    #pm.polyTriangulate(ch = False)
    #pm.select(cl = True)

    #create outputGeo
    #----------------------------------
    #outputGeo
    outputGeoTrans = pm.polyPlane(sx=subx, sy=suby, w=10, h=10, ch=False)[0]
    outputGeoShape = outputGeoTrans.getShape()
    pm.select(cl=True)
    #set Texture
    #if pm.checkBox(GlobalVars["DefaultText"], q = True, value = True) == True:
    #	pm.sets("lambert2SG", e = True, forceElement = inputGeoTrans)

    #create cloth solver node
    #----------------------------------
    clothSolver = pm.createNode('TwClothSolverIOPaperBlockout')
    clothSolver.verbose.set(0)
    clothSolver.repetitions.set(10)
    GlobalVars["clothSolver"] = clothSolver
    pm.select(cl=True)

    #create positionConstraintLocators
    #----------------------------------
    positionConstraintLocatorIndex0Trans = pm.spaceLocator(
        n='positionConstraintLocatorIndex0')
    positionConstraintLocatorIndex0Shape = positionConstraintLocatorIndex0Trans.getShape(
    )
    positionConstraintLocatorIndex0Trans.translate.set(-5, 5, 5)
    pm.select(cl=True)

    positionConstraintLocatorIndex110Trans = pm.spaceLocator(
        n='positionConstraintLocatorIndex110')
    positionConstraintLocatorIndex110Shape = positionConstraintLocatorIndex110Trans.getShape(
    )
    positionConstraintLocatorIndex110Trans.translate.set(-5, 5, -5)
    pm.select(cl=True)

    positionConstraintLocatorIndex120Trans = pm.spaceLocator(
        n='positionConstraintLocatorIndex120')
    positionConstraintLocatorIndex120Shape = positionConstraintLocatorIndex120Trans.getShape(
    )
    positionConstraintLocatorIndex120Trans.translate.set(5, 5, -5)
    pm.select(cl=True)

    positionConstraintLocatorIndex10Trans = pm.spaceLocator(
        n='positionConstraintLocatorIndex10')
    positionConstraintLocatorIndex10Shape = positionConstraintLocatorIndex10Trans.getShape(
    )
    positionConstraintLocatorIndex10Trans.translate.set(5, 5, 5)
    pm.select(cl=True)

    positionConstraintLocatorIndex60Trans = pm.spaceLocator(
        n='positionConstraintLocatorIndex60')
    positionConstraintLocatorIndex60Shape = positionConstraintLocatorIndex60Trans.getShape(
    )
    positionConstraintLocatorIndex60Trans.translate.set(0, 5, 0)
    pm.select(cl=True)

    #connect locators and set index attrs on clothSolver
    #----------------------------------
    clothSolver.positionConstraint[0].positionConstraintVertexIndex.set(0)
    positionConstraintLocatorIndex0Shape.worldPosition >> clothSolver.positionConstraint[
        0].positionConstraintCoordinate
    pm.select(cl=True)
    clothSolver.positionConstraint[1].positionConstraintVertexIndex.set((
        (subx + 1) * (suby + 1) - 1) - subx)
    positionConstraintLocatorIndex110Shape.worldPosition >> clothSolver.positionConstraint[
        1].positionConstraintCoordinate
    pm.select(cl=True)
    clothSolver.positionConstraint[2].positionConstraintVertexIndex.set(
        (subx + 1) * (suby + 1) - 1)
    positionConstraintLocatorIndex120Shape.worldPosition >> clothSolver.positionConstraint[
        2].positionConstraintCoordinate
    pm.select(cl=True)
    clothSolver.positionConstraint[3].positionConstraintVertexIndex.set(subx)
    positionConstraintLocatorIndex10Shape.worldPosition >> clothSolver.positionConstraint[
        3].positionConstraintCoordinate
    pm.select(cl=True)
    clothSolver.positionConstraint[4].positionConstraintVertexIndex.set(
        ((subx + 1) * (suby + 1) - 1) / 2)
    positionConstraintLocatorIndex60Shape.worldPosition >> clothSolver.positionConstraint[
        4].positionConstraintCoordinate
    pm.select(cl=True)

    #set clothSolver active attr
    #----------------------------------
    clothSolver.positionConstraint[0].positionConstraintActive.set(
        pm.checkBox(GlobalVars["Locator_LeftTopCorner"], q=True, value=True))
    clothSolver.positionConstraint[1].positionConstraintActive.set(
        pm.checkBox(GlobalVars["Locator_RightTopCorner"], q=True, value=True))
    clothSolver.positionConstraint[2].positionConstraintActive.set(
        pm.checkBox(GlobalVars["Locator_RightBottomCorner"],
                    q=True,
                    value=True))
    clothSolver.positionConstraint[3].positionConstraintActive.set(
        pm.checkBox(GlobalVars["Locator_LeftBottomCorner"], q=True,
                    value=True))
    clothSolver.positionConstraint[4].positionConstraintActive.set(
        pm.checkBox(GlobalVars["Locator_Middle"], q=True, value=True))
    #connect time
    #----------------------------------
    timeNode = pm.PyNode('time1')
    pm.select(cl=True)
    timeNode.outTime >> clothSolver.currentFrame

    #connect inputGeo
    #----------------------------------
    inputGeoShape.outMesh >> clothSolver.inputGeo

    #connect inputGeo parentMatrix
    #----------------------------------
    inputGeoShape.parentMatrix >> clothSolver.transformMatrix

    #connect outputGeo
    #----------------------------------
    clothSolver.outputGeo >> outputGeoShape.inMesh

    #set clothSolver gravity
    #----------------------------------
    gravityPerSec = -1.0 * grav
    framesPerSec = 400
    clothSolver.gravity.set(0, gravityPerSec / framesPerSec, 0)

    #set clothSolver WindForce
    #----------------------------------
    clothSolver.WindForce.set(wind_x / framesPerSec, wind_y / framesPerSec,
                              wind_z / framesPerSec)

    #set clothSolber Noise
    #----------------------------------
    clothSolver.Noise.set(noise / framesPerSec)

    #set De
    #set time range
    #----------------------------------
    pm.playbackOptions(ast=1, aet=5000, max=5000, min=1)

    #rename and select clothSolver
    #----------------------------------
    clothSolverTrans = clothSolver.getParent()
    pm.rename(clothSolver, 'twClothSolverShape')
    pm.rename(clothSolverTrans, 'twClothSolver')
    pm.select(clothSolver, r=True)
Esempio n. 49
0
    def equalize_node_speed(cls):
        """Equalizes the node animation to keep the speed constant
        """
        #
        # This only works for position
        #
        # To make it also work with Rotation you need to do some nasty stuff,
        # like creating the camera transformation frame with two locators, one
        # showing the up or the local y-axis and other showing the z-axis of
        # the camera, trace them with a curve, smooth them as you did with the
        # position, then read them back create local y and z axis and set the
        # euler rotations.
        #
        # For now I don't need it. So I'll code it later on.
        #
        start_frame = int(pm.playbackOptions(q=1, min=1))
        end_frame = int(pm.playbackOptions(q=1, max=1))

        selected_node = pm.selected()[0]

        # duplicate the input graph
        node = pm.duplicate(selected_node, un=1, rr=1)[0]
        node.rename("%s_Equalized#" % selected_node.name())

        # create speed attribute
        if not node.hasAttr("speed"):
            node.addAttr("speed", at="double")
        pm.currentTime(start_frame)
        pm.setKeyframe(node.speed)

        prev_pos = node.t.get()

        pos_data = []
        rot_data = []

        for i in range(start_frame, end_frame + 1):
            pm.currentTime(i)
            current_pos = node.t.get()
            pos_data.append(current_pos)
            rot_data.append(node.r.get())
            speed = (current_pos - prev_pos).length()
            prev_pos = current_pos
            node.speed.set(speed)
            pm.setKeyframe(node.speed)

        camera_path = pm.curve(d=3, p=pos_data)
        camera_path_curve = camera_path.getShape()

        pm.rebuildCurve(camera_path_curve,
                        ch=1,
                        rpo=1,
                        rt=0,
                        end=1,
                        kr=0,
                        kcp=0,
                        kep=1,
                        kt=0,
                        s=end_frame - start_frame + 1,
                        d=3,
                        tol=0.01)

        curve_cv_positions = camera_path_curve.getCVs()

        # pop the unnecessary CVs
        curve_cv_positions.pop(1)
        curve_cv_positions.pop(-2)

        prev_pos = curve_cv_positions[0]
        for i, j in enumerate(range(start_frame, end_frame)):
            pm.currentTime(j)
            current_pos = curve_cv_positions[i]
            node.t.set(curve_cv_positions[i])
            node.speed.set((current_pos - prev_pos).length())
            pm.setKeyframe(node.speed)
            prev_pos = current_pos
Esempio n. 50
0
    def genereateAnim(self, reopen=True):
        # export_path,_ = self.getFilename()
        Scene = self.preExport()
        FBXAnim = os.path.join(Scene.dirname(), "FBXAnim")
        os.mkdir(FBXAnim) if not os.path.exists(FBXAnim) else None
        export_path = os.path.join(FBXAnim, "%s.FBX" % Scene.namebase)
        export_path = export_path.replace('\\', '/')

        # NOTE 导入所有的 reference
        ref_list = pm.listReferences()
        if len(ref_list) > 1:
            raise RuntimeError("动画文件包含多个引用文件")

        [ref.importContents(True) for ref in pm.listReferences()]

        # NOTE 如果找不到 root 骨骼则自动生成一套 root 骨骼
        root_list = pm.ls("root", dag=1, type="joint")
        mesh_list = self.getMeshList()
        if not root_list:
            # # NOTE 删除非变形器历史
            # pm.bakePartialHistory( mesh_list,prePostDeformers=True )
            jnt_list = self.getJntList(mesh_list)

            pm.select(cl=1)
            root = pm.joint(n="root")

            jnt_parent = self.getRelParent(jnt_list, root)

            anim_parent = {}
            for jnt in jnt_list:
                pm.select(cl=1)
                anim_jnt = pm.joint(n="%s_bind" % jnt)
                pm.parentConstraint(jnt, anim_jnt, mo=0)
                pm.scaleConstraint(jnt, anim_jnt, mo=0)
                parent = jnt_parent[jnt]
                anim_parent[
                    anim_jnt] = "%s_bind" % parent if parent != root else root

            jnt_transform = {}
            for anim_jnt, parent in anim_parent.items():
                anim_jnt.setParent(parent)
                # NOTE 删除骨骼缩放修正组
                transform = anim_jnt.getParent()
                if transform != parent:
                    pm.ungroup(transform)

            root_list = anim_parent.keys()

        # NOTE bake 关键帧
        start_time = pm.playbackOptions(q=1, min=1)
        end_time = pm.playbackOptions(q=1, max=1)
        pm.bakeResults(root_list, simulation=1, t=(start_time, end_time))

        pm.select(root_list)

        # NOTE 导出文件
        mel.eval('FBXExport -f "' + export_path + '" -s')
        os.startfile(os.path.dirname(export_path))

        # NOTE 重新打开当前文件
        if reopen:
            pm.openFile(pm.sceneName(), f=1)
Esempio n. 51
0
def get_end_frame():
    """Get current scene end frame.

    :rtype: float
    """
    return pm.playbackOptions(animationEndTime=True, query=True)
Esempio n. 52
0
def get_start_frame():
    """Get current scene start frame.

    :rtype: float
    """
    return pm.playbackOptions(animationStartTime=True, query=True)
Esempio n. 53
0
    def animation(self, animations, ignore=None, warn=True):
        """
        Exports all or given piper animation groups.

        Args:
            animations (list): Piper animation nodes to export.

            ignore (string): If given and piper node is a child of given ignore type, do not return the piper node.

            warn (boolean): If True, warns the user of no nodes found.

        Returns:
            (list): All export paths.
        """
        export_paths = []
        pm.refresh(suspend=True)
        self.animation_errors.clear()
        start = pm.playbackOptions(q=True, min=True)
        end = pm.playbackOptions(q=True, max=True)

        if not animations:
            animations = pipernode.get('piperAnimation', ignore=ignore)

        # check to make sure animation is healthy
        if pcfg.check_anim_health_on_export:
            namespaces = {rig.namespace() for anim in animations for rig in anim.getChildren(ad=True, type='piperRig')}
            self.animation_errors = animation.health(namespaces, resume=False)

        for anim in animations:
            anim_name = anim.name(stripNamespace=True)
            skinned_meshes = anim.getChildren(ad=True, type='piperSkinnedMesh')
            skinned_mesh = list(filter(lambda node: pcfg.skeleton_namespace in node.namespace(), skinned_meshes))

            if len(skinned_mesh) != 1:
                pm.warning('Found {} skinned meshes in {}!'.format(len(skinned_mesh), anim_name)) if warn else None
                continue

            root = skinned_mesh[0].getChildren(type='joint')
            if not root:
                pm.warning('{} has no root joints!'.format(skinned_mesh[0].name())) if warn else None
                continue

            # get joints from rig
            root = root[0]
            joints = root.getChildren(ad=True, type='joint')
            joints.append(root)

            # duplicate rig joints
            root_duplicate = pm.duplicate(root)[0]
            pm.parent(root_duplicate, w=True)
            duplicates = root_duplicate.getChildren(ad=True, type='joint')
            duplicates.append(root_duplicate)

            for joint, duplicate in zip(joints, duplicates):

                # delete unwanted attributes
                attributes = duplicate.listAttr()
                for attr in attributes:
                    attribute_name = attr.name().split('.')[-1]

                    if attribute_name.startswith(pcfg.use_attributes) or attribute_name.endswith('Space'):
                        pm.setAttr(attr, lock=False)
                        pm.deleteAttr(attr)

                # connect channels from original to duplicate
                [joint.attr(attr) >> duplicate.attr(attr) for attr in ['t', 'r', 's']]

            # get clip data
            starts = []
            ends = []
            data = anim.clipData.get()  # could be empty string, empty dictionary, or dictionary with data
            data = json.loads(data) if data else {}  # json.loads fails with empty string

            if not data:
                data = {'': {'start': start, 'end': end}}

            for clip_name, clip_data in data.items():
                starts.append(clip_data['start'])
                ends.append(clip_data['end'])

            # bake animation keys onto duplicate joints and export
            pm.select(duplicates)
            pm.bakeResults(sm=True, time=(min(starts), max(ends)))

            # export each clip
            for clip_name, clip_data in data.items():
                pm.playbackOptions(min=clip_data['start'], max=clip_data['end'])
                export_name = anim_name + '_' + clip_name if clip_name else anim_name
                export_path = self.export_method(export_name, self.animation_settings)  # export happens here
                export_paths.append(export_path)

            pm.delete(root_duplicate)

        pm.playbackOptions(min=start, max=end)
        pm.refresh(suspend=False)

        if not export_paths:
            pm.warning('No skinned meshes found under any animation nodes! Export failed. ') if warn else None

        return export_paths
Esempio n. 54
0
class PlayblastManager(object):
    __uploadToShotgun = True
    """
    Main playblast functionality
    """
    def __init__(self, app, context=None):
        """
        Construction
        """
        self._app = app
        self._context = context if context else self._app.context

    def showDialog(self):
        try:
            self._app.engine.show_dialog("Playblaster", self._app,
                                         PlayblastDialog, self._app, self)
        except:
            traceback.print_exc()

    def doPlayblast(self, playblastCamera='persp', **overridePlayblastParams):
        template_work_file = self._app.get_template("template_work_file")
        template_work_playblast = self._app.get_template(
            "template_work_playblast")
        sceneName = pm.sceneName()
        fields = template_work_file.get_fields(sceneName)
        self.shotPlayblastPath = template_work_playblast.apply_fields(fields)

        # Get value of optional config field "temp_directory". If path is
        # invalid or not absolute, use default tempdir.
        # temp_directory = os.path.normpath(self._app.get_setting("temp_directory", "default"))
        # if not os.path.isabs(temp_directory):
        #     import tempfile
        #     temp_directory = tempfile.gettempdir()

        # make sure it is exists
        # if not os.path.isdir(temp_directory):
        #     os.mkdir(temp_directory)
        # use the basename of generated names
        # self.localPlayblastPath = os.path.join(temp_directory, os.path.basename(self.shotPlayblastPath))
        # run actual playblast routine
        self.__createPlayblast(playblastCamera=playblastCamera,
                               **overridePlayblastParams)
        self._app.log_info("Playblast for %s succesful" % sceneName)

    def __createPlayblast(self,
                          playblastCamera='persp',
                          **overridePlayblastParams):
        localPlayblastPath = self.shotPlayblastPath

        # setting playback range
        originalPlaybackRange = (pm.playbackOptions(query=True, minTime=True),
                                 pm.playbackOptions(query=True, maxTime=True))
        startTime = pm.playbackOptions(query=True, animationStartTime=True)
        endTime = pm.playbackOptions(query=True, animationEndTime=True)
        pm.playbackOptions(edit=True, minTime=startTime, maxTime=endTime)

        # get playblast parameters from hook
        playblastParams = self._app.execute_hook("hook_setup_window",
                                                 action="playblast_params",
                                                 data=localPlayblastPath)
        # get window and editor parameters from hook
        createWindow = self._app.execute_hook("hook_setup_window",
                                              action='create_window',
                                              data=playblastCamera)

        # with the created window, do a playblast
        with createWindow():
            playblastParams.update(overridePlayblastParams)
            playblastSuccessful = False
            while not playblastSuccessful:
                try:
                    # set required visibleHUDs from hook
                    visibleHUDs = self._app.execute_hook("hook_setup_window",
                                                         action="hud_set")

                    resultPlayblastPath = pm.playblast(**playblastParams)
                    playblastSuccessful = True
                except RuntimeError, e:
                    result = QtGui.QMessageBox.critical(
                        None, u"Playblast Error",
                        "%s\n\n... or just close your QuickTime player, and Retry."
                        % unicode(e),
                        QtGui.QMessageBox.Retry | QtGui.QMessageBox.Abort)
                    if result == QtGui.QMessageBox.Abort:
                        self._app.log_error("Playblast aborted")
                        return
                finally:
                    # restore HUD state
                    self._app.execute_hook("hook_setup_window",
                                           action="hud_unset",
                                           data=visibleHUDs)
                    # restore playback range
                    originalMinTime, originalMaxTime = originalPlaybackRange
                    pm.playbackOptions(edit=True,
                                       minTime=originalMinTime,
                                       maxTime=originalMaxTime)
Esempio n. 55
0
    def process(self, instance):
        self.log.info("Extracting capture..")

        # get scene fps
        fps = mel.eval('currentTimeUnitToFPS()')

        # if start and end frames cannot be determined, get them
        # from Maya timeline
        start = instance.data.get("startFrameReview")
        end = instance.data.get("endFrameReview")
        if start is None:
            start = cmds.playbackOptions(query=True, animationStartTime=True)
        if end is None:
            end = cmds.playbackOptions(query=True, animationEndTime=True)
        self.log.info("start: {}, end: {}".format(start, end))
        handles = instance.data.get("handles", 0)
        if handles:
            start -= handles
            end += handles

        # get cameras
        camera = instance.data['review_camera']
        capture_preset = instance.context.data['presets']['maya']['capture']

        try:
            preset = lib.load_capture_preset(data=capture_preset)
        except:
            preset = {}
        self.log.info('using viewport preset: {}'.format(preset))

        preset['camera'] = camera
        preset['format'] = "image"
        # preset['compression'] = "qt"
        preset['quality'] = 95
        preset['compression'] = "jpg"
        preset['start_frame'] = start
        preset['end_frame'] = end
        preset['camera_options'] = {
            "displayGateMask": False,
            "displayResolution": False,
            "displayFilmGate": False,
            "displayFieldChart": False,
            "displaySafeAction": False,
            "displaySafeTitle": False,
            "displayFilmPivot": False,
            "displayFilmOrigin": False,
            "overscan": 1.0,
            "depthOfField": cmds.getAttr("{0}.depthOfField".format(camera)),
        }

        stagingdir = self.staging_dir(instance)
        filename = "{0}".format(instance.name)
        path = os.path.join(stagingdir, filename)

        self.log.info("Outputting images to %s" % path)

        preset['filename'] = path
        preset['overwrite'] = True

        pm.refresh(f=True)

        refreshFrameInt = int(pm.playbackOptions(q=True, minTime=True))
        pm.currentTime(refreshFrameInt - 1, edit=True)
        pm.currentTime(refreshFrameInt, edit=True)

        with maintained_time():
            playblast = capture_gui.lib.capture_scene(preset)

        self.log.info("file list  {}".format(playblast))

        collected_frames = os.listdir(stagingdir)
        collections, remainder = clique.assemble(collected_frames)
        input_path = os.path.join(
            stagingdir, collections[0].format('{head}{padding}{tail}'))
        self.log.info("input {}".format(input_path))

        if "representations" not in instance.data:
            instance.data["representations"] = []

        representation = {
            'name': 'mov',
            'ext': 'mov',
            'files': collected_frames,
            "stagingDir": stagingdir,
            "frameStart": start,
            "frameEnd": end,
            'fps': fps,
            'preview': True,
            'tags': ['review', 'delete']
        }
        instance.data["representations"].append(representation)
    def setAnimationRange(self):

        self.leAnimationStart.setText(
            str(pm.playbackOptions(minTime=True, q=True)))
        self.leAnimationEnd.setText(
            str(pm.playbackOptions(maxTime=True, q=True)))
Esempio n. 57
0
def _build_general_settings_tab(parent_layout):
    # Create column Layout for General settings
    general_settings_tab_layout = pm.columnLayout('generalSettings',
                                                  adj=True,
                                                  width=100)
    pm.separator(height=3, style='none')

    pm.rowLayout(numberOfColumns=3,
                 columnWidth3=(55, 250, 30),
                 adjustableColumn=2,
                 columnAlign=[(1, 'left'), (2, 'left')],
                 columnAttach=[(1, 'both', -1), (2, 'both', 0),
                               (3, 'both', 0)])
    pm.text(label="Directory:")
    pm.textField('t_programDirectoryText', text='', ed=False, font=FONT)

    pm.symbolButton('b_directoryImage',
                    image="setDirectory_icon.png",
                    width=32,
                    height=20,
                    command=mimic_utils.set_program_dir)
    pm.setParent('..')

    pm.rowLayout(numberOfColumns=2,
                 adjustableColumn=2,
                 columnAttach=(1, 'left', -1),
                 columnWidth=[(1, 90), (2, 100)],
                 height=20)
    pm.text(label='Output name:')
    pm.textField('t_outputFileName',
                 text=postproc_config.DEFAULT_OUTPUT_NAME,
                 font=FONT)

    pm.setParent('..')

    pm.rowLayout(numberOfColumns=2,
                 adjustableColumn=2,
                 columnAttach=(1, 'left', -1),
                 columnWidth=[(1, 90), (2, 100)],
                 height=20)
    pm.text(label='Template name:')
    pm.textField('t_templateFileName',
                 text=postproc_config.DEFAULT_TEMPLATE_NAME,
                 font=FONT)

    pm.setParent('..')

    # Sample rate radio buttons
    pm.separator(height=3, style='none')
    selected_units = postproc_config.DEFAULT_SAMPLE_RATE_UNITS
    selected_value = postproc_config.DEFAULT_SAMPLE_RATE_VALUE
    radio_indent = 3
    pm.radioCollection('sample_rate_radio_collection')
    pm.rowLayout(numberOfColumns=3,
                 adjustableColumn=3,
                 columnAttach=(1, 'left', radio_indent),
                 columnWidth=[(1, 90), (2, 45)],
                 height=20)
    pm.radioButton('rb_timeInterval', label='Sample rate:', select=True)
    pm.textField('t_timeBetweenSamples', text=selected_value, font=FONT)
    pm.radioButtonGrp(
        'time_unit_radio_group',
        labelArray2=['s', 'f'],
        annotation='Sample rate units: seconds or frames',
        numberOfRadioButtons=2,
        columnWidth2=[32, 30],
        select=1 if selected_units == 'seconds' else 2)  # 1-based integer
    pm.setParent('..')

    pm.rowLayout(numberOfColumns=1,
                 adjustableColumn=1,
                 columnAttach=(1, 'left', radio_indent),
                 height=20)
    pm.radioButton('rb_keyframesOnly',
                   label='Sample keyframes only',
                   enable=True)
    pm.setParent('..')

    pm.rowLayout(numberOfColumns=3,
                 adjustableColumn=3,
                 columnAttach=(1, 'left', -1),
                 columnWidth=[(1, 132), (2, 40), (3, 30)],
                 height=20)
    pm.text(label='Animation frame range:')

    pm.intField("i_programStartFrame",
                value=pm.playbackOptions(animationStartTime=True, query=True),
                minValue=-10,
                maxValue=100000,
                step=1)

    pm.intField("i_programEndFrame",
                value=pm.playbackOptions(animationEndTime=True, query=True),
                minValue=-10,
                maxValue=100000,
                step=1)
    pm.setParent('..')

    pm.separator(height=5, style='none')

    # Post processor option menu list
    pm.optionMenu('postProcessorList',
                  label='Processor:',
                  height=18,
                  changeCommand=postproc_options.overwrite_options)

    # Get supported post-processors and fill option menu list
    supported_post_processors = postproc_setup.get_processor_names()
    for post in supported_post_processors:
        pm.menuItem(label=post)
    pm.separator(height=3, style='none')

    pm.setParent(parent_layout)
    return general_settings_tab_layout
Esempio n. 58
0
def generateFollowPlane(*args):
    startTime = pm.playbackOptions(q=1, min=1)
    endTime = pm.playbackOptions(q=1, max=1)

    sel_list = pm.ls(sl=1, ni=1, type="transform")
    if not sel_list:
        pm.confirmDialog(message='请选择物体', button=['确定'])
        return

    for sel in sel_list:
        # snapshot = pm.snapshot(sel,st=startTime,et=endTime)[1]
        snapshot = pm.createNode("snapshot")
        sel.selectHandle.connect(snapshot.localPosition)
        sel.worldMatrix[0].connect(snapshot.inputMatrix)
        snapshot.startTime.set(startTime)
        snapshot.endTime.set(endTime)
        snapshot.increment.set(1)
        anim_curve = pm.curve(n=sel + "_follow_curve",
                              d=3,
                              p=snapshot.pts.get())
        pm.delete(snapshot)

        curve_length = pm.arclen(anim_curve, ch=0)
        plane, plane_node = pm.polyPlane(n=sel + "_follow_plane",
                                         sx=20,
                                         sy=3,
                                         w=curve_length,
                                         h=20)

        # NOTE 创建运动路径跟随
        motion_path = pm.pathAnimation(
            plane,
            anim_curve,
            fractionMode=1,
            follow=1,
            followAxis="x",
            upAxis="y",
            worldUpType="vector",
            worldUpVector=(0, 1, 0),
            inverseUp=0,
            inverseFront=0,
            bank=0,
            startTimeU=startTime,
            endTimeU=endTime,
        )
        flow_node, ffd_node, lattice_node, ffd_base = pm.flow(plane,
                                                              dv=(100, 2, 2))

        # NOTE 设置外部影响
        ffd_node.outsideLattice.set(1)
        ffd_node.local.set(1)
        plane_node.width.set(50)

        lattice_node.v.set(0)
        ffd_base.v.set(0)

        # NOTE 设置运动路径
        motion_path.fractionMode.set(1)
        animCurve = motion_path.listConnections(type="animCurve")[0]
        # NOTE 关键帧设置为线性
        animCurve.setTangentTypes(range(animCurve.numKeys()),
                                  inTangentType="linear",
                                  outTangentType="linear")

        # NOTE 打组
        pm.group(lattice_node,
                 ffd_base,
                 plane,
                 anim_curve,
                 n=sel + "_follow_grp")
        pm.select(plane)
Esempio n. 59
0
def save(filename,
         objs=None,
         forceOverwrite=False,
         forceKeys=False,
         start=None,
         end=None):
    '''
    Given a list of objects, save all the anim curves for t/r/s/v and user defined
    to the given filename.
    
    :param bool forceOverwrite: Allow prompting if the dest file already exists
    :param bool forceKeys: Put keys on the objects
    
    ..  todo::
        * Check if an attribute ISN'T keyed in the source and mark the static
            value somehow.  Specifically, if parent/world stuff isn't present,
            copying animations goes poorly.
        * At some point animation layers need to be addressed properly.
    
    '''
    global TAGGING_ATTR
    # USING CMDS VERSION FOR SPEED
    #listAttr = cmds.listAttr
    #listConnections = cmds.listConnections
    #addAttr = cmds.addAttr
    #setAttr = cmds.setAttr
    #duplicate = cmds.duplicate
    # ---
    sel = selected()
    objs = objs if objs else selected()

    info = createNode('network')
    info.addAttr('start', at='long')
    info.addAttr('end', at='long')
    info.addAttr('staticValues', dt='string')

    if start is None:
        start = playbackOptions(q=True, min=True)
    if end is None:
        end = playbackOptions(q=True, max=True)

    if start >= end:
        end = start + 1

    info.start.set(start)
    info.end.set(end)

    defaultAttrs = [t + a for t in 'trs' for a in 'xyz'] + ['visibility']

    dups = []
    staticValues = {}

    for obj in objs:
        zooHack = ['ikBlend'] if obj.hasAttr('ikBlend') else [
        ]  # Since use uses builtin ik trans, this doesn't get picked up.

        if obj.hasAttr('tx'):
            attrs = chain(listAttr(obj.name(), ud=True, k=True), defaultAttrs,
                          zooHack)
        else:
            attrs = chain(listAttr(obj.name(), ud=True, k=True), zooHack)

        for attr in attrs:
            _processAttr(obj.name() + '.' + attr, dups, forceKeys,
                         staticValues, start, end)

    if not dups:
        warning("Nothing was animated")
        return

    info.staticValues.set(core.text.asciiCompress(json.dumps(staticValues)))

    select(dups, info)
    exportSelected(filename, force=forceOverwrite)
    select(sel)
    delete(dups)
Esempio n. 60
0
    def exportSelected(self, scene, shot, filename, dumbify, history):
        # geo list is the one that will be exported
        geoList = []
        # dumbify set contains all geo under current selection
        dumbifySet = set()
        lightSet = set()

        selection = pm.selected()

        # add file node from displacements to selection. otherwise it will be ignored in export
        for obj in selection:
            if obj.type() =='VRayDisplacement' and obj.displacement.connections():
                selection.append(obj.displacement.connections()[0])

        if dumbify:
            # dumbify
            # this duplicates all geometry and links them with a blendshape.
            # the duplicates are moved to a seperate group and then cached.
            # this has the effect of removing any logic and just leaving geometry
            for sel in selection:
                for mesh in sel.getChildren(ad=True, type='mesh'):
                    if not mesh.intermediateObject.get() and self.visibleInHierarchy(mesh):
                        dumbifySet.add(mesh.getParent())
                for light in sel.getChildren(ad=True, type=['VRayLightSphereShape', 'VRayLightDomeShape', 'VRayLightRectShape','VRayLightIESShape', 'VRayLightMesh']):
                    lightSet.add(light.getParent())

            exportGrp = pm.group(em=True, name=filename+'_grp')
            geoGrp = pm.group(em=True, name='geoGrp')
            geoGrp.setParent(exportGrp)

            for obj in dumbifySet:
                dupli = pm.duplicate(obj)[0]
                for child in dupli.getChildren():
                    if not child.type() == 'mesh':
                        pm.delete(child)
                    elif child.hasAttr('intermediateObject') and child.intermediateObject.get():
                        pm.delete(child)
                dupli.setParent(geoGrp)
                # renaming the duplicate so it get's the namespace back
                dupli.rename(obj.nodeName())
                try:
                    pm.blendShape(self.getNonIntermediateShape(obj), self.getNonIntermediateShape(dupli), origin='world', n=dupli.nodeName()+'_bs', w=[0,1])
                except Exception as e:
                    print '%s throws %s'%(obj,e)
                # keep object sets for easy vray clipping
                inheritedSets = self.getInheritedSetMembership(obj)
                for s in inheritedSets:
                    if not pm.objExists(s.nodeName(stripNamespace=True)+'Export'):
                        newSet = pm.sets(em=True, n = s.nodeName(stripNamespace=True)+'Export')
                        geoList.append(newSet)
                    pm.sets(pm.PyNode(s.nodeName(stripNamespace=True)+'Export'), forceElement=dupli)

            if lightSet:
                lightGrp = pm.group(em=True, name='lightGrp')        
                lightGrp.setParent(exportGrp)
                for light in lightSet:
                    dupli = pm.duplicate(light)[0]                
                    dupli.setParent(lightGrp)
                    dupli.rename(light.nodeName())
                
            geoList.append(exportGrp)
        else:
            geoList = selection


        # export geo
        pm.select(geoList, r=True, ne=True)
        geoPath = pm.exportSelected(os.path.join(self.cachePath, scene, shot, filename+'.ma'), 
                typ='mayaAscii', 
                constructionHistory = history, 
                channels = False, 
                constraints = False, 
                expressions = False, 
                force =True, 
                shader = True,
                preserveReferences=False
                )
        self.removeStudentLic(geoPath)
        self.removeNamespaces(geoPath)


        # export abc
        abcOptions = []
        for sel in geoList:
            if 'dagNode' in sel.type(inherited=True):
                abcOptions.append('-root %s'%sel.fullPath())

        frameRange = [pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True)]
        abcOptions.append('-frameRange %s %s'%(frameRange[0], frameRange[1]))

        abcPath = os.path.join(self.cachePath, scene, shot, filename+'.abc')
        abcOptions.append('-file "' + abcPath.replace('\\', '/') + '"')
        abcOptions.append('-uvWrite')
        abcOptions.append('-wholeFrameGeo')
        abcOptions.append('-worldSpace')
        abcOptions.append('-writeVisibility')
        abcOptions.append('-writeCreases')
        abcOptions.append('-writeUVSets')
        abcOptions.append('-dataFormat ogawa')

        pm.AbcExport(verbose = True, jobArg = ' '.join(abcOptions))

        # cleanup
        if dumbify:
            for obj in geoList:
                pm.delete(obj)