def func(*args, **kwargs):
     initialState = cmd.autoKeyframe(q=True, state=True)
     cmd.autoKeyframe(state=False)
     try:
         return f(*args, **kwargs)
     finally:
         cmd.autoKeyframe(state=initialState)
Пример #2
0
 def putObjects(self, atCurrentFrame=False):
     # print self.sel
     # print self.putObjectList
     autoKey = cmds.autoKeyframe(q=True, state=True)
     cmds.autoKeyframe(state=False)
     # current #NO LONGER USED, REMOVE ONCE MERGED WITH WORK COPY OF KET
     # CLASS
     if atCurrentFrame:
         current = cmds.currentTime(q=True)
         if self.start > current:
             self.offset = current - self.start
         else:
             self.offset = ((self.start - current) * -1.0) + 0.0
         # print self.offset
     # put
     num = len(self.objects)
     i = 1
     uiEnable()
     for obj in self.objects:
         if cmds.objExists(obj.name):
             message(str(i) + ' of ' + str(num) + ' --  ' + obj.name, maya=True)
             cmds.refresh(f=1)
             obj.offset = self.offset
             obj.putAttribute()
         else:
             cmds.warning(
                 'Object   ' + obj.name + '   does not exist, skipping.')
         i = i + 1
     uiEnable()
     cmds.autoKeyframe(state=autoKey)
Пример #3
0
 def __exit__(self,exit_type,value,traceback):
     '''Exit the scope, restoring all of the state information'''
     if self.cache_mgr:
         self.cache_mgr.restore_state()
     if self.em_mgr:
         self.em_mgr.restore_state()
     cmds.autoKeyframe(e=True, state=self.auto_key_state, characterOption=self.auto_key_chars)
Пример #4
0
    def __enter__(self):
        '''Enter the scope, setting up the evaluator managers and initial states'''
        self.em_mgr = emModeManager()
        self.em_mgr.setMode('emp')
        self.em_mgr.setMode('+cache')
        # Enable idle build to make sure we can rebuild the graph when waiting.
        self.em_mgr.idle_action = emModeManager.idle_action_build

        # Setup caching options
        self.cache_mgr = CacheEvaluatorManager()
        self.cache_mgr.save_state()
        self.cache_mgr.plugin_loaded = True
        self.cache_mgr.enabled = True
        self.cache_mgr.cache_mode = CACHE_STANDARD_MODE_EVAL
        self.cache_mgr.resource_guard = False
        self.cache_mgr.fill_mode = 'syncAsync'

        # Setup autokey options
        self.auto_key_state = cmds.autoKeyframe(q=True, state=True)
        self.auto_key_chars = cmds.autoKeyframe(q=True, characterOption=True)
        cmds.autoKeyframe(e=True, state=False)

        self.waitForCache()

        return self
Пример #5
0
	def func( *args, **kwargs ):
		initialState = cmd.autoKeyframe( q=True, state=True )
		cmd.autoKeyframe( state=False )
		try:
			return f( *args, **kwargs )
		finally:
			cmd.autoKeyframe( state=initialState )
Пример #6
0
def load():
    '''loads animation environment'''
    print "loading animation environment presets..."
    #set autoKey
    cmds.autoKeyframe( state=True )
    #set 24fps and playback on all viewports
    cmds.playbackOptions(ps=1.0, v='all')
    #set unlimited undo's
    cmds.undoInfo( state=True, infinity=True )
    #set manipulator sizes
    if lib.checkAboveVersion(2014):
        cmds.manipOptions( r=False, hs=55, ls=4, sph=1 )
    else:
        cmds.manipOptions( r=False, hs=55, ls=4 )
    #set framerate visibility
    mel.eval("setFrameRateVisibility(1);")
    #gimbal rotation
    cmds.manipRotateContext('Rotate', e=True, mode=2)
    #world translation
    cmds.manipMoveContext('Move', e=True, mode=2)
    #time slider height
    aPlayBackSliderPython = mel.eval('$tmpVar=$gPlayBackSlider')
    cmds.timeControl(aPlayBackSliderPython, h=45, e=True);
    #special tick color
    cmds.displayRGBColor("timeSliderTickDrawSpecial", 1,0.5,0)

    #check if hotkeys have been set
    if (cmds.hotkey( 't', ctl=True, query=True, name = True)== 'CharacterAnimationEditorNameCommand'):
        print "Hotkeys have been previously loaded"
    else:
        setHotkeys('default')

    print "ENVIRONMENT SET\n", #the comma forces output on the status line
Пример #7
0
    def __exit__(self, *exc_info):

        cmds.autoKeyframe(state=self.autoKeyState)
        cmds.currentTime(self.time)

        if self.selection:
            cmds.select(self.selection)
Пример #8
0
    def __exit__(self, exc_type, exc_value, traceback):
        # Close the undo chunk, warn if any exceptions were caught:
        cmds.autoKeyframe(state=self.autoKeyState)
        log.debug('autoKeyState restored: %s' % self.autoKeyState)

        if self.manage_em and self.evalmode:
            evalManagerState(mode=self.evalmode)
            log.debug('evalManager restored: %s' % self.evalmode)
        if self.manage_time:
            cmds.currentTime(self.timeStore['currentTime'])
            cmds.playbackOptions(min=self.timeStore['minTime'])
            cmds.playbackOptions(max=self.timeStore['maxTime'])
            cmds.playbackOptions(ast=self.timeStore['startTime'])
            cmds.playbackOptions(aet=self.timeStore['endTime'])
            cmds.playbackOptions(ps=self.timeStore['playSpeed'])
            log.debug('currentTime restored: %f' %
                      self.timeStore['currentTime'])
        if self.mangage_undo:
            cmds.undoInfo(closeChunk=True)
        else:
            cmds.undoInfo(swf=True)
        if not exc_type == None and self.suppress_exceptions:
            log.exception('%s : %s' % (exc_type, exc_value))
        # If we're suppressing exceptions, return True, otherwise return
        # according to if an exception is being handled or not
        # https://stackoverflow.com/questions/43946416/return-value-of-exit
        return self.suppress_exceptions or exc_type == None
Пример #9
0
    def __exit__(self, exc_type, exc_value, traceback):
        # Close the undo chunk, warn if any exceptions were caught:
        cmds.autoKeyframe(state=self.autoKeyState)
        log.info('autoKeyState restored: %s' % self.autoKeyState)

        if self.manage_em and self.evalmode:
            evalManagerState(mode=self.evalmode)
            log.info('evalManager restored: %s' % self.evalmode)
        if self.manage_time:
            cmds.currentTime(self.timeStore['currentTime'])
            cmds.playbackOptions(min=self.timeStore['minTime'])
            cmds.playbackOptions(max=self.timeStore['maxTime'])
            cmds.playbackOptions(ast=self.timeStore['startTime'])
            cmds.playbackOptions(aet=self.timeStore['endTime'])
            cmds.playbackOptions(ps=self.timeStore['playSpeed'])
            log.info('currentTime restored: %f' %
                     self.timeStore['currentTime'])
        if self.mangage_undo:
            cmds.undoInfo(closeChunk=True)
        else:
            cmds.undoInfo(swf=True)
        if exc_type:
            log.exception('%s : %s' % (exc_type, exc_value))
        # If this was false, it would re-raise the exception when complete
        return True
Пример #10
0
 def store(self):
     '''
     store animation
     '''
     # make sure o
     if self.poseOnly:
         self.mtrx.append(cmds.xform(self.obj, q=True, m=True, ws=True))
     else:
         if self.keys:
             current = cmds.currentTime(q=True)
             # ui off
             cn.uiEnable(controls='modelPanel')
             # autokey state
             autoK = cmds.autoKeyframe(q=True, state=True)
             cmds.autoKeyframe(state=False)
             for key in self.keys:
                 cmds.currentTime(key)
                 self.pos.append(cmds.xform(self.obj, q=True, rp=True, ws=True))
                 self.rot.append(cmds.xform(self.obj, q=True, ro=True, ws=True))
                 self.mtrx.append(cmds.xform(self.obj, q=True, m=True, ws=True))
             # restore everything
             cmds.currentTime(current)
             cmds.autoKeyframe(state=autoK)
             cn.uiEnable(controls='modelPanel')
         else:
             message('No keys, forcing timeline range.', maya=True)
             self.keys = range(int(self.rng.start), int(self.rng.end))
             self.rng.keyStart = self.rng.start
             self.rng.keyEnd = self.rng.end
             self.store()
Пример #11
0
def changeRO(obj, ro):
    '''
    '''
    roLst = ['xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx']
    if cmds.getAttr(obj + '.rotateOrder', settable=1):
        keyframes = getKeyedFrames(obj)
        origRO = cmds.getAttr(obj + '.rotateOrder')
        if ro != roLst[origRO]:
            if keyframes:
                cn.uiEnable(controls='modelPanel')
                r = getRange()
                autoK = cmds.autoKeyframe(q=True, state=True)
                cmds.autoKeyframe(state=False)
                i = r[0]
                current = r[2]
                cmds.currentTime(i)
                cmds.currentTime(cmds.findKeyframe(which='previous'))
                cmds.xform(obj, roo=ro)
                for key in keyframes:
                    cmds.currentTime(key)
                    cmds.setAttr(obj + '.rotateOrder', origRO)
                    cmds.xform(obj, roo=ro)
                    cmds.setKeyframe(obj + '.rotate')
                cmds.currentTime(current)
                cmds.autoKeyframe(state=autoK)
                cn.eulerFilter(obj, tangentFix=True)
                cn.uiEnable(controls='modelPanel')
            else:
                cmds.xform(obj, roo=ro)
            # done
            message('Rotate order changed: -- ' + roLst[origRO] + '   to   ' + ro, maya=True)
        else:
            message('Rotate order already set -- ' + ro)
    else:
        message('FAIL. Rotate order is LOCKED or CONNECTED to a custom attribute.', maya=True)
Пример #12
0
    def restoreSettings(self):
        '''
        restore all UI settings
        '''
        cmds.autoKeyframe(state=self.dataStore['autoKey'])

        # timeline management
        cmds.currentTime(self.dataStore['currentTime'])
        cmds.playbackOptions(min=self.dataStore['minTime'])
        cmds.playbackOptions(max=self.dataStore['maxTime'])
        cmds.playbackOptions(ast=self.dataStore['startTime'])
        cmds.playbackOptions(aet=self.dataStore['endTime'])
        cmds.playbackOptions(ps=self.dataStore['playSpeed'])
        cmds.playbackOptions(loop=self.dataStore['playLoop'])

        # unit management
        cmds.currentUnit(time=self.dataStore['timeUnit'])
        cmds.currentUnit(linear=self.dataStore['sceneUnits'])
        if not cmds.upAxis(axis=True, q=True) == self.dataStore['upAxis']:
            cmds.upAxis(axis=self.dataStore['upAxis'])

        log.debug('Restored PlayBack / Timeline setup')

        # viewport colors
        cmds.displayPref(displayGradient=self.dataStore['displayGradient'])
        cmds.displayRGBColor(resetToSaved=True)

        # objects colors
        cmds.displayColor("curve", self.dataStore['curvecolor'], dormant=True)

        # panel management
        for panel, data in self.dataStore['panelStore'].items():
            try:
                cmdString = data['settings'].replace('$editorName', panel)
                mel.eval(cmdString)
                log.debug("Restored Panel Settings Data >> %s" % panel)
                mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel))
                log.debug("Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam']))
            except:
                log.debug("Failed to fully Restore ActiveCamera Data >> %s >> cam : %s" % (panel, data['activeCam']))

        # camera management
        for cam, settings in self.dataStore['cameraTransforms'].items():
            try:
                cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2])
                cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2])
                cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2])
                log.debug('Restored Default Camera Transform Data : % s' % cam)
            except:
                log.debug("Failed to fully Restore Default Camera Transform Data : % s" % cam)

        # sound management
        if self.dataStore['displaySound']:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound'])
            log.debug('Restored Audio setup')
        else:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=0)
        log.debug('Scene Restored fully')
        return True
Пример #13
0
    def restoreSettings(self):
        '''
        restore all UI settings
        '''
        cmds.autoKeyframe(state=self.dataStore['autoKey'])

        # timeline management
        cmds.currentTime(self.dataStore['currentTime'])
        cmds.playbackOptions(min=self.dataStore['minTime'])
        cmds.playbackOptions(max=self.dataStore['maxTime'])
        cmds.playbackOptions(ast=self.dataStore['startTime'])
        cmds.playbackOptions(aet=self.dataStore['endTime'])
        cmds.playbackOptions(ps=self.dataStore['playSpeed'])
        cmds.playbackOptions(loop=self.dataStore['playLoop'])

        # unit management
        cmds.currentUnit(time=self.dataStore['timeUnit'])
        cmds.currentUnit(linear=self.dataStore['sceneUnits'])
        if not cmds.upAxis(axis=True, q=True) == self.dataStore['upAxis']:
            cmds.upAxis(axis=self.dataStore['upAxis'])

        log.debug('Restored PlayBack / Timeline setup')

        # viewport colors
        cmds.displayPref(displayGradient=self.dataStore['displayGradient'])
        cmds.displayRGBColor(resetToSaved=True)

        # objects colors
        cmds.displayColor("curve", self.dataStore['curvecolor'], dormant=True)

        # panel management
        for panel, data in self.dataStore['panelStore'].items():
            try:
                cmdString = data['settings'].replace('$editorName', panel)
                mel.eval(cmdString)
                log.debug("Restored Panel Settings Data >> %s" % panel)
                mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel))
                log.debug("Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam']))
            except:
                log.debug("Failed to fully Restore ActiveCamera Data >> %s >> cam : %s" % (panel, data['activeCam']))

        # camera management
        for cam, settings in self.dataStore['cameraTransforms'].items():
            try:
                cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2])
                cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2])
                cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2])
                log.debug('Restored Default Camera Transform Data : % s' % cam)
            except:
                log.debug("Failed to fully Restore Default Camera Transform Data : % s" % cam)

        # sound management
        if self.dataStore['displaySound']:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound'])
            log.debug('Restored Audio setup')
        else:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=0)
        log.debug('Scene Restored fully')
        return True
Пример #14
0
def distributeKeys(step=3.0, destructive=True, forceWholeFrames=True):
    '''
    operates on selected curves
    '''
    s = GraphSelection()
    sel = cmds.ls(sl=1, fl=True)
    rng = fr.Get()
    if s.crvs:
        # gather info
        autoK = cmds.autoKeyframe(q=True, state=True)
        frames = getKeyedFrames(s.crvs)
        # process start/end of loop
        framesNew = []
        if rng.selection:
            for f in frames:
                if f >= rng.keyStart and f <= rng.keyEnd:
                    framesNew.append(f)
            frames = framesNew
        #
        cut = []
        # print frames
        if forceWholeFrames:
            framesOrig = frames
            frames = [round(frame) for frame in frames]
            framesPartial = list(set(framesOrig) - set(frames))
            cut = [frame for frame in framesPartial]
            # print cut, '______cut'
        lastFrame = frames[len(frames) - 1]
        count = frames[0]
        i = frames[0]
        # turn off autokey
        cmds.autoKeyframe(state=False)
        framesNew = []
        # process keys
        while i < lastFrame:
            if i == count:
                cmds.setKeyframe(s.crvs, i=True, t=count)
                framesNew.append(count)
                count = count + step
            else:
                if i in frames:
                    cut.append(i)
            i = i + 1
        # remove keys is destructive
        if destructive:
            framesDel = sorted(list(set(frames) - set(framesNew)))
            for frame in framesDel:
                cut.append(frame)
            # print framesOrig, '________orig'
            # print framesNew, '________new'
            # print cut, '_________cut'
            if cut:
                for frame in cut:
                    if frame >= rng.keyStart and frame <= rng.keyEnd:
                        cmds.cutKey(sel, clear=1, time=(frame, frame))
        # restore autokey
        cmds.autoKeyframe(state=autoK)
    else:
        message('Select one or more anima curves', maya=1)
Пример #15
0
def snap_objects(driver, driven, bake=False, translate=True, rotate=True):
    """This function will take an object of list of objects (driven) and snap them in world space
    translate and rotation to match the driver. If bake, do this across the time range"""

    if not isinstance(driver, basestring) or not cmds.objExists(driver):
        raise RuntimeError(
            '{0} does not exist in the maya session'.format(driver))
    if isinstance(driven, list):
        for each in driven:
            if not isinstance(each, basestring) or not cmds.objExists(each):
                raise RuntimeError(
                    '{0} does not exist in the maya session'.format(each))
    elif isinstance(driven, basestring):
        if not cmds.objExists(driven):
            raise RuntimeError(
                '{0} does not exist in the maya session'.format(driven))
        driven = [driven]

    # if bake is off, snap a single frame
    if not bake:
        for each in driven:
            match_tranformation(driver, each, translate, rotate)

    # else
    else:
        # query the user's auto key state
        autokey_enabled = cmds.autoKeyframe(query=True, state=True)
        # query the current frame
        current_frame = get_current_frame()
        # set the keyable attributes
        attributes = []
        if translate:
            attributes.append("translate")
        if rotate:
            attributes.append("rotate")

        # turn off auto key. this is because for some reason using this bake process, the current
        # frame doesn't get correctly snapped with autokey on
        cmds.autoKeyframe(state=False)

        # loop through the time range
        start, end = get_timeline_range()
        for i in range(start, (end + 1)):
            # change the frame
            cmds.setAttr("time1.outTime", int(i))
            # loop through the selection and locator lists
            for each in driven:
                # snap the locator to the selection
                match_tranformation(driver, each, translate, rotate)
                # key the locator
                cmds.setKeyframe(each,
                                 time=i,
                                 shape=False,
                                 attribute=attributes)

        # restore the current frame
        cmds.setAttr("time1.outTime", current_frame)
        # restore the autokey
        cmds.autoKeyframe(state=autokey_enabled)
Пример #16
0
def setValue(mPlug, value, autoKey):
    """Set the argument value on the argument plug, setting an
    autoKeyframe on that attribute, if autoKey is True.

    The plug argument must be an MPlug."""

    if autoKey:
        cmds.autoKeyframe(edit=True, addAttr=mPlug.name())

    plug.Plug(mPlug).value = value
Пример #17
0
 def __exit__(self, *args):
         
     #reset settings
     mc.cycleCheck(evaluation=self.resetCycleCheck)
     mc.autoKeyframe(state=self.resetAutoKey)
     
     if self.sel:
         mc.select(self.sel)
         
     self.isolate(False)
Пример #18
0
    def bakeTempLocator(self, startTime=None, endTime=None):
        _str_func = 'PostBake.bakeTempLocator'

        if startTime is None:
            startTime = self.startTime
        if endTime is None:
            endTime = self.endTime

        ct = mc.currentTime(q=True)

        self._bakedLoc = cgmMeta.asMeta(LOC.create(name='bakeLoc'))
        self._bakedLoc.rotateOrder = self.obj.rotateOrder

        SNAP.matchTarget_set(self._bakedLoc.mNode, self.obj.mNode)

        _len = endTime - startTime
        _progressBar = cgmUI.doStartMayaProgressBar(_len, "Processing...")

        _obj = VALID.objString(self._bakedLoc.mNode, noneValid=False)
        _target = VALID.objString(
            self.obj.mNode, noneValid=False
        )  #ATTR.get_message(_obj, 'cgmMatchTarget','cgmMatchDat',0)

        ak = mc.autoKeyframe(q=True, state=True)
        mc.autoKeyframe(state=False)
        mc.refresh(su=True)

        completed = True

        for i in range(startTime, endTime + 1):
            mc.currentTime(i)
            SNAP.go(_obj, _target, True, True, pivot='rp')
            mc.setKeyframe(_obj, at=['translate', 'rotate'])

            if _progressBar:
                if mc.progressBar(_progressBar, query=True, isCancelled=True):
                    log.warning('Bake cancelled!')
                    completed = False
                    break

                mc.progressBar(_progressBar,
                               edit=True,
                               status=("{0} On frame {1}".format(_str_func,
                                                                 i)),
                               step=1,
                               maxValue=_len)

        mc.refresh(su=False)
        mc.autoKeyframe(state=ak)

        cgmUI.doEndMayaProgressBar(_progressBar)

        mc.currentTime(ct)

        return completed
Пример #19
0
	def func(*args, **kwargs):
		initialState = cmd.autoKeyframe(q=True, state=True)
		cmd.autoKeyframe(state=False)
		try:
			ret = f(*args, **kwargs)
		except:
			raise
		finally:
			cmd.autoKeyframe(state=initialState)

		return ret
Пример #20
0
 def __exit__(self, exc_type, exc_value, traceback):
     # Close the undo chunk, warn if any exceptions were caught:
     cmds.autoKeyframe(state=self.autoKeyState)
     cmds.currentTime(self.timeStore)
     log.info('autoKeyState restored: %s' % self.autoKeyState)
     log.info('currentTime restored: %f' % self.timeStore)
     cmds.undoInfo(closeChunk=True)
     if exc_type:
         log.exception('%s : %s'%(exc_type, exc_value))
     # If this was false, it would re-raise the exception when complete
     return True
Пример #21
0
 def __exit__(self, exc_type, exc_value, traceback):
     # Close the undo chunk, warn if any exceptions were caught:
     cmds.autoKeyframe(state=self.autoKeyState)
     cmds.currentTime(self.timeStore)
     log.info('autoKeyState restored: %s' % self.autoKeyState)
     log.info('currentTime restored: %f' % self.timeStore)
     cmds.undoInfo(closeChunk=True)
     if exc_type:
         log.exception('%s : %s' % (exc_type, exc_value))
     # If this was false, it would re-raise the exception when complete
     return True
Пример #22
0
    def func(*args, **kwargs):
        initialState = cmd.autoKeyframe(q=True, state=True)
        cmd.autoKeyframe(state=False)
        try:
            ret = f(*args, **kwargs)
        except:
            raise
        finally:
            cmd.autoKeyframe(state=initialState)

        return ret
Пример #23
0
	def actualFunc(*args):
		start = time.clock()
		initialAutoKeyState = cmd.autoKeyframe(q=True,state=True)
		cmd.autoKeyframe(state=False)
		api.mel.zooAllViews(0)

		retVal = f(*args)

		api.mel.zooAllViews(1)
		cmd.autoKeyframe(state=initialAutoKeyState)
		print 'time taken',time.clock()-start,'secs'
		return retVal
Пример #24
0
    def actualFunc(*args):
        start = time.clock()
        initialAutoKeyState = cmd.autoKeyframe(q=True, state=True)
        cmd.autoKeyframe(state=False)
        api.mel.zooAllViews(0)

        retVal = f(*args)

        api.mel.zooAllViews(1)
        cmd.autoKeyframe(state=initialAutoKeyState)
        print 'time taken', time.clock() - start, 'secs'
        return retVal
Пример #25
0
    def restoreSettings(self):
        '''
        restore all UI settings
        '''
        cmds.autoKeyframe(state=self.dataStore['autoKey'])

        #timeline management
        cmds.currentTime(self.dataStore['currentTime'])
        cmds.playbackOptions(min=self.dataStore['minTime'])
        cmds.playbackOptions(max=self.dataStore['maxTime'])
        cmds.playbackOptions(ast=self.dataStore['startTime'])
        cmds.playbackOptions(aet=self.dataStore['endTime'])
        cmds.playbackOptions(ps=self.dataStore['playSpeed'])

        #unit management
        cmds.currentUnit(time=self.dataStore['timeUnit'])
        cmds.currentUnit(linear=self.dataStore['sceneUnits'])
        cmds.upAxis(axis=self.dataStore['upAxis'])

        log.info('Restored PlayBack / Timeline setup')

        #panel management
        for panel, data in self.dataStore['panelStore'].items():
            cmdString = data['settings'].replace('$editorName', panel)
            mel.eval(cmdString)
            log.info("Restored Panel Settings Data >> %s" % panel)
            mel.eval('lookThroughModelPanel("%s","%s")' %
                     (data['activeCam'], panel))
            log.info("Restored Panel Active Camera Data >> %s >> cam : %s" %
                     (panel, data['activeCam']))

        # camera management
        for cam, settings in self.dataStore['cameraTransforms'].items():
            cmds.setAttr('%s.translate' % cam, settings[0][0][0],
                         settings[0][0][1], settings[0][0][2])
            cmds.setAttr('%s.rotate' % cam, settings[1][0][0],
                         settings[1][0][1], settings[1][0][2])
            cmds.setAttr('%s.scale' % cam, settings[2][0][0],
                         settings[2][0][1], settings[2][0][2])
            log.info('Restored Default Camera Transform Data : % s' % cam)

        #sound management
        if self.dataStore['displaySound']:
            cmds.timeControl(self.gPlayBackSlider,
                             e=True,
                             ds=1,
                             sound=self.dataStore['activeSound'])
            log.info('Restored Audio setup')
        else:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=0)
        return True
Пример #26
0
 def __enter__(self):
 
     self.sel = mc.ls(sl=True)
     self.modelPanels = mc.getPanel(type='modelPanel')
     self.isolate(True)
     
     mc.select(clear=True)
     
     #save and turn off settings that might print to the script editor
     self.resetCycleCheck = mc.cycleCheck(query=True, evaluation=True)
     mc.cycleCheck(evaluation=False)
     
     self.resetAutoKey = mc.autoKeyframe(query=True, state=True)
     mc.autoKeyframe(state=False)
Пример #27
0
def distributeKeys(count=3.0, destructive=True):
    sel = cmds.ls(sl=1, fl=True)
    rng = fr.Get()
    if sel:
        # gather info
        autoK = cmds.autoKeyframe(q=True, state=True)
        frames = getKeyedFrames(sel)
        if not frames:
            # add a bake if no keys exist, then get keys again
            message('No keys found, setting a key start/end of range.', maya=1)
            cmds.setKeyframe(sel, t=(rng.start, rng.start))
            cmds.setKeyframe(sel, t=(rng.end, rng.end))
            frames = getKeyedFrames(sel)
            # return None
        # process start/end of loop
        framesNew = []
        if rng.selection:
            for f in frames:
                if f >= rng.keyStart and f <= rng.keyEnd:
                    framesNew.append(f)
            frames = framesNew
        #
        print frames
        lastFrame = frames[len(frames) - 1]
        step = frames[0]
        i = frames[0]
        cut = []
        # turn off autokey
        cmds.autoKeyframe(state=False)
        # process keys
        while i < lastFrame:
            if i == step:
                cmds.setKeyframe(sel, i=True, t=step)
                step = step + count
            else:
                if i in frames:
                    cut.append(i)
            i = i + 1
        # remove keys is destructive
        if destructive:
            # print cut, '_________'
            if cut:
                for frame in cut:
                    cmds.cutKey(sel, clear=1, time=(frame, frame))
        # restore autokey
        cmds.autoKeyframe(state=autoK)
    else:
        message('Select one or more objects', maya=1)
Пример #28
0
def snapWorld():
    sels = cmds.ls(sl=True)
    if not sels: return
    tc = mel.eval('$tmpVar=$gPlayBackSlider')
    tcRange = range(
        *[int(num) for num in cmds.timeControl(tc, q=True, rangeArray=True)])
    if len(tcRange) == 1: tcRange.append(tcRange[0] + 1)

    sel = sels[-1]
    cmds.currentTime(tcRange[0])
    cmds.autoKeyframe(state=True)
    __keyFrameTransform__(sel, False)
    tw = cmds.xform(sel, q=True, worldSpace=True, translation=True)
    rw = cmds.xform(sel, q=True, worldSpace=True, rotation=True)

    if len(sels) == 1:
        for ct in tcRange[1:]:
            cmds.currentTime(ct)
            try:
                cmds.xform(sel, translation=tw, worldSpace=True)
            except:
                pass
            try:
                cmds.xform(sel, rotation=rw, worldSpace=True)
            except:
                pass
            __keyFrameTransform__(sel)
        __keyFrameTransform__(sel, False)
    else:
        try:
            cmds.parentConstraint(sels,
                                  name='snapTargetParentConstraint',
                                  maintainOffset=True)
        except:
            cmds.headsUpMessage(u'对象属性被锁定,无法吸附目标', time=1)
            return
        for ct in tcRange[1:]:
            cmds.currentTime(ct)
            __keyFrameTransform__(sel)
        __keyFrameTransform__(sel, False)
        cmds.delete('snapTargetParentConstraint')

    cmds.currentTime(tcRange[-1])
    cmds.timeControl(tc, e=True, forceRefresh=True)
Пример #29
0
    def storeSettings(self):
        '''
        main work function, store all UI settings
        '''
        self.dataStore['autoKey'] = cmds.autoKeyframe(query=True, state=True)

        # timeline management
        self.dataStore['currentTime'] = cmds.currentTime(q=True)
        self.dataStore['minTime'] = cmds.playbackOptions(q=True, min=True)
        self.dataStore['maxTime'] = cmds.playbackOptions(q=True, max=True)
        self.dataStore['startTime'] = cmds.playbackOptions(q=True, ast=True)
        self.dataStore['endTime'] = cmds.playbackOptions(q=True, aet=True)
        self.dataStore['playSpeed'] = cmds.playbackOptions(query=True,
                                                           playbackSpeed=True)

        # unit management
        self.dataStore['timeUnit'] = cmds.currentUnit(q=True,
                                                      fullName=True,
                                                      time=True)
        self.dataStore['sceneUnits'] = cmds.currentUnit(q=True,
                                                        fullName=True,
                                                        linear=True)
        self.dataStore['upAxis'] = cmds.upAxis(q=True, axis=True)

        #panel management
        self.dataStore['panelStore'] = {}
        for panel in [
                'modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4'
        ]:
            if not cmds.modelPanel(panel, q=True, exists=True):
                continue
            self.dataStore['panelStore'][panel] = {}
            self.dataStore['panelStore'][panel]['settings'] = cmds.modelEditor(
                panel, q=True, sts=True)
            activeCam = cmds.modelPanel(panel, q=True, camera=True)
            if not cmds.nodeType(activeCam) == 'camera':
                activeCam = cmds.listRelatives(activeCam)[0]
            self.dataStore['panelStore'][panel]['activeCam'] = activeCam

        #camera management
        #TODO : store the camera field of view etc also
        self.dataStore['cameraTransforms'] = {}
        for cam in ['persp', 'top', 'side', 'front']:
            self.dataStore['cameraTransforms'][cam] = [
                cmds.getAttr('%s.translate' % cam),
                cmds.getAttr('%s.rotate' % cam),
                cmds.getAttr('%s.scale' % cam)
            ]

        #sound management
        self.dataStore['activeSound'] = cmds.timeControl(self.gPlayBackSlider,
                                                         q=True,
                                                         s=1)
        self.dataStore['displaySound'] = cmds.timeControl(self.gPlayBackSlider,
                                                          q=True,
                                                          ds=1)
Пример #30
0
    def restoreSettings(self):
        '''
        restore all UI settings
        '''
        cmds.autoKeyframe(state=self.dataStore['autoKey'])
        
        #timeline management
        cmds.currentTime(self.dataStore['currentTime'])
        cmds.playbackOptions(min=self.dataStore['minTime'])
        cmds.playbackOptions(max=self.dataStore['maxTime'])
        cmds.playbackOptions(ast=self.dataStore['startTime'])
        cmds.playbackOptions(aet=self.dataStore['endTime'])
        cmds.playbackOptions(ps=self.dataStore['playSpeed'])
        
        #unit management
        cmds.currentUnit(time=self.dataStore['timeUnit'])
        cmds.currentUnit(linear=self.dataStore['sceneUnits'])
        cmds.upAxis(axis=self.dataStore['upAxis'])
        
        log.info('Restored PlayBack / Timeline setup')
        
        #panel management
        for panel, data in self.dataStore['panelStore'].items():
            cmdString = data['settings'].replace('$editorName', panel)
            mel.eval(cmdString)
            log.info("Restored Panel Settings Data >> %s" % panel)
            mel.eval('lookThroughModelPanel("%s","%s")' % (data['activeCam'], panel))
            log.info("Restored Panel Active Camera Data >> %s >> cam : %s" % (panel, data['activeCam']))
            
        # camera management
        for cam, settings in self.dataStore['cameraTransforms'].items():
            cmds.setAttr('%s.translate' % cam, settings[0][0][0], settings[0][0][1], settings[0][0][2])
            cmds.setAttr('%s.rotate' % cam, settings[1][0][0], settings[1][0][1], settings[1][0][2])
            cmds.setAttr('%s.scale' % cam, settings[2][0][0], settings[2][0][1], settings[2][0][2])
            log.info('Restored Default Camera Transform Data : % s' % cam)

        #sound management
        if self.dataStore['displaySound']:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=1, sound=self.dataStore['activeSound'])
            log.info('Restored Audio setup')
        else:
            cmds.timeControl(self.gPlayBackSlider, e=True, ds=0)
        return True
Пример #31
0
    def replay(s, data):
        """
        Places the data back onto the objects in the scene at the current time.
        Accepts = { object : { attribute : [val1, val2, val3, ... ] } }
        """
        frame = cmds.currentTime(q=True)  # Current time to start at
        index = 0  # Current index
        # Validate objects and build a working set of data
        validData = {}
        for o, attrs in data.items():
            if cmds.objExists(o):  # Check for object existance
                for at in attrs:
                    if cmds.attributeQuery(at, n=o, ex=True):
                        validData["%s.%s" % (o, at)] = data[o][at]
                    else:
                        print "%s.%s could not be found. Skipping!" % (o, at)
            else:
                print "%s could not be found. Skipping!" % o
        # Ok our data is now valid. Lets get a posin! Phew. The final step...
        if not validData: raise RuntimeError, "Nothing in the Clip to pose."

        cmds.undoInfo(openChunk=True)
        autokeyState = cmds.autoKeyframe(q=True, state=True)
        cmds.autoKeyframe(state=False)  # Turn off autokey
        try:  # Open undo block!
            for attr, vals in validData.iteritems():
                frames = len(vals)  # Get length to iterate!
                break

            for i in range(frames):
                cmds.currentTime(frame + i)  # Jump to frame
                for attr, vals in validData.iteritems():  # Lots of looping. :(
                    try:
                        cmds.setAttr(attr, vals[i])
                        cmds.setKeyframe(attr)
                    except RuntimeError as e:
                        print "Warning \"%s\" :: %s" % (attr, e)
            print "Clip posed!"
        finally:
            cmds.autoKeyframe(state=autokeyState)
            cmds.undoInfo(closeChunk=True)
Пример #32
0
    def replay(s, data):
        """
        Places the data back onto the objects in the scene at the current time.
        Accepts = { object : { attribute : [val1, val2, val3, ... ] } }
        """
        frame = cmds.currentTime(q=True) # Current time to start at
        index = 0 # Current index
        # Validate objects and build a working set of data
        validData = {}
        for o, attrs in data.items():
            if cmds.objExists(o): # Check for object existance
                for at in attrs:
                    if cmds.attributeQuery(at, n=o, ex=True):
                        validData["%s.%s" % (o, at)] = data[o][at]
                    else:
                        print "%s.%s could not be found. Skipping!" % (o, at)
            else:
                print "%s could not be found. Skipping!" % o
        # Ok our data is now valid. Lets get a posin! Phew. The final step...
        if not validData: raise RuntimeError, "Nothing in the Clip to pose."

        cmds.undoInfo(openChunk=True)
        autokeyState = cmds.autoKeyframe(q=True, state=True)
        cmds.autoKeyframe(state=False) # Turn off autokey
        try: # Open undo block!
            for attr, vals in validData.iteritems():
                frames = len(vals) # Get length to iterate!
                break

            for i in range(frames):
                cmds.currentTime(frame + i) # Jump to frame
                for attr, vals in validData.iteritems(): # Lots of looping. :(
                    try:
                        cmds.setAttr(attr, vals[i])
                        cmds.setKeyframe(attr)
                    except RuntimeError as e:
                        print "Warning \"%s\" :: %s" % (attr, e)
            print "Clip posed!"
        finally:
            cmds.autoKeyframe(state=autokeyState)
            cmds.undoInfo(closeChunk=True)
Пример #33
0
    def __enter__(self):
        self.autoKeyState = cmds.autoKeyframe(query=True, state=True)
        self.timeStore['currentTime'] = cmds.currentTime(q=True)
        self.timeStore['minTime'] = cmds.playbackOptions(q=True, min=True)
        self.timeStore['maxTime'] = cmds.playbackOptions(q=True, max=True)
        self.timeStore['startTime'] = cmds.playbackOptions(q=True, ast=True)
        self.timeStore['endTime'] = cmds.playbackOptions(q=True, aet=True)
        self.timeStore['playSpeed'] = cmds.playbackOptions(query=True, playbackSpeed=True)

        # force AutoKey OFF
        cmds.autoKeyframe(state=self.autokey)

        if self.mangage_undo:
            cmds.undoInfo(openChunk=True)
        else:
            cmds.undoInfo(swf=False)
        if self.manage_em:
            if r9Setup.mayaVersion() >= 2016:
                self.evalmode = cmds.evaluationManager(mode=True, q=True)[0]
                if self.evalmode == 'parallel':
                    evalManagerState(mode='off')
Пример #34
0
    def __enter__(self):
        self.autoKeyState = cmds.autoKeyframe(query=True, state=True)
        self.timeStore['currentTime'] = cmds.currentTime(q=True)
        self.timeStore['minTime'] = cmds.playbackOptions(q=True, min=True)
        self.timeStore['maxTime'] = cmds.playbackOptions(q=True, max=True)
        self.timeStore['startTime'] = cmds.playbackOptions(q=True, ast=True)
        self.timeStore['endTime'] = cmds.playbackOptions(q=True, aet=True)
        self.timeStore['playSpeed'] = cmds.playbackOptions(query=True, playbackSpeed=True)

        # force AutoKey OFF
        cmds.autoKeyframe(state=self.autokey)

        if self.mangage_undo:
            cmds.undoInfo(openChunk=True)
        else:
            cmds.undoInfo(swf=False)
        if self.manage_em:
            if r9Setup.mayaVersion() >= 2016:
                self.evalmode = cmds.evaluationManager(mode=True, q=True)[0]
                if self.evalmode == 'parallel':
                    evalManagerState(mode='off')
Пример #35
0
def autoKeyed():
    """Returns the attribute(s) that the autoKeyframe command will set.

    The attribute(s) is returned in a set.  If autoKeyframe is off, an
    empty set is returned."""

    # If autoKeyframe is off, nothing to do.
    if not isEnabled():
        return set()

    autoKeyed = cmds.autoKeyframe(query=True, listAttr=True)
    return set() if autoKeyed is None else set(autoKeyed)
Пример #36
0
    def storeSettings(self):
        '''
        main work function, store all UI settings
        '''
        self.dataStore['autoKey'] = cmds.autoKeyframe(query=True, state=True)

        # timeline management
        self.dataStore['currentTime'] = cmds.currentTime(q=True)
        self.dataStore['minTime'] = cmds.playbackOptions(q=True, min=True)
        self.dataStore['maxTime'] = cmds.playbackOptions(q=True, max=True)
        self.dataStore['startTime'] = cmds.playbackOptions(q=True, ast=True)
        self.dataStore['endTime'] = cmds.playbackOptions(q=True, aet=True)
        self.dataStore['playSpeed'] = cmds.playbackOptions(query=True, playbackSpeed=True)
        self.dataStore['playLoop'] = cmds.playbackOptions(query=True, loop=True)

        # unit management
        self.dataStore['timeUnit'] = cmds.currentUnit(q=True, fullName=True, time=True)
        self.dataStore['sceneUnits'] = cmds.currentUnit(q=True, fullName=True, linear=True)
        self.dataStore['upAxis'] = cmds.upAxis(q=True, axis=True)

        # viewport colors
        self.dataStore['displayGradient'] = cmds.displayPref(q=True, displayGradient=True)

        # objects colors
        self.dataStore['curvecolor'] = cmds.displayColor("curve", q=True, dormant=True)

        # panel management
        self.dataStore['panelStore'] = {}
        for panel in ['modelPanel1', 'modelPanel2', 'modelPanel3', 'modelPanel4']:
            if not cmds.modelPanel(panel, q=True, exists=True):
                continue
            self.dataStore['panelStore'][panel] = {}
            self.dataStore['panelStore'][panel]['settings'] = cmds.modelEditor(panel, q=True, sts=True)
            activeCam = cmds.modelPanel(panel, q=True, camera=True)
            if not cmds.nodeType(activeCam) == 'camera':
                activeCam = cmds.listRelatives(activeCam, f=True)[0]
            self.dataStore['panelStore'][panel]['activeCam'] = activeCam

        # camera management
        # TODO : store the camera field of view etc also
        self.dataStore['cameraTransforms'] = {}
        for cam in ['persp', 'top', 'side', 'front']:
            try:
                self.dataStore['cameraTransforms'][cam] = [cmds.getAttr('%s.translate' % cam),
                                                     cmds.getAttr('%s.rotate' % cam),
                                                     cmds.getAttr('%s.scale' % cam)]
            except:
                log.debug("Camera doesn't exists : %s" % cam)

        # sound management
        self.dataStore['activeSound'] = cmds.timeControl(self.gPlayBackSlider, q=True, s=1)
        self.dataStore['displaySound'] = cmds.timeControl(self.gPlayBackSlider, q=True, ds=1)
Пример #37
0
def apply_operation(in_frame, out_frame, attr1, attr2, out_attr, func):
    autokey = cmds.autoKeyframe(state=True, q=True)
    err = cmds.undoInfo(openChunk=True)
    try:
        cmds.autoKeyframe(state=False)
        # Collect data:
        attr1_data = []
        attr2_data = []
        for frame in range(int(in_frame), int(out_frame) + 1):
            attr1_data.append(cmds.getAttr(attr1, t=frame))
            attr2_data.append(cmds.getAttr(attr2, t=frame))
        for i, (at1, at2) in enumerate(zip(attr1_data, attr2_data)):
            frame = i + in_frame
            ans = func(at1, at2)
            cmds.setKeyframe(out_attr, t=frame, v=ans)
    except Exception as err:
        raise
    finally:
        cmds.autoKeyframe(state=autokey)
        cmds.undoInfo(closeChunk=True)
        if err:
            cmds.undo()
Пример #38
0
    def addCharacter(self, close, *args):
        project = cmds.optionMenu(self.widgets["project"], q=True, value=True)
        selectedCharacter = cmds.textScrollList(self.widgets["characterList"],
                                                q=True,
                                                si=True)[0]
        rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + selectedCharacter + ".mb"

        #find existing namespaces in scene
        namespaces = cmds.namespaceInfo(listOnlyNamespaces=True)

        #reference the rig file
        cmds.file(rigPath,
                  r=True,
                  type="mayaBinary",
                  loadReferenceDepth="all",
                  namespace=selectedCharacter,
                  options="v=0")

        #clear selection and fit view
        cmds.select(clear=True)

        #query autoKeyFrame state
        if not cmds.autoKeyframe(q=True, state=True):
            cmds.viewFit()
        #cmds.viewFit()
        panels = cmds.getPanel(type='modelPanel')

        #turn on smooth shading
        for panel in panels:
            editor = cmds.modelPanel(panel, q=True, modelEditor=True)
            cmds.modelEditor(editor,
                             edit=True,
                             displayAppearance="smoothShaded",
                             displayTextures=True,
                             textures=True)

        #find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created)
        newCharacterName = selectedCharacter
        newNamespaces = cmds.namespaceInfo(listOnlyNamespaces=True)

        for name in newNamespaces:
            if name not in namespaces:
                newCharacterName = name

        #launch UI
        import ART_animationUI
        reload(ART_animationUI)
        ART_animationUI.AnimationUI()

        if close:
            cmds.deleteUI(self.widgets["window"])
Пример #39
0
 def __exit__(self, exc_type, exc_value, traceback):
     # Close the undo chunk, warn if any exceptions were caught:
     cmds.autoKeyframe(state=self.autoKeyState)
     log.info('autoKeyState restored: %s' % self.autoKeyState)
     
     if self.manage_em and self.evalmode:
         evalManagerState(mode=self.evalmode)
         log.info('evalManager restored: %s' % self.evalmode)
     if self.manage_time:
         cmds.currentTime(self.timeStore['currentTime'])
         cmds.playbackOptions(min=self.timeStore['minTime'])
         cmds.playbackOptions(max=self.timeStore['maxTime'])
         cmds.playbackOptions(ast=self.timeStore['startTime'])
         cmds.playbackOptions(aet=self.timeStore['endTime'])
         cmds.playbackOptions(ps=self.timeStore['playSpeed'])
         log.info('currentTime restored: %f' % self.timeStore['currentTime'])
     if self.mangage_undo:
         cmds.undoInfo(closeChunk=True)
     else:
         cmds.undoInfo(swf=True)
     if exc_type:
         log.exception('%s : %s'%(exc_type, exc_value))
     # If this was false, it would re-raise the exception when complete
     return True
Пример #40
0
def extractShp(normalPoseFrame, downPoseFrame, upPoseFrame, geo):
	'''
	Description:
	Main function.
	Extract target shape for selected controls.
	Select controls and select geometry last.

	Arguments:
	normalPoseFrame(int)
	downPoseFrame(int)
	upPoseFrame(int)
	geo(string)

	Returns:
	Nothing
	'''

	cmds.autoKeyframe(state = False)

	ctrls = cmds.ls(sl = True)

	# Unlock translate attribute of geo
	cmds.setAttr('%s.translate' %geo, lock = False)

	for ctrl in ctrls:
		# Go to the down pose frame and get translate and rotate
		ctrlTrns, ctrlRo = getTrRo(ctrl, downPoseFrame)
		
		# Back to the normal pose frame and extract target
		duplicateGeo(normalPoseFrame, ctrl, ctrlTrns, ctrlRo, geo, 'down')
		
		# Go to the up pose frame and get translate and rotate
		ctrlTrns, ctrlRo = getTrRo(ctrl, upPoseFrame)
		
		# Back to the normal pose frame and extract target
		duplicateGeo(normalPoseFrame, ctrl, ctrlTrns, ctrlRo, geo, 'up')
Пример #41
0
def transferAnimation(markers, mocap, offsets, frameNumber, areDividedMarkers):

    cmds.autoKeyframe(state=True)

    markerGroupOffset = getObjectPoint(markers)
    mocapGroupOffset = getObjectPoint(mocap)

    markersList = []
    if (areDividedMarkers):
        markersParents = cmds.listRelatives(markers)
        for i in range(len(markersParents)):
            markersList += cmds.listRelatives(markersParents[i])
        markersList = sorted(markersList)
    else:
        markersList = cmds.listRelatives(markers)

    cmds.currentTime(frameNumber)

    for i in range(len(markersList)):

        mocapPoint = getObjectPoint(markersList[i][:-4])

        newMarkerPoint = [
            mocapPoint[0] + mocapGroupOffset[0] + offsets[i][0],
            mocapPoint[1] + mocapGroupOffset[1] + offsets[i][1],
            mocapPoint[2] + mocapGroupOffset[2] + offsets[i][2]
        ]

        cmds.setAttr(markersList[i] + ".translateX",
                     newMarkerPoint[0] - markerGroupOffset[0])
        cmds.setAttr(markersList[i] + ".translateY",
                     newMarkerPoint[1] - markerGroupOffset[1])
        cmds.setAttr(markersList[i] + ".translateZ",
                     newMarkerPoint[2] - markerGroupOffset[2])

        cmds.setKeyframe(markersList[i])
    def addCharacter(self, close, *args):
        project = cmds.optionMenu(self.widgets["project"], q = True, value = True)
        selectedCharacter = cmds.textScrollList(self.widgets["characterList"], q = True, si = True)[0]
        rigPath = self.mayaToolsDir + "/General/ART/Projects/" + project + "/AnimRigs/" + selectedCharacter + ".mb"


        #find existing namespaces in scene
        namespaces = cmds.namespaceInfo(listOnlyNamespaces = True)

        #reference the rig file
        cmds.file(rigPath, r = True, type = "mayaBinary", loadReferenceDepth = "all", namespace = selectedCharacter, options = "v=0")

        #clear selection and fit view
        cmds.select(clear = True)
        
        #query autoKeyFrame state
        if not cmds.autoKeyframe(q = True, state = True):
            cmds.viewFit()
        #cmds.viewFit()
        panels = cmds.getPanel(type = 'modelPanel')


        #turn on smooth shading
        for panel in panels:
            editor = cmds.modelPanel(panel, q = True, modelEditor = True)
            cmds.modelEditor(editor, edit = True, displayAppearance = "smoothShaded", displayTextures = True, textures = True )



        #find new namespaces in scene (this is here in case I need to do something later and I need the new name that was created)
        newCharacterName = selectedCharacter
        newNamespaces = cmds.namespaceInfo(listOnlyNamespaces = True)

        for name in newNamespaces:
            if name not in namespaces:
                newCharacterName = name

        #launch UI
        import ART_animationUI
        reload(ART_animationUI)
        ART_animationUI.AnimationUI()

        if close:
            cmds.deleteUI(self.widgets["window"])
Пример #43
0
#**********************************************************************************
#*********************   IK FK switch matching   **********************************
#**********************************************************************************

import maya.cmds as cmds

akf = cmds.autoKeyframe(q=True, state=True)
if akf:
    cmds.autoKeyframe(state=0)
    
selecList = cmds.ls(sl=True)

for selection in selecList:
    if "IK" in selection or "FK" in selection:
        namespace = selection.split(':')
        namespace = namespace[0]+":" if len(namespace)>1  else ""
        ctrl_IK =""
        ctrl_IK_pole = ""
        ctrls_FK_tip = ""
        ctrls_FK_mid = ""
        ctrls_FK_base = ""
        ctrl_IK_FK_switch = ""
        jnt_base = ""
        jnt_mid = ""
        lc_base = ""
        lc_mid = ""
        if "ctrl_arm_IK_left" == selection or "ctrl_hand_FK_left" == selection:
            ctrl_IK = namespace+"ctrl_arm_IK_left"
            ctrl_IK_pole = namespace+"ctrl_elbow_IK_left"
            ctrls_FK_tip = namespace+"ctrl_hand_FK_left"
            ctrls_FK_mid = namespace+"ctrl_elbow_FK_left"
Пример #44
0
	def __init__( self, *args ):
		self.get_global()

		selected = cmds.ls( sl = True )

		controller_list = {}
		opposite_set = None
		auto_key = cmds.autoKeyframe( st = True, q = True )

		if auto_key:
			cmds.autoKeyframe( st = False )

		if selected:

			for obj in selected:
				obj_set_attr = '{0}.{1}'.format( obj, self.set_parent_str )

				if cmds.objExists( obj_set_attr ):
					obj_set = cmds.listConnections( obj_set_attr )

					if obj_set:
						obj_set = obj_set[0]

						opposite_set_attr = '{0}.{1}'.format( obj_set, self.opposite_set_str )

						if cmds.objExists( opposite_set_attr ):
							opposite_set = cmds.listConnections( opposite_set_attr )

						if opposite_set:
							opposite_set = opposite_set[0]

							for controller in cmds.sets( opposite_set, q = True ):
								controller_order_attr = '{0}.{1}'.format( controller, self.snap_order_attr )

								if cmds.objExists( controller_order_attr ):
									controller_order = cmds.getAttr( controller_order_attr )

									if controller_order:
										controller_order = int( controller_order[0] )

										controller_list[controller_order] = controller

			for controller in controller_list.values():

				obj_snap_attr = '{0}.{1}'.format( controller, self.snap_parent_str )

				print obj_snap_attr

				if cmds.objExists( obj_snap_attr ):
					snap_obj = cmds.listConnections( obj_snap_attr )

					if snap_obj:
						snap_obj = snap_obj[0]

						tra = cmds.xform( snap_obj, ws = True, rp = True, q = True )
						rot = cmds.xform( snap_obj, ws = True, ro = True, q = True )

						try:
							cmds.xform( controller, ws = True, t = tra )

						except:
							pass

						try:
							cmds.xform( controller, ws = True, ro = rot )

						except:
							try:
								rot_x = cmds.getAttr( '{0}.rotateX'.format( snap_obj ) )
								cmds.setAttr( '{0}.rotateX'.format( controller ), rot_x )

							except:
								pass

							try:
								rot_x = cmds.getAttr( '{0}.rotateY'.format( snap_obj ) )
								cmds.setAttr( '{0}.rotateY'.format( controller ), rot_x )

							except:
								pass

							try:
								rot_x = cmds.getAttr( '{0}.rotateZ'.format( snap_obj ) )
								cmds.setAttr( '{0}.rotateZ'.format( controller ), rot_x )

							except:
								pass

			if not opposite_set:
				OpenMaya.MGlobal.displayError( "Can not find FKIK Snap on selected controller!" )

			else:

				switch_attr = cmds.listConnections( '{0}.{1}'.format( opposite_set, self.switch_parent_str ), plugs = True )[0]

				current_time = cmds.currentTime( query = True )
				cmds.setKeyframe( switch_attr, time = current_time - 1 )
				cmds.setKeyframe( cmds.sets( obj_set, q = True ), cmds.sets( opposite_set, q = True ) )

				if cmds.getAttr( switch_attr ) == 0:
					cmds.setAttr( switch_attr, 1 )

				elif cmds.getAttr( switch_attr ) == 1:
					cmds.setAttr( switch_attr, 0 )

				cmds.setKeyframe( switch_attr )

		else:
			OpenMaya.MGlobal.displayError( "You need to select a controller!" )

		if auto_key:
			cmds.autoKeyframe( st = True )

		cmds.select( cl = True )
Пример #45
0
	cmds.rowColumnLayout('drvrRowColLo', p = 'mainColLo', numberOfColumns = 5)
	cmds.textField('drvrTxtFld', p = 'drvrRowColLo', text = 'Driver Object')
	cmds.text(p = 'drvrRowColLo', label = '.')
	cmds.textField('drvrAttrTxtFld', p = 'drvrRowColLo', text = 'Driver Attribute')
	cmds.textField('drvrMinValTxtFld', p = 'drvrRowColLo', text = 'Min Value')
	cmds.textField('drvrMaxTxtFld', p = 'drvrRowColLo', text = 'Max Value')

	cmds.window(winName, e = True, w = 300, h = 300)
	cmds.showWindow(winName)




# Transfer Attributes Value to Parent #
selLs = cmds.ls(sl = True)
cmds.autoKeyframe(state = False)
for sel in selLs:	
	loc = sel
	prnt = cmds.listRelatives(loc, p = True)[0]
	attrList = cmds.listAttr(loc, keyable = True)
	for attr in attrList:
	    locAttrVal = cmds.getAttr('%s.%s' %(loc, attr))
	    cmds.setAttr('%s.%s' %(prnt, attr), locAttrVal)
	    
	    # Set default value for locator attribute
	    if 'scale' in attr or 'visibility' in attr:
	        dftVal = 1
	    else:
	        dftVal = 0
	    cmds.setAttr('%s.%s' %(loc, attr), dftVal)
Пример #46
0
 def __enter__(self):
     self.autoKeyState = cmds.autoKeyframe(query=True, state=True)
     self.time = int(cmds.currentTime(q=True))
     self.selection = cmds.ls(sl=True)
Пример #47
0
 def __enter__(self):
     self.autoKeyState=cmds.autoKeyframe(query=True, state=True)
     self.timeStore=cmds.currentTime(q=True)
     cmds.undoInfo(openChunk=True)
Пример #48
0
def matchValue_iterator(matchObj = None,
                        matchAttr = None,
                        drivenObj = None,
                        drivenAttr = None,
                        driverAttr = None, 
                        minIn = -179, maxIn = 179, maxIterations = 40, matchValue = None,
                        iterMode = 'step'):
    """
    Started with Jason Schleifer's afr js_iterator and 'tweaked'

    matchObj - The object to match to the driven
    driven - the object moved by the driver


    """
    _str_func = 'matchValue_iterator'
    log.debug("|{0}| >> ...".format(_str_func))    

    if type(minIn) not in [float,int]:raise ValueError,"matchValue_iterator>>> bad minIn: %s"%minIn
    if type(maxIn) not in [float,int]:raise ValueError,"matchValue_iterator>>> bad maxIn: %s"%maxIn

    __matchMode__ = False

    #>>> Data gather and arg check        
    mi_matchObj = cgmMeta.validateObjArg(matchObj,'cgmObject',noneValid=True)
    d_matchAttr = cgmMeta.validateAttrArg(matchAttr,noneValid=True)

    if mi_matchObj:
        __matchMode__ = 'matchObj'
        minValue = minIn
        maxValue = maxIn 

    elif d_matchAttr:
        __matchMode__ = 'matchAttr'
    elif matchValue is not None:
        __matchMode__ = 'value'
    else:
        raise ValueError,"|{0}| >> No match given. No matchValue given".format(_str_func)


    __drivenMode__ = False
    mi_drivenObj = None

    if drivenObj and drivenAttr:
        d_drivenAttr = cgmMeta.validateAttrArg("{0}.{1}".format(drivenObj,drivenAttr),noneValid=True)        
    else:
        mi_drivenObj = cgmMeta.validateObjArg(drivenObj,'cgmObject',noneValid=True)
        d_drivenAttr = cgmMeta.validateAttrArg(drivenAttr,noneValid=True)

    if mi_drivenObj and not drivenAttr:#not an object match but a value
        __drivenMode__ = 'object'
    elif d_drivenAttr:
        __drivenMode__ = 'attr'
        mPlug_driven = d_drivenAttr['mi_plug']
        f_baseValue = mPlug_driven.value	
        minRange = float(f_baseValue - 10)
        maxRange = float(f_baseValue + 10)  
        mPlug_driven
        log.debug("|{0}| >> Attr mode. Attr: {1} | baseValue: {2} ".format(_str_func,mPlug_driven.p_combinedShortName,f_baseValue))

    else:
        raise ValueError,"|{0}| >> No driven given".format(_str_func)


    d_driverAttr = cgmMeta.validateAttrArg(driverAttr,noneValid=False)
    mPlug_driver = d_driverAttr['mi_plug']
    if not mPlug_driver:
        raise ValueError,"|{0}| >> No driver given".format(_str_func)


    log.debug("|{0}| >> Source mode: {1} | Target mode: {2}| Driver: {3}".format(_str_func,__matchMode__,__drivenMode__,mPlug_driver.p_combinedShortName))

    # Meat ==========================================================================================
    b_autoFrameState = mc.autoKeyframe(q=True, state = True)
    if b_autoFrameState:
        mc.autoKeyframe(state = False)

    minValue = float(minIn)
    maxValue = float(maxIn)

    minUse = copy.copy(minValue)
    maxUse = copy.copy(maxValue)
    f_lastClosest = None
    f_lastValue = None
    cnt_sameValue = 0
    b_matchFound = None
    b_firstIter = True
    d_valueToSetting = {}

    #Source type: value
    for i in range(maxIterations):
        if __matchMode__ == 'value':
            if __drivenMode__ == 'attr':
                if iterMode == 'bounce':
                    log.debug("matchValue_iterator>>> Step : %s | min: %s | max: %s | baseValue: %s | current: %s"%(i,minValue,maxValue,f_baseValue,mPlug_driven.value))
                    if MATH.is_float_equivalent(mPlug_driven.value,matchValue,3):
                        log.debug("matchValue_iterator>>> Match found: %s == %s | %s: %s | step: %s"%(mPlug_driven.p_combinedShortName,matchValue,mPlug_driver.p_combinedShortName,minValue,i))  			    
                        b_matchFound = minValue
                        break

                    f_currentDist = abs(matchValue-mPlug_driven.value)
                    mPlug_driver.value = minValue#Set to min
                    f_minDist = abs(matchValue-mPlug_driven.value)#get Dif
                    f_minSetValue = mPlug_driven.value
                    mPlug_driver.value = maxValue#Set to max
                    f_maxDist = abs(matchValue-mPlug_driven.value)#Get dif
                    f_maxSetValue = mPlug_driven.value

                    f_half = ((maxValue-minValue)/2.0) + minValue#get half
                    #First find range
                    if f_minSetValue > matchValue or f_maxSetValue < matchValue:
                        log.error("Bad range, alternate range find. minSetValue = %s > %s < maxSetValue = %s"%(f_minSetValue,matchValue,f_maxSetValue))

                    if not MATH.is_float_equivalent(matchValue,0) and not MATH.is_float_equivalent(minValue,0) and not MATH.is_float_equivalent(f_minSetValue,0):
                        #if none of our values are 0, this is really fast
                        minValue = (minValue * matchValue)/f_minSetValue
                        log.debug("matchValue_iterator>>> Equated: %s"%minValue)		    
                        f_closest = f_minDist
                        mPlug_driver.value = minValue#Set to min			
                    else:	
                        if f_minDist>f_maxDist:#if min dif greater, use half as new min
                            if f_half < minIn:
                                raise StandardError, "half min less than minValue"
                                f_half = minIn
                            minValue = f_half
                            #log.debug("matchValue_iterator>>>Going up")
                            f_closest = f_minDist
                        else:
                            if f_half > maxIn:
                                raise StandardError, "half max less than maxValue"			    
                                f_half = maxIn			
                            maxValue = f_half
                            #log.debug("matchValue_iterator>>>Going down")  
                            f_closest = f_maxDist

                elif iterMode == 'step':
                    currentDriven = mPlug_driven.value
                    if i == 0:
                        log.debug("|{0}| >> First step getting base data...".format(_str_func))                        
                        f_lastValue = currentDriven
                        _stepSmall = .000001
                        minStep = _stepSmall
                        _stepBig = 10
                        f_stepBase = mPlug_driver.value
                        f_stepEnd = f_stepBase + _stepBig

                        """
                        mPlug_driver.value = currentDriven + .1
                        f_up = mPlug_driven.value 

                        mPlug_driver.value = currentDriven - .1
                        f_down = mPlug_driven.value

                        diff_up = abs(f_baseValue - f_down)
                        diff_dn = abs(f_baseValue - f_up)
                        log.debug("|{0}| >> up :{1} | down: {2}".format(_str_func,diff_up,diff_dn))
                        if diff_up > diff_dn:
                            _dir = 'up'
                            _mult = 1
                        else:
                            _dir = 'dn'
                            _mult = -1"""

                    log.info(cgmGEN._str_subLine)

                    log.debug("|{0}| >> Iter :{1} | stepBase: {2} | stepEnd: {5} | step: {6} | current: {3} | match: {4}".format(_str_func,
                                                                                                                                 i,
                                                                                                                                 f_stepBase,
                                                                                                                                 currentDriven,
                                                                                                                                 matchValue,
                                                                                                                                 f_stepEnd,
                                                                                                                                 _stepBig))
                    if MATH.is_float_equivalent(currentDriven,matchValue,3):
                        log.debug("|{0}| >> Match found...".format(_str_func))
                        b_matchFound = f_stepBase
                        break

                    f_currentDist = (matchValue-currentDriven)
                    mPlug_driver.value = f_stepBase#setp min
                    f_minValue = mPlug_driven.value
                    f_minDist = (matchValue-mPlug_driven.value)#get Dif

                    mPlug_driver.value = f_stepEnd
                    f_maxDist = (matchValue-mPlug_driven.value)#Get dif
                    f_maxValue = mPlug_driven.value


                    f_stepHalf = f_stepBase + ((_stepBig/2.0))
                    f_half = f_stepHalf
                    mPlug_driver.value = f_half
                    f_halfDist = (matchValue-mPlug_driven.value)#Get dif
                    f_halfValue = mPlug_driven.value

                    log.debug("|{0}| >> minValue: {1} | halfValue: {3} | maxValue: {2} | current: {4}".format(_str_func,f_minValue,f_maxValue,f_halfValue,currentDriven))

                    log.debug("|{0}| >> minDist: {1} | halfDist: {3} | maxDist: {2} |  | currentDist: {4}".format(_str_func,f_minDist,f_maxDist,f_halfDist,f_currentDist))

                    log.debug("|{0}| >> baseStep: {1} | halfStep: {3} | endStep: {2} | ".format(_str_func,f_stepBase,f_stepEnd,f_stepHalf))

                    if matchValue > f_minValue and matchValue < f_maxValue:
                        log.debug("|{0}| >> Between...".format(_str_func))
                        #(minStep *_mult)
                        if matchValue < f_halfValue:
                            log.debug("|{0}| >> Less than half".format(_str_func))
                            f_stepBase = f_stepBase
                            f_stepEnd = f_stepHalf
                        elif matchValue > f_halfValue:
                            log.debug("|{0}| >> more than half".format(_str_func))
                            f_stepBase = f_stepHalf
                            f_stepEnd = f_stepBase + (_stepBig)
                        else:
                            f_stepBase = f_stepBase + (_stepSmall)

                        _stepBig = _stepBig/2.0

                        #minStep = f_lastValue + minStep
                    elif matchValue > f_maxValue:
                        log.debug("|{0}| >> Greater".format(_str_func))
                        _dir = 'up'
                        _mult = 1
                        _stepBig = 10
                        f_stepBase = f_stepEnd
                        f_stepEnd = f_stepEnd + (_stepBig)

                    elif matchValue < f_minValue:
                        log.debug("|{0}| >> Less...".format(_str_func))
                        _dir = 'dn'
                        _stepBig = -10
                        f_stepBase = f_stepBase + (_stepBig)
                        f_stepEnd = f_stepBase + (_stepBig)
                    else:
                        raise ValueError,"nope"

                    f_closest = f_stepBase


                #Old method
                """
		mPlug_driver.value = minValue#Set to min
		f_minDist = abs(matchValue-mPlug_driven.value)#get Dif
		f_minSetValue = mPlug_driven.value
		mPlug_driver.value = maxValue#Set to max
		f_maxDist = abs(matchValue-mPlug_driven.value)#Get dif
		f_maxSetValue = mPlug_driven.value

		f_half = ((maxValue-minValue)/2.0) + minValue#get half	

		#First find range
		if not MATH.is_float_equivalent(matchValue,0) and not MATH.is_float_equivalent(minValue,0) and not MATH.is_float_equivalent(f_minSetValue,0):
		    #if none of our values are 0, this is really fast
		    minValue = (minValue * matchValue)/f_minSetValue
		    log.debug("matchValue_iterator>>> Equated: %s"%minValue)		    
		    f_closest = f_minDist
		    mPlug_driver.value = minValue#Set to min		    
		elif b_firstIter:
		    log.debug("matchValue_iterator>>> first iter. Trying matchValue: %s"%minValue)		    		    
		    b_firstIter = False
		    minValue = matchValue
		    f_closest = f_minDist		    
		elif f_minSetValue > matchValue or f_maxSetValue < matchValue:
		    log.debug("matchValue_iterator>>> Finding Range....")		    
		    if matchValue < mPlug_driven.value:
			#Need to shift our range down
			log.debug("matchValue_iterator>>> Down range: minSetValue: %s"%f_minSetValue)
			f_baseValue = f_maxDist		    
			minValue = f_baseValue - f_minDist
			maxValue = f_baseValue + f_minDist
			f_closest = f_minDist			
		    elif matchValue > mPlug_driven.value:
			#Need to shift our range up
			log.debug("matchValue_iterator>>> Up range: maxSetValue: %s"%f_maxSetValue)  
			f_baseValue = f_minDist		    
			minValue = f_baseValue - f_maxDist
			maxValue = f_baseValue + f_maxDist
			f_closest = f_maxDist			
		else:	
		    if f_minDist>f_maxDist:#if min dif greater, use half as new min
			if f_half < minIn:f_half = minIn
			minValue = f_half
			#log.debug("matchValue_iterator>>>Going up")
			f_closest = f_minDist
		    else:
			if f_half > maxIn:f_half = maxIn			
			maxValue = f_half
			#log.debug("matchValue_iterator>>>Going down")  
			f_closest = f_maxDist"""

                #log.debug("matchValue_iterator>>>f1: %s | f2: %s | f_half: %s"%(f_minDist,f_maxDist,f_half))  
                #log.debug("#"+'-'*50)

                if f_closest == f_lastClosest:
                    cnt_sameValue +=1
                    if cnt_sameValue >3:
                        log.error("matchValue_iterator>>> Value unchanged. Bad Driver. lastValue: %s | currentValue: %s"%(f_lastValue,mPlug_driven.value))		
                        break
                else:
                    cnt_sameValue = 0 
                f_lastClosest = f_closest
            else:
                log.warning("matchValue_iterator>>> driven mode not implemented with value mode: %s"%__drivenMode__)
                break		

        #>>>>>matchObjMode
        elif __matchMode__ == 'matchObj':
            pos_match = mc.xform(mi_matchObj.mNode, q=True, ws=True, rp=True)
            pos_driven = mc.xform(mi_drivenObj.mNode, q=True, ws=True, rp=True)
            log.debug("matchValue_iterator>>> min: %s | max: %s | pos_match: %s | pos_driven: %s"%(minValue,maxValue,pos_match,pos_driven))  						    
            if MATH.is_vector_equivalent(pos_match,pos_driven,2):
                log.debug("matchValue_iterator>>> Match found: %s <<pos>> %s | %s: %s | step: %s"%(mi_matchObj.getShortName(),mi_drivenObj.getShortName(),mPlug_driver.p_combinedShortName,minValue,i))  			    
                b_matchFound = mPlug_driver.value
                break

            mPlug_driver.value = minValue#Set to min
            pos_min = mc.xform(mi_drivenObj.mNode, q=True, ws=True, rp=True)
            #f_minDist = MATH.mag( MATH.list_subtract(pos_match,pos_min))#get Dif
            f_minDist = distance.returnDistanceBetweenObjects(mi_drivenObj.mNode,mi_matchObj.mNode)

            mPlug_driver.value = maxValue#Set to max
            pos_max = mc.xform(mi_drivenObj.mNode, q=True, ws=True, rp=True)
            f_maxDist = distance.returnDistanceBetweenObjects(mi_drivenObj.mNode,mi_matchObj.mNode)
            f_half = ((maxValue-minValue)/2.0) + minValue#get half	

            if f_minDist>f_maxDist:#if min dif greater, use half as new min
                minValue = f_half
                f_closest = f_minDist
            else:
                maxValue = f_half
                f_closest = f_maxDist	

            if f_minDist==f_maxDist:
                minValue = minValue + .1

            if f_closest == f_lastClosest:
                cnt_sameValue +=1
                if cnt_sameValue >3:
                    log.error("matchValue_iterator>>> Value unchanged. Bad Driver. lastValue: %s | currentValue: %s"%(f_lastValue,mPlug_driver.value))		
                    break
            else:
                cnt_sameValue = 0 
            f_lastClosest = f_closest

            log.debug("matchValue_iterator>>>f1: %s | f2: %s | f_half: %s"%(f_minDist,f_maxDist,f_half))  
            log.debug("#"+'-'*50)	    

        else:
            log.warning("matchValue_iterator>>> matchMode not implemented: %s"%__matchMode__)
            break

    #>>> Check autokey back on
    if b_autoFrameState:
        mc.autoKeyframe(state = True) 

    if b_matchFound is not None:
        return b_matchFound
    #log.warning("matchValue_iterator>>> Failed to find value for: %s"%mPlug_driven.p_combinedShortName)    
    return False
Пример #49
0
 def restore(self, useSelected=False, offset=[]):
     '''
     restore animation
     '''
     reOrder = False
     if useSelected:
         self.obj = cmds.ls(sl=1)[0]
     rooPut = cmds.getAttr(self.obj + '.rotateOrder')
     if self.rooGet != rooPut:
         reOrder = True
         print 'reorder'
     # type of restore
     if self.poseOnly:
         # find if obj is keyed, if keyed insert key otherwise setAttr
         pass
     else:
         if self.keys:
             current = cmds.currentTime(q=True)
             # ui off
             cn.uiEnable(controls='modelPanel')
             # autokey state
             autoK = cmds.autoKeyframe(q=True, state=True)
             cmds.autoKeyframe(state=False)
             i = 0
             for key in self.keys:
                 if key >= self.rng.keyStart and key <= self.rng.keyEnd:
                     cmds.currentTime(key)
                     cmds.xform(self.obj, t=self.pos[i], ws=True)
                     # new method for applying rotations, accounts for differences in rotation order
                     if reOrder:
                         self.rot[i] = reorderAngles(matrix=self.mtrx[i], rooOld=self.rooGet, rooNew=rooPut)
                     cmds.xform(self.obj, ro=self.rot[i], ws=True)
                     '''
                     # removed due to crappyness, applying matrix messes with jointOrient Value
                     if cmds.nodeType(self.obj) == 'lol':
                         cmds.xform(self.obj, t=self.pos[i], ws=True)
                         if reOrder:
                             rot[i] = reorderAngles(matrix=mtrx[i], rooOld=rooGet, rooNew=rooPut)
                         cmds.xform(self.obj, ro=self.rot[i], ws=True)
                     else:
                         cmds.xform(self.obj, m=self.mtrx[i], ws=True)
                     '''
                     # object space offset X, Y, Z
                     if offset:
                         # objects need to be in same rotate order space
                         # add feature to translate values to different rotate orders
                         cmds.xform(self.obj, r=True, os=True, ro=(offset[0], 0, 0))
                         cmds.xform(self.obj, r=True, os=True, ro=(0, offset[1], 0))
                         cmds.xform(self.obj, r=True, os=True, ro=(0, 0, offset[2]))
                     # account for non-keyable rotate or translate attrs
                     cmds.setKeyframe(self.obj + '.rotate')
                     cmds.setKeyframe(self.obj + '.translate')
                     # getCurves for translate and rotate
                     # crv = getAnimCurves(self.obj)
                     cn.eulerFilter(self.obj, tangentFix=True)
                 else:
                     pass
                     # print 'nope'
                 i = i + 1
             # tangent fix
             # cn.eulerFilter(crv, tangentFix=True)
             # restore everything
             cmds.currentTime(current)
             cmds.autoKeyframe(state=autoK)
             cn.uiEnable(controls='modelPanel')
         else:
             message('No keys.', maya=True)
def _update_inversion_for_deformer(deformer):
    # The deformer outputs to the inverted mesh, which then generally goes into a blendShape
    # and then a skinCluster to get the final mesh.  We need to figure out how changes to
    # the inverted mesh affect the final output mesh that the user is sculpting.
    #
    # First, we need to find the inverted mesh.  This is the first mesh in our future.
    # Note that the deformer could be plugged directly into the blendShape, but if this
    # is done, we have no mesh to modify to do this.
    #
    # Doing this instead of just looking at .outputGeometry avoids problems when Maya
    # silently adds helper nodes between us and the geometry, such as createColorSet.

    inverted_shape = _find_inverted_shape_for_deformer(deformer)
    if not inverted_shape:
        raise Exception('Couldn\'t find the output inverted mesh for "%s".' % deformer)

    # Get the mesh that's being sculpted.
    posed_mesh = _get_active_sculpting_mesh_for_deformer(deformer)
    if not posed_mesh:
        OpenMaya.MGlobal.displayError('Deformer "%s" isn\'t being sculpted.' % deformer)
        return

    # Temporarily disable the deformer.
    old_node_state = cmds.getAttr('%s.nodeState' % deformer)
    cmds.setAttr('%s.nodeState' % deformer, 1)

    # In 2016 SP1, auto-keyframe makes cmds.move extremely slow, so disable it while we
    # do this.
    old_autokeyframe = cmds.autoKeyframe(q=True, st=True)
    cmds.autoKeyframe(st=False)
    try:
        # We need to find out the effect that translating the blend shape vertices
        # has.  Do this by moving vertices on the actual blend shape.  We've disabled
        # the deformer while we test this.

        # The base shape data:
        basePoints = _get_mesh_points(posed_mesh)

        # The base shape after being deformed on each axis:
        cmds.move(1, 0, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        xPoints = _get_mesh_points(posed_mesh)
        cmds.move(-1, 0, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        cmds.move(0, 1, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        yPoints = _get_mesh_points(posed_mesh)
        cmds.move(0, -1, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        cmds.move(0, 0, 1, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        zPoints = _get_mesh_points(posed_mesh)
        cmds.move(0, 0, -1, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        # If moving points has no effect, something's wrong.  The blend shape may not
        # be enabled, or there could be another deformer in the way that's replacing
        # the shape entirely.
        if basePoints and abs(basePoints[0].x - xPoints[0].x) < 0.001:
            OpenMaya.MGlobal.displayError('Moving the inverted mesh isn\'t moving the output mesh.  Is the blend shape for this mesh enabled?')
            return
        
    finally:
        # Restore the deformer's state.
        cmds.setAttr('%s.nodeState' % deformer, old_node_state)

        # Restore autoKeyframe.
        cmds.autoKeyframe(st=old_autokeyframe)

    # Calculate the inversion matrices.
    deformer_node = _get_mobject(deformer)
    inversion_matrix_plug = OpenMaya.MFnDependencyNode(deformer_node).findPlug('inversionMatrix', False)
    fnMatrixData = OpenMaya.MFnMatrixData()

    for i in xrange(basePoints.length()):
        matrix = OpenMaya.MMatrix()
        _set_matrix_row(matrix, 0, xPoints[i] - basePoints[i])
        _set_matrix_row(matrix, 1, yPoints[i] - basePoints[i])
        _set_matrix_row(matrix, 2, zPoints[i] - basePoints[i])
        matrix = matrix.inverse()

        matrix_node = fnMatrixData.create(matrix)
        matrix_element_plug = inversion_matrix_plug.elementByLogicalIndex(i)
        matrix_element_plug.setMObject(matrix_node)

    # Now that we've updated the inversion, tell the deformer to recalculate the
    # .tweak values based on the .inverseTweak and the new .inversionMatrix.
    cmds.setAttr('%s.recalculateTweak' % deformer, 1)
Пример #51
0
def isEnabled():
    return cmds.autoKeyframe(query=True, state=True)
def _update_inversion_for_deformer(deformer):
    # The deformer outputs to the inverted mesh, which then generally goes into a blendShape
    # and then a skinCluster to get the final mesh.  We need to figure out how changes to
    # the inverted mesh affect the final output mesh that the user is sculpting.
    #
    # First, we need to find the inverted mesh.  This is the first mesh in our future.
    # Note that the deformer could be plugged directly into the blendShape, but if this
    # is done, we have no mesh to modify to do this.
    #
    # Doing this instead of just looking at .outputGeometry avoids problems when Maya
    # silently adds helper nodes between us and the geometry, such as createColorSet.

    inverted_shape = _find_inverted_shape_for_deformer(deformer)
    if not inverted_shape:
        raise Exception('Couldn\'t find the output inverted mesh for "%s".' %
                        deformer)

    # Get the mesh that's being sculpted.
    posed_mesh = _get_active_sculpting_mesh_for_deformer(deformer)
    if not posed_mesh:
        OpenMaya.MGlobal.displayError('Deformer "%s" isn\'t being sculpted.' %
                                      deformer)
        return

    # Temporarily disable the deformer.
    old_node_state = cmds.getAttr('%s.nodeState' % deformer)
    cmds.setAttr('%s.nodeState' % deformer, 1)

    # In 2016 SP1, auto-keyframe makes cmds.move extremely slow, so disable it while we
    # do this.
    old_autokeyframe = cmds.autoKeyframe(q=True, st=True)
    cmds.autoKeyframe(st=False)
    try:
        # We need to find out the effect that translating the blend shape vertices
        # has.  Do this by moving vertices on the actual blend shape.  We've disabled
        # the deformer while we test this.

        # The base shape data:
        basePoints = _get_mesh_points(posed_mesh)

        # The base shape after being deformed on each axis:
        cmds.move(1, 0, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        xPoints = _get_mesh_points(posed_mesh)
        cmds.move(-1, 0, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        cmds.move(0, 1, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        yPoints = _get_mesh_points(posed_mesh)
        cmds.move(0, -1, 0, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        cmds.move(0, 0, 1, '%s.vtx[*]' % inverted_shape, r=True, os=True)
        zPoints = _get_mesh_points(posed_mesh)
        cmds.move(0, 0, -1, '%s.vtx[*]' % inverted_shape, r=True, os=True)

        # If moving points has no effect, something's wrong.  The blend shape may not
        # be enabled, or there could be another deformer in the way that's replacing
        # the shape entirely.
        if basePoints and abs(basePoints[0].x - xPoints[0].x) < 0.001:
            OpenMaya.MGlobal.displayError(
                'Moving the inverted mesh isn\'t moving the output mesh.  Is the blend shape for this mesh enabled?'
            )
            return

    finally:
        # Restore the deformer's state.
        cmds.setAttr('%s.nodeState' % deformer, old_node_state)

        # Restore autoKeyframe.
        cmds.autoKeyframe(st=old_autokeyframe)

    # Calculate the inversion matrices.
    deformer_node = _get_mobject(deformer)
    inversion_matrix_plug = OpenMaya.MFnDependencyNode(deformer_node).findPlug(
        'inversionMatrix', False)
    fnMatrixData = OpenMaya.MFnMatrixData()

    for i in xrange(basePoints.length()):
        matrix = OpenMaya.MMatrix()
        _set_matrix_row(matrix, 0, xPoints[i] - basePoints[i])
        _set_matrix_row(matrix, 1, yPoints[i] - basePoints[i])
        _set_matrix_row(matrix, 2, zPoints[i] - basePoints[i])
        matrix = matrix.inverse()

        matrix_node = fnMatrixData.create(matrix)
        matrix_element_plug = inversion_matrix_plug.elementByLogicalIndex(i)
        matrix_element_plug.setMObject(matrix_node)

    # Now that we've updated the inversion, tell the deformer to recalculate the
    # .tweak values based on the .inverseTweak and the new .inversionMatrix.
    cmds.setAttr('%s.recalculateTweak' % deformer, 1)
Пример #53
0
        death    : Scales down the particle to 0 at the end of its lifetime
        bake     : Combines all animation layers
emitCurve   : Emits particles from a curve
followCurve : Animates a trail of particles following a curve
planeEmit   : Emits particles from a plane
reloadFile  : Reloads Maya scene to free memory and increase performance

In this module, one of the functions is called with a 
particle list. Those particles are then individually 
animated using a combination of the class specific functions.
'''
import maya.cmds as cmds
import random

cmds.cycleCheck(e=0)
cmds.autoKeyframe(state=0)

class particles():
    '''Contains procedures to animate individual particles and stores their unique variables'''
    def __init__(self,name):
        '''Saves the object's name to an instance of the class'''
        
        self.name=name
        
    def explode(self,start,duration,distance):
        '''
        Emits a particle along its local Y axis with decreasing speed
        
        start : Start of emission frame
        duration : Number of frames to reach final destination
        distance : Total distance to move object
Пример #54
0
    def __init__(self, *args):
        self.get_global()

        selected = cmds.ls(sl=True)

        controller_list = {}
        opposite_set = None
        auto_key = cmds.autoKeyframe(st=True, q=True)

        if auto_key:
            cmds.autoKeyframe(st=False)

        if selected:

            for obj in selected:
                obj_set_attr = '{0}.{1}'.format(obj, self.set_parent_str)

                if cmds.objExists(obj_set_attr):
                    obj_set = cmds.listConnections(obj_set_attr)

                    if obj_set:
                        obj_set = obj_set[0]

                        opposite_set_attr = '{0}.{1}'.format(
                            obj_set, self.opposite_set_str)

                        if cmds.objExists(opposite_set_attr):
                            opposite_set = cmds.listConnections(
                                opposite_set_attr)

                        if opposite_set:
                            opposite_set = opposite_set[0]

                            for controller in cmds.sets(opposite_set, q=True):
                                controller_order_attr = '{0}.{1}'.format(
                                    controller, self.snap_order_attr)

                                if cmds.objExists(controller_order_attr):
                                    controller_order = cmds.getAttr(
                                        controller_order_attr)

                                    if controller_order:
                                        controller_order = int(
                                            controller_order[0])

                                        controller_list[
                                            controller_order] = controller

            for controller in controller_list.values():

                obj_snap_attr = '{0}.{1}'.format(controller,
                                                 self.snap_parent_str)

                print obj_snap_attr

                if cmds.objExists(obj_snap_attr):
                    snap_obj = cmds.listConnections(obj_snap_attr)

                    if snap_obj:
                        snap_obj = snap_obj[0]

                        tra = cmds.xform(snap_obj, ws=True, rp=True, q=True)
                        rot = cmds.xform(snap_obj, ws=True, ro=True, q=True)

                        try:
                            cmds.xform(controller, ws=True, t=tra)

                        except:
                            pass

                        try:
                            cmds.xform(controller, ws=True, ro=rot)

                        except:
                            try:
                                rot_x = cmds.getAttr(
                                    '{0}.rotateX'.format(snap_obj))
                                cmds.setAttr('{0}.rotateX'.format(controller),
                                             rot_x)

                            except:
                                pass

                            try:
                                rot_x = cmds.getAttr(
                                    '{0}.rotateY'.format(snap_obj))
                                cmds.setAttr('{0}.rotateY'.format(controller),
                                             rot_x)

                            except:
                                pass

                            try:
                                rot_x = cmds.getAttr(
                                    '{0}.rotateZ'.format(snap_obj))
                                cmds.setAttr('{0}.rotateZ'.format(controller),
                                             rot_x)

                            except:
                                pass

            if not opposite_set:
                OpenMaya.MGlobal.displayError(
                    "Can not find FKIK Snap on selected controller!")

            else:

                switch_attr = cmds.listConnections('{0}.{1}'.format(
                    opposite_set, self.switch_parent_str),
                                                   plugs=True)[0]

                current_time = cmds.currentTime(query=True)
                cmds.setKeyframe(switch_attr, time=current_time - 1)
                cmds.setKeyframe(cmds.sets(obj_set, q=True),
                                 cmds.sets(opposite_set, q=True))

                if cmds.getAttr(switch_attr) == 0:
                    cmds.setAttr(switch_attr, 1)

                elif cmds.getAttr(switch_attr) == 1:
                    cmds.setAttr(switch_attr, 0)

                cmds.setKeyframe(switch_attr)

        else:
            OpenMaya.MGlobal.displayError("You need to select a controller!")

        if auto_key:
            cmds.autoKeyframe(st=True)

        cmds.select(cl=True)