예제 #1
2
def bakeInfinity(sparseKeys=True, smart=True, sim=False):
    crvs = cmds.keyframe(q=True, name=True, sl=True)
    if crvs:
        start = cmds.playbackOptions(q=True, minTime=True)
        end = cmds.playbackOptions(q=True, maxTime=True)
        objs = cmds.listConnections(crvs, d=True, s=False, plugs=True)
        cmds.refresh(suspend=1)
        print sim, '________'
        cmds.bakeResults(objs, t=(start, end), simulation=sim, pok=True, smart=smart, sac=sparseKeys, sampleBy=1)
        cmds.refresh(suspend=0)
        message(str(len(objs)) + ' curves baked --' + str(objs), maya=1)
    else:
        message('no curves are selected', maya=1)
예제 #2
1
def bd_bakeControllers(args):
    cmds.select('*_Anim')
    animCtrls = cmds.ls(sl=True, type='transform')
    minTime = cmds.playbackOptions(q=True,minTime=True)
    maxTime = cmds.playbackOptions(q=True,maxTime=True)
    cmds.bakeResults(animCtrls,simulation=True, t=(minTime,maxTime) )

    cmds.select('*_Anim')
    animCtrls = cmds.ls(sl=True, type='transform')
    cmds.select(clear=True)
    for anim in animCtrls:
        constr = cmds.listRelatives(anim, children=True,type = 'constraint')
        if constr:
            cmds.delete(constr)
예제 #3
0
def bake(constraint,
         start=None,
         end=None,
         sampleBy=1,
         simulation=True):
    """
    Bake specified constraint
    @param constraint: Constraint to bake animation for.
    @type constraint: str
    @param start: Start frame of bake animation range
    @type start: float or None
    @param end: End frame of bake animation range
    @type end: float or None
    @param sampleBy: Sample every Nth frame
    @type sampleBy: int
    @param simulation: Simulation option for bakeResults
    @type simulation: bool
    """
    # ==========
    # - Checks -
    # ==========

    # Check Constraint
    if not glTools.utils.constraint.isConstraint(constraint):
        raise Exception('Object "' + constraint + '" is not a valid constraint node!')

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

    # ====================================
    # - Get Slave Transform and Channels -
    # ====================================

    # Get Slave Transform
    slave = glTools.utils.constraint.slave(constraint)

    # Get Slave Channels
    attrList = cmds.listConnections(constraint, s=False, d=True, p=True) or []
    slaveAttrs = [i.split('.')[-1] for i in attrList if i.startswith(slave + '.')] or []
    if not slaveAttrs: raise Exception('No slave channels to bake!')

    # ===================
    # - Bake Constraint -
    # ===================

    cmds.refresh(suspend=True)
    cmds.bakeResults(slave,
                   at=slaveAttrs,
                   time=(start, end),
                   disableImplicitControl=True,
                   simulation=simulation,
                   sampleBy=sampleBy)
    cmds.refresh(suspend=False)

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

    return [slave + '.' + i for i in slaveAttrs]
예제 #4
0
	def createFreeCameras(self):
		debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'self.cameras: %s' % self.cameras, verbose = False)
		
		for camera in self.cameras:
			debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'Processing camera: %s' % camera, verbose = False)
			cmds.select(camera, r= True)
		  
			newCamera = cmds.duplicate( rr=True )
			newCamera = newCamera[0]
			
			debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCamera: %s' % newCamera, verbose = False)
			for attr in ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']:
				cmds.setAttr(newCamera + "." + attr, lock=False)
			
			hisObject = cmds.listHistory(newCamera)
			for attr in ['hfa', 'vfa', 'fl', 'lsr', 'fs', 'fd', 'sa', 'coi']:
				cmds.setAttr(hisObject[0] + "." + attr, lock=False)	
			
			parentNode = cmds.listRelatives(camera, p= True)
			if parentNode != None:
				cmds.parent( newCamera, world= True)
      
			pointConst = cmds.pointConstraint( camera, newCamera )
			orientConst = cmds.orientConstraint( camera, newCamera )
      
			cmds.bakeResults( newCamera+'*', t=(self.startFrame, self.endFrame), simulation=True, sparseAnimCurveBake=False, shape=False)
			debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCamera %s baked successfully...' % newCamera, verbose = False)
			
			cmds.delete(pointConst, orientConst, cn=True )
			
			newCameraName = cmds.rename(newCamera, '%s_Cpy' % camera)
			debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'newCameraName: %s' % newCameraName, verbose = False)

			self.newCameras.extend([newCameraName])
			debug(app = None, method = 'FromMaya2Nuke.createFreeCameras', message = 'self.newCameras: %s' % self.newCameras, verbose = False)
예제 #5
0
파일: bake.py 프로젝트: jonntd/mayadev-1
 def exportBake( self, ctls, timeRange ):
     
     cmds.undoInfo( swf=0 )
     time = ( timeRange[0], timeRange[1] )
     sampleValue = timeRange[2]
     
     cmds.bakeResults( ctls, simulation=True, t=time, sampleBy=sampleValue, disableImplicitControl=True, preserveOutsideKeys=False, 
               sparseAnimCurveBake=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, minimizeRotation=False, 
               controlPoints=False, shape=False )
     
     timeControl = cmds.createNode( 'timeControl', n='timeControl' )
     
     dgtrAnimCurves = cmds.ls( 'DGTR_*', type='animCurve' )
 
     for anim in dgtrAnimCurves:
         cmds.connectAttr( timeControl+'.outTime', anim+'.input' )
         
     for ctl in ctls:
         animNodeRx = cmds.listConnections( ctl+'.rx', s=1, d=0, type='animCurve' )[0]
         animNodeRy = cmds.listConnections( ctl+'.ry', s=1, d=0, type='animCurve' )[0]
         animNodeRz = cmds.listConnections( ctl+'.rz', s=1, d=0, type='animCurve' )[0]
         
         animNodeIrx = cmds.listConnections( ctl+'.irx', s=1, d=0, type='animCurve' )[0]
         animNodeIry = cmds.listConnections( ctl+'.iry', s=1, d=0, type='animCurve' )[0]
         animNodeIrz = cmds.listConnections( ctl+'.irz', s=1, d=0, type='animCurve' )[0]
         
         self.eulerFilter( [animNodeRx, animNodeRy, animNodeRz] )
         self.eulerFilter( [animNodeIrx, animNodeIry, animNodeIrz] )
     cmds.undoInfo( swf=1 )
예제 #6
0
def reCenterPivot(obj):
    locName = obj + "_loc"
    
    cmds.spaceLocator(n=locName )
    cmds.parent( locName, obj )
    
    cmds.setAttr(locName + ".translateX",0)
    cmds.setAttr(locName + ".translateY",0)
    cmds.setAttr(locName + ".translateZ",0)
    cmds.setAttr(locName + ".rotateX",0)
    cmds.setAttr(locName + ".rotateY",0)
    cmds.setAttr(locName + ".rotateZ",0)
    
    cmds.Unparent(locName)
    pConst = cmds.parentConstraint(obj,locName,mo=True,w=1)
    
    cmds.bakeResults(locName,sm=True, t=(0,44),at=["tx","ty","tz","rx","ry","rz"])
    cmds.delete(pConst)
    newObj = cmds.duplicate(obj,n=obj+"_new")

    cmds.xform(newObj[0],cp=True)
    nConst = cmds.parentConstraint(locName,newObj, mo=True,w=1)
    
    cmds.bakeResults(newObj,sm=True, t=(0,44),at=["tx","ty","tz","rx","ry","rz"])
    
    cmds.delete(nConst)
    cmds.delete(locName)
예제 #7
0
def bakeDynamicCmd(*args):
    '''
    Bake the dynamic simulation as key frames on the joints rotations for the specified frame range
    '''
    # display warning message
    result = cmds.confirmDialog(messageAlign="left", title="Bake Simulation", message="Baking simulation will replace the dynamics\nfor keyframe animation. Action is undoable. Do you wish to continue?", button=["Yes", "No"])
     
    if result == "Yes":
        # get selected object
        selected = cmds.ls(sl=True)
         
        if selected:
            # manage the dynamic node
            dNode = lpDynamicChain(node=selected[0])
            startJoint = dNode.startJoint[0]
            endJoint = dNode.endJoint[0]
             
            # get frame range
            startFrame = cmds.intFieldGrp("frameRangeIFG", q=True, v1=True)
            endFrame = cmds.intFieldGrp("frameRangeIFG", q=True, v2=True)
             
            if cmds.checkBoxGrp("useTimeSliderCBG", q=True, v1=True):
                startFrame = cmds.playbackOptions(q=True, minTime=True)
                endFrame = cmds.playbackOptions(q=True, maxTime=True)
             
            # get the joints
            joints = [startJoint]
            joints.extend( findAllJointsFromTo(startJoint, endJoint) )
             
        # bake the simulation for the frame range - this action is undoable
        cmds.bakeResults(joints, t=(startFrame, endFrame), dic=False, preserveOutsideKeys=True, simulation=True)
예제 #8
0
def export(path_to_save, script_name, namespace):
	util.debug("Importing all references, flattening scene.")
	scene.importReferences("all")
	
	shots = scene.getShots()
	scene_start, scene_end = scene.length()

	#util.debug("Selecting all joint hierarchies.")
	#cmds.select(all=1, hi=1)
	#cmds.select(cmds.ls(sl=1, typ='joint'), r=1)

	util.debug("Baking all animations.")
	scene_start, scene_end = scene.length()
	cmds.select("%s:root" % namespace, hi=1)
	cmds.select(cmds.ls(sl=1, typ='joint'), r=1)
	cmds.bakeResults(sm=1, t=(scene_start,scene_end), sb=1, sac=0, pok=0,at= ["tx","ty","tz","rx","ry","rz"])


	ns.deleteOthers(namespace)
	ns.remove()
	
	util.debug("Setting tangent to stepped for keys that occur on cuts: %s" % shots)
	cut_frames = []
	for shot in shots:
		cut_frames.append(shot['end'])
	scene.makeCutTangentsStep(cut_frames)

	psa_name = "%(script_name)s_%(namespace)s" % {
		'script_name': script_name,
		'namespace': namespace
	}
	util.debug("Creating .PSA file: %s" % psa_name)
	
	#for shot in shots:
	#	## Unreal xyz
	#	util.debug("{",shot,"[",\
	#	-cmds.getAttr("%s:root.translateZ" % namespace,t=shot['start']),\
	#	cmds.getAttr("%s:root.translateX" % namespace,t=shot['start']),\
	#	-cmds.getAttr("%s:root.translateY" % namespace,t=shot['start']),\
	#	"][",\
	#	-cmds.getAttr("%s:root.rotateZ" % namespace,t=shot['start']),\
	#	cmds.getAttr("%s:root.rotateX" % namespace,t=shot['start']),\
	#	-cmds.getAttr("%s:root.rotateY" % namespace,t=shot['start']),\
	#	"]}")

	for shot in shots:
		cmds.playbackOptions(min = shot['start'], max = shot['end'])
		sequence_name = "%(psa_name)s_%(#)02d" % {
			'psa_name'	:	psa_name, 
			'#'					:	shots.index(shot)
		}
		util.debug("Adding Sequence %s" % sequence_name)
		if shots.index(shot) == len(shots)-1 :
			if 'command AXExecute executed. ' == cmds.axexecute(path = path_to_save, animfile = psa_name, sequence = sequence_name, rate = scene.GAME_RATE, saveanim = 1):
				return True
			else:
				return False
		else:
			cmds.axexecute(path = path_to_save, animfile = psa_name, sequence = sequence_name, rate = scene.GAME_RATE)
예제 #9
0
def bakeSkinJoints():
	startTime = cmds.playbackOptions(q=True, min = True)
	endTime = cmds.playbackOptions(q=True, max = True)
	listJoints = cmds.attributeQuery( 'list', node='listSkinJoints', listEnum=True )
	bakeJoints = listJoints[0].rsplit(':')
	del bakeJoints[0:1]
	print bakeJoints 
	cmds.bakeResults( bakeJoints , t=(startTime ,endTime), simulation=True )
예제 #10
0
def _bakeObj(obj):
    '''Bake animazione.'''

    constrName = _getParentConstraint(obj)
    constrExists = cmds.ls(constrName)

    # se il constraint non esiste o non contiene keyframe esci
    if not constrExists or cmds.keyframe(constrName, q=True, kc=True) == 0:
        sys.stdout.write('Nothing to bake\n')
        return

    # primo frame
    currentFrame = cmds.currentTime(q=True)
    firstFrame = cmds.playbackOptions(q=True, ast=True)
    cmds.currentTime(firstFrame)

    # salva come lastFrame l'ultimo frame d'animazione del constraint o dell'oggetto
    keyTimes = cmds.keyframe(obj, q=True, tc=True)
    if not keyTimes:
        keyTimes = cmds.keyframe(constrName, q=True, tc=True)
    else:
        keyTimes.extend(cmds.keyframe(constrName, q=True, tc=True))
    lastFrame = max(keyTimes)

    # se all'ultimo frame rimane attached oppure il corpo e' rigido allora usa animation end time
    if max(cmds.keyframe(constrName, q=True, ev=True, t=(lastFrame, lastFrame))) > 0.0 or _getRigidBody(obj):
        lastFrame = max(lastFrame, cmds.playbackOptions(q=True, aet=True))

    # crea il locator
    locatorName = obj + _locSfx
    _setRootNamespace()
    loc = cmds.spaceLocator(n=locatorName)[0]
    cmds.hide(loc)

    # trova il parent del gruppo PH
    parent = cmds.listRelatives(_getParentHandle(obj), p=True)
    if parent:
        cmds.parent([loc, parent[0]])

    # copia l'ordine degli assi
    cmds.setAttr(loc + '.rotateOrder', cmds.getAttr(obj + '.rotateOrder'))

    # copia matrice e pivot
    cmds.xform(loc, m=cmds.xform(obj, q=True, m=True, ws=True), ws=True)
    cmds.xform(loc, piv=cmds.xform(obj, q=True, rp=True, ws=True), ws=True)

    # costringi il locator
    constraint = cmds.parentConstraint(obj, loc, mo=True)[0]

    # fai il bake
    cmds.bakeResults(loc, at=['t', 'r'], sm=True, t=(firstFrame, lastFrame), dic=True, pok=True)

    # cancella il constraint
    cmds.delete(constraint)

    # ripristina il frame precedente
    cmds.currentTime(currentFrame)
예제 #11
0
def mBakeRigkey(rigCtrlList, playbackRange):
	"""
	"""
	cmds.bakeResults(rigCtrlList, at= ['.t', '.r', '.s'], t= playbackRange,
					sm= 1, s= 0)
	for ctrl in rigCtrlList:
		findPC = cmds.listRelatives(ctrl, c= 1, typ= 'parentConstraint')
		for pc in _xList(findPC):
			cmds.delete(pc)
예제 #12
0
def legIkToFk(rigNS,side,start=None,end=None,sampleBy=1):
	'''
	Bake IK leg animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param side: Leg side ("lf" or "rt")
	@type side: str
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
	# Get Start/End
	if start == None: start = mc.playbackOptions(q=True,min=True)
	if end == None: end = mc.playbackOptions(q=True,max=True)
	
	# Set Leg to IK mode
	mc.setAttr(rigNS+':config.'+side+'LegIkFkBlend',0) # IK
	
	# Build IK/FK Joint List
	ikJntList = [rigNS+':'+side+'_leg_ik'+i+'_jnt' for i in ['A','B']]
	ikJntList += [rigNS+':'+side+'_foot_ik'+i+'_jnt' for i in ['A','B']]
	fkJntList = [rigNS+':'+side+'_leg_fk'+i+'_jnt' for i in ['A','B']]
	fkJntList += [rigNS+':'+side+'_foot_fk'+i+'_jnt' for i in ['A','B']]
	
	# Duplicate FK Joints and Constrain to IK
	fkDupList = []
	fkOriList = []
	for i in range(len(ikJntList)):
		fkDupList.append(mc.duplicate(fkJntList[i],po=True)[0])
		fkOriList.append(mc.orientConstraint(ikJntList[i],fkDupList[-1])[0])
	
	# Transfer Baked Anim to FK Joints
	mc.refresh(suspend=True)
	for i in range(len(fkDupList)):
		mc.bakeResults(	fkDupList[i],
						t=(start,end),
						at=['rx','ry','rz'],
						simulation=True,
						preserveOutsideKeys=True,
						sampleBy=sampleBy	)
		mc.copyKey(fkDupList[i],at=['rx','ry','rz'],t=(start,end))
		mc.pasteKey(fkJntList[i],at=['rx','ry','rz'],t=(start,end),option='replace')
	mc.refresh(suspend=False)
	
	# Delete Duplicate Joints and Constraints
	if fkOriList:
		try: mc.delete(fkOriList)
		except Exception, e: print('Error deleting nodes '+str(fkOriList)+'! Exception Msg: '+str(e))
	if fkDupList:
		try: mc.delete(fkDupList)
		except Exception, e: print('Error deleting nodes '+str(fkDupList)+'! Exception Msg: '+str(e))
	
	# Set to FK mode
	mc.setAttr(rigNS+':config.'+side+'LegIkFkBlend',1) # FK
예제 #13
0
def drop_simulation():
    start = time.time()
    cmds.playbackOptions(min = STARTFRAME, max = ENDFRAME)
    cmds.currentTime(STARTFRAME)
    cmds.select(clear = True)
    cmds.select("shirt")
    cmds.bakeResults(simulation = True, controlPoints = True, shape = True, time = (STARTFRAME, ENDFRAME))
    cmds.currentTime(ENDFRAME)
    end = time.time()
    return end-start
예제 #14
0
def bakeMoc( mocLoc ):
    
    import sgBFunction_dag
    
    targetLocs = sgBFunction_dag.getChildrenJointExists( mocLoc )
    targetLocs.append( mocLoc )
    
    cmds.select( targetLocs )
    minFrame = cmds.playbackOptions( q=1, min=1 )
    maxFrame = cmds.playbackOptions( q=1, max=1 )
    cmds.bakeResults( sm=True, t=(minFrame, maxFrame), sb=1, dic=True, pok=True, sac=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, cp=False, s=True)
예제 #15
0
def bakeCharacterChannels(charSet, start=None, end=None, attrList=[]):
    """
    Bake character set channels.
    Used to bake trax animation directly to channels
    @param charSet: Character set to bake channels for.
    @type charSet: str
    @param start: Start frame of bake results range. If empty, use timeline start frame.
    @type start: int or None
    @param end: End frame of bake results range. If empty, use timeline end frame.
    @type end: int or None
    @param attrList: Override the list of character character set attributes to bake. If empty, use attribute list from character set.
    @type attrList: str
    """
    # ==========
    # - Checks -
    # ==========

    if not isCharSet(charSet):
        raise Exception('Object "' + charSet + '" is not a valid character set!')

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

    # =========================
    # - Character Set Details -
    # =========================

    # Get Character Set Channels
    charChannels = cmds.sets(charSet, q=True)

    # Get Character Set Objects
    charObjList = cmds.ls(charChannels, o=True)

    # Get Character Set Channel Names
    if not attrList:
        attrList = []
        for ch in charChannels:
            attr = cmds.attributeName(ch, s=True)
            if not attrList.count(attr):
                attrList.append(attr)

    # ================
    # - Bake Results -
    # ================

    cmds.bakeResults(charObjList, t=(1, 600), at=attrList, simulation=True)

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

    return charObjList
예제 #16
0
파일: LightSkeleton.py 프로젝트: akkey/maya
def motion_bake():
    # モーションをベイク Root_M以下
    endTime = cmds.playbackOptions(q=True, max=True)
    cmds.select("Root_M", hi=True)
    cmds.select("Knee_R_Locator", hi=True, add=True)
    cmds.select("Knee_L_Locator", hi=True, add=True)
    cmds.select("foot_R_controller", hi=True, add=True)
    cmds.select("foot_L_controller", hi=True, add=True)
    cmds.bakeResults(simulation=True, t=(1, endTime), sb=1, at=["rx", "ry", "rz"])

    cmds.parent("Root_M", world=True)

    if cmds.objExists("main_controller"):
        cmds.select("main_controller", hi=True)
        cmds.delete()

    if cmds.objExists("Knee_R_Locator"):
        cmds.select("Knee_R_Locator", hi=True)
        cmds.delete()

    if cmds.objExists("Knee_L_Locator"):
        cmds.select("Knee_L_Locator", hi=True)
        cmds.delete()

    if cmds.objExists("foot_R_controller"):
        cmds.select("foot_R_controller", hi=True)
        cmds.delete()

    if cmds.objExists("foot_L_controller"):
        cmds.select("foot_L_controller", hi=True)
        cmds.delete()

    # 全選択
    cmds.select(ado=True)
    cmds.select(hi=True)
    deleteObj = cmds.ls(sl=True)

    count = 0
    matchTxtDeleteCont = re.compile("(_)(.*?)(controller)(.*)")
    matchTxtDeleteEffec = re.compile("(_)(.*?)(effector)(.*)")

    for n in deleteObj:
        matchTrueDeleteCont = matchTxtDeleteCont.search(deleteObj[count])
        matchTrueDeleteEffec = matchTxtDeleteEffec.search(deleteObj[count])

        if matchTrueDeleteCont != None:
            print deleteObj[count]
            # cmds.delete(deleteObj[count])

        if matchTrueDeleteEffec != None:
            cmds.delete(deleteObj[count])

        count += 1
예제 #17
0
    def bake(self, controls, frame_range):
        """
        Responsible for baking out the dynamic animation to the original rig.
        @params:
            controls: Controls that you're baking the animation onto.
            frame_range: Targeted frame range (int(start), int(end)).
        """
        start = frame_range[0]
        end = frame_range[1]

        # bake
        cmds.bakeResults(controls, sm=True, t=(start, end), at=TR_ATTRS)
예제 #18
0
def create() :

    sel = m.ls(sl=True)
    rbn = mel.eval('peelSolve2RigidBody()')
 
    # find the common parent   
    ret = set()
    for n in sel :
        p = m.listRelatives(n, p=True)
        if p is None : continue
        ret.add(p[0])

    if len(ret) == 1 :
        parent = list(ret)[0]
    else :
        parent = None

    cons = []
    locs = []

    # for each marker
    for i in range (len(sel)) :

        input = m.listConnections( rbn + ".input[%d]" % i )[0] 
        local = m.listConnections( rbn + ".local[%d]" % i )[0] 

        # create locators and constrain to local rigidbody markers
        loc = m.spaceLocator( name=sel[i] + '_temp' )[0]
        if parent :
            loc = m.parent( loc, parent ) [0]
        cons.append(  m.pointConstraint( local, loc )[0] )
        locs.append( loc )

        # link active to weight
        src = input + ".active"
        dst = local + ".weight"
        if m.objExists(src) :
            m.connectAttr( src, dst )

    # bake
    try :
        m.refresh(suspend=True)
        start = m.playbackOptions(q=True, min=True)
        end = m.playbackOptions(q=True, max=True)
        m.bakeResults(locs, sm=True, t=(start,end), sb=1, dic=True, pok=True, sac=False, at=('tx', 'ty', 'tz') )

    finally :
        m.refresh(suspend=False)

    m.delete( cons )
예제 #19
0
 def ctrlBake(self):
     selTSL = cmds.textScrollList( Win.TSL, q=1, si=1)
     selTSLsize = len(selTSL)
     selA = cmds.ls(sl=1)
     
     import maya.cmds as cmds
     endF = cmds.playbackOptions( q=1, max=1 )
     staF = cmds.playbackOptions( q=1, min=1 )
     samby = 1
     simyl = 0
     for y in  range(0, selTSLsize):
         print 'aa'
         cmds.bakeResults( '%s_animkey_Con_xform'%selTSL[y], t=(staF,endF), sb='%s'%samby, simulation=simyl)
         cmds.delete('%s_animkey_Con_xform_parentConstraint1'%selTSL[y])
예제 #20
0
	def alt_b(self):
		if self.getSelection() == 'None':
			cmds.CycleBackgroundColor() # cycles the background color as per the default
		else:
			if self.getType(0) == 'face' or self.getType(0) == 'vertex' or self.getType(0) == 'edge':
				self.bevelTool()
			# switch this over to recognize the animation category later on istead of just fitting to a camera selection. Should be able to work on any object selected
			else:
				start = cmds.findKeyframe( self.getSelection(), which = "first" )
				end = cmds.findKeyframe( self.getSelection(), which = "last" )
				if start == end: # this means there's no keyframes
					start = cmds.playbackOptions(q=1, minTime=1)
					end =   cmds.playbackOptions(q=1, maxTime=1)
				cmds.bakeResults(self.getSelection(), simulation = True, time =(start,end), sampleBy = 1 )
예제 #21
0
def bakeExportSkeleton(exportNS, start=1, end=0):
    """
    Bake export skeleton constraints to joint channel keysframes.
    @param exportNS: The namespace of the export skeleton.
    @type exportNS: str
    @param start: Start frame of the bake animation range. If greater that end, use current playback settings.
    @type start: float
    @param end: End frame of the bake animation range. If less that start, use current playback settings.
    @type end: float
    """
    # ==========
    # - Checks -
    # ==========

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

    # Namespace
    if not exportNS:
        raise Exception('An export namespace must be specified')

    exportNS = exportNS + ':'
    if not cmds.namespace(exists=':' + exportNS):
        raise Exception('Export namespace "' + exportNS + '" does not exist!')

    # ======================
    # - Bake Export Joints -
    # ======================

    jointList = cmds.ls(exportNS + '*', type='joint')
    bakeList = [i for i in jointList if cmds.ls(cmds.listConnections(i, s=True, d=False), type='constraint')]
    cmds.bakeResults(bakeList, t=(start, end), at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'], simulation=True)

    # ======================
    # - Delete Constraints -
    # ======================

    constraintList = cmds.ls(exportNS + '*', type='constraint')
    if not constraintList:
        raise Exception('Unbale to determine export skeleton constraint list!')
    cmds.delete(constraintList)

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

    return bakeList
예제 #22
0
 def bakeMotion(self):
     '''\n
     Constrains trackCt[0] object to self.track object, bakes the constraint.
     '''
     constraint = cmds.parentConstraint(self.track, self.trackCt[0], mo=True)
     #self.start = cmds.playbackOptions(q=True, min=True)
     #self.end   = cmds.playbackOptions(q=True, max=True)
     cmds.bakeResults(self.trackCt[0], t=(self.start, self.end), sb=1, at=["tx", "ty", "tz", "rx", "ry", "rz"], hi="none")
     cmds.delete(constraint)
     constraint = cmds.parentConstraint(self.trackCt[2], self.obj, mo=True)[0]
     UsrAttr = cmds.listAttr(constraint, ud=True)
     for attr in UsrAttr:
         if self.trackCt[2] not in attr:
             cmds.setAttr(constraint + '.' + attr, 0)
     cmds.select(self.trackCt[0])
예제 #23
0
def _fixThis(ctrl, timeRange):
    '''Fixa lo snap per questo controllo.'''

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

        # target attivo
        activeTarget = _getActiveAttachTarget(constrName)

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

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

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

        sys.stdout.write('Snap fixed at frame %d\n' % currentFrame)
예제 #24
0
def mBakeOutkey(outNodeDict, playbackRange, assetNS):
	"""
	"""
	def findObj(dag):
		targetList = cmds.ls('*' + dag, r= 1, l= 1, et= 'transform')
		inverseResult = []
		for T in targetList:
			if not T.startswith('|' + assetNS):
				inverseResult.append(T)
		return list(set(targetList) - set(inverseResult))

	for obj in outNodeDict:
		attrs = outNodeDict[obj]
		result = findObj(obj)
		if len(result) == 1:
			cmds.bakeResults(result[0], at= attrs, t= playbackRange, sm= 1, s= 0)
예제 #25
0
파일: bombKey.py 프로젝트: atsbomb/bombKey
def bake(world=0, constraint=0):
	if _getTime('rangeSelected'):
		range = [_getTime('rangeMin'), _getTime('rangeMax')]
	else:
		range = [_getTime('playbackMin'), _getTime('playbackMax')]

	if world:
		sels = mc.ls(sl=1)
		selLocs = []
		for sel in sels:
			loc = mc.spaceLocator(name=sel+'_worldBake_loc')[0]
			mc.addAttr(loc, ln='target', dt='string')
			mc.setAttr(loc+'.target', sel, type='string')
			mc.pointConstraint(sel, loc)
			mc.orientConstraint(sel, loc)
			mc.scaleConstraint(sel, loc)
			selLocs.append(loc)

		mc.select(selLocs)
		mc.bakeResults(time=(int(range[0]), int(range[1])), sampleBy=1, sm=1)
		mc.delete(constraints=1)

		if constraint:
			for loc in selLocs:
				target = mc.getAttr(loc+'.target')
				mc.delete(target, channels=1)
				if mc.getAttr(target+'.tx', l=1) or mc.getAttr(target+'.ty', l=1) or mc.getAttr(target+'.tz', l=1):
					mc.warning('Skipping applying pointConstraint because translate channel is locked.')
					pass
				else:
					mc.pointConstraint(loc, target)

				if mc.getAttr(target+'.rx', l=1) or mc.getAttr(target+'.ry', l=1) or mc.getAttr(target+'.rz', l=1):
					mc.warning('Skipping applying orientConstraint because rotate channel is locked.')
					pass
				else:
					mc.orientConstraint(loc, target)

				if mc.getAttr(target+'.sx', l=1) or mc.getAttr(target+'.sy', l=1) or mc.getAttr(target+'.sz', l=1):
					mc.warning('Skipping applying scaleConstraint because scale channel is locked.')
					pass
				else:
					mc.scaleConstraint(loc, target)

	else:
		mc.selectKey(cl=1)
		mc.bakeResults(time=(int(range[0]), int(range[1])), sampleBy=1, sm=1)
예제 #26
0
파일: rigTools.py 프로젝트: myCodeTD/pkmel
def createCleanedCamera() :

	# Select camera then run the script.
	# Script will duplicate selected camera.

	cleanedCam = 'cleanedNuke_cam'

	if mc.objExists( cleanedCam ) :
		mc.delete( cleanedCam )

	selectedCam = ''
	selectedCamShp = ''

	selected = mc.ls( sl=True , l=True )[0]
	
	if mc.nodeType( selected ) == 'camera' :
		selectedCamShp = selected
		selectedCam = mc.listRelatives( selected , p=True , f=True )[0]
	else :
		selectedCam = selected
		selectedCamShp = mc.listRelatives( selected , type='shape' , f=True )[0]

	mc.select( selectedCam )
	mc.duplicate( selectedCam , rr=True , n=cleanedCam )
	mc.parent( w=True )

	duppedCamShp = mc.listRelatives( cleanedCam , type='shape' , f=True )[0]

	for attr in ( 'tx' , 'ty' , 'tz' , 'rx' , 'ry' , 'rz' ) :
		mc.setAttr( '%s.%s' % ( cleanedCam , attr ) , l=False )

	minTime = mc.playbackOptions( q=True , min=True )
	maxTime = mc.playbackOptions( q=True , max=True )

	animCurves = mc.listConnections( selectedCamShp , s=True , type='animCurve' )
	attrs = []
	if animCurves :
		for animCurve in animCurves :
			
			attr = mc.listConnections( animCurve , d=True , p=True )[0].split( '.' )[1]
			
			mc.copyKey( selectedCamShp , attribute=attr )
			mc.pasteKey( duppedCamShp , attribute=attr )
	
	parCons = mc.parentConstraint( selectedCam , cleanedCam )
	mc.bakeResults( cleanedCam , simulation=True , t=( minTime , maxTime ) )
	mc.delete( parCons )
예제 #27
0
def bake_binder_data(rootNode=None, debugView=False, runFilter=True, ignoreInFilter=[]):
    '''
    From a given Root Node search all children for the 'BoundCtr' attr marker. If none
    were found then search for the BindNode attr and use the message links to walk to
    the matching Controller.
    Those found are then baked out and the marker attribute is deleted
    '''
    BoundCtrls = get_bound_controls(rootNode)
    
    #Found no Ctrls, try and walk the message from the BndNodes
    if not BoundCtrls:
        BndNodes = get_bind_nodes()
        for node in BndNodes:
            cons=cmds.listConnections('%s.%s' % (node,BNDNODE_MARKER))
            if cons:
                BoundCtrls.append(cmds.ls(cons[0],l=True)[0])
            else:
                log.info('Nothing connected to %s.%s' % (node,BNDNODE_MARKER))
            
    if BoundCtrls:
        try:
            if not debugView:
                cmds.refresh(su=True)
            with r9General.AnimationContext():
                cmds.bakeResults(BoundCtrls, simulation=True,
                             sampleBy=1,
                             time=(cmds.playbackOptions(q=True, min=True), cmds.playbackOptions(q=True, max=True)),
                             disableImplicitControl=True,
                             preserveOutsideKeys=True,
                             sparseAnimCurveBake=True,
                             removeBakedAttributeFromLayer=False,
                             controlPoints=False,
                             shape=False)
            
            for node in BoundCtrls:
                #Remove the BindMarker from the baked node
                try:
                    cmds.deleteAttr('%s.%s' % (node,BAKE_MARKER))
                except StandardError,error:
                    log.info(error)
            if ignoreInFilter:
                BoundCtrls = [node for node in BoundCtrls if node.split('|')[-1].split(':')[-1] not in ignoreInFilter]
            if runFilter:
                cmds.filterCurve(BoundCtrls)
            cmds.delete(BoundCtrls, sc=True)  # static channels
        except StandardError,error:
            raise StandardError(error)
예제 #28
0
def keyAllChildren(op="set", jointsOnly=False): #set, cut, copy, paste
   selectedObjects = mc.ls(sl=True)
   targetObjects = mc.listRelatives( selectedObjects, ad=True ) + selectedObjects
   if(jointsOnly):
      targetObjects = mc.ls(targetObjects, type='joint')
   if(op=="set"):
      py.setKeyframe( targetObjects )
   elif(op=="cut"):
      py.cutKey( targetObjects )
   elif(op=="copy"):
      py.copyKey( targetObjects )
   elif(op=="paste"):
      py.pasteKey( targetObjects )   
   elif(op=="bake"):
      inTime=mc.playbackOptions(q=1,ast=1)
      outTime=mc.playbackOptions(q=1,aet=1)
      mc.bakeResults(targetObjects,simulation=1,sampleBy=1,time=(inTime,outTime))
예제 #29
0
    def writeObjVis(self, statVis, dynVis):
        dynVisObject, staticVisObj, ast2BakeAttrs, attrTmpLocs = [], [], [], [] 
        assetRefs = self.mayaShot.refNodes
        for ref in assetRefs:
            ast = MayaAsset(ref)
            astGeoBake, astGeoInvis = ast.getVisGeo()
            dynVisObject.extend(astGeoBake)
            staticVisObj.extend(astGeoInvis)

        stF = mc.playbackOptions(q=1,ast=1)
        edF = mc.playbackOptions(q=1,aet=1)
        for obj in dynVisObject:
            if mc.objExists((obj + "_TMPLOC")):
                mc.delete((obj + "_TMPLOC"))
            mc.spaceLocator(name = (obj + "_TMPLOC"))
            attrTmpLocs.append((obj + "_TMPLOC"))
            mc.connectAttr((obj + ".v"), (obj + "_TMPLOC.v"), f = True)
            ast2BakeAttrs.append((obj + "_TMPLOC.v"))
        ast2BakeAttrs = list(set(ast2BakeAttrs))
        if ast2BakeAttrs:
            mc.bakeResults(ast2BakeAttrs,at=['v'],sm=1,t=(stF,edF),sr=1,dic=1,pok=0,sac=0,ral=0,bol=0)
            for bkAst in ast2BakeAttrs:
                conns = mc.listConnections(bkAst, d=0, s=1)
                if mc.nodeType(conns[0]) == "animCurveTU":
                    if utils.chkStaticCurve(conns[0]):
                        objName = bkAst.split("_TMPLOC.v")[0]
                        dynVisObject.pop(dynVisObject.index(objName))
                        if not mc.getAttr("%s.v"%objName):
                            staticVisObj.append(objName)
                    else:
                        mc.keyTangent(bkAst, itt = 'step', ott = 'step')
        for statV in staticVisObj:
            objDotName = statV.replace(":", ".") if ":" in statV else statV
            ET.SubElement(statVis, objDotName)
        for dynV in dynVisObject:
            utils.writeAnimXML("%s_TMPLOC"%dynV, dynVis, ["visibility"], dynV)
        for tmpLoc in attrTmpLocs:
            try:
                mc.delete(tmpLoc)
            except:
                pass

        self.msg += "Visibility baked for all geometry\n"
예제 #30
0
def BakeBinderData(rootNode=None):
    '''
    From a given Root Node search all children for the 'BoundCtr' attr marker. If none
    were found then search for the BindNode attr and use the message links to walk to
    the matching Controller.
    Those found are then baked out and the marker attribute is deleted
    '''
    BoundCtrls = GetBoundControls(rootNode)
    
    #Found no Ctrls, try and walk the message from the BndNodes
    if not BoundCtrls:        
        BndNodes = GetBindNodes()
        for node in BndNodes:
            cons=cmds.listConnections('%s.BindNode' % node)
            if cons:
                BoundCtrls.append(cmds.ls(cons[0],l=True)[0])
            else:
                log.info('Nothing connected to %s.BindNode' % node)
            
    if BoundCtrls:
        try:
            cmds.bakeResults(BoundCtrls, simulation=True,
                             sampleBy=1,
                             time=(cmds.playbackOptions(q=True, min=True), cmds.playbackOptions(q=True, max=True)),
                             disableImplicitControl=True,
                             preserveOutsideKeys=True,
                             sparseAnimCurveBake=True,
                             removeBakedAttributeFromLayer=False,
                             controlPoints=False,
                             shape=False)
            
            for node in BoundCtrls:
                #Remove the BindMarker from the baked node
                try:
                    cmds.deleteAttr('%s.BoundCtr' % node)
                except StandardError,error:
                    log.info(error)
                    
            cmds.filterCurve(BoundCtrls)
            cmds.delete(BoundCtrls,sc=True) #static channels
        except StandardError,error:
            raise StandardError(error)
예제 #31
0
def ANIMATIONTRANSFER(inputNameSpace, outputNameSpace, outputReference, home):
    translationValues = ["translateX", "translateY", "translateZ"]
    rotationValues = ["rotateX", "rotateY", "rotateZ"]
    keyableValues = translationValues + rotationValues
    constraints = []
    controllers = []
    outputRoot = "none"
    outputPelvis = "none"
    outputTrajectory = "none"

    armElements = [
        "arm", "armPV", "armOptionsBox", "clavicle", "shoulder", "elbow",
        "wrist"
    ]
    legElements = [
        "leg", "legPV", "legOptionsBox", "hip", "knee", "ankle", "ball"
    ]
    ikElements = ["arm", "armPV", "leg", "legPV", "toe"]

    autoKeyState = py.autoKeyframe(state=1, q=1)
    py.autoKeyframe(state=0)
    py.playbackOptions(ps=1, e=1, min=0)
    #30FPS
    if (py.about(b=1, q=1) == 0):
        py.FrameSelected()
        py.currentUnit(time="ntsc")
        mel.eval('setUpAxis "y";  fitPanel -selected;')
    customFile = home + "CUSTOM.json" if (".json"
                                          not in home.split("/")[-1]) else home
    customFileCheck = py.file(customFile, q=1, ex=1)
    if (customFileCheck == 1):
        with open(customFile, 'r') as f:
            line = json.load(f)
###############################################################################
#"""# CREATE A LIST OF CONTROLLERS FROM THE RIG ANIMATION WILL BE IMPORTED ON #
###############################################################################
    selections = py.ls(sl=1)[0]
    if (inputNameSpace == "none"):
        inputNameSpace = ""
    if (":" in selections):
        name = selections.split(":")[-1]
    else:
        name = selections
    masterCenter = name.replace("_L_", "_M_").replace("_R_", "_M_")
    masterName = masterCenter.replace(masterCenter.split("_")[2], "master")
    trajectoryName = masterCenter.replace(
        masterCenter.split("_")[2], "trajectory")
    masterController = inputNameSpace + masterName.replace(
        masterName.split("_")[-1], "CTRL")
    trajectoryController = inputNameSpace + trajectoryName.replace(
        trajectoryName.split("_")[-1], "CTRL")
    py.setAttr(masterController + ".KEYALL", 0)
    inputControllers = []
    outputControllers = []
    inputInitialControllers = py.ls(inputNameSpace + "c_*")
    outputInitialControllers = py.ls(outputNameSpace + ":c_*")
    i = 0
    while (i < len(inputInitialControllers)):
        if (inputInitialControllers[i].split("_")[-1] == "CTRL"
                and "Shape" not in inputInitialControllers[i]):
            inputControllers.append(inputInitialControllers[i])
        i += 1
    i = 0
    while (i < len(outputInitialControllers)):
        if (outputInitialControllers[i].split("_")[-1] == "CTRL"
                and "Shape" not in outputInitialControllers[i]):
            outputControllers.append(outputInitialControllers[i])
        i += 1
###############################################################################
#"""#CREATE A LIST OF CONTROLLERS FROM THE RIG ANIMATION WILL BE EXPORTED FROM#
###############################################################################
#outputControllers = [];#!
    outputItems = py.ls(outputNameSpace + ":*", type="transform", o=1)
    outputJoint = py.ls(outputNameSpace + ":*", type="joint")[0]
    #SPECIAL CASE: IF OLD SKELETON (E JOINTS) EXISTS, REPLACE
    if (len(outputJoint) > 2):
        if (outputJoint[:2] == "e_"):
            if (py.objExists(outputJoint.replace("e_", "b_", 1)) == 1):
                outputJoint = outputJoint.replace("e_", "b_", 1)
        elif (":e_" in outputJoint):
            if (py.objExists(outputJoint.replace(":e_", ":b_")) == 1):
                outputJoint = outputJoint.replace(":e_", ":b_")
    #GET RELATED JOINTS FROM INITIAL SELECTION
    outputRootInitial = py.ls(outputJoint, l=1)[0].split("|")[2]
    outputRootGroup = py.ls(outputJoint, l=1)[0].split("|")[1]
    outputJoints = py.listRelatives(outputRootInitial,
                                    type="joint",
                                    ad=1,
                                    pa=1,
                                    s=0)
    outputJoints.reverse()
    outputJoints.insert(0, outputRootInitial)
    referenceFile = outputReference.split("/")[-1]
    ###############################################################################
    #"""# CREATE A CAMERA TO TRACK/FOLLOW THE ANIMATION                           #
    ###############################################################################
    if (py.about(b=1, q=1) == 0):
        characterCamera = py.camera()[0]
        characterCameraGroup = py.group()
        py.setAttr(characterCamera + ".t", 220, 220, 400)
        py.setAttr(characterCamera + ".r", -15, 30, 0)
        initialCamera = py.lookThru(q=1)
        py.lookThru(characterCamera)
        py.setAttr(initialCamera + ".t", 220, 220, 400)
        py.setAttr(initialCamera + ".r", -15, 30, 0)
        py.pointConstraint(trajectoryController,
                           characterCameraGroup,
                           mo=0,
                           w=1)
###############################################################################
#"""# SETS RIGS TO T POSE                                                     #
###############################################################################
    skipAttributes = ["attachment", "visibility"]
    #INPUT
    i = 0
    while (i < len(inputControllers)):
        keyableAttributes = py.listAttr(inputControllers[i], u=1, k=1, v=1)
        if (isinstance(keyableAttributes, list) == 1):
            ii = 0
            while (ii < len(keyableAttributes)):
                if not any(x in keyableAttributes[ii].lower()
                           for x in skipAttributes):
                    if ("SPACE" not in keyableAttributes[ii]):
                        py.setAttr(
                            inputControllers[i] + "." + keyableAttributes[ii],
                            0)
                    else:
                        py.setAttr(
                            inputControllers[i] + "." + keyableAttributes[ii],
                            1)
                ii += 1
        i += 1
    #OUTPUT
    i = 0
    while (i < len(outputControllers)):
        keyableAttributes = py.listAttr(outputControllers[i], u=1, k=1, v=1)
        if (isinstance(keyableAttributes, list) == 1):
            ii = 0
            while (ii < len(keyableAttributes)):
                if ("translate" in keyableAttributes[ii]
                        or "rotate" in keyableAttributes[ii]):
                    py.setAttr(
                        outputControllers[i] + "." + keyableAttributes[ii], 0)
                ii += 1
        i += 1
###############################################################################
#"""# COLLECT TRANSFORM VALUES OF OUTPUT JOINTS AFTER TPOSE                   #
###############################################################################
    if (outputControllers != []):
        transformList = []
        i = 0
        while (i < len(outputJoints)):
            translations = list(py.getAttr(outputJoints[i] + ".t")[0])
            transformList.append(translations)
            i += 1
    else:
        transformList = "invalid"
        py.headsUpMessage(
            '"No valid controllers found. Will attempt to use joints instead." - HiGGiE',
            t=2)
        print '"No valid controllers found. Will attempt to use joints instead." - HiGGiE'
###############################################################################
#"""# TURN OFF SOLO MODE FOR EACH LAYER                                       #
###############################################################################
    animationLayers = py.ls(type="animLayer")
    if (outputInitialControllers != []):
        isRiGGiE = py.listAttr(outputInitialControllers[0], st=["RiGGiE"], r=1)
        if (isinstance(isRiGGiE, list) == 1 and animationLayers != []):
            i = 0
            while (i < len(animationLayers)):
                py.animLayer(animationLayers[i], solo=0, lock=0, e=1)
                i += 1
###############################################################################
#"""# FIND THE SOONEST AND LATEST KEYS OF ALL OUTPUT ITEMS                    #
###############################################################################
    firstFrame = 0
    lastFrame = 0
    i = 0
    while (i < len(outputItems)):
        currentFirstKey = 0
        currentLastKey = 0
        if not any(s in outputItems[i]
                   for s in keyableValues):  #IN CASE ITEM IS KEY
            currentFirstKey = round(py.findKeyframe(outputItems[i], w="first"),
                                    0)
            currentLastKey = round(py.findKeyframe(outputItems[i], w="last"),
                                   0)
            if (currentFirstKey < firstFrame):
                firstFrame = currentFirstKey
            if (currentLastKey > lastFrame):
                lastFrame = currentLastKey
            if (currentLastKey > 1000):
                print '"Warning: "' + outputItems[
                    i] + '" has over 1000 keys. Transfer may take a while..." - HiGGiE'
        i += 1
    difference = 0 - firstFrame
    ###############################################################################
    #"""# IF RIG IS FROM HiGGiE: DO A DIRECT TRANSFER THROUGH CONTROLLERS         #
    ###############################################################################
    RiGGiE = False
    outputMasterController = outputNameSpace + ":" + "c_M_master_v1_CTRL"
    if (py.objExists(outputMasterController) == 1):
        isRiGGiE = py.listAttr(outputMasterController, st=["RiGGiE"], r=1)
        if (isinstance(isRiGGiE, list) == 1):
            #OUTPUT RIG IS CREATED BY HiGGiE; DIRECT TRANSFER IS ALLOWED
            RiGGiE = True
            py.headsUpMessage(
                '"This rig is RiGGiE status (made by HiGGiE)!" - HiGGiE', t=2)
            print '"This rig is RiGGiE status (made by HiGGiE)!" - HiGGiE'
    RiGGiE = False
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ###############################################################################
    #"""# SETS THE RIG TO FK MODE                                                 #
    ###############################################################################
    optionsBoxList = []
    i = 0
    while (i < len(inputControllers)):
        if ("OptionsBox_" in inputControllers[i]
                and inputControllers[i].split("_")[-1] == "CTRL"):
            MODE = py.listAttr(inputControllers[i], st=["MODE"], r=1)
            if (isinstance(MODE, list) == True):
                py.setAttr(inputControllers[i] + ".MODE", 0)
                optionsBoxList.append(inputControllers[i])
            inputControllers.remove(inputControllers[i])
        i += 1
###############################################################################
#"""# BAKE THE SKELETON IN CASE IT IS ANIMATED BY CONTROLLERS (CONSTRAINTS)   #
###############################################################################
    if (RiGGiE == False):
        py.playbackOptions(minTime=0, maxTime=lastFrame + difference)
        py.currentTime(round(py.currentTime(q=1), 0))
        py.headsUpMessage('"Baking imported skeleton." - HiGGiE', t=2)
        print '"Baking imported skeleton." - HiGGiE'
        py.bakeResults(outputJoints[:],
                       t=(firstFrame, lastFrame),
                       at=keyableValues,
                       sm=1,
                       s=0)
###############################################################################
#"""# MAKE CONSTRAINT LAYER                                                   #
###############################################################################
    version = 1
    while (py.objExists("a_M_importedConstraints_v" + str(version) + "_LYR")):
        version += 1
    conLayer = "a_M_importedConstraints_v" + str(version) + "_LYR"
    ###############################################################################
    #"""# CONNECT RIGS                                                            #
    ###############################################################################
    nameSpace = inputNameSpace
    py.select(outputJoint, r=1)
    py.headsUpMessage('"Starting animation transfer..." - HiGGiE', t=2)
    print '"Starting animation transfer..." - HiGGiE'
    if (RiGGiE == False):
        out = matchProportions.MATCHPROPORTIONS(transformList, nameSpace,
                                                outputNameSpace, conLayer)
###############################################################################
#"""# SPECIAL CASE: TRANSFER ANIMATION DIRECTLY FROM CONTROLLERS              #
###############################################################################
    else:
        #CREATE NEW CONSTRAINT LAYER
        conLayer = py.animLayer("a_M_importedConstraints_v" + str(version) +
                                "_LYR")
        py.setAttr(conLayer + ".rotationAccumulationMode", 1)
        py.setAttr(conLayer + ".scaleAccumulationMode", 0)
        #py.animLayer(conLayer,solo=1,e=1);
        #MUTE LAYERS CONNECTED TO THE INPUT RIG

        py.select(outputControllers[:], r=1)
        relevantOutputLayers = py.animLayer(affectedLayers=1, q=1)

        py.select(inputControllers[:], r=1)
        relevantLayers = py.animLayer(affectedLayers=1, q=1)
        if (isinstance(relevantLayers, list) == 1):
            i = 0
            while (i < len(relevantLayers)):
                py.animLayer(relevantLayers[i], solo=0, mute=1, e=1)
                py.setAttr(relevantLayers[i] + ".override", 0)
                i += 1
        #py.animLayer(conLayer,aso=1,e=1);
        #SET OUTPUT RIG TO T POSE (AGAIN)
        for i in range(0, len(inputControllers)):
            outputController = outputNameSpace + ":" + inputControllers[
                i].split(":")[-1]
            if (py.objExists(outputController) == 1):
                keyableAttributes = py.listAttr(outputController,
                                                u=1,
                                                k=1,
                                                v=1)
                if (isinstance(keyableAttributes, list) == 1):
                    for ii in range(0, len(keyableAttributes)):
                        if ("translate" in keyableAttributes[ii]
                                or "rotate" in keyableAttributes[ii]):
                            py.setAttr(
                                outputController + "." + keyableAttributes[ii],
                                0)
                            py.animLayer(conLayer,
                                         at=outputController + "." +
                                         keyableAttributes[ii],
                                         e=1)
        #BEGIN TRANSFER...
        ikControllerList = []
        for i in range(0, len(inputControllers)):
            #CHANGE OUTPUT CONTROLLER TARGET BASED ON THE IK/FK STATUS
            typeName = inputControllers[i].split("_")[-3]
            if (typeName in armElements):
                inputOptionsBox = inputControllers[i].replace(
                    typeName, "armOptionsBox", -1)
            elif (typeName in legElements):
                inputOptionsBox = inputControllers[i].replace(
                    typeName, "legOptionsBox", -1)
            else:
                inputOptionsBox = "invalid"
            if (inputOptionsBox != "invalid"):
                inputMode = 0 if (typeName not in ikElements) else 1
                outputOptionsBox = outputNameSpace + ":" + inputOptionsBox.split(
                    ":")[-1]
                outputMode = int(py.getAttr(outputOptionsBox + ".MODE"))
                if (inputMode != outputMode):
                    if (inputMode == 0):
                        #PAIR INPUT FK CONTROLLER TO OUTPUT IK JNT
                        outputController = outputNameSpace + ":" + inputControllers[
                            i].split(":")[-1]
                        outputController = outputController.replace(
                            "CTRL", "JNT", -1)
                        if (typeName == armElements[-1]):
                            outputController = outputController.replace(
                                typeName, "armInitialPositionFK", -1)
                            outputController = outputController.replace(
                                "JNT", "LOC", -1)
                        if (typeName == legElements[-2]):
                            outputController = outputController.replace(
                                typeName, "legInitialPositionFK", -1)
                            outputController = outputController.replace(
                                "JNT", "LOC", -1)
                    else:
                        #PAIR INPUT IK CONTROLLER TO OUTPUT FK LOCATORS
                        outputController = outputNameSpace + ":" + inputControllers[
                            i].split(":")[-1]
                        if (typeName == "arm"):
                            outputController = outputController.replace(
                                typeName, "wristIK", -1)
                            outputController = outputController.replace(
                                "CTRL", "LOC", -1)
                        elif (typeName == "leg"):
                            outputController = outputController.replace(
                                typeName, "ankleIK", -1)
                            outputController = outputController.replace(
                                "CTRL", "LOC", -1)
                        elif (typeName == "armPV" or typeName == "legPV"):
                            outputController = outputController.replace(
                                "CTRL", "LOC", -1)
                        elif (typeName == "toe"):
                            outputController = outputController.replace(
                                typeName, "ball", -1)
                else:
                    #PAIR INPUT CONTROLLER TO OUTPUT CONTROLLER 1-To-1
                    outputController = outputNameSpace + ":" + inputControllers[
                        i].split(":")[-1]
            else:
                #PAIR INPUT CONTROLLER TO OUTPUT CONTROLLER 1-To-1
                outputController = outputNameSpace + ":" + inputControllers[
                    i].split(":")[-1]
            isWeapon = py.listAttr(inputControllers[i], st=["WiGGiE"], r=1)
            if (isinstance(isWeapon, list) == 0):
                if ("_arm_" in inputControllers[i]
                        or "_leg_" in inputControllers[i]):
                    ikControllerList.append(inputControllers[i])
                    parents = py.listRelatives(inputControllers[i], p=1,
                                               s=0)[0]
                    SAFE = py.listAttr(parents, st=["SAFE"], r=1)
                    if (isinstance(SAFE, list) == 1):
                        py.setAttr(parents + ".SAFE", 1)
                if (py.objExists(outputController) == 1):
                    try:
                        #py.parentConstraint(outputController,inputControllers[i],l=conLayer,mo=1,w=1);
                        py.pointConstraint(outputController,
                                           inputControllers[i],
                                           mo=0,
                                           w=1)
                        py.orientConstraint(outputController,
                                            inputControllers[i],
                                            l=conLayer,
                                            mo=0,
                                            w=1)
                    except:
                        try:
                            py.orientConstraint(outputController,
                                                inputControllers[i],
                                                l=conLayer,
                                                mo=0,
                                                w=1)
                        except:
                            try:
                                py.pointConstraint(outputController,
                                                   inputControllers[i],
                                                   l=conLayer,
                                                   mo=1,
                                                   w=1)
                            except:
                                #FOR CONTROLLERS WHERE 3 AXIS AREN'T AVAILABLE (IE: BREATH)
                                pass
###############################################################################
#"""# CONNECT WEAPON TO ATTACHMENT POINT                                      #
###############################################################################
    weaponID = [
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"
    ]
    weapons = [
        "none", "sword", "R_blade", "R_hammer", "spear", "longBow", "wand",
        "heavySword", "L_sword.R_sword", "harp", "shield.R_blade"
    ]
    secondaryWeapons = ["shield"]
    py.currentTime((py.currentTime(q=1) + 1))
    #STEP ANIMATION FORWARD 1 FRAME
    i = 0
    while (i < len(weaponID)):
        if (weaponID[i] in referenceFile.split("_")[-1]
                and "_" in referenceFile):  #!
            weaponsSet = weapons[i].split(".")
            ii = 0
            while (ii < len(weaponsSet)):
                position = "primary"
                if any(s in weaponsSet[ii] for s in secondaryWeapons):
                    position = "secondary"
                if (weaponsSet[ii] != "none"):
                    properWeaponController = 0
                    weaponController = [
                        s for s in inputControllers
                        if weaponsSet[ii] + "_" in s
                    ]
                    if (weaponController != []):
                        #CHECK MAX WEAPON BEFORE MAYA
                        weaponController = weaponController[0]
                        side = "_R_" if ("_R_" in weaponController) else "_L_"
                        weaponPosition = position + "Weapon"
                        name = side + position + "Weapon"
                        weaponPosition = [
                            s for s in outputJoints if name in s
                        ]
                        if (len(weaponPosition) == 0):
                            #SECOND MAX WEAPON CHECK
                            name = "RightWeapon" if (
                                side == "_R_") else "LeftWeapon"
                            weaponPosition = [
                                s for s in outputJoints if name in s
                            ]
                            properWeaponController = 0
                        if (len(weaponPosition) == 0):
                            #FIND OLD RIG WEAPON
                            name = side + "weapon"
                            weaponPosition = [
                                s for s in outputJoints if name in s
                            ]
                            properWeaponController = 0
                        if (len(weaponPosition) == 0):
                            #FIND NEW RIG WEAPON
                            name = side + weaponsSet[ii] + "_"
                            weaponPosition = [
                                s for s in outputJoints if name in s
                            ]
                            properWeaponController = 1
                        #HOLSTER ATTACHMENT
                        holster = 1
                        if (side == "_L_" and position == "primary"):
                            holster = 2
                        elif (side == "_L_" and position == "secondary"):
                            holster = 3
                        try:
                            py.setAttr(weaponController + ".ATTACHMENT",
                                       holster)
                            target = masterController + "." + weaponsSet[
                                ii].upper()
                            py.setAttr(target, 1)
                        except:
                            pass
                        if (len(weaponPosition) != 0):
                            controllerAP = weaponPosition[0].replace(
                                "t_", "c_").replace("JNT", "CTRL")
                            if (py.objExists(outputNameSpace + ":" +
                                             controllerAP) == 1):
                                weaponPosition = outputNameSpace + ":" + controllerAP
                            else:
                                weaponPosition = weaponPosition[0]
                            if (holster == 1 or holster == 2):
                                weaponJoint = weaponPosition.split(
                                    ":")[-1].replace("c_", "t_").replace(
                                        "CTRL", "JNT")
                                weaponJoint = outputNameSpace + ":" + weaponJoint
                                if (properWeaponController == 0):
                                    py.orientConstraint(weaponPosition,
                                                        weaponController,
                                                        l=conLayer,
                                                        mo=0,
                                                        w=1)
                                elif (py.objExists(weaponJoint) == 1):
                                    py.parentConstraint(weaponJoint,
                                                        weaponController,
                                                        l=conLayer,
                                                        mo=0,
                                                        w=1)
                ii += 1
        i += 1
###############################################################################
#"""# BAKE ANIMATION FROM CONSTRAINT LAYER TO ANIMATION LAYER                 #
###############################################################################
    if (masterController in inputControllers and RiGGiE == 0):
        inputControllers.remove(masterController)
    py.select(inputControllers[:], r=1)
    py.animLayer(conLayer, solo=1, mute=0, e=1)
    py.setAttr(conLayer + ".override", 1)
    version = 1
    while (py.objExists("a_M_importedAnimation_v" + str(version) + "_LYR")):
        version += 1
    bakeLayer = py.animLayer("a_M_importedAnimation_v" + str(version) + "_LYR")
    py.setAttr(bakeLayer + ".rotationAccumulationMode", 1)
    py.setAttr(bakeLayer + ".scaleAccumulationMode", 0)
    py.animLayer(bakeLayer, solo=1, e=1)
    #!
    py.bakeResults(t=(firstFrame, lastFrame),
                   dl=bakeLayer,
                   at=keyableValues,
                   sm=1,
                   s=0)
    py.animLayer(conLayer, solo=0, mute=0, e=1)
    py.delete(out[-1], conLayer)
    py.animLayer(bakeLayer, solo=0, e=1)
    if (py.about(b=1, q=1) == 0):
        py.lookThru(initialCamera)
        py.delete(characterCameraGroup)
    py.autoKeyframe(state=autoKeyState)
    py.select(masterController, r=1)
    py.setAttr(bakeLayer + ".rotationAccumulationMode", 0)
    py.setAttr(bakeLayer + ".scaleAccumulationMode", 1)
    #SET IKFK MODE FROM OPTIONS BOX LIST
    i = 0
    while (i < len(out[1])):
        if py.objExists(out[1][i]) == False:
            print "the object doesnt exist"
        else:
            if (("leg" in out[1][i] and line['LEG IK'] == 1)
                    or ("arm" in out[1][i] and line['ARM IK'] == 1)):
                py.setAttr(out[1][i] + ".MODE", 1)
        i += 1
    #FINALIZE
    if (py.about(b=1, q=1) == 0):
        py.FrameSelected()
    i = 0
    while (i < len(out[0])):
        parents = py.listRelatives(out[0][i], p=1, s=0)[0]
        SAFE = py.listAttr(parents, st=["SAFE"], r=1)
        if (isinstance(SAFE, list) == 1):
            py.setAttr(parents + ".SAFE", 0)
        i += 1
    py.headsUpMessage('"Animation successfully converted!" - HiGGiE', t=2)
    py.file(outputReference, rr=1)
    py.select(masterController, r=1)
예제 #32
0
def BakeFunction():
    cmds.commandEcho(ln=False)

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

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

    #undo
    cmds.undoInfo(openChunk=True)

    bake_channels = bake_channel(channelCheck, channelBox_attrs,
                                 appliedChannels)

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

    cmds.undoInfo(closeChunk=True)
예제 #33
0
파일: __init__.py 프로젝트: octvision/oct
def OCT_BakeCamera():
    allSelCamera = mc.ls(selection=True)
    find = False
    if not allSelCamera:
        mc.confirmDialog(title='Confirm', message=u'请选择摄像机')
        return
    for obj in allSelCamera:
        buf = mc.listRelatives(obj, fullPath=True, children=True)
        if buf:
            if mc.nodeType(buf[0]) == "camera" or mc.nodeType(
                    buf[0]) == "stereoRigCamera":
                find = True
            else:
                find = False
                break
        else:
            find = False
            break

    if not find:
        mc.confirmDialog(title='Confirm', message=u'请选择摄像机')
        return

    timeLine = mc.playbackOptions(q=True, min=True)
    timeLine1 = mc.playbackOptions(q=True, max=True)

    for baked in allSelCamera:
        mc.select(d=True)
        mc.select(baked, r=True)
        #复制相机
        CopyCamera = mc.duplicate(rr=True)
        #改名
        selCamreaName = baked + baked
        mc.rename(baked, selCamreaName)
        mc.rename(CopyCamera[0], baked)
        mc.parent(baked, w=True)

        attrs = mc.listAttr(baked, keyable=True, locked=True)
        if attrs:
            for attr in attrs:
                mc.setAttr("%s.%s" % (baked, attr), l=False)

        buf = mc.listRelatives(baked, fullPath=True, children=True)
        attrShapes = mc.listAttr(buf[0], keyable=True, locked=True)
        if attrShapes:
            for at in attrShapes:
                mc.setAttr("%s.%s" % (baked, at), l=False)

        mc.parentConstraint(selCamreaName, baked, w=1)
        mc.bakeResults(baked,
                       simulation=True,
                       t=(timeLine, timeLine1),
                       sampleBy=True,
                       disableImplicitControl=True,
                       preserveOutsideKeys=True,
                       sparseAnimCurveBake=False,
                       removeBakedAttributeFromLayer=False,
                       bakeOnOverrideLayer=False,
                       minimizeRotation=True,
                       controlPoints=False,
                       shape=True)

        oldShapes = mc.listRelatives(selCamreaName,
                                     fullPath=True,
                                     children=True)

        attrs = [
            "horizontalFilmOffset", "verticalFilmOffset", "filmFitOffset",
            "focalLength"
        ]

        focal = mc.listConnections("%s.focalLength" % buf[0],
                                   s=True,
                                   plugs=True)
        if focal:
            mc.disconnectAttr(focal[0], "%s.focalLength" % buf[0])

        for i in range(int(timeLine), int(timeLine1) + 1):
            mc.currentTime(i)
            for attr in attrs:
                num = mc.getAttr("%s.%s" % (oldShapes[0], attr))
                mc.setKeyframe(buf[0], v=num, at=attr, t=i)

        # nameShapes = mc.listRelatives(baked,c= True)
        # for i in range(int(timeLine), int(timeLine1)+1):
        #     mc.setKeyframe(nameShapes,at = "filmFitOffset",t = i)
        #     mc.setKeyframe(nameShapes,at = "horizontalFilmOffset",t = i)
        #     mc.setKeyframe(nameShapes,at = "verticalFilmOffset",t = i)
        # setKeyframe -v $translate[0] -at scaleX -t $keyframe[0] $child;


#OCT_BakeCamera()
예제 #34
0
def legIkToFk(rigNS, side, start=None, end=None, sampleBy=1):
    '''
	Bake IK leg animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param side: Leg side ("lf" or "rt")
	@type side: str
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
    # Get Start/End
    if start == None: start = mc.playbackOptions(q=True, min=True)
    if end == None: end = mc.playbackOptions(q=True, max=True)

    # Set Leg to IK mode
    mc.setAttr(rigNS + ':config.' + side + 'LegIkFkBlend', 0)  # IK

    # Build IK/FK Joint List
    ikJntList = [
        rigNS + ':' + side + '_leg_ik' + i + '_jnt' for i in ['A', 'B']
    ]
    ikJntList += [
        rigNS + ':' + side + '_foot_ik' + i + '_jnt' for i in ['A', 'B']
    ]
    fkJntList = [
        rigNS + ':' + side + '_leg_fk' + i + '_jnt' for i in ['A', 'B']
    ]
    fkJntList += [
        rigNS + ':' + side + '_foot_fk' + i + '_jnt' for i in ['A', 'B']
    ]

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

    # Transfer Baked Anim to FK Joints
    mc.refresh(suspend=True)
    for i in range(len(fkDupList)):
        mc.bakeResults(fkDupList[i],
                       t=(start, end),
                       at=['rx', 'ry', 'rz'],
                       simulation=True,
                       preserveOutsideKeys=True,
                       sampleBy=sampleBy)
        mc.copyKey(fkDupList[i], at=['rx', 'ry', 'rz'], t=(start, end))
        mc.pasteKey(fkJntList[i],
                    at=['rx', 'ry', 'rz'],
                    t=(start, end),
                    option='replace')
    mc.refresh(suspend=False)

    # Delete Duplicate Joints and Constraints
    if fkOriList:
        try:
            mc.delete(fkOriList)
        except Exception, e:
            print('Error deleting nodes ' + str(fkOriList) +
                  '! Exception Msg: ' + str(e))
예제 #35
0
def CreateLoc(oObj, ver):
    if ver == 0:
        Order = cmds.optionMenu('Order_List', q=True, sl=True) - 1
        BakeAll = cmds.checkBox("FrameLock", q=True, value=True)
    else:
        Order = cmds.optionMenu('Check_Order_List', q=True, sl=True) - 1
        BakeAll = cmds.checkBox("Check_FrameLock", q=True, value=True)
    timeIn = cmds.playbackOptions(q=True, min=True)
    timeout = cmds.playbackOptions(q=True, max=True)
    inframe = []
    outframe = []
    Flag = 0
    plotObj = []
    plotDummy = []
    obj_tmp = []
    delConst = []
    for i in oObj:
        obj_tmp.append(i)
        #キー、オーダー、アトリビュート取得
        Original_Orders = cmds.listAttr(i, r=True, string="Original_Order*")
        oObj_Order = cmds.getAttr(i + ".rotateOrder")
        oKey_Rot = []
        if cmds.findKeyframe(i, c=True, at='rotateX') != None:
            oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateX'))
        if cmds.findKeyframe(i, c=True, at='rotateY') != None:
            oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateY'))
        if cmds.findKeyframe(i, c=True, at='rotateZ') != None:
            oKey_Rot.append(cmds.findKeyframe(i, c=True, at='rotateZ'))
        if len(oKey_Rot) > 1:
            keys = cmds.keyframe(oKey_Rot[0], query=True)
            if len(keys) > 1:
                #ここからが実行文
                #アトリビュートの設定とオリジナルのキーを保存しておく
                if not cmds.objExists(i + ".Original_Order"):
                    cmds.addAttr(i, sn="Ori", ln="Original_Order", dt="string")
                    cmds.setAttr(i + ".Original_Order",
                                 oObj_Order,
                                 type="string")
                if not cmds.objExists(i + ".Original_Order_RotX"):
                    cmds.addAttr(i,
                                 sn="RotX",
                                 ln="Original_Order_RotX",
                                 at="double")
                    cmds.setAttr(i + ".Original_Order_RotX",
                                 e=True,
                                 k=True,
                                 cb=False)
                    cmds.copyKey(i, at="rotateX", o="curve")
                    cmds.pasteKey(i + '.Original_Order_RotX')
                if not cmds.objExists(i + ".Original_Order_RotY"):
                    cmds.addAttr(i,
                                 sn="RotY",
                                 ln="Original_Order_RotY",
                                 at="double")
                    cmds.setAttr(i + ".Original_Order_RotY",
                                 e=True,
                                 k=True,
                                 cb=False)
                    cmds.copyKey(i, at="rotateY", o="curve")
                    cmds.pasteKey(i + '.Original_Order_RotY')
                if not cmds.objExists(i + ".Original_Order_RotZ"):
                    cmds.addAttr(i,
                                 sn="RotZ",
                                 ln="Original_Order_RotZ",
                                 at="double")
                    cmds.setAttr(i + ".Original_Order_RotZ",
                                 e=True,
                                 k=True,
                                 cb=False)
                    cmds.copyKey(i, at="rotateZ", o="curve")
                    cmds.pasteKey(i + '.Original_Order_RotZ')

                #ロケータを作ってオーダーを変えてプロット
                oLoc = cmds.spaceLocator(n=i + "_TempObj")
                inframe.append(keys[0])
                outframe.append(keys[-1])
                PointCons = cmds.pointConstraint(i, oLoc, n="Dummy_point")
                OrientCons = cmds.orientConstraint(i, oLoc, n="Dummy_orient")
                cmds.setAttr(i + ".rotateOrder", Order)
                Connections = cmds.listRelatives(oLoc,
                                                 c=True,
                                                 typ="constraint",
                                                 fullPath=True)
                delConst.append(Connections)
                if BakeAll == True:
                    plotObj.append(i + ".rotateX")
                    plotObj.append(i + ".rotateY")
                    plotObj.append(i + ".rotateZ")
                    dummy = oLoc[0]
                    plotDummy.append(dummy + ".rotateX")
                    plotDummy.append(dummy + ".rotateY")
                    plotDummy.append(dummy + ".rotateZ")
                else:
                    cmds.bakeResults([
                        oLoc[0] + ".rotateX", oLoc[0] + ".rotateY",
                        oLoc[0] + ".rotateZ"
                    ],
                                     sm=False,
                                     t=(keys[0], keys[-1]),
                                     pok=True)
                    for d in Connections:
                        cmds.select(d)
                        cmds.delete()
                    To_OrientCons = cmds.orientConstraint(oLoc,
                                                          i,
                                                          n="Dummy_orient")

                    cmds.delete(i + "_rotateX")
                    cmds.delete(i + "_rotateY")
                    cmds.delete(i + "_rotateZ")
                    cmds.bakeResults(
                        [i + ".rotateX", i + ".rotateY", i + ".rotateZ"],
                        sm=False,
                        t=(keys[0], keys[-1]),
                        pok=True)
                    Connections = cmds.listRelatives(i,
                                                     c=True,
                                                     typ="constraint",
                                                     fullPath=True)
                    for c in Connections:
                        cmds.select(c)
                        cmds.delete()
                    cmds.delete(oLoc)
                    if len(plotDummy) > 0:
                        #配列済なので、sortedでソート実行
                        S_in = sorted(inframe)
                        S_out = sorted(outframe)
                        Sort_in = set(S_in)
                        Sort_out = set(S_out)
                        Min_Frame = list(Sort_in)[0]
                        Max_Frame = list(Sort_out)[-1]
                        #Plot
                        cmds.bakeResults(plotDummy,
                                         sm=False,
                                         t=(Min_Frame, Max_Frame),
                                         pok=True)
                        for d in delConst:
                            cmds.select(d)
                            cmds.delete()
                        if len(obj_tmp) != []:
                            delConst = []
                            for tmp in obj_tmp:
                                OrientCons = cmds.orientConstraint(
                                    tmp + "_TempObj", tmp, n="Dummy_orient")
                                Connections = cmds.listRelatives(
                                    tmp,
                                    c=True,
                                    typ="constraint",
                                    fullPath=True)
                                delConst.append(Connections)
                            cmds.bakeResults(plotObj,
                                             sm=False,
                                             t=(Min_Frame, Max_Frame),
                                             pok=True)
                            for d in delConst:
                                cmds.select(d)
                                cmds.delete()
                            for tmp in obj_tmp:
                                cmds.delete(tmp + "_TempObj")
            else:
                cmds.warning(u'キーが2つ以上打たれていません。')
                DirectChange = cmds.confirmDialog(
                    title='ChangeOrder',
                    m=u'キーが2つ以上打たれていません。そのままオーダーが変えますがよろしいでしょうか?',
                    button=['Yes', 'No'],
                    defaultButton='Yes',
                    cancelButton='No',
                    dismissString='No')
                if DirectChange == "Yes":
                    cmds.setAttr(i + ".rotateOrder", Order)
                else:
                    cmds.warning(u'終了しました。')
        else:
            cmds.warning(u'回転XYZの2つ以上キー設定がされてません')
            cmds.confirmDialog(title='ChangeOrder',
                               m=u'回転XYZの2つ以上キー設定がされてません',
                               icon='warning')
    if BakeAll == True:
        delConect = []
        Min_Frame = sorted(inframe)[0]
        Max_Frame = sorted(outframe)[-1]

        cmds.bakeResults(plotDummy,
                         sm=False,
                         t=(Min_Frame, Max_Frame),
                         pok=True)
        for d in Connections:
            cmds.select(d)
            cmds.delete()
        for i in oObj:
            To_OrientCons = cmds.orientConstraint(i + "_TempObj",
                                                  i,
                                                  n="Dummy_orient")
            cmds.delete(i + "_rotateX")
            cmds.delete(i + "_rotateY")
            cmds.delete(i + "_rotateZ")
            delConect.append(
                cmds.listRelatives(i, c=True, typ="constraint", fullPath=True))
        cmds.bakeResults(plotObj, sm=False, t=(Min_Frame, Max_Frame), pok=True)
        for dc in delConect:
            cmds.select(dc)
            cmds.delete()
        delConect = []
        for tmp in oObj:
            OrientCons = cmds.orientConstraint(tmp + "_TempObj",
                                               tmp,
                                               n="Dummy_orient")
            Connections = cmds.listRelatives(tmp,
                                             c=True,
                                             typ="constraint",
                                             fullPath=True)
            delConect.append(Connections)
        cmds.bakeResults(plotObj, sm=False, t=(Min_Frame, Max_Frame), pok=True)
        for d in delConect:
            cmds.select(d)
            cmds.delete()
        for tmp in oObj:
            cmds.delete(tmp + "_TempObj")
예제 #36
0
def bakeControlOverride(controlList, start=None, end=None, bakeSim=True):
    '''
	Bake control constraint to transform channel keys.
	@param controlList: The control list that will have its constraints baked to keyframes.
	@type controlList: list
	@param start: Start frame of the bake animation range. If greater that end, use current playback settings.
	@type start: float
	@param end: End frame of the bake animation range. If less that start, use current playback settings.
	@type end: float
	@param bakeSim: Bake results using simulation option which updates the entire scene at each bake sample.
	@type bakeSim: bool
	'''
    print(
        '!!==== DEPRICATED ====!! (glTools.rig.mocapOverride.bakeControlOverride)'
    )

    # ==========
    # - Checks -
    # ==========

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

    # For Each Control
    bakeControlList = []
    constraintList = []
    for control in controlList:

        # Control
        if not mc.objExists(control):
            raise Exception('Rig control transform "' + control +
                            '" does not exist!')

        # Override Target Constraint
        overrideConstraint = mc.ls(mc.listConnections(control + '.' +
                                                      overrideAttribute(),
                                                      d=True,
                                                      s=False),
                                   type='constraint')
        if not overrideConstraint:

            # Check PairBlend (intermediate) Connection
            # - This fix was made in preparation for baking keys from multiple mocap sources (bake in frame chunks).
            overridePairBlend = mc.ls(mc.listConnections(control,
                                                         s=True,
                                                         d=False),
                                      type='pairBlend')
            if overridePairBlend:
                overrideConstraint = mc.ls(mc.listConnections(
                    overrideTargetPairBlend, s=True, d=False) or [],
                                           type='constraint')

            if not overrideConstraint:
                print(
                    'Unable to determine override constraint from control transform "'
                    + control + '"!')
                continue

        # Append to Override Target List
        bakeControlList.append(control)
        # Append to Override Constraint List
        [
            constraintList.append(i) for i in overrideConstraint
            if not i in constraintList
        ]

    # =================================
    # - Bake Override Target Channels -
    # =================================

    # Check Bake Control List
    if not bakeControlList:
        print('Found no controls to bake! Skipping...')
        return None

    # Bake to Controls
    mc.bakeResults(bakeControlList,
                   t=(start, end),
                   at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'],
                   preserveOutsideKeys=True,
                   simulation=bakeSim)

    # ======================
    # - Delete Constraints -
    # ======================

    if constraintList: mc.delete(constraintList)

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

    return bakeControlList
예제 #37
0
def armIkToFk(rigNS, side, bakeWrist=True, start=None, end=None, sampleBy=1):
    '''
	Bake IK arm animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param side: Arm side ("lf" or "rt")
	@type side: str
	@param bakeWrist: Bake wrist animation
	@type bakeWrist: bool
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
    # ==========
    # - Checks -
    # ==========

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

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

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

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

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

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

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

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

    # Delete Duplicate Joints and Constraints
    if fkOriList:
        try:
            mc.delete(fkOriList)
        except Exception, e:
            print('Error deleting nodes ' + str(fkOriList) +
                  '! Exception Msg: ' + str(e))
예제 #38
0
def update(bake=False):
    def namespaced(n):
        return '%s:%s' % (name_space, n)

    cmds.currentUnit(time='pal')
    if not f.exists(scene_check_joints):
        exit_message = 'Not all joints from %s present in scene' % scene_check_joints
        sys.exit(exit_message)
    # Imports file in scene with a given name space
    import_file = cmds.fileDialog2(dialogStyle=2, fm=1)[0]
    name_space = os.path.basename(import_file).split('.')[0] + '_namespace'
    cmds.file(import_file, i=True, namespace=name_space)
    # Delete animation from joints in Biped hierarchy
    cmds.currentTime(0)
    cmds.select(f.get_joints())
    cmds.cutKey()
    # Exports skin cluster weights for body meshes in scene
    all_meshes = f.get_meshes()
    head_meshes = []
    search_pattern_r = '|'.join([sp for sp in search_pattern.split('\n')])
    regex = r"\b.*(%s).*\b" % search_pattern_r

    for m in all_meshes:
        if re.search(regex, m):
            head_meshes.append(m)

    body_meshes = [m for m in all_meshes if m not in head_meshes]
    if body_meshes:
        cmds.select(body_meshes)
        sie.export_weights_sp()

    for sc in cmds.ls(type='skinCluster'):
        cmds.skinCluster(sc, ub=True, edit=True)

    # Deletes bind poses in scene
    cmds.delete(cmds.ls(type='dagPose'))
    # Checks if scene joints are scaled
    length = f.get_length(f.get_pos(length_joints[0]),
                          f.get_pos(length_joints[1]))
    imported_length = f.get_length(f.get_pos(namespaced(length_joints[0])),
                                   f.get_pos(namespaced(length_joints[1])))
    scale_factor = length / imported_length
    if round(scale_factor, 0) != 1:
        scaled_joints_group = cmds.group(namespaced(root_joint))
        cmds.xform(scaled_joints_group,
                   scale=(scale_factor, scale_factor, scale_factor))
    # Aligns imported skeleton to the one in scene
    # All created constraints will be deleted alongside with imported mesh later
    cmds.pointConstraint(head_joint, namespaced(head_joint))
    head_children_joints = cmds.listRelatives(head_joint,
                                              ad=True,
                                              type='joint')
    head_children_joints = filter_nubs(head_children_joints)

    for j in head_children_joints:
        if f.exists(namespaced(j)):
            f.unlock_attributes(j)
            cmds.pointConstraint(namespaced(j), j)
            cmds.orientConstraint(namespaced(j), j)

    # Keys all biped joints to prevent joints shift
    if bake:
        # Gets information about keyed range of imported bones
        ns_biped = [
            namespaced(j) for j in f.get_joints() if f.exists(namespaced(j))
        ]
        imported_biped_keys = cmds.keyframe(ns_biped,
                                            query=True,
                                            timeChange=True)
        ns_min, ns_max = min(imported_biped_keys), max(imported_biped_keys)
        cmds.bakeResults(f.get_joints(), time=(ns_min, ns_max + 1), sm=True)
        cmds.playbackOptions(min=ns_min, max=ns_max + 1)
    else:
        cmds.setKeyframe(f.get_joints(), time=0)
    cmds.namespace(removeNamespace=name_space, deleteNamespaceContent=True)
    # Imports all skin cluster weights for meshes in scene
    cmds.select(f.get_meshes())
    sie.import_weights_sp()
    # Fix eyes joints pivot.
    # When bones are imported from another character
    sy = batch_skin_eyes.SkinEyes()
    sy.set_skin()
예제 #39
0
            if not '_Plot' in o:
                sNull = NamespaceToggle(o)

                if not cmds.objExists(sNull):
                    cmds.spaceLocator(name=sNull)

    for s in aPlotList:

        sNull = NamespaceToggle(s)
        sConst = sNull + 'Const'

        cmds.parentConstraint(s, sNull, weight=1, n='TempConst')

        cmds.refresh(su=True)

        cmds.bakeResults(sNull, t=(iIn, iOut), simulation=True)
        cmds.delete('TempConst')

        cmds.refresh(su=False)

        ApplyConst(sNull, s)

    cmds.select(cl=True)
    restoreLayout('Custom_AnimWithCam')

elif K == 13:  # Ctl + Alt + Shift # Special Plot
    if not oSel:
        cmds.warning(' Please Select an obj first.')
    else:
        oCamera = ''
        oPanel = cmds.getPanel(wf=True)
예제 #40
0
def limbsIkToFkOLD(rigNS, start=None, end=None, sampleBy=1):
    '''
	Bake IK limb animation to FK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
    # ==========
    # - Checks -
    # ==========

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

    # ==========================
    # - Build IK/FK Joint List -
    # ==========================

    ikJntList = []
    fkJntList = []

    index = ['A', 'B']
    sides = ['lf', 'rt']
    for side in sides:
        if not mc.getAttr(rigNS + ':config.' + side + 'ArmIkFkBlend'):
            #ikJntList += [rigNS+':'+side+'_arm_ik'+i+'_jnt' for i in index]
            #fkJntList += [rigNS+':'+side+'_arm_fk'+i+'_jnt' for i in index]

            armIkToFk(rigNS, side, True, start, end, sampleBy)

        if not mc.getAttr(rigNS + ':config.' + side + 'LegIkFkBlend'):
            #ikJntList += [rigNS+':'+side+'_leg_ik'+i+'_jnt' for i in index]
            #fkJntList += [rigNS+':'+side+'_leg_fk'+i+'_jnt' for i in index]
            #ikJntList += [rigNS+':'+side+'_foot_ik'+i+'_jnt' for i in index]
            #fkJntList += [rigNS+':'+side+'_foot_fk'+i+'_jnt' for i in index]

            legIkToFk(rigNS, side, start, end, sampleBy)

    # Check IK/FK State
    if not fkJntList:
        print('Limbs already in FK mode! Nothing to do...')
        return fkJntList

    # ====================================
    # - Bake Wrist Animation to Locators -
    # ====================================

    # Build Wrist Duplicates for Baking
    wristJnts = [rigNS + ':' + side + '_handA_jnt' for side in sides]
    wristDups = [mc.duplicate(jnt, po=True)[0] for jnt in wristJnts]
    keys = mc.copyKey(wristJnts, at=['rx', 'ry', 'rz'], t=(start, end))
    if keys:
        mc.pasteKey(wristDups,
                    at=['rx', 'ry', 'rz'],
                    t=(start, end),
                    option='replace')

    # Bake Wrists to Locators
    wristLocs = glTools.anim.utils.bakeAnimToLocators(
        objList=wristJnts,
        start=start,
        end=end,
        sampleBy=sampleBy,
        simulation=True,
        attrList=['rx', 'ry', 'rz'])

    # =======================
    # - Bake Limb Animation -
    # =======================

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

    # Transfer Baked Anim to FK Joints
    mc.refresh(suspend=True)
    for i in range(len(fkDupList)):
        mc.bakeResults(fkDupList[i],
                       t=(start, end),
                       at=['rx', 'ry', 'rz'],
                       simulation=True,
                       preserveOutsideKeys=True,
                       sampleBy=sampleBy)

    # Transfer Keys
    for i in range(len(fkDupList)):
        keys = mc.copyKey(fkDupList[i], at=['rx', 'ry', 'rz'], t=(start, end))
        if keys:
            mc.pasteKey(fkJntList[i],
                        at=['rx', 'ry', 'rz'],
                        t=(start, end),
                        option='replace')

    mc.refresh(suspend=False)

    # Delete Duplicate Joints and Constraints
    if fkOriList:
        try:
            mc.delete(fkOriList)
        except Exception, e:
            print('Error deleting nodes ' + str(fkOriList) +
                  '! Exception Msg: ' + str(e))
예제 #41
0
import maya.cmds as cmds
예제 #42
0
    def overlap(self):
        NotUseFirstCtrl = self.First_CB.isChecked()
        CycleCheckBox = self.Cycle_CB.isChecked()
        TRANSLATEmode = self.Translate_CB.isChecked()
        OnLayerSwitch = self.Bake_CB.isChecked()

        WindSwitch = self.Wind_CB.isChecked()
        windScaleValue = self.Wind_Scale_SP.value()
        windSpeedValue = self.Wind_Speed_SP.value()

        overlapIntensity = self.Scale_SP.value()
        timeShift = self.Softness_SP.value()
        timeStart = cmds.playbackOptions(q=1, min=1)
        timeEnd = cmds.playbackOptions(q=1, max=1)

        controller_list = cmds.ls(sl=1)

        # NOTE 生成骨骼 | 调整轴向
        cmds.select(cl=1)
        jnt_list = []
        _jnt = None
        for controller in controller_list:
            pos = cmds.xform(controller, q=1, rp=1, ws=1)
            jnt = cmds.joint(p=pos, rad=1, n="%s_OverlapJoint" % controller)
            if _jnt:
                cmds.joint(_jnt, e=1, zso=1, oj="xyz", sao="yup")
            jnt_list.append(jnt)
            _jnt = jnt
        else:
            last_jnt = cmds.duplicate(jnt,
                                      rr=1,
                                      n="%s_LastOrientJoint" % controller)[0]
            cmds.move(2, 0, 0, r=1, ls=1, wd=1)
            cmds.parent(last_jnt, jnt)
            jnt_list.append(last_jnt)
            cmds.joint(jnt, e=1, zso=1, oj="xyz", sao="yup")

            sumLenghtJoints = sum(
                [cmds.getAttr("%s.tx" % jnt) for jnt in jnt_list])
            averageLenghtJoints = (sumLenghtJoints - 2) / len(jnt_list)
            cmds.setAttr(last_jnt + ".tx", averageLenghtJoints)

        constraint_list = []
        for controller, jnt in zip(controller_list, jnt_list):
            constraint_list.extend(cmds.parentConstraint(controller, jnt,
                                                         mo=1))

        # NOTE 烘焙骨骼跟随控制器的关键帧
        cmds.bakeResults(
            jnt_list,
            simulation=1,  # NOTE 开启模拟 解决卡顿问题
            t=(timeStart, timeEnd),
            sampleBy=1,
            oversamplingRate=1,
            disableImplicitControl=1,
            preserveOutsideKeys=1,
            sparseAnimCurveBake=0,
            removeBakedAttributeFromLayer=0,
            removeBakedAnimFromLayer=0,
            bakeOnOverrideLayer=0,
            minimizeRotation=1,
            at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

        cmds.delete(constraint_list)

        if CycleCheckBox:
            # NOTE 将骨骼关键帧复制多几份
            for i, jnt in enumerate(jnt_list):
                cmds.selectKey(cmds.listConnections(jnt + ".tx",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".ty",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".tz",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".rx",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".ry",
                                                    type="animCurve"),
                               cmds.listConnections(jnt + ".rz",
                                                    type="animCurve"),
                               r=1,
                               k=1,
                               t=(timeStart, timeEnd))
                cmds.copyKey()
                cmds.pasteKey(time=(timeEnd, timeEnd),
                              float=(timeEnd, timeEnd),
                              option="insert",
                              copies=2,
                              connect=0,
                              timeOffset=0,
                              floatOffset=0,
                              valueOffset=0)

            cycleLenghts = timeEnd - timeStart
            timeEnd = timeEnd + 2 * cycleLenghts

        # NOTE 进行 overlap
        overlapIntensityMult = averageLenghtJoints / overlapIntensity * 5
        timeShiftNeg = -timeShift
        timeShiftCurrent = 1 + timeShift

        gc_list = []
        aim_data = {}
        for i, jnt in enumerate(jnt_list):

            offset_loc = cmds.spaceLocator(n="overlapOffsetLocator%s" % i)[0]
            cmds.delete(cmds.parentConstraint(jnt, offset_loc, w=1))

            cmds.move(overlapIntensityMult, 0, 0, r=1, os=1, ls=1)
            con = cmds.parentConstraint(jnt, offset_loc, mo=1)

            cmds.bakeResults(offset_loc,
                             simulation=0,
                             t=(timeStart, timeEnd),
                             sampleBy=1,
                             disableImplicitControl=1,
                             preserveOutsideKeys=1,
                             minimizeRotation=1,
                             at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

            cmds.delete(con)

            wind_loc = cmds.spaceLocator(n="overlapOffsetLocatorWind%s" % i)[0]
            gc_list.append(wind_loc)
            cmds.parent(wind_loc, offset_loc)
            cmds.makeIdentity(wind_loc, a=0, t=1, r=1, s=1, n=0, pn=1)

            animCurve_list = [
                (offset_loc + "_translateX"),
                (offset_loc + "_translateY"),
                (offset_loc + "_translateZ"),
                (offset_loc + "_rotateX"),
                (offset_loc + "_rotateY"),
                (offset_loc + "_rotateZ"),
            ]

            for animCurve in animCurve_list:
                cmds.keyframe(animCurve,
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=timeShift)
                cmds.keyframe(animCurve,
                              t=(timeShiftCurrent, timeShiftCurrent),
                              option="over",
                              relative=1,
                              timeChange=timeShiftNeg)

            aim_loc = cmds.spaceLocator(n="overlapInLocator_aim_%s" % i)[0]

            aim_grp = cmds.group(aim_loc, n=aim_loc + "_grp")
            cmds.pointConstraint(jnt, aim_grp)
            aim_data[aim_loc] = aim_grp

            cmds.aimConstraint(wind_loc,
                               aim_grp,
                               aimVector=[1, 0, 0],
                               upVector=[0, 1, 0],
                               worldUpType="object",
                               worldUpObject=wind_loc)
            cmds.orientConstraint(wind_loc,
                                  aim_loc,
                                  mo=1,
                                  skip=["y", "z"],
                                  w=1)

            # NOTE 添加控制器 translate 坐标位移
            if TRANSLATEmode and i != len(jnt_list) - 1:
                IK_loc = cmds.spaceLocator(n="overlapOffsetIKLocator%s" % i)[0]
                cmds.pointConstraint(jnt, IK_loc)
                cmds.bakeResults(IK_loc,
                                 simulation=0,
                                 t=(timeStart, timeEnd),
                                 sampleBy=1,
                                 disableImplicitControl=1,
                                 preserveOutsideKeys=1,
                                 minimizeRotation=1,
                                 at=['tx', 'ty', 'tz'])
                animCurve_list = [
                    (IK_loc + "_translateX"),
                    (IK_loc + "_translateY"),
                    (IK_loc + "_translateZ"),
                ]
                for animCurve in animCurve_list:
                    cmds.keyframe(animCurve,
                                  e=1,
                                  iub=1,
                                  r=1,
                                  o="over",
                                  tc=timeShift)
                    cmds.keyframe(animCurve,
                                  t=(timeShiftCurrent, timeShiftCurrent),
                                  option="over",
                                  relative=1,
                                  timeChange=timeShiftNeg)

                cmds.pointConstraint(IK_loc, aim_loc)
                gc_list.append(IK_loc)

            # NOTE 添加随机风向控制
            if WindSwitch:
                windMultiply = 0.07 * overlapIntensityMult * windScaleValue
                speedMultiply = 20 / windSpeedValue

                cmds.setKeyframe(wind_loc,
                                 attribute=['translateY', 'translateZ'],
                                 t=[timeStart, timeStart])

                cmds.bakeResults(wind_loc,
                                 simulation=0,
                                 t=(timeStart, timeEnd + speedMultiply),
                                 sampleBy=speedMultiply,
                                 oversamplingRate=1,
                                 disableImplicitControl=1,
                                 preserveOutsideKeys=1,
                                 at=['ty', 'tz'])

                for attr in cmds.listAttr(wind_loc, k=1):
                    animCurve = cmds.listConnections("%s.%s" %
                                                     (wind_loc, attr),
                                                     type="animCurve")
                    if not animCurve:
                        continue
                    for animCurveCurrent in animCurve:
                        for animCurveCurrentKeysTime in cmds.keyframe(
                                animCurveCurrent,
                                q=1,
                                t=(timeStart, timeEnd),
                                tc=1):
                            t = (animCurveCurrentKeysTime,
                                 animCurveCurrentKeysTime)
                            animCurveCurrentKeysTimeArray = cmds.keyframe(
                                animCurveCurrent, q=1, time=t, vc=1)
                            RandomizerValue = random.random() * 2 - 1
                            animCurveCurrentKeysValueArrayAddRandom = animCurveCurrentKeysTimeArray[
                                0] + windMultiply * RandomizerValue
                            cmds.keyframe(
                                animCurveCurrent,
                                e=1,
                                iub=1,
                                r=1,
                                o="over",
                                vc=animCurveCurrentKeysValueArrayAddRandom,
                                t=t)

                attr = (wind_loc + "_translateY")
                cmds.keyframe(attr,
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=speedMultiply / 2)
                t = (speedMultiply / 2) + 1
                cmds.selectKey(attr, add=1, k=1, t=(t, t))
                cmds.keyframe(attr,
                              animation="keys",
                              r=1,
                              o="over",
                              tc=speedMultiply / -2)

            cmds.bakeResults(aim_grp,
                             aim_loc,
                             simulation=0,
                             t=(timeStart, timeEnd),
                             sampleBy=1,
                             disableImplicitControl=1,
                             preserveOutsideKeys=1,
                             minimizeRotation=1,
                             at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

            cmds.parentConstraint(aim_loc, jnt, mo=1)

            gc_list.append(offset_loc)
            gc_list.append(aim_grp)

        # NOTE 动画循环控制
        if CycleCheckBox:
            timeStart = cmds.playbackOptions(q=1, min=1)
            timeEnd = cmds.playbackOptions(q=1, max=1)
            cycleLenghts = timeEnd - timeStart
            # NOTE 将关键帧挪动回去两个时间范围
            for aim_loc, aim_grp in aim_data.items():
                cmds.keyframe(cmds.listConnections(aim_loc + ".tx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".ty",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".tz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".rx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".ry",
                                                   type="animCurve"),
                              cmds.listConnections(aim_loc + ".rz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".tx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".ty",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".tz",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".rx",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".ry",
                                                   type="animCurve"),
                              cmds.listConnections(aim_grp + ".rz",
                                                   type="animCurve"),
                              e=1,
                              iub=1,
                              r=1,
                              o="over",
                              tc=cycleLenghts * -2)

        constraint_list = []
        for i, [controller, jnt] in enumerate(zip(controller_list, jnt_list)):
            if NotUseFirstCtrl and i == 0:
                continue
            if cmds.getAttr(controller+".tx",k=1) and not cmds.getAttr(controller+".tx",l=1) and \
               cmds.getAttr(controller+".ty",k=1) and not cmds.getAttr(controller+".ty",l=1) and \
               cmds.getAttr(controller+".tz",k=1) and not cmds.getAttr(controller+".tz",l=1):
                constraint_list.extend(
                    cmds.pointConstraint(jnt, controller, mo=1))
            if cmds.getAttr(controller+".rx",k=1) and not cmds.getAttr(controller+".rx",l=1) and \
               cmds.getAttr(controller+".ry",k=1) and not cmds.getAttr(controller+".ry",l=1) and \
               cmds.getAttr(controller+".rz",k=1) and not cmds.getAttr(controller+".rz",l=1):
                constraint_list.extend(
                    cmds.orientConstraint(jnt, controller, mo=1))

        if NotUseFirstCtrl:
            controller_list = controller_list[1:]

        # NOTE 输出到控制器上
        cmds.bakeResults(
            controller_list,
            simulation=1,  # NOTE 开启模拟 解决卡顿问题
            t=(timeStart, timeEnd),
            sampleBy=1,
            disableImplicitControl=1,
            bakeOnOverrideLayer=OnLayerSwitch,
            preserveOutsideKeys=1,
            minimizeRotation=1,
            at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])

        cmds.delete(constraint_list)
        cmds.delete(jnt_list)
        cmds.delete(gc_list)
예제 #43
0
def CreateOptimizedSkeletonOnlyAndRetargetAnim(bFilterCurves=True,
                                               inBeepAfterComplete=True):
    print 'Starting skeleton optimization'
    start = time.clock()
    cmds.currentTime(0, edit=True)  #set skeleton to 'reference' position

    dazUtils.RemoveObjectsByWildcard(['Fingernails_*'], 'transform')
    dazUtils.RemoveObjectsByWildcard(['HazardFemaleGenitalia_*Shape'],
                                     'transform')

    mayaUtils.ParentAllGeometryToWorld()

    primaryMesh = mayaUtils.FindMeshByWildcard('Genesis8*',
                                               preferShapeWithMaxVertices=True,
                                               checkForMatWithName='Torso')

    if primaryMesh:
        cmds.select(primaryMesh)
    else:
        cmds.select(all=True)

    mel.eval('gotoBindPose')
    cmds.select(clear=True)

    #delete all meshes
    shapesToDelete = mayaUtils.GetMultipleShapesTransforms(
        cmds.ls(geometry=True, objectsOnly=True))
    if shapesToDelete:
        for s in shapesToDelete:
            cmds.delete(s)
            print 'Deleting {0}'.format(s)

    dazUtils.RenameSkeletonJoints()
    oldJoints = mayaUtils.GetHierarchy('root')

    dazUtils.DuplicateSkeletonJoints('root', 'DAZ_')

    dazUtils.FixNewJointsOrientation()
    dazUtils.RecreateHierarchy('root', 'DAZ_')
    dazUtils.JointOrientToRotation('DAZ_root')

    #delete twist joints for animation retargetting/ they are procedurally animated in engine
    unusedJoints = cmds.ls('DAZ_*twist*')
    for j in unusedJoints:
        cmds.delete(j)
        print '\tDeleting {0}'.format(j)

    print 'Renaming OLD skeleton'
    oldJoints = mayaUtils.GetHierarchy('root')
    for j in oldJoints:
        mayaUtils.RenameJoint(j, 'OLD_' + j)

    dazUtils.RenameNewSkeleton()  #remove DAZ_ prefix

    dazUtils.AddNippleJointsAndAimBreast()

    cmds.select(clear=True)
    #create constraint from old skeleton to new
    print 'Creating constraints'
    newJoints = mayaUtils.GetHierarchy('root')

    for j in newJoints:
        oldJoint = 'OLD_' + j
        print '\tCreating parentConstraint from {0} to {1}'.format(oldJoint, j)
        #not all joints can exist on old skeleton (e.g. nipples)
        if cmds.objExists(oldJoint) and cmds.nodeType(oldJoint) == 'joint':
            cmds.parentConstraint(oldJoint, j, maintainOffset=True)

    dazUtils.CreateIkJoints()  #create AFTER constraining new skeleton to old

    # No need to bake IK joints, they are auto baked during exporting to fbx

    print '\n'
    print "\t\t******** BAKING ANIMATION ********"
    print '\n'
    attributesToBake = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz']
    timeRange = (cmds.playbackOptions(animationStartTime=True, query=True),
                 cmds.playbackOptions(animationEndTime=True, query=True))
    print 'timeRange = {0}'.format(timeRange)
    cmds.bakeResults(newJoints,
                     attribute=attributesToBake,
                     time=timeRange,
                     minimizeRotation=True,
                     preserveOutsideKeys=True,
                     simulation=True,
                     disableImplicitControl=True)

    print '\n'
    print "\t\t******** Filtering curves ********"
    print '\n'

    if bFilterCurves:
        animNodes = cmds.listConnections(newJoints, type="animCurve")
        if animNodes:
            print 'Performing filtering for {0} anim curves'.format(
                len(animNodes))
            oldKeysCount = cmds.keyframe(animNodes, q=True, keyframeCount=True)
            cmds.filterCurve(animNodes,
                             filter='simplify',
                             timeTolerance=0.01,
                             tolerance=0.01)
            newKeysCount = cmds.keyframe(animNodes, q=True, keyframeCount=True)
            percent = float(newKeysCount) / float(oldKeysCount) * 100.0
            print '{0} keys filtered to {1} keys ({2:.1f}%)'.format(
                oldKeysCount, newKeysCount, percent)
    else:
        print 'Filtering NOT requested'

    #clean scene after finishing
    print 'Deleting old skeleton'
    cmds.select(clear=True)
    cmds.select(mayaUtils.GetHierarchy('OLD_root'))
    cmds.delete()

    print 'FINISHED animation retargeting: time taken %.02f seconds' % (
        time.clock() - start)
    if inBeepAfterComplete:
        mayaUtils.NotifyWithSound()
예제 #44
0
def positionStart():

    global asT
    asT = cmds.playbackOptions(query=True, min=True)  # Левая граница анимации
    global aeT
    aeT = cmds.playbackOptions(query=True, max=True)  # Правая граница анимации
    resetLoopTime()

    global listObjects
    listObjects = cmds.ls(sl=True)  # Список трансформов

    #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

    global listFixed
    listFixed = listObjects[:]

    for i in range(len(listFixed)):
        listFixed[i] = listFixed[i].replace("|", "_")

    #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

    global mainLayerName
    mainLayerName = "OVERLAPPER"  # Имя главного слоя

    if (cmds.objExists(mainLayerName)):
        print "\n||| OVERLAPPER start |||\n"
    else:
        cmds.animLayer(mainLayerName)
        print "\n||| OVERLAPPER start ||| Layer created |||\n"

    #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

    for i in range(len(listFixed)):  # Основной цикл

        global aimLoc
        aimLoc = listFixed[i] + "_aim_loc"  # Имя аим локатора
        global tempLoc
        tempLoc = listFixed[i] + "_temp_loc"  # Имя физ локатора
        global tempPart
        tempPart = listFixed[i] + "_temp_part"  # Имя физ частицы
        global tempNucl
        tempNucl = "nucleus1"  # Имя физ ноды

        global partAimLoc
        partAimLoc = aimLoc + ".translate"  # Обращение к позиции аим локатора
        global partRtype
        partRtype = tempPart + "Shape.particleRenderType"  # Обращение к типу отображения частицы
        global partRrad
        partRrad = tempPart + "Shape.radius"  # Обращение к размеру частицы
        global partRsm
        partRsm = tempPart + "Shape.goalSmoothness"  # Обращение к мягкости физики
        global partRwe
        partRwe = tempPart + "Shape.goalWeight[0]"  # Обращение к весу ноды
        global partPos
        partPos = tempPart + ".center"  # Обращение к центру частицы
        global partNucl
        partNucl = tempNucl + ".timeScale"  # Обращение к скейлу времени физ ноды
        global nuclStart
        nuclStart = tempNucl + ".startFrame"  # Обращение к старту симуляции физ ноды

        cmds.spaceLocator(n=tempLoc)  # Создаём физ локатор
        cmds.matchTransform(tempLoc, listObjects[i],
                            pos=True)  # Перемещаем локатор в пивот объекта

        objCenter = tempLoc + ".translate"  # Обращение к центру объекта
        objC = cmds.getAttr(objCenter)  # Записываем центр объекта

        locCenter = tempLoc + ".center"  # Обращение к центру физ локатора
        locTr = tempLoc + ".translate"  # Обращение к позиции физ локатора

        cmds.nParticle(p=objC, n=tempPart,
                       c=1)  # Создаём частицу в целевой позиции
        cmds.goal(tempPart, w=goalW, utr=1,
                  g=tempLoc)  # Создаём физическую связь

        cmds.select(tempLoc, r=True)  # Выделяем физ локатор
        cmds.select(listObjects[i], add=True)  # Выделяем целевого родителя
        cmds.parent(r=True)  # Создаём иерархию

        cmds.matchTransform(tempLoc, listObjects[i],
                            pos=True)  # Перемещаем локатор в пивот объекта

        #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        cmds.setAttr(partRtype, pShape)
        cmds.setAttr(partRrad, pRad)
        cmds.setAttr(partRsm, goalSmooth)
        cmds.setAttr(partRwe, goalW)
        cmds.setAttr(partNucl, timeScale)
        cmds.setAttr(nuclStart, asT)

        #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        cmds.duplicate(tempLoc, rr=True, n=aimLoc)  # Дублируем локатор
        cmds.select(aimLoc, r=True)  # Выделяем аим локатор
        cmds.parent(w=True)  # Разбираем иерархию
        cmds.connectAttr(partPos, partAimLoc,
                         f=True)  # Привязываем аим локатор к частице

        global minLoopTime
        minLoopTime = aeT * -2
        global maxLoopTime
        maxLoopTime = aeT * 2

        if (cycle):

            #cmds.playbackOptions (e=True, min=minLoopTime, max=maxLoopTime)
            cmds.setAttr(nuclStart, minLoopTime)
            #setTimeToMin()

            cmds.bakeResults(
                aimLoc, t=(minLoopTime, maxLoopTime), sm=True,
                at="translate")  # Запекание аим локатора для цикла
            cmds.delete(tempLoc, tempPart, tempNucl)  # Удаляем объекты физики
            #cmds.select (aimLoc, r=True) # Выделяем аим локатор
            #cmds.keyframe (tc = (aeT*-2), r=True) # Сдвигаем тройной цикл на один проход влево
            #cmds.setInfinity (pri="cycle", poi="cycle")

            setTimeToMin()

            cmds.select(aimLoc, r=True)  # Выделяем аим локатор как родителя
            cmds.select(listObjects[i],
                        add=True)  # Выделяем объект как подчиненного
            cmds.parentConstraint(mo=True, sr=["x", "y", "z"],
                                  w=1)  # Создаём позиционный констрейн

            resetLoopTime()

        else:

            cmds.bakeResults(
                aimLoc, t=(asT, aeT), sm=True,
                at="translate")  # Запекание аим локатора для линейной анимации
            cmds.delete(tempLoc, tempPart, tempNucl)  # Удаляем объекты физики

            resetLoopTime()

            cmds.select(aimLoc, r=True)  # Выделяем аим локатор как родителя
            cmds.select(listObjects[i],
                        add=True)  # Выделяем объект как подчиненного
            cmds.parentConstraint(mo=True, sr=["x", "y", "z"],
                                  w=1)  # Создаём позиционный констрейн

    #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        layerBase = "overlap_"  # Имя базы слоя
        layerName = layerBase + listFixed[i]  # Имя слоя
        layerComp = listFixed[i] + '_layer_{0}'.format(
            "0")  # Имя компонента слоя

        if (cmds.objExists(layerName)):

            cmds.bakeResults(listObjects[i],
                             t=(asT, aeT),
                             sm=True,
                             bol=True,
                             at="translate")  # Запекаем объект в слой
            cmds.select(listObjects[i], r=True)
            cmds.setInfinity(pri="cycle", poi="cycle")
            cmds.delete(aimLoc)  # Удаляем объекты скрипта
            cmds.container("BakeResultsContainer", e=True,
                           rc=True)  # Удаляем контейнер
            cmds.animLayer(
                "BakeResults", e=True, p=layerName
            )  # Переносим слой с анимацией в основной слой объекта
            cmds.rename("BakeResults", layerComp)  # Переименовываем слой

            resetLoopTime()
        else:
            cmds.animLayer(
                layerName)  # Создаём пустой слой для всех оверлапов объекта
            cmds.animLayer(
                layerName, e=True,
                p=mainLayerName)  # Переносим базу слоя в главный слой
            cmds.bakeResults(listObjects[i],
                             t=(asT, aeT),
                             sm=True,
                             bol=True,
                             at="translate")  # Запекаем объект в слой
            cmds.select(listObjects[i], r=True)
            cmds.setInfinity(pri="cycle", poi="cycle")
            cmds.delete(aimLoc)  # Удаляем объекты скрипта
            cmds.container("BakeResultsContainer", e=True,
                           rc=True)  # Удаляем контейнер
            cmds.animLayer(
                "BakeResults", e=True, p=layerName
            )  # Переносим слой с анимацией в основной слой объекта
            cmds.rename("BakeResults", layerComp)  # Переименовываем слой

            resetLoopTime()

        cmds.select(d=True)  # Деселект

    for l in listObjects:
        cmds.select(l, add=True)

    print "\n||| OVERLAPPER end |||\n"
예제 #45
0
    def Constraints(self, *args):
        # creat a loc
        # creat constrain rootM to loc, all
        # bake anim for loc
        # rootm --> parent -w
        # rootm delete keyfarme
        # creat constrain loc to root ,tx,tz, rz
        # parent(rootm, root)
        # creat constrain loc to root ,all

        # startNum = cmds.playbackOptions(q = True , ast = True)
        # endNum = cmds.playbackOptions(q = True , aet = True)

        # returnMess = cmds.confirmDialog( title='Confirm', message='烘焙时间轴为' + str(startNum) + '-' + str(endNum), button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
        # if returnMess == "No":
        #     return
        startNum = cmds.intFieldGrp("StartFrame", q=True, value1=True)
        endNum = cmds.intFieldGrp("EndFrame", q=True, value1=True)
        cmds.currentUnit(time='ntsc', linear='centimeter')
        cmds.currentTime(startNum)

        locPos = cmds.spaceLocator()
        cmds.parentConstraint('Root_M', locPos, mo=True)

        cmds.bakeResults(locPos,
                         simulation=True,
                         t=(startNum, endNum),
                         hierarchy="below",
                         sb=1,
                         dic=True,
                         pok=True,
                         ral=False,
                         rwl=False,
                         cp=True)

        cmds.parent('Root_M', world=True)
        keyframelist = cmds.ls(type='animCurveTL') + cmds.ls(
            type='animCurveTA') + cmds.ls(type='animCurveTU')
        for i in keyframelist:
            if not ('Root_M' not in i):
                cmds.delete(i)

        t = cmds.checkBoxGrp("translateAxes", q=True, value2=True)
        if t:
            trans = []
        else:
            trans = ["y"]

        r = cmds.checkBoxGrp("rotateAxes", q=True, value2=True)
        if r:
            rot = ["x", "z"]
        else:
            rot = ["x", "y", "z"]

        parentConA = cmds.parentConstraint(locPos,
                                           'Root',
                                           st=trans,
                                           sr=rot,
                                           mo=True)
        cmds.bakeResults('Root',
                         simulation=True,
                         t=(startNum, endNum),
                         hierarchy="below",
                         sb=1,
                         dic=True,
                         pok=True,
                         ral=False,
                         rwl=False,
                         cp=True)
        cmds.delete(parentConA)

        cmds.parent('Root_M', 'Root')
        parentConB = cmds.parentConstraint(locPos, 'Root_M', mo=True)
        cmds.bakeResults('Root_M',
                         simulation=True,
                         t=(startNum, endNum),
                         hierarchy="below",
                         sb=1,
                         dic=True,
                         pok=True,
                         ral=False,
                         rwl=False,
                         cp=True)
        cmds.delete(parentConB)
        cmds.delete(locPos)
예제 #46
0
def Bake(assets, bakeSetName = 'bakeSet',
         startFrame = None,
         endFrame = None):
    _str_func = 'Bake'
    
    if startFrame is None:
        startFrame =  mc.playbackOptions(q=True, min=True)
    if endFrame is None:
        endFrame =  mc.playbackOptions(q=True, max=True)
        
    
    baked = False

    #if(mc.optionVar(exists='cgm_bake_set')):
        #bakeSetName = mc.optionVar(q='cgm_bake_set')

    # set tangent options to spline
    currentTangent = mc.keyTangent( q=True, g=True, ott=True )[0]
    mc.keyTangent( g=True, ott="spline" )
    
    #Eval mode ----
    _evalMode = mc.evaluationManager(q=True, mode=True)
    mc.evaluationManager(mode='off')
    
    bakeTransforms = []
    bakeSets = []

    currentTime = mc.currentTime(q=True)
    log.debug("{0} ||currentTime: {1}".format(_str_func,currentTime))

    for asset in assets:
        #if ':' in assets:
        log.debug("{0} || asset: {1}".format(_str_func,asset))
        
        topNodeSN = asset.split(':')[-1]

        # gather data
        namespaces = asset.split(':')[:-1]

        if len(namespaces) > 0:
            ns = ':'.join( asset.split(':')[:-1] ) + ':'
        else:
            ns = "%s_" % asset.split('|')[-1]
        
        # bake
        bakeSet = "%s%s" % (ns, bakeSetName)
        if mc.objExists(bakeSet):
            if bakeSet not in bakeSets:
                bakeSets.append(bakeSet)
                bakeTransforms += mc.sets(bakeSet, q=True)
        else:
            bakeTransforms.append(asset)
        #else:
        #    bakeTransforms.append(asset)
        log.debug("{0} || bakeSet: {1}".format(_str_func,bakeSet))

    if len(bakeTransforms) > 0:
        log.debug("{0} || baking transforms".format(_str_func))
        
        #pprint.pprint(bakeTransforms)
        log.debug("{0} || time | start: {1} | end: {2}".format(_str_func,startFrame,endFrame))
        
        mc.bakeResults( bakeTransforms, 
                        simulation=True, 
                        t=( startFrame, endFrame), 
                        sampleBy=1, 
                        disableImplicitControl=True,
                        preserveOutsideKeys = False, 
                        sparseAnimCurveBake = False,
                        removeBakedAttributeFromLayer = False, 
                        removeBakedAnimFromLayer = True, 
                        bakeOnOverrideLayer = False, 
                        minimizeRotation = True, 
                        controlPoints = False, 
                        shape = True )

        mc.setInfinity(bakeTransforms, pri='constant', poi='constant')

        baked = True
    else:
        baked = False

    mc.keyTangent( g=True, ott=currentTangent )

    #eval mode restore ----
    if _evalMode[0] != 'off':
        print "Eval mode restored: {0}".format(_evalMode[0])
        mc.evaluationManager(mode = _evalMode[0])

    mc.currentTime(currentTime)

    return baked
예제 #47
0
    rot = cmds.xform(obj, q=1, ws=1, ro=1)
    scl = cmds.xform(obj, q=1, ws=1, s=1)

    try:
        locName = obj.partition("_obj")[0] + "_LOC_%i" % x
    except:
        pass

    print
    "%s --->%s" % (locName, obj)

    # create a locator at obj pivot
    loc = cmds.spaceLocator(n=locName)
    cmds.xform(loc, ws=1, t=trans)
    cmds.xform(loc, ws=1, ro=rot)
    cmds.xform(loc, ws=1, s=scl)
    print
    loc
    locList.append(loc[0])

    # parent constrain the each loc to the object
    pc = cmds.parentConstraint(obj, loc, mo=1)
    pcList.append(pc)

cmds.select(cl=1)
cmds.select(locList, r=True)
cmds.bakeResults(sm=1, t=(startF, endF))

for pc in pcList:
    cmds.delete(pc)
예제 #48
0
def copy_bake_camera(cam, replace_cam=False):
    # camName = cam
    camShape = cmds.listRelatives(cam, typ='camera')[0]
    garbages = []
    keyables = cmds.listAttr(cam, camShape, keyable=True)
    keyables += cmds.listAttr(cam, st=['rotateOrder', '*Pivot*'])
    # roMapping = ('xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx')
    # roCurrent = roMapping[cmds.getAttr(cam + '.rotateOrder')]
    # roIndex = roMapping.index(roGiven)
    parents = cmds.listRelatives(cam, parent=True, fullPath=True)
    # copy camera and cleanup children
    dup_cam = cmds.duplicate(cam, name=cam + '_baked', returnRootsOnly=True)[0]
    childs = cmds.listRelatives(dup_cam,
                                children=True,
                                typ='transform',
                                fullPath=True)
    if childs:
        cmds.delete(childs)
    # unlock new camera
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # parent attrs may also have been locked somehow...
    for attr in 'trs':
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # unparent and cleanup pivots
    if parents:
        dup_cam = cmds.parent(dup_cam, w=True)[0]
    cmds.xform(dup_cam, zeroTransformPivots=True)
    cmds.makeIdentity(dup_cam,
                      apply=True,
                      translate=True,
                      rotate=True,
                      scale=True)
    # contraint new camera to original one and set rotateOrder
    garbages.extend(cmds.parentConstraint(cam, dup_cam, maintainOffset=True))
    # cmds.setAttr(dup_cam + '.rotateOrder', roIndex)
    # connect imagePlane to dup_cam
    imagePlane = cmds.imagePlane(cam, q=True, name=True)
    if imagePlane:
        imagePlane = imagePlane[0]
        cmds.imagePlane(imagePlane, detach=True, edit=True)
        cmds.imagePlane(camera=dup_cam, edit=True)
    # copy focal animation if exist
    if cmds.copyKey(cam, at='fl'):
        cmds.pasteKey(dup_cam, at='fl')
    # cleanup old camera
    if replace_cam:
        # check existence
        existing = cmds.ls(cam)
        if existing:
            # if cmds.confirmDialog(message='%s already exists, do you want to replace it?' %
            #         cam, button=['Yes', 'No'], defaultButton='Yes', cancelButton='No', dismissString='No') == 'Yes':
            garbages.extend(existing)

    # unlock camera
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=False)
    # make sure the curves on camera continue on for motion blur
    time_range = get_time_range_in_slider()
    cmds.bakeResults(dup_cam, t=time_range)
    cmds.delete(dup_cam, staticChannels=True)
    cmds.filterCurve(dup_cam)
    cmds.keyTangent(dup_cam, itt='spline', ott='spline')
    # master.extendKeyframes([dup_cam])
    # cleanup garbages
    if garbages:
        cmds.delete(garbages)
        while parents:
            if not cmds.listConnections(parents[0]) \
                    and not cmds.listRelatives(parents[0], children=True):
                parent = parents[0]
                parents = cmds.listRelatives(parent,
                                             parent=True,
                                             fullPath=True)
                cmds.delete(parent)
            else:
                break
    # set key at startFrame if attr has no animation
    for attr in cmds.listAttr(dup_cam,
                              camShape,
                              keyable=True,
                              st=['translate*', 'rotate*', 'focalLength']):
        if not cmds.listConnections(dup_cam + '.' + attr, destination=False):
            cmds.setKeyframe(dup_cam,
                             itt='spline',
                             ott='spline',
                             attribute=attr,
                             t=time_range[0])
    # set scale and visibility
    for attr in cmds.listAttr(dup_cam,
                              keyable=True,
                              st=['scale*', 'visibility']):
        cmds.delete(dup_cam + '.' + attr, icn=True)
        cmds.setAttr(dup_cam + '.' + attr, 1)
    # set camera clip range
    l_objs = cmds.ls(typ='mesh')
    l_objs.append(dup_cam)
    l_bbox = cmds.exactWorldBoundingBox(l_objs)
    maxDist = math.sqrt((l_bbox[3] - l_bbox[0])**2 +
                        (l_bbox[4] - l_bbox[1])**2 +
                        (l_bbox[5] - l_bbox[2])**2)
    farClip = math.ceil(maxDist) * 2
    nearClip = 0.1
    cmds.setAttr(dup_cam + '.farClipPlane', farClip)
    cmds.setAttr(dup_cam + '.nearClipPlane', nearClip)
    # lock attributes
    for attr in keyables:
        cmds.setAttr(dup_cam + '.' + attr, lock=True)
    # look through cam and rename
    # pane = cmds.playblast(activeEditor=True)
    # pane = pane if not pane.count('|') else pane.split('|')[-1]
    # cmds.modelPanel(pane, e=True, camera=dup_cam)
    # camName = cmds.rename(cam, camName)
    # # create motion trail
    # if cmds.menuItem(master.ui['mtrailCB'], q=True, checkBox=True):
    #     if not cmds.listConnections(camName, t='snapshot', d=True):
    #         l_cameraPath = cmds.snapshot(camName,
    #                                      ch=True,
    #                                      st=master.getStartFrame(),
    #                                      et=master.getEndFrame(),
    #                                      motionTrail=True)
    #         camPath = cmds.rename(l_cameraPath[0], camName + '_path')
    #         if cmds.objExists('|layout|misc'):
    #             cmds.parent(camPath, '|layout|misc')
    # # cleanup horizon line
    # curves = cmds.ls('horizon*', exactType='transform')
    # for c in curves:
    #     if cmds.attributeQuery('camera', node=c, exists=True) and not cmds.listConnections(c + '.camera'):
    #         cmds.delete(c)
    # # create horizon line
    # plugs = cmds.listConnections(camName + '.message', plugs=True, d=True)
    # if not plugs or not any(i.endswith('.camera') for i in plugs):
    #     if cmds.menuItem(master.ui['horizonRenderCB'], query=True, checkBox=True):
    #         horizon = cmds.polyCylinder(radius=1, height=1,
    #                                     name='horizon_mesh1',
    #                                     subdivisionsX=50, subdivisionsY=5, subdivisionsZ=0,
    #                                     axis=(0, 1, 0), createUVs=False, constructionHistory=False)[0]
    #         cmds.delete(horizon + '.f[250:251]')
    #         cmds.addAttr(horizon, longName='depth', attributeType='double', minValue=0.1, defaultValue=1)
    #         cmds.setAttr(horizon + '.depth', keyable=True)
    #         cmds.expression(o=horizon, name=horizon + '_expr',
    #                         string=('sx = sz = depth;'
    #                                 'sy = (20/defaultResolution.height)'
    #                                 '* (%s.verticalFilmAperture*depth/%s.focalLength);' % (camName, camName)))
    #         setupHorizon(horizon, camName)
    #     if cmds.menuItem(master.ui['horizonCB'], query=True, checkBox=True):
    #         horizon = cmds.circle(normal=(0, 1, 0),
    #                               name='horizon_curve1',
    #                               constructionHistory=False)[0]
    #         setupHorizon(horizon, camName)

    return dup_cam
예제 #49
0
def rotationStart():

    global asT
    asT = cmds.playbackOptions(query=True, min=True)  # Левая граница анимации
    global aeT
    aeT = cmds.playbackOptions(query=True, max=True)  # Правая граница анимации
    resetLoopTime()

    global listObjects
    listObjects = cmds.ls(sl=True)  # Список трансформов

    if (len(listObjects) <= 1):

        print "\n||| Need to select two or more objects |||\n"

    else:

        #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        global listFixed
        listFixed = listObjects[:]

        for i in range(len(listFixed)):
            listFixed[i] = listFixed[i].replace("|", "_")

        #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        global mainLayerName
        mainLayerName = "OVERLAPPY"  # Имя главного слоя

        if (cmds.objExists(mainLayerName)):
            print "\n||| OVERLAPPY start |||\n"
        else:
            cmds.animLayer(mainLayerName)
            print "\n||| OVERLAPPY start ||| Layer created |||\n"

        #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

        for i in range(len(listFixed)):  # Основной цикл

            if (i + 1 != len(listFixed)):

                global zeroLoc
                zeroLoc = listFixed[i] + "_base_loc"  # Имя нулевого локатора
                global aimLoc
                aimLoc = listFixed[i] + "_aim_loc"  # Имя следящего локатора
                global tempLoc
                tempLoc = listFixed[i] + "_temp_loc"  # Имя физического локатора
                global tempAimLoc
                tempAimLoc = listFixed[
                    i] + "_tempAim_loc"  # Имя целевого локатора

                global tempPart
                tempPart = listFixed[i] + "_temp_part"  # Имя частицы
                global tempNucl
                tempNucl = "nucleus1"  # Имя физической ноды

                global partRtype
                partRtype = tempPart + "Shape.particleRenderType"  # Обращение к типу отображения частицы
                global partRrad
                partRrad = tempPart + "Shape.radius"  # Обращение к размеру частицы
                global partRsm
                partRsm = tempPart + "Shape.goalSmoothness"  # Обращение к мягкости физики
                global partRwe
                partRwe = tempPart + "Shape.goalWeight[0]"  # Обращение к весу ноды
                global partNucl
                partNucl = tempNucl + ".timeScale"  # Обращение к скейлу времени физ ноды
                global nuclStart
                nuclStart = tempNucl + ".startFrame"  # Обращение к старту симуляции физ ноды

                #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

                cmds.spaceLocator(n=zeroLoc)  # Создаём нулевой локатор
                cmds.spaceLocator(n=aimLoc)  # Создаём следящий локатор
                cmds.spaceLocator(n=tempLoc)  # Создаём физический локатор

                cmds.matchTransform(
                    zeroLoc, listObjects[i], pos=True
                )  # Перемещаем нулевой локатор в пивот главного объекта
                cmds.matchTransform(
                    tempLoc, listObjects[i + 1], pos=True
                )  # Перемещаем физический локатор в пивот целевого объекта

                cmds.select(tempLoc, r=True)  # Выделяем физический локатор
                cmds.duplicate(
                    n=tempAimLoc)  # Дублируем его и создаём целевой локатор

                cmds.select(listObjects[0], r=True)  # Выделяем главный объект
                cmds.select(zeroLoc, add=True)  # Выделяем нулевой локатор
                cmds.parentConstraint(mo=True, w=1)  # Создаём пэрент констрейн

                cmds.select(aimLoc, r=True)  # Выделяем следящий локатор
                cmds.select(zeroLoc, add=True)  # Выделяем нулевой локатор
                cmds.parent(r=True)  # Создаём иерархию

                cmds.select(listObjects[1], r=True)  # Выделяем целевой объект
                cmds.select(tempLoc, add=True)  # Выделяем физический локатор
                cmds.parentConstraint(mo=True, sr=["x", "y", "z"],
                                      w=1)  # Создаём позиционный констрейн

                aimPosName = tempLoc + ".translate"  # Обращение к позиции физического локатора
                partCenter = tempPart + ".center"  # Обращение к центру частицы
                aimLocPos = tempAimLoc + ".translate"  # Обращение к позиции целевого локатора

                aimPos = cmds.getAttr(
                    aimPosName)  # Берём позицию физического локатора
                cmds.nParticle(p=aimPos, n=tempPart,
                               c=1)  # Создаём частицу в целевой позиции
                cmds.goal(tempPart, w=0.5, utr=1, g=tempLoc
                          )  # Создаём физическую связь с физическим локатором
                cmds.connectAttr(
                    partCenter, aimLocPos,
                    f=True)  # Привязываем целевой локатор к частице

                cmds.select(tempAimLoc, r=True)  # Выделяем целевой локатор
                cmds.select(aimLoc, add=True)  # Выделяем следящий локатор
                cmds.aimConstraint(
                    w=1,
                    aim=(0, 1, 0),
                    u=(0, 1, 0),
                    wut="vector",
                    wu=(0, 1, 0),
                    sk="y")  # Создаём аим констреён по двум осям

                #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

                cmds.setAttr(partRtype, pShape)
                cmds.setAttr(partRrad, pRad)
                cmds.setAttr(partRsm, goalSmoothRot)
                cmds.setAttr(partRwe, goalWRot)
                cmds.setAttr(partNucl, timeScaleRot)
                cmds.setAttr(nuclStart, asT)

                #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

                global minLoopTime
                minLoopTime = aeT * -2
                global maxLoopTime
                maxLoopTime = aeT * 2

                if (cycleRot):

                    cmds.setAttr(nuclStart, minLoopTime)

                    cmds.bakeResults(
                        zeroLoc,
                        t=(asT, aeT),
                        sm=True,
                        at=("translate",
                            "rotate"))  # Запекание нулевого локатора для цикла
                    cmds.bakeResults(
                        aimLoc,
                        t=(minLoopTime, maxLoopTime),
                        sm=True,
                        at="rotate")  # Запекание аим локатора для цикла
                    cmds.delete(tempAimLoc, tempLoc, tempPart,
                                tempNucl)  # Удаляем объекты физики

                    zeroParent = zeroLoc + "_parentConstraint1"
                    cmds.delete(zeroParent)

                    setTimeToMin()

                    cmds.select(aimLoc,
                                r=True)  # Выделяем аим локатор как родителя
                    cmds.select(listObjects[i],
                                add=True)  # Выделяем объект как подчиненного
                    cmds.parentConstraint(mo=True, st=["x", "y", "z"],
                                          w=1)  # Создаём ротэйт констрейн

                    resetLoopTime()

                else:

                    cmds.bakeResults(
                        zeroLoc,
                        t=(asT, aeT),
                        sm=True,
                        at=("translate", "rotate")
                    )  # Запекание нулевого локатора для линейной анимации
                    cmds.bakeResults(
                        aimLoc, t=(asT, aeT), sm=True, at="rotate"
                    )  # Запекание аим локатора для линейной анимации
                    cmds.delete(tempAimLoc, tempLoc, tempPart,
                                tempNucl)  # Удаляем объекты физики

                    zeroParent = zeroLoc + "_parentConstraint1"
                    cmds.delete(zeroParent)

                    resetLoopTime()

                    cmds.select(aimLoc,
                                r=True)  # Выделяем аим локатор как родителя
                    cmds.select(listObjects[i],
                                add=True)  # Выделяем объект как подчиненного
                    cmds.parentConstraint(mo=True, st=["x", "y", "z"],
                                          w=1)  # Создаём ротэйт констрейн

            #||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

                layerBase = "rotate_"  # Имя базы слоя
                layerName = layerBase + listFixed[i]  # Имя слоя
                layerComp = listFixed[i] + '_layer_{0}'.format(
                    "0")  # Имя компонента слоя

                if (cmds.objExists(layerName)):

                    cmds.bakeResults(listObjects[i],
                                     t=(asT, aeT),
                                     sm=True,
                                     bol=True,
                                     at="rotate")  # Запекаем объект в слой
                    cmds.select(listObjects[i], r=True)
                    cmds.setInfinity(pri="cycle", poi="cycle")
                    cmds.delete(aimLoc, zeroLoc)  # Удаляем объекты скрипта
                    cmds.container("BakeResultsContainer", e=True,
                                   rc=True)  # Удаляем контейнер
                    cmds.animLayer(
                        "BakeResults", e=True, p=layerName
                    )  # Переносим слой с анимацией в основной слой объекта
                    cmds.rename("BakeResults",
                                layerComp)  # Переименовываем слой
                    cmds.deleteAttr(n=listObjects[i], at="blendParent1")

                    resetLoopTime()
                else:
                    cmds.animLayer(
                        layerName
                    )  # Создаём пустой слой для всех оверлапов объекта
                    cmds.animLayer(
                        layerName, e=True,
                        p=mainLayerName)  # Переносим базу слоя в главный слой
                    cmds.bakeResults(listObjects[i],
                                     t=(asT, aeT),
                                     sm=True,
                                     bol=True,
                                     at="rotate")  # Запекаем объект в слой
                    cmds.select(listObjects[i], r=True)
                    cmds.setInfinity(pri="cycle", poi="cycle")
                    cmds.delete(aimLoc, zeroLoc)  # Удаляем объекты скрипта
                    cmds.container("BakeResultsContainer", e=True,
                                   rc=True)  # Удаляем контейнер
                    cmds.animLayer(
                        "BakeResults", e=True, p=layerName
                    )  # Переносим слой с анимацией в основной слой объекта
                    cmds.rename("BakeResults",
                                layerComp)  # Переименовываем слой
                    cmds.deleteAttr(n=listObjects[i], at="blendParent1")

                    resetLoopTime()

                cmds.select(d=True)  # Деселект

    for l in listObjects:
        cmds.select(l, add=True)

    print "\n||| OVERLAPPY end |||\n"
예제 #50
0
def bakeAnimation(objs, start, end) : 
    mc.bakeResults(objs,simulation=True,t=(start,end),sampleBy=1,disableImplicitControl=True,
                    preserveOutsideKeys=True ,sparseAnimCurveBake=False,removeBakedAttributeFromLayer=False,
                    removeBakedAnimFromLayer=False, bakeOnOverrideLayer=False, minimizeRotation=True,
                    controlPoints=False ,shape=True )
예제 #51
0
import maya.cmds as mc

filePath = mc.file(query=True, l=True)[0]
fileDirectory = filePath.rpartition("/")[0]
fileNumber = int((filePath.rpartition("_")[2]).rpartition(".")[0]) + 1
print filePath
print fileDirectory
print fileNumber
mc.bakeResults("*_JNT",
               simulation=True,
               t=(1, 48),
               sampleBy=1,
               disableImplicitControl=True,
               preserveOutsideKeys=True,
               sparseAnimCurveBake=False,
               removeBakedAttributeFromLayer=False,
               removeBakedAnimFromLayer=False,
               bakeOnOverrideLayer=False,
               minimizeRotation=True,
               controlPoints=False,
               shape=True)
mc.delete("*Constraint*")
mc.delete("*_CTL")
mc.select("*_JNT")
mc.select("*_GEO", add=True)
mc.file(fileDirectory + "/Animation_" + str(fileNumber) + ".fbx",
        force=True,
        options="groups=1;ptgroups=1;materials=1;smoothing=1;normals=1",
        type="FBX export",
        pr=True,
        es=True)
예제 #52
0
def translationStart():
	
	global asT; asT = cmds.playbackOptions( query=True, min=True ) # Get min anim range
	global aeT; aeT = cmds.playbackOptions( query=True, max=True ) # Get max anim range
	resetLoopTime()
	
	global listObjects; listObjects = cmds.ls( sl=True ) # Get list of selected objects
	
	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

	global listFixed; listFixed = listObjects [:]

	for i in range( len( listFixed ) ):
		listFixed[i] = listFixed[i].replace( "|", "_" )
		listFixed[i] = listFixed[i].replace( ":", "_" )

	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	
	global mainLayerName; mainLayerName = "OVERLAPPY" # Name of main layer

	if( cmds.objExists( mainLayerName ) ):
		print "\n||| OVERLAPPY start |||\n"
	else:
		cmds.animLayer( mainLayerName )
		print "\n||| OVERLAPPY start ||| Layer created |||\n"

	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

	for i in range( len( listFixed ) ):
		
		global aimLoc; aimLoc = listFixed[i] + "_aim_loc" # Aim locator name
		global tempLoc; tempLoc = listFixed[i] + "_temp_loc" # Physical locator name
		global tempPart; tempPart = listFixed[i] + "_temp_part" # nParticle name
		global tempNucl; tempNucl = "nucleus1" # Nucleus node name
	
		global partAimLoc; partAimLoc = aimLoc + ".translate" # Aim locator position pull
		global partRtype; partRtype = tempPart + "Shape.particleRenderType" # nParticle render type pull
		global partRrad; partRrad = tempPart + "Shape.radius" # nParticle shape radius
		global partRsm; partRsm = tempPart + "Shape.goalSmoothness" # Goal smoothness pull
		global partRwe; partRwe = tempPart + "Shape.goalWeight[0]" # Goal weight pull
		global partPos; partPos = tempPart + ".center" # nParticle center position pull
		global partNucl; partNucl = tempNucl + ".timeScale" # Time scale pull
		global nuclStart; nuclStart = tempNucl + ".startFrame" # Start frame of simulation nucleus node
		
		cmds.spaceLocator( n = tempLoc )
		cmds.matchTransform( tempLoc, listObjects[i], pos=True )
		
		objCenter = tempLoc + ".translate"
		objC = cmds.getAttr( objCenter )
		
		locCenter = tempLoc + ".center"
		locTr = tempLoc + ".translate"
		
		cmds.nParticle( p = objC, n = tempPart , c = 1 )
		cmds.goal( tempPart, w=goalW, utr=1, g = tempLoc )
		
		cmds.select( tempLoc, r=True )
		cmds.select( listObjects[i], add=True )
		cmds.parent( r=True )
		
		cmds.matchTransform( tempLoc, listObjects[i], pos=True )


	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

		cmds.setAttr( partRtype, pShape )
		cmds.setAttr( partRrad, pRad )
		cmds.setAttr( partRsm, goalSmooth )
		cmds.setAttr( partRwe, goalW )
		cmds.setAttr( partNucl, timeScale )
		cmds.setAttr( nuclStart, asT )
		
	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

		cmds.duplicate( tempLoc, rr=True, n = aimLoc )
		cmds.select( aimLoc, r=True )
		cmds.parent( w=True )
		cmds.connectAttr( partPos, partAimLoc, f=True )
		
		global minLoopTime; minLoopTime = aeT * minLoopScale
		global maxLoopTime; maxLoopTime = aeT * maxLoopScale
		
		if( cycle ):
			
			cmds.setAttr( nuclStart, minLoopTime )
				
			cmds.bakeResults( aimLoc, t = ( minLoopTime, maxLoopTime ), sm=True, at = "translate")
			cmds.delete( tempLoc, tempPart, tempNucl )

			setTimeToMin()
			
			cmds.select( aimLoc, r=True )
			cmds.select( listObjects[i], add=True )
			cmds.parentConstraint( mo=True, sr=["x", "y", "z"], w = 1 )
			
			resetLoopTime()

		else:
			
			cmds.bakeResults( aimLoc, t = ( asT, aeT ), sm=True, at = "translate" )
			cmds.delete( tempLoc, tempPart, tempNucl )
			
			resetLoopTime()
			
			cmds.select( aimLoc, r=True )
			cmds.select( listObjects[i], add=True )
			
			#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
			
			attrX = listObjects[i] + '.translateX'
			attrY = listObjects[i] + '.translateY'
			attrZ = listObjects[i] + '.translateZ'
			
			lockX = cmds.getAttr( attrX, lock=True )
			lockY = cmds.getAttr( attrY, lock=True )
			lockZ = cmds.getAttr( attrZ, lock=True )

			if ( lockX != True ):
				cmds.parentConstraint( mo=True, st=["y","z"], sr=["x","y","z"], w = 1 )

			if ( lockY != True ):
				cmds.parentConstraint( mo=True, st=["x","z"], sr=["x","y","z"], w = 1 )
				
			if ( lockZ != True ):
				cmds.parentConstraint( mo=True, st=["x","y"], sr=["x","y","z"], w = 1 )

	#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

		layerBase = "translate_"
		layerName = layerBase + listFixed[i]
		layerComp = listFixed[i] + '_layer_{0}'.format("0")

		if ( cmds.objExists( layerName ) ):
			
			cmds.bakeResults( listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "translate")
			cmds.select( listObjects[i], r=True )
			
			if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" )
			else: cmds.setInfinity( pri="constant", poi="constant" )
			
			cmds.delete( aimLoc )
			cmds.container( "BakeResultsContainer", e=True, rc=True )
			cmds.animLayer( "BakeResults", e=True, p = layerName )
			cmds.rename( "BakeResults", layerComp )
			#cmds.deleteAttr( n=listObjects[i], at="blendParent1" )
			
			resetLoopTime()
		else:
			cmds.animLayer (layerName)
			cmds.animLayer (layerName, e=True, p = mainLayerName)
			cmds.bakeResults (listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "translate")
			cmds.select (listObjects[i], r=True)
			
			if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" )
			else: cmds.setInfinity( pri="constant", poi="constant" )
			
			cmds.delete (aimLoc)
			cmds.container("BakeResultsContainer", e=True, rc=True)
			cmds.animLayer ("BakeResults", e=True, p = layerName)
			cmds.rename ("BakeResults", layerComp)
			#cmds.deleteAttr( n=listObjects[i], at="blendParent1" )
			
			resetLoopTime()

		
		cmds.select (d=True)
		
	for l in listObjects:
		cmds.select (l, add=True)
		
	print "\n||| OVERLAPPY end |||\n"
예제 #53
0
def Bake(minFrame, maxFrame):
    Cmds.bakeResults(sm=True, t=(minFrame, maxFrame), hi="below", sb=1, dic=True, pok=False, sac=False, ral=False, cp=False, shape=False)
예제 #54
0
def rotationStart():
	
	global asT; asT = cmds.playbackOptions (query=True, min=True)
	global aeT; aeT = cmds.playbackOptions (query=True, max=True)
	resetLoopTime()
	
	global listObjects; listObjects = cmds.ls (sl=True)
	
	if( len( listObjects ) <= 1 ):
		
		print "\n||| Need to select two or more objects |||\n"
	
	else:
			
		#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	
		global listFixed; listFixed = listObjects [:]
	
		for i in range( len( listFixed ) ):
			listFixed[i] = listFixed[i].replace( "|", "_" )
			listFixed[i] = listFixed[i].replace( ":", "_" )
	
	
		#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
		
		global mainLayerName; mainLayerName = "OVERLAPPY"
	
		if (cmds.objExists(mainLayerName)):
			print "\n||| OVERLAPPY start |||\n"
		else:
			cmds.animLayer (mainLayerName)
			print "\n||| OVERLAPPY start ||| Layer created |||\n"
	
		#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	
		for i in range(len(listFixed)):
			
			if ( i+1 != len(listFixed) ):
			
				global zeroLoc; zeroLoc = listFixed[i] + "_base_loc"
				global aimLoc; aimLoc = listFixed[i] + "_aim_loc"
				global tempLoc; tempLoc = listFixed[i] + "_temp_loc"
				global tempAimLoc; tempAimLoc = listFixed[i] + "_tempAim_loc"
				
				global tempPart; tempPart = listFixed[i] + "_temp_part"
				global tempNucl; tempNucl = "nucleus1"
				
				global partRtype; partRtype = tempPart + "Shape.particleRenderType"
				global partRrad; partRrad = tempPart + "Shape.radius"
				global partRsm; partRsm = tempPart + "Shape.goalSmoothness"
				global partRwe; partRwe = tempPart + "Shape.goalWeight[0]"
				global partNucl; partNucl = tempNucl + ".timeScale"
				global nuclStart; nuclStart = tempNucl + ".startFrame"
				
				if aimVectorReverse: rotAimVector = -1
				else: rotAimVector = 1
				
			#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
				
				cmds.spaceLocator( n = zeroLoc )
				cmds.spaceLocator( n = aimLoc )
				cmds.spaceLocator( n = tempLoc )
				
				cmds.matchTransform ( zeroLoc, listObjects[i], pos=True )
				cmds.matchTransform ( tempLoc, listObjects[i+1], pos=True )
				
				cmds.select( tempLoc, r=True )
				cmds.duplicate( n = tempAimLoc )
				
				cmds.select( listObjects[0], r=True )
				cmds.select( zeroLoc, add=True )
				cmds.parentConstraint( mo=True, w = 1 )
				
				cmds.select( aimLoc, r=True )
				cmds.select( zeroLoc, add=True )
				cmds.parent( r=True )
				
				cmds.select( listObjects[1], r=True )
				cmds.select( tempLoc, add=True )
				cmds.parentConstraint( mo=True, sr=["x", "y", "z"], w = 1 )
				
				aimPosName = tempLoc + ".translate"
				partCenter = tempPart + ".center"
				aimLocPos = tempAimLoc + ".translate"
				
				aimPos = cmds.getAttr( aimPosName )
				cmds.nParticle( p = aimPos , n = tempPart , c = 1 )
				cmds.goal( tempPart, w=0.5, utr=1, g = tempLoc )
				cmds.connectAttr( partCenter, aimLocPos, f=True )
				
				cmds.select( tempAimLoc, r=True )
				cmds.select( aimLoc, add=True )
				cmds.aimConstraint( w=1, aim=(0, rotAimVector, 0), u=(0, 1, 0), wut="vector", wu=(0, 1, 0), sk="y" )
		
			#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
				
				cmds.setAttr (partRtype, pShape)
				cmds.setAttr (partRrad, pRad)
				cmds.setAttr (partRsm, goalSmoothRot)
				cmds.setAttr (partRwe, goalWRot)
				cmds.setAttr (partNucl, timeScaleRot)
				cmds.setAttr (nuclStart, asT)
				
			#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
		
				global minLoopTime; minLoopTime = aeT * minLoopScale
				global maxLoopTime; maxLoopTime = aeT * maxLoopScale
		
		
				if (cycle):
					
					cmds.setAttr( nuclStart, minLoopTime )
					
					cmds.bakeResults( zeroLoc, t = (asT, aeT), sm=True, at=( "translate", "rotate") )
					cmds.bakeResults( aimLoc, t = (minLoopTime, maxLoopTime), sm=True, at="rotate" )
					cmds.delete( tempAimLoc, tempLoc, tempPart, tempNucl )
					
					zeroParent = zeroLoc + "_parentConstraint1"
					cmds.delete( zeroParent )
					
					setTimeToMin()
					
					cmds.select( aimLoc, r=True )
					cmds.select( listObjects[i], add=True )
					
					#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
					
					attrX = listObjects[i] + '.rotateX'
					attrY = listObjects[i] + '.rotateY'
					attrZ = listObjects[i] + '.rotateZ'
					
					lockX = cmds.getAttr( attrX, lock=True )
					lockY = cmds.getAttr( attrY, lock=True )
					lockZ = cmds.getAttr( attrZ, lock=True )

					if ( lockX != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["y","z"], w = 1 )
				
					if ( lockY != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["x","z"], w = 1 )
					
					if ( lockZ != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["x","y"], w = 1 )
					
					resetLoopTime()
		
				else:
					
					cmds.bakeResults( zeroLoc, t = (asT, aeT), sm=True, at=( "translate", "rotate") )
					cmds.bakeResults( aimLoc, t = (asT, aeT), sm=True, at="rotate" )
					cmds.delete( tempAimLoc, tempLoc, tempPart, tempNucl )
					
					zeroParent = zeroLoc + "_parentConstraint1"
					cmds.delete( zeroParent )
					
					resetLoopTime()
					
					cmds.select( aimLoc, r=True )
					cmds.select( listObjects[i], add=True )
					
					#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
					
					attrX = listObjects[i] + '.rotateX'
					attrY = listObjects[i] + '.rotateY'
					attrZ = listObjects[i] + '.rotateZ'
					
					lockX = cmds.getAttr( attrX, lock=True )
					lockY = cmds.getAttr( attrY, lock=True )
					lockZ = cmds.getAttr( attrZ, lock=True )

					if ( lockX != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["y","z"], w = 1 )
					
					if ( lockY != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["x","z"], w = 1 )
					
					if ( lockZ != True ):
						cmds.parentConstraint( mo=True, st=["x","y","z"], sr=["x","y"], w = 1 )
					
			#||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
		
				layerBase = "rotate_"
				layerName = layerBase + listFixed[i]
				layerComp = listFixed[i] + '_layer_{0}'.format("0")
		
				if ( cmds.objExists( layerName ) ):
					
					cmds.bakeResults( listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "rotate" )
					cmds.select( listObjects[i], r=True )
					
					if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" )
					else: cmds.setInfinity( pri="constant", poi="constant" )
					
					cmds.delete( aimLoc, zeroLoc )
					cmds.container( "BakeResultsContainer", e=True, rc=True )
					cmds.animLayer( "BakeResults", e=True, p = layerName )
					cmds.rename( "BakeResults", layerComp )
					#cmds.deleteAttr( n=listObjects[i], at="blendParent1" )
					
					resetLoopTime()
				else:
					cmds.animLayer( layerName )
					cmds.animLayer( layerName, e=True, p = mainLayerName )
					cmds.bakeResults( listObjects[i], t = (asT, aeT), sm=True, bol=True, at = "rotate" )
					cmds.select( listObjects[i], r=True )
					
					if (cycleInfinity): cmds.setInfinity( pri="cycle", poi="cycle" )
					else: cmds.setInfinity( pri="constant", poi="constant" )
					
					cmds.delete( aimLoc, zeroLoc )
					cmds.container( "BakeResultsContainer", e=True, rc=True )
					cmds.animLayer( "BakeResults", e=True, p = layerName )
					cmds.rename( "BakeResults", layerComp )
					#cmds.deleteAttr( n=listObjects[i], at="blendParent1" )
					
					resetLoopTime()
		
				
				cmds.select (d=True)
		
	for l in listObjects:
		cmds.select (l, add=True)
		
	print "\n||| OVERLAPPY end |||\n"
예제 #55
0
    def sk_sceneCameraBK(self ,shotInfos = [],shotType = sk_infoConfig.sk_infoConfig().checkShotType() , stereoCam = 0,stereoMode = 1,step = 1,bkCam = '' ):
        if not shotInfos:
            shotInfo = sk_infoConfig.sk_infoConfig().checkShotInfo()
        else:
            shotInfo = shotInfos
        camBase = ''
        camFind = 1
        if bkCam:
            camBase = bkCam
        else:
            if shotType == 2:
                camBase = 'cam_' + str(shotInfo[1]) + '_' + str(shotInfo[2])
            if shotType == 3:
                camBase = 'cam_' + str(shotInfo[1]) + '_' + str(shotInfo[2]) + '_' + str(shotInfo[3])
            if '.' in camBase:
                camBase = camBase.split('.')[0]
            if stereoMode:
                camBase += '_stCam'
            # 判断cam在不在
            if not camBase:
                camFind = 0
            if not mc.ls(camBase):
                camFind = 0
            else:
                if len(mc.ls(camBase)) != 1:
                    camFind = 0
        if not camFind:
            #errorInfo = (u'==========No Correct Cam[%s],or More Than One Cam[%s],please Fix the Camera Name=========='%(camBase,camBase))
            errorInfo = (u'==========未找到正版cam[%s],或cam名字不合法==========\n'%camBase)
            print errorInfo
            sk_infoConfig.sk_infoConfig().checkErrorWindows(errorInfo)
            sk_infoConfig.errorCode = errorInfo
            mc.error(errorInfo)

        # 准备工作
        # 时间轴信息
        io = (mc.playbackOptions(q=1, minTime=1)-10, mc.playbackOptions(q=1, maxTime=1)+10)

        # 一次BK开始
        locTemp = mc.spaceLocator()
        cons = mc.parentConstraint(camBase , locTemp , maintainOffset = 0)

        # 一次烘焙
        mc.bakeResults(locTemp,  t = io,
                simulation = 0,
                sampleBy=step,
                disableImplicitControl=1,
                preserveOutsideKeys=1,
                sparseAnimCurveBake=1,
                removeBakedAttributeFromLayer=0,
                bakeOnOverrideLayer=0,
                controlPoints=0,
                shape=1)
        mc.delete(cons)

        # 复制出信息
        camNeed = (camBase.split('|')[-1] + '_baked')
        checkCam = mc.ls(camNeed,l=1)
        if checkCam:
            mc.delete(checkCam)
        if stereoMode:
            pluginName = 'stereoCamera'
            if not mc.pluginInfo(pluginName,q= 1,loaded = 1):
                mc.loadPlugin(pluginName)
            from maya.app.stereo import stereoCameraRig
            camNew = stereoCameraRig.createStereoCameraRig(rigName='StereoCamera')
            camNew = mc.rename(camNew[0],camNeed)
            shapesOld = mc.listRelatives(camBase,s=1,f=1)
            shapesNew = mc.listRelatives(camNew,s=1,f=1)
            for i in range(len(shapesOld)):
                # 连接
                self.sk_bakeStereoCameraConnect(shapesOld[i],shapesNew[i])
        else:
            camNew = mc.duplicate(camBase,returnRootsOnly = 1,inputConnections = 1)
            camNew = mc.rename(camNew[0],camNeed.split('|')[-1])

        # cam mode不需要sx,sy,sz和v
        noNeedList = ['.sx','.sy','.sz','.v']
        for checkAttr in noNeedList:
            camAttr = camNew + checkAttr
            cons = mc.listConnections(camAttr,s=1,d=0,plugs=1)
            mc.setAttr(camAttr,l=0)
            if cons:
                mc.disconnectAttr(cons[0],camAttr)
            lockState = mc.getAttr(camAttr,l=1)
            if lockState:
                tempAttr = mc.connectionInfo(camAttr,gla=1)
                if tempAttr:
                    mc.setAttr(tempAttr,l=0)
            mc.setAttr(camAttr,1)

        # 清理目标camera物体
        chilrdNodes = mc.listRelatives(camNew,ad = 1,f=1)
        for checkNode in chilrdNodes:
            if not mc.ls(checkNode):
                continue
            checkType = mc.nodeType(checkNode)
            if checkType in ['camera','stereoRigFrustum','stereoRigCamera']:
                continue
            deleteState = 1
            if checkType in ['transform']:
                child = mc.listRelatives(checkNode,s=1,f=1)
                if not child:
                    deleteState = 0
                else:
                    for checkChild in child:
                        checkType = mc.nodeType(checkChild)
                        if checkType in ['camera','stereoRigFrustum','stereoRigCamera']:
                            deleteState = 0
            if deleteState:
                mc.delete(checkNode)
        # 解锁
        from idmt.maya.commonCore.core_mayaCommon import sk_sceneTools
        reload(sk_sceneTools)
        sk_sceneTools.sk_sceneTools().checkLockObjs([camNeed],0,1)

        # 祛除translate和rotate的约束
        if shotInfo[0] !='nj':
            camNewFull = mc.ls(camNew,l=1)[0]
            if len(camNewFull.split('|')) != 2:
                mc.parent(camNew,world = 1)
            for attr in ['.tx','.ty','.tz','.rx','.ry','.rz']:
                mc.setAttr((camNew + attr), lock = False)
                consAttr = mc.listConnections((camNew + attr),s=1,d=0,plugs=1)
                if not consAttr:
                    continue
                mc.disconnectAttr(consAttr[0],(camNew + attr))

        # 二次BK开始
        cons = mc.parentConstraint(locTemp , camNew , maintainOffset = 0)

        # 二次烘焙
        mc.bakeResults(camNew,  t=io,
                simulation = 0,
                sampleBy=step,
                disableImplicitControl = 1 ,
                preserveOutsideKeys = 1 ,
                sparseAnimCurveBake = 1 ,
                removeBakedAttributeFromLayer = 0 ,
                bakeOnOverrideLayer = 0 ,
                controlPoints = 0 ,
                shape = 1 )

        if stereoMode:
            camShape = mc.listRelatives(camNew,s = 1,ni=1)[0]
            childGrps = mc.listRelatives(camNew,c=1,type = 'transform')
            leftGrp = ''
            rightGrp = ''
            for checkGrp in childGrps:
                if 'Left' in checkGrp:
                    leftGrp = checkGrp
                if 'Right' in checkGrp:
                    rightGrp = checkGrp
            # 重新处理立体连接
            leftGrpAttr = '%s|%s.tx'%(camNew,leftGrp)
            tempAttr = mc.connectionInfo(leftGrpAttr,gla=1)
            if tempAttr:
                mc.setAttr(tempAttr,l=0)
            cons = mc.listConnections(leftGrpAttr,s=1,d=0,plugs=1)
            if shotInfo[0] in ['do6'] and cons:
                mel.eval('source "channelBoxCommand.mel"')
                mel.eval('CBunlockAttr %s'%leftGrpAttr)
            if cons:
                mc.disconnectAttr(cons[0],leftGrpAttr)
            mc.expression(s = '%s=-0.5*%s.interaxialSeparation'%(leftGrpAttr,camShape),o = leftGrp )

            rightGrpAttr = '%s|%s.tx'%(camNew,rightGrp)
            tempAttr = mc.connectionInfo(rightGrpAttr,gla=1)
            if tempAttr:
                mc.setAttr(tempAttr,l=0)
            cons = mc.listConnections(rightGrpAttr,s=1,d=0,plugs=1)
            if shotInfo[0] =='do6' and cons:
                mel.eval('source "channelBoxCommand.mel"')
                mel.eval('CBunlockAttr %s' %rightGrpAttr)
            if cons:
                mc.disconnectAttr(cons[0],rightGrpAttr)
            mc.expression(s = '%s=0.5*%s.interaxialSeparation'%(rightGrpAttr,camShape),o = rightGrp )

            # pairx
            rigShape = mc.listRelatives(camNew,s=1,type = 'stereoRigCamera')[0]
            rigFrustum = mc.listRelatives(camNew,s=1,type = 'stereoRigFrustum')[0]
            print '------------tMode'
            print camShape
            print rigShape
            mc.connectAttr('%s.zeroParallax'%camShape,'%s.zeroParallax'%camNew,f=1)
            mc.connectAttr('%s.zeroParallax'%camShape,'%s.zeroParallax'%rigFrustum,f=1)

            # center
            attrs = ['.filmOffsetLeftCam','.filmOffsetRightCam','.interaxialSeparation','.stereo','.toeInAdjust']
            centerPre = camNeed
            centerShape = centerPre + 'CenterCamShape'
            centerGrp = centerPre
            for attr in attrs:
                mc.setAttr((centerGrp + attr),l = 0)
                mc.connectAttr((centerShape + attr),(centerGrp + attr) ,f = 1)
        cons = mc.listConnections(camNew,s = 1 ,type = 'constraint')
        if cons:
            cons = list(set(cons))
            mc.delete(cons)
        # 清理shape的某些信息
        camNewShape = mc.listRelatives(camNew,s=1,type = 'camera',f=1)
        shapeCons = mc.listConnections(camNewShape,s=1,d=0,c=1,plugs=1)
        if shapeCons:
            consNum = len(shapeCons)
            for num in range(consNum/2):
                consAttr = shapeCons[num*2+1]
                if '>' in consAttr:
                    consAttr = consAttr.split('>')[-1]
                consNode = consAttr.split('.')[0]
                # 判断
                nodeType = mc.nodeType(consNode)
                if 'animCurve' in nodeType:
                    continue
                checkAttr = shapeCons[num*2+1]
                if (not mc.referenceQuery(checkAttr.split('.')[0],inr = 1)) and mc.getAttr(checkAttr,l=1):
                    mc.setAttr(checkAttr,l=0)
                checkAttr = shapeCons[num*2]
                if (not mc.referenceQuery(checkAttr.split('.')[0],inr = 1)) and mc.getAttr(checkAttr,l=1):
                    mc.setAttr(checkAttr,l=0)
                # 断开
                mc.disconnectAttr(shapeCons[num*2+1],shapeCons[num*2])

        # 善后,清理
        mc.delete(locTemp)

        # 属性
        baseShape = mc.listRelatives(camBase,s=1,f=1)[0]
        newShape = mc.listRelatives(camNew,s=1,type = 'camera',f=1)[0]
        fixAttrList = ['.horizontalFilmAperture','.verticalFilmAperture','.filmFit']
        for attr in fixAttrList:
            newAttr = newShape + attr
            if not mc.ls(newAttr):
                continue
            oldAttr = baseShape + attr
            mc.setAttr(newAttr,l=0)
            mc.setAttr(newAttr,mc.getAttr(oldAttr))

        # 处理scale,属性打1
        for attr in ['.sx','.sy','.sz']:
            cons = mc.listConnections((camNew + attr),s=1,d=0,plugs=1)
            if cons:
                mc.disconnectAttr(cons[0],(camNew + attr))
            mc.setAttr((camNew + attr),l=0)
            mc.setAttr((camNew + attr),1)

        # 恢复立体连接
        # 锁、出组
        fixCamList = []
        if stereoMode:
            camShapes = mc.listRelatives(camNew,ad=1,type='camera',f=1)
            fixCamList = mc.listRelatives(camShapes,p=1,type='transform',f=1)
        sk_sceneTools.sk_sceneTools().checkLockObjs(fixCamList,1,1)
        for checkCam in fixCamList:
            attrs = mc.listAttr(checkCam,k=1)
            if not attrs:
                continue
            for attr in attrs:
                mc.setAttr((checkCam + '.' +attr),l = 1)
예제 #56
0
def publishAnim():    
    allNS= cmds.namespaceInfo(lon=1,r=1)
    defaultNS = ["UI","shared"]
    others = [ns for ns in allNS if ns not in defaultNS]
    maxTime = str(int(cmds.playbackOptions(q=1,max=1)))
    minTime = str(int(cmds.playbackOptions(q=1,min=1)))
    frameRate = cmds.currentUnit(q=1,t=1)
    
    #both are the same, some Maya doesn't work with cmds.file(q=1, sceneName=1)
    #currentFileNameList = cmds.file(q=1,sceneName =1 ).split("/")[-1].split(".")[0]
    currentFileNameList = cmds.file(q=1,l=1)[0].split("/")[-1].split(".")[0]
    extension = cmds.file(q=1,l=1)[0].split("/")[-1].split(".")[-1]
    abcOutPath = cmds.workspace(fileRuleEntry="abcOut")     
    nsInfo = cmds.namespaceInfo(lon=1,r=1)  
    splitFileName = currentFileNameList.split("_")

    allCam = cmds.ls(type = "camera",l=1)
    defaultCam = ['backShape','bottomShape','leftShape','frontShape', 'perspShape','sideShape', 'topShape']
    allCam = [cam for cam in allCam if cam.split("|")[-1] not in defaultCam]
    animationLayer = cmds.ls(type="animLayer")
   
    #--------------------------VALIDATION--------------------------------------
    informationRig = ""
    informationCam = ""
    informationText = ""
    regCamStr = ""
    animLay = ""
    regCamList=[]

    if len(animationLayer) > 1: #Ensure all animation layers are merged before publishing
        for b in animationLayer:
            animLay += (b+";"+"\n")
        
        animLayerBox = QtWidgets.QMessageBox()
        animLayerBox.setIcon(QtWidgets.QMessageBox.Warning)
        animLayerBox.setWindowTitle("Alert!")
        animLayerBox.setText("Validation Error!")
        animLayerBox.setInformativeText("Publish unsuccessful."+"\n\n"+
                                        "Multiple animation layers found. Please clean up or merge them."+
                                        "\n\n"+ animLay)
        animLayerBox.exec_()   
        return             

    #Ensure camera is registered before publishing
    for regCam in allCam:
        regCamInfo = cmds.listRelatives(regCam,parent =1,type = "transform")[0]
        if "objType" in cmds.listAttr(regCamInfo):
            if cmds.getAttr("%s.objType"%regCamInfo) == "camera":
                regCamList.append(regCamInfo)
                
    if len(regCamList) == 0 : #No camera registered error
        regCamBox = QtWidgets.QMessageBox()
        regCamBox.setIcon(QtWidgets.QMessageBox.Warning)
        regCamBox.setWindowTitle("Alert!")
        regCamBox.setText("Validation Error!")
        regCamBox.setInformativeText("Publish unsuccessful."+"\n\n"+"No registered camera found.")
        regCamBox.exec_()   
        return         
    
    elif len(regCamList) != 1:
        for a in regCamList:
            regCamStr += (a+";"+"\n")

    else:
        regCamStr += ""

    for q in allNS:
        if "rig" in q:
            i=q.split(":")
            if len(i) >= 2 and "_rig" not in i[0]:
                informationRig += (q+";"+"\n")
                
    if len(allCam) > 1:
        for finalCam in allCam:
            cleanUpCam = finalCam.split("|")[-1]   
            informationCam += (cleanUpCam+";"+"\n")
            
    numOfCam = len(allCam)
    numOfRegCam = len(regCamList)
    
    if informationRig != "" or informationCam != "" or regCamStr != "": #if either of these are not empty string, means there's error
        if informationRig != "" and informationCam == "" and regCamStr == "": #namespace within namespace error
            informationText += ("Please clean up namespace"+informationRig)
            
        elif informationRig == "" and informationCam != "" and regCamStr == "": #multiple camera error
            informationText += ("%s cameras in the Scene"%numOfCam+"\n"+"Please clean up camera"+informationCam)
            
        elif informationRig == "" and informationCam == "" and regCamStr != "": #multiple registered cam error
            informationText += ("%s cameras registered"%numOfRegCam+"\n"+"Please only register 1 camera"+"\n"+regCamStr)
            
        elif informationRig != "" and informationCam == "" and regCamStr != "": #namespace and multiple registered cam error
            informationText += ("Please clean up namespace"+"\n"+informationRig+"\n"+
                                "Please register only 1 camera. ( %s cameras registerd )"%numOfRegCam+"\n"+regCamStr) 
                                
        elif informationRig != "" and informationCam != "" and regCamStr == "": #namespace and multiple cam error
            informationText += ("Please clean up namespace"+"\n"+informationRig+"\n"+
                                "Please clean up camera. ( %s cameras in the scene )"%numOfCam+"\n"+informationCam+"\n")
                                
        elif informationRig == "" and informationCam != "" and regCamStr != "": #multiple cam error and multiple registered cam error  
            informationText += ("Please clean up camera. ( %s cameras in the scene )"%numOfCam+"\n"+informationCam+"\n"
                                "Please register only 1 camera. ( %s cameras registerd )"%numOfRegCam+"\n"+regCamStr)              
                       
        elif informationRig != "" and informationCam != "" and regCamStr != "" : #namespace, multiple cam and multiple registered cam error
            informationText += ("Please clean up namespace"+"\n"+informationRig+"\n"+
                                "Please clean up camera. ( %s cameras in the scene )"%numOfCam+"\n"+informationCam+"\n"
                                "Please register only 1 camera. ( %s cameras registerd )"%numOfRegCam+"\n"+regCamStr)
                                
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Warning)
        msgBox.setWindowTitle("Alert!")
        msgBox.setText("Validation Error!")
        msgBox.setInformativeText("Publish unsuccessful."+"\n\n"+informationText)
        msgBox.exec_()
        return
    
        #----------------------------------------------------------------------

    list = ["sq","sc"]
    for ind, q in enumerate(splitFileName):
        if q.isalpha() == False: #check if there are any words (words like trailer, teaser or rnd)
            if ind == 1: #take the 1st and 2nd index (for sequence and scene)
                abcOutPath += "/%s"%list[0] + splitFileName[ind]
            if ind == 2:
                abcOutPath += "/%s"%list[1] + splitFileName[ind]

    for i in currentFileNameList.split("_"):
        if "sh" in i:
            abcOutPath += "/%s" %i
            continue
            
    if not os.path.exists(abcOutPath):
        os.makedirs(abcOutPath)
        
    namespaceList=[]
    for a in nsInfo:
        if a == 'UI' or a == 'shared':
            continue
        else:
            namespaceList.append(a)

    transformList=[]
    pConstraint=[]
    for nc in cmds.ls(type="nurbsCurve"):
        nctrans = cmds.listRelatives(nc, type="transform",p=1,f=1)[0]
        if "objType" in cmds.listAttr(nctrans):
            if cmds.getAttr("%s.objType"%nctrans) == "ctrl":              
                transformList.append(nctrans)
                if "blendParent1" in cmds.listAttr(nctrans):
                    for const in cmds.listConnections(nctrans,type="constraint",d=1,s=0):
                        if ":" not in const:
                            pConstraint.append(const)
                
        if len(transformList) == 0:
            continue
    if len(transformList)>0:
        cmds.bakeResults(transformList,sm=1,t=(int(cmds.playbackOptions(q=1,min=1)),int(cmds.playbackOptions(q=1,max=1))),sb=1,osr=1,rba=0,dic=1,pok=1,sac=0,ral=0,bol=0,mr=1,cp=0,s=0)

    if len(pConstraint)>0:
        cmds.delete(pConstraint)

    start = time.time() 
    for i in namespaceList:
        animCurveObj=[]  
        for j in cmds.ls("%s:*"%i,type="nurbsCurve"):
            transform = cmds.listRelatives(j,type="transform",p=1,f=1)[0]
            if "objType" in cmds.listAttr(transform):
                if cmds.getAttr("%s.objType"%transform) == "ctrl":
                    animNode = cmds.listConnections(transform,type="animCurve",d=0)
                    if animNode != None:
                        for obj in animNode:
                            animCurveObj.append(obj)

        for ind,curveObj in enumerate(animCurveObj):
            dest = cmds.listConnections(curveObj,d=1,c=0,p=1)[0]
            
            if "animDest" not in cmds.listAttr(curveObj):
                cmds.addAttr(curveObj,longName="animDest",dataType="string",keyable=1)

            cmds.setAttr("%s.animDest"%curveObj,lock=0)
            cmds.setAttr("%s.animDest"%curveObj,dest,type="string")
            cmds.setAttr("%s.animDest"%curveObj,lock=1)
            
            if "preInfinity" in cmds.listAttr(curveObj):
            
                cmds.setAttr("%s.preInfinity"%curveObj,lock=0)
                cmds.setAttr("%s.preInfinity"%curveObj,4)
                cmds.setAttr("%s.preInfinity"%curveObj,lock=1)
                
        if len(animCurveObj)>0:
            cmds.select(animCurveObj)
            if extension == "ma":
                if ":" in i:
                    cmds.file((abcOutPath+"/"+i.split(":")[-1]+"Anim"),f=1,op="v=0",typ = "mayaAscii",pr=1,es=1) #Export Animation Curve Data
                    end = time.time()
                    print "Animation data exported in ",(end-start),"seconds"
                    start = time.time()
                else:
                    cmds.file((abcOutPath+"/"+i+"Anim"),f=1,op="v=0",typ = "mayaAscii",pr=1,es=1) #Export Animation Curve Data
                    end = time.time()
                    print "Animation data exported in ",(end-start),"seconds"
                    start = time.time()
                    
            elif extension == "mb":
                if ":" in i:
                    cmds.file((abcOutPath+"/"+i.split(":")[-1]+"Anim"),f=1,op="v=0",typ = "mayaBinary",pr=1,es=1) #Export Animation Curve Data
                    end = time.time()
                    print "Animation data exported in ",(end-start),"seconds"
                    start = time.time()
                else:
                    cmds.file((abcOutPath+"/"+i+"Anim"),f=1,op="v=0",typ = "mayaBinary",pr=1,es=1) #Export Animation Curve Data
                    end = time.time()
                    print "Animation data exported in ",(end-start),"seconds"
                    start = time.time()
                
            else:
                print "file type unknown, can't be exported"
                continue
        else:
            pass
                            
    for ns in others:
        objString = ''
        if cmds.namespaceInfo(ns,lod=1,dp=1) == None:
            continue
        for obj in cmds.namespaceInfo(ns,lod=1,dp=1):        
            if "objType" in cmds.listAttr(obj) and cmds.objectType(obj,i="transform"):
                if cmds.getAttr("%s.objType"%obj) == "geometry" or cmds.getAttr("%s.objType"%obj) == "sets": 
                    objString+= (" -root " + obj)
        if objString == '':
            continue        
        finalString = "AbcExport -j \"-frameRange %s %s -attr objType -attrPrefix rs -stripNamespaces -dataFormat ogawa -uvWrite -attrPrefix xgen -writeVisibility -worldSpace%s -file %s\"" %(minTime,maxTime,objString,abcOutPath+"/"+ns.split(":")[-1]+".abc")
        mel.eval(finalString)

    objString = ''
    for cam in allCam:
        objString = ''
        transformNode = cmds.listRelatives(cam,parent =1,type = "transform" )[0]
        if "objType" in cmds.listAttr(transformNode):
            if cmds.getAttr("%s.objType"%transformNode) == "camera": 
                objString+= (" -root " + transformNode)
        if objString == '':
            continue
        finalString = "AbcExport -j \"-frameRange %s %s -attr objType -attrPrefix rs -attrPrefix rman -stripNamespaces -dataFormat ogawa -uvWrite -attrPrefix xgen -worldSpace%s -file %s\"" %(minTime,maxTime,objString,abcOutPath+"/"+transformNode.split(":")[-1]+"_cam.abc")
        mel.eval(finalString)
        
    publishBox = QtWidgets.QMessageBox()
    publishBox.setIcon(QtWidgets.QMessageBox.Information)
    publishBox.setWindowTitle("Information")
    publishBox.setText("Your files have been published successfully!")
    publishBox.setInformativeText("Please check them at their designated location.")
    publishBox.exec_()
    return
예제 #57
0
    def sk_bkCore(self , bkSourceobjs , preFrame = 10 , posFrame = 10 , simulation = 1 ,step = 1,returnObjs = []):
        if bkSourceobjs:
            if not mc.ls(bkSourceobjs):
                errorInfo = u'===待约束物体中,有物体不存在==='
                print bkSourceobjs
                sk_infoConfig.sk_infoConfig().checkErrorWindows(errorInfo)
                sk_infoConfig.errorCode = errorInfo
                mc.error(errorInfo)
        else:
            return []
        if not returnObjs:
            returnObjs = bkSourceobjs
            
        io = (mc.playbackOptions(q=1, minTime=1)-preFrame, mc.playbackOptions(q=1, maxTime=1)+posFrame)

        # 改进版,不bake,而是给新locator bake
        # 删除locators
        locators = mc.ls('FOOD_BakeAnim*',type = 'transform')
        if locators:
            mc.delete(locators)
        # 数值传递到locators
        locators = []
        constraintTemp = []
        for i in range(len(bkSourceobjs)):
            locTemp = mc.spaceLocator()
            locTemp = mc.rename(locTemp[0] , ('FOOD_BakeAnim_BakeAnim_' + str(i)))
            # 父子约束
            cons = mc.parentConstraint(bkSourceobjs[i] , locTemp , maintainOffset = 0)
            constraintTemp.append(cons[0])
            # 缩放约束
            cons = mc.scaleConstraint(bkSourceobjs[i] , locTemp , maintainOffset = 0)
            constraintTemp.append(cons[0])
            
            locators.append(locTemp)
        # 一次烘焙
        mc.bakeResults(locators,  t=io,
                simulation = simulation,
                sampleBy=step,
                disableImplicitControl=1,
                preserveOutsideKeys=1,
                sparseAnimCurveBake=1,
                removeBakedAttributeFromLayer=0,
                bakeOnOverrideLayer=0,
                controlPoints=0,
                shape=1)
        print u'---预BK完毕\n'
        import datetime
        print u'---当前时间.:%s'%(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
        mc.delete(constraintTemp)
        print u'---当前时间.:%s'%(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
        print u'---预约束处理完毕\n'
        
        # 重新约束物体
        attrs = ['.tx','.ty','.tz','.rx','.ry','.rz','.sx','.sy','.sz']
        #locators = mc.ls('FOOD_BakeAnim*',type = 'transform')
        if locators:
            for i in range(len(locators)):
                # 打断t和r属性
                for attr in attrs:
                    if not mc.getAttr((bkSourceobjs[i] + attr),settable = 1):
                        continue
                    self.checkDeleteConnection(bkSourceobjs[i] + attr)
                locatorGrp = locators[i]
                #  父子约束 ,cam已经锁住
                if 'cam_' in bkSourceobjs[i]:
                    continue
                
                #print u'----------------'
                #print locatorGrp
                #print bkSourceobjs[i].split('|')[-1]
                
                # 位移检测
                skipTranslateAxis = []
                checkTAttr = ['.tx','.ty','.tz']
                for j in range(3):
                    passAttr = ['x','y','z']
                    tState = mc.getAttr((bkSourceobjs[i] + checkTAttr[j]),settable = 1)

                    if tState:
                        pass
                    else:
                        skipTranslateAxis.append(passAttr[j])
                # 旋转检测
                skipRotateAxis = []
                checkRAttr = ['.rx','.ry','.rz']
                for k in range(3):
                    passAttr = ['x','y','z']
                    rState = mc.getAttr((bkSourceobjs[i] + checkRAttr[k]),settable = 1)
                    if rState:
                        pass
                    else:
                        skipRotateAxis.append(passAttr[k])
                # 缩放检测
                skipScaleAxis = []
                checkRAttr = ['.sx','.sy','.sz']
                for k in range(3):
                    passAttr = ['x','y','z']
                    sState = mc.getAttr((bkSourceobjs[i] + checkRAttr[k]),settable = 1)
                    if sState:
                        pass
                    else:
                        skipScaleAxis.append(passAttr[k])
                        
                #print u'----------------'
                #print locatorGrp
                #print bkSourceobjs[i].split('|')[-1]
                        
                # 父子约束
                if skipTranslateAxis and skipRotateAxis == []:
                    mc.parentConstraint(locatorGrp , bkSourceobjs[i] , skipTranslate = skipTranslateAxis , maintainOffset = 0)
                if skipTranslateAxis == [] and skipRotateAxis:
                    mc.parentConstraint(locatorGrp , bkSourceobjs[i] , skipRotate = skipRotateAxis , maintainOffset = 0)
                if skipTranslateAxis and skipRotateAxis:
                    # 修正全忽略的问题,全部忽略再去创建约束会报错
                    if (skipTranslateAxis == ['x','y','z']) and (skipRotateAxis == ['x','y','z']):
                        pass
                    else:
                        mc.parentConstraint(locatorGrp , bkSourceobjs[i] , skipTranslate = skipTranslateAxis, skipRotate = skipRotateAxis , maintainOffset = 0)
                if skipTranslateAxis == [] and skipRotateAxis == []:
                    mc.parentConstraint(locatorGrp , bkSourceobjs[i] , maintainOffset = 0)
                    
                # scale约束
                if skipScaleAxis == []:
                    try:
                        mc.scaleConstraint(locatorGrp , bkSourceobjs[i])
                    except:
                        pass
                else:
                    # xyz都忽略时,还需要scale约束吗
                    if skipScaleAxis != ['x','y','z']:
                        try:
                            mc.scaleConstraint(locatorGrp , bkSourceobjs[i] , skip = skipScaleAxis )
                        except:
                            pass
                        
            # 二次烘焙
            mc.bakeResults(bkSourceobjs,    t=io,
                    simulation = simulation,
                    sampleBy=step,
                    disableImplicitControl=1,
                    preserveOutsideKeys=1,
                    sparseAnimCurveBake=1,
                    removeBakedAttributeFromLayer=0,
                    bakeOnOverrideLayer=0,
                    controlPoints=0,
                    shape=1)
            
            print u'---清理临时信息开始\n'
            mc.delete(locators)
            print u'---清理临时信息完毕\n'
            
            #self.checkAnimCurvesFix()

            print(u'\n==========【约束】【烘焙】【成功】=========')
            print u'\n'
예제 #58
0
파일: lookAt.py 프로젝트: fsanges/glTools-1
def create(	target,
			slaveList,
			slaveAimUp=None,
			weightList=None,
			bakeAnim=False,
			bakeStartEnd=[None,None],
			offsetAnim=None,
			offset=(0,0,0),
			cleanup=False	):
	'''
	Create a lookAt constraint setup based in the input arguments
	@param target: LookAt target transform.
	@type target: str
	@param slaveList: LookAt slave transform list.
	@type slaveList: list
	@param slaveAimUp: List of slave lookAt aim and up vectors. [(aim,up),('z',x),...]
	@type slaveAimUp: list
	@param weightList: LookAt weight list. If None, use default weight list (evenly distributed).
	@type weightList: list
	@param bakeAnim: Bake lookAt animation to controls.
	@type bakeAnim: bool
	@param bakeStartEnd: Tuple containing start and end frame value.
	@type bakeStartEnd: tuple
	@param offsetAnim: Offset baked lookAt animation.
	@type offsetAnim: float or None
	@param offset: Constraint offset.
	@type offset: tuple
	'''
	# ==========
	# - Checks -
	# ==========
	
	# Target
	if not glTools.utils.transform.isTransform(target):
		raise Exception('LookAt target "'+target+'" is not a valid transform! Unable to create lookAt setup...')
	
	# Slave List
	if not slaveList:
		raise Exception('Invalid lookAt slave list! Unable to create lookAt setup...')
	
	# Weight List
	if not weightList:
		print('Invalid lookAt weight list! Generating default lookAt weight list...')
		weightList = range(0,101,100.0/len(slaveList))[1:]
	if len(weightList) != len(slaveList):
		print('Invalid lookAt weight list! Generating default lookAt weight list...')
		weightList = range(0,101,100.0/len(slaveList))[1:]
	
	# Slave Aim/Up Vectors
	if not slaveAimUp:
		print('Invalid lookAt slave aim/up vector values! Using default lookAt vectors (aim="z",up="y")...')
		slaveAimUp = [('z','y') for slave in slaveList]
	if len(slaveAimUp) != len(slaveList):
		print('Invalid lookAt slave aim/up vector values! Using default lookAt vectors (aim="z",up="y")...')
		slaveAimUp = [('z','y') for slave in slaveList]
	
	# ===========
	# - Look At -
	# ===========
	
	slaveReferenceList = []
	slaveLookAtList = []
	slaveLookAt_aimList = []
	slaveLookAt_orientList = []
	
	slaveBakeList = []
	
	for i in range(len(slaveList)):
		
		# Check Slave Object
		if not mc.objExists(slaveList[i]):
			print('Slave object "'+slaveList[i]+'" not found! Skipping...')
			continue
		
		# Get Slave Short Name
		slaveSN = slaveList[i].split(':')[0]
		
		# Duplicate Slave to get Reference and LookAt Targets
		slaveReference = mc.duplicate(slaveList[i],po=True,n=slaveSN+'_reference')[0]
		slaveLookAt = mc.duplicate(slaveList[i],po=True,n=slaveSN+'_lookAt')[0]
		
		# Transfer Anim to Reference
		slaveKeys = mc.copyKey(slaveList[i])
		if slaveKeys: mc.pasteKey(slaveReference)
		
		# Delete Slave Rotation Anim
		mc.cutKey(slaveList[i],at=['rx','ry','rz'])
		
		# Create Slave LookAt
		slaveLookAt_aim = glTools.tools.constraint.aimConstraint(	target=target,
																	slave=slaveLookAt,
																	aim=slaveAimUp[i][0],
																	up=slaveAimUp[i][1],
																	worldUpType='scene',
																	offset=offset,
																	mo=False	)[0]
		
		# Weighted Orient Constraint
		slaveLookAt_orient = mc.orientConstraint([slaveReference,slaveLookAt],slaveList[i],mo=False)[0]
		slaveLookAt_targets = glTools.utils.constraint.targetAliasList(slaveLookAt_orient)
		
		# Set Constraint Target Weights
		mc.setAttr(slaveLookAt_orient+'.'+slaveLookAt_targets[0],1.0-(weightList[i]*0.01))
		mc.setAttr(slaveLookAt_orient+'.'+slaveLookAt_targets[1],weightList[i]*0.01)
		mc.setAttr(slaveLookAt_orient+'.interpType',2) # Shortest
		
		# Add Message Connections
		mc.addAttr(slaveList[i],ln='lookAtTarget',at='message')
		mc.addAttr(slaveList[i],ln='lookAtAnmSrc',at='message')
		mc.connectAttr(slaveLookAt+'.message',slaveList[i]+'.lookAtTarget',f=True)
		mc.connectAttr(slaveReference+'.message',slaveList[i]+'.lookAtAnmSrc',f=True)
		
		# Append Lists
		slaveReferenceList.append(slaveReference)
		slaveLookAtList.append(slaveLookAt)
		slaveLookAt_aimList.append(slaveLookAt_aim)
		slaveLookAt_orientList.append(slaveLookAt_orient)
		
		slaveBakeList.append(slaveList[i])
	
	# =============
	# - Bake Anim -
	# =============
	
	if bakeAnim:
		
		# Get Bake Range
		start = bakeStartEnd[0]
		end = bakeStartEnd[1]
		if start == None: start = mc.playbackOptions(q=True,min=True)
		if end == None: end = mc.playbackOptions(q=True,max=True)
		
		# Bake Results
		mc.refresh(suspend=True)
		#for slave in slaveBakeList:
		mc.bakeResults(slaveBakeList,t=(start,end),at=['rx','ry','rz'],simulation=True)
		mc.refresh(suspend=False)
		
		# Post Bake Cleanup
		if cleanup:
			try: mc.delete(slaveLookAt_orientList)
			except: pass
			try: mc.delete(slaveLookAt_aimList)
			except: pass
			try: mc.delete(slaveReferenceList)
			except: pass
			try: mc.delete(slaveLookAtList)
			except: pass
	
	# ====================
	# - Bake Anim Offset -
	# ====================
	
	if offsetAnim != None:
		
		# For Each Slave Object
		for slave in slaveList:
			
			# Check Slave Object
			if not mc.objExists(slave):
				print('Slave object "'+slave+'" not found! Skipping...')
				continue
			
			# Offset Rotate Channels
			for r in ['rx','ry','rz']:
				mc.keyframe(slave+'.'+r,e=True,relative=True,timeChange=offsetAnim)
	
	# =================
	# - Return Result -
	# =================
	
	return slaveList
예제 #59
0
                                if cmds.objExists("root." + attr):
                                    cmds.deleteAttr("root", at=attr)

        #bake the animation down onto the export skeleton
        #sys.__stdout__.write("    bake animation" + "\n")
        cmds.progressBar(self.widgets["currentFileProgressBar"],
                         edit=True,
                         step=step)
        cmds.select("root", hi=True)

        #disabling redraw
        try:
            if cmds.checkBox(self.widgets["disableRedraw"], q=True,
                             v=True) == True:
                mel.eval("paneLayout -e -manage false $gMainPane")
            cmds.bakeResults(simulation=True, t=(startFrame, endFrame))
        except Exception, e:
            logger.error(e, title='Crash in bakeResults')
        finally:
            mel.eval("paneLayout -e -manage true $gMainPane")
        cmds.delete(constraints)

        #run an euler filter
        cmds.select("root", hi=True)
        cmds.filterCurve()

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
예제 #60
0
def armFkToIk(rigNS, side, bakeWrist=True, start=None, end=None, sampleBy=1):
    '''
	Bake FK arm animation to IK controls
	@param rigNS: IK/FK toggle attribute
	@type rigNS: str
	@param side: Arm side ("lf" or "rt")
	@type side: str
	@param bakeWrist: Bake wrist animation
	@type bakeWrist: bool
	@param start: Transfer animation start frame
	@type start: int or None
	@param end: Transfer animation end frame
	@type end: int or None
	@param sampleBy: Bake animation by N frames
	@type sampleBy: int
	'''
    # ==========
    # - Checks -
    # ==========

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

    # Get FK Joints
    fkShoulder = rigNS + ':' + side + '_arm_fkA_jnt'
    fkElbow = rigNS + ':' + side + '_arm_fkB_jnt'
    fkWrist = rigNS + ':' + side + '_handA_jnt'

    # Get IK Controls
    ikWrist = rigNS + ':' + side + '_arm_ik_ctrl'
    ikElbow = rigNS + ':' + side + '_arm_pv_ctrl'

    # =====================
    # - Transfer FK to IK -
    # =====================

    # Set Arm to FK mode
    mc.setAttr(rigNS + ':config.' + side + 'ArmIkFkBlend', 1)  # FK

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

    # Duplicate IK Controls
    ikWristLoc = mc.duplicate(ikWrist, po=True)[0]
    ikElbowLoc = mc.duplicate(ikElbow, po=True)[0]

    # Constrain IK to FK joints
    ikWristCon = mc.pointConstraint(fkWrist, ikWristLoc)[0]
    pvWristCon = mc.pointConstraint(fkElbow, ikElbowLoc)[0]

    # Bake Constraint Keys
    mc.refresh(suspend=True)
    mc.bakeResults([ikWristLoc, ikElbowLoc],
                   t=(start, end),
                   at=['tx', 'ty', 'tz'],
                   simulation=True,
                   preserveOutsideKeys=True,
                   sampleBy=sampleBy)
    mc.refresh(suspend=False)

    # Transfer Keys to IK Controls
    mc.copyKey(ikWristLoc, at=['tx', 'ty', 'tz'], t=(start, end))
    mc.pasteKey(ikWrist,
                at=['tx', 'ty', 'tz'],
                t=(start, end),
                option='replace')
    mc.copyKey(ikElbowLoc, at=['tx', 'ty', 'tz'], t=(start, end))
    mc.pasteKey(ikElbow,
                at=['tx', 'ty', 'tz'],
                t=(start, end),
                option='replace')

    # Delete Duplicate Joints and Constraints
    for item in [ikWristLoc, ikElbowLoc]:
        if mc.objExists(item):
            try:
                mc.delete(item)
            except Exception, e:
                print('Error deleting node "' + str(item) + '"!')
                print(str(e))