Python maya.cmds.currentTime() Examples

The following are 30 code examples of maya.cmds.currentTime(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya.cmds , or try the search function .
Example #1
Source File: anim_utils.py    From mgear_core with MIT License 6 votes vote down vote up
def spine_IKToFK(fkControls, ikControls, matchMatrix_dict=None):
    """position the IK controls to match, as best they can, the fk controls.
    Supports component: spine_S_shape_01, spine_ik_02

    Args:
        fkControls (list): list of fk controls, IN THE ORDER OF HIERARCHY,
        ["spine_C0_fk0_ctl", ..., ..., "spine_C0_fk6_ctl"]
        ikControls (list): all ik controls
    """
    if matchMatrix_dict is None:
        currentTime = pm.currentTime(q=True)
        matchMatrix_dict = recordNodesMatrices(fkControls,
                                               desiredTime=currentTime)

    attribute.reset_SRT(ikControls)

    for fk in fkControls:
        fk = pm.PyNode(fk)
        fk.setMatrix(matchMatrix_dict[fk.name()], worldSpace=True) 
Example #2
Source File: ml_utilities.py    From ml_tools with MIT License 6 votes vote down vote up
def setAnimValue(plug, value, tangentType=None):
    '''
    Sets key if the channel is keyed, otherwise setAttr
    '''

    if mc.keyframe(plug, query=True, name=True):
        mc.setKeyframe(plug, value=value)
        if tangentType:
            time = mc.currentTime(query=True)
            itt = tangentType
            ott = tangentType
            if tangentType == 'step':
                itt = 'linear'
            mc.keyTangent(plug, time=(time,), edit=True, itt=itt, ott=ott)

    mc.setAttr(plug, value) 
Example #3
Source File: mayascene.py    From cross3d with MIT License 6 votes vote down vote up
def setCurrentFrame(self, frame):
		""" sets the current frame
			\param		frame <float>
			\return		<bool> success
		"""
		return cmds.currentTime(frame) == frame
	
#	def loadFile(self, filename='', confirm=True):
#		""" Loads the specified filename in the application.
#		
#		Loads the inputed filename into the application, returning true on success
#		args:
#			filename: The filename as a string
#		Returns:
#			a boolean value indicating success
#		"""
#		# Using the prompt argument will affect all future calls to cmds.file, so backup the current
#		# value and restore it later.
#		prompt = cmds.file(query=True, prompt=True)
#		loaded = cmds.file(filename, open=True, prompt=confirm)
#		# restore the previous prompt behavior
#		cmds.file(prompt=prompt)
#		return filename == loaded 
Example #4
Source File: samplingFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def blendShapeSampling(node, interval=1):
    """
    Args:
      node (str)
      interval (int)
    
    Returns:
      int
    """
    assert cmds.nodeType(node) == 'blendShape', \
        "node must be a blendShape type"
    start = cmds.currentTime(q=1)
    
    attrs = cmds.listAttr('%s.weight' % node, m=1)
    attrData = {node: [[attr, 0.0, 1.0] for attr in attrs]}
    
    currTime = attrsSampling(attrData, interval)

    end = currTime-1
    utils.trimTimeRange(start, end)
    cmds.currentTime(start)

#---------------------------------------------------------------------- 
Example #5
Source File: samplingFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def customAttrsSampling(attrData, interval=1):
    """
    Args:
      attrData (dict): {node1: [[attr1, min, max], [attr2, min, max], ...],
                        node2: [[attr1, min, max], [attr2, min, max], ...],
                        ...}
      interval (int)
    
    Returns:
      int
    """
    start = cmds.currentTime(q=1)
    currTime = attrsSampling(attrData, interval)
    end = currTime-1
    utils.trimTimeRange(start, end)
    cmds.currentTime(start) 

#---------------------------------------------------------------------- 
Example #6
Source File: samplingFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def attrsSampling(attrData, interval=1):
    """
    Args:
      attrData (dict): {node1: [[attr1, min, max], [attr2, min, max], ...],
                        node2: [[attr1, min, max], [attr2, min, max], ...],
                        ...}
      interval (int)
    
    Returns:
      int
    """
    currTime = cmds.currentTime(q=1)
    for node, attrVals in attrData.iteritems():        
        for vals in attrVals:
            attr, minVal, maxVal = vals
            if not cmds.objExists('.'.join([node, attr])):
                continue
            currTime = attrSampling(node, attr, minVal, maxVal, interval)
            currTime -= 2 * interval
            cmds.currentTime(currTime)
    return currTime+1 * interval

#---------------------------------------------------------------------- 
Example #7
Source File: samplingFunc.py    From DeformationLearningSolver with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def attrSampling(node, attr, minVal, maxVal, interval=1):
    """
    Args:
      node (str)
      attrs (list)
      minVal (float)
      maxVal (float)
      interval (int)
    
    Returns:
      int
    """    
    currTime = cmds.currentTime(q=1)
    currVal = cmds.getAttr('%s.%s' % (node, attr))
    vals = [currVal, currVal+minVal, currVal+maxVal, currVal]

    for i, v in enumerate(vals):
        if i not in [0, len(vals)-1] and (currVal - v) == 0:
            continue
        
        cmds.setKeyframe(node, at=attr, v=v, t=currTime)
        currTime += interval
    return currTime

#---------------------------------------------------------------------- 
Example #8
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 6 votes vote down vote up
def scaleTime(percent=100, selectionOption=1, pivotOption=0):

    value = percent/100.0
    keySel = _getKeySelection(selectionOption)

    timePivot = 0
    if pivotOption == 0:
        timePivot = mc.currentTime(query=True)
    else:
        times = keySel.getSortedKeyTimes()
        if pivotOption == 1:
            timePivot = times[0]
        elif pivotOption == 2:
            timePivot = times[-1]
        elif pivotOption == 3:
            timePivot = (times[0]+times[-1])/2

    keySel.scaleKey(timeScale=value, timePivot=timePivot) 
Example #9
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 5 votes vote down vote up
def insertFrame(selectionOption=1):

    keySel = _getKeySelection(selectionOption)

    #move everything after the current frame
    keySel.keyframe(edit=True, time=(str(mc.currentTime(query=True))+':',), relative=True, timeChange=1) 
Example #10
Source File: ml_stopwatch.py    From ml_tools with MIT License 5 votes vote down vote up
def previousFrame(self, *args):
        '''
        Go to the previous frame based on the current time and frame list.
        '''
        current = mc.currentTime(query=True)
        for f in [x+self.startFrame for x in reversed(self.frameMarks)]:
            if current <= f:
                continue
            mc.currentTime(f)
            break 
Example #11
Source File: ml_stopwatch.py    From ml_tools with MIT License 5 votes vote down vote up
def nextFrame(self, *args):
        '''
        Go to the next frame based on the current time and frame list.
        '''
        current = mc.currentTime(query=True)
        for f in [x+self.startFrame for x in self.frameMarks]:
            if current >= f:
                continue
            mc.currentTime(f)
            break 
Example #12
Source File: app.py    From maya-capture-gui with MIT License 5 votes vote down vote up
def refresh(self):
        """Refresh the playblast preview"""

        frame = cmds.currentTime(query=True)

        # When playblasting outside of an undo queue it seems that undoing
        # actually triggers a reset to frame 0. As such we sneak in the current
        # time into the undo queue to enforce correct undoing.
        cmds.currentTime(frame, update=True)

        # check if plugin outputs are correct
        valid = self.validator()
        if not valid:
            return

        with lib.no_undo():
            options = self.options_getter()
            tempdir = tempfile.mkdtemp()

            # override settings that are constants for the preview
            options = options.copy()
            options['filename'] = None
            options['complete_filename'] = os.path.join(tempdir, "temp.jpg")
            options['width'] = self.preview_width
            options['height'] = self.preview_height
            options['viewer'] = False
            options['frame'] = frame
            options['off_screen'] = True
            options['format'] = "image"
            options['compression'] = "jpg"
            options['sound'] = None

            fname = capture.capture(**options)
            if not fname:
                log.warning("Preview failed")
                return

            image = QtGui.QPixmap(fname)
            self.preview.setPixmap(image)
            os.remove(fname) 
Example #13
Source File: lib.py    From maya-capture-gui with MIT License 5 votes vote down vote up
def get_active_editor():
    """Return the active editor panel to playblast with"""
    # fixes `cmds.playblast` undo bug
    cmds.currentTime(cmds.currentTime(query=True))
    panel = cmds.playblast(activeEditor=True)
    return panel.split("|")[-1] 
Example #14
Source File: lib.py    From maya-capture-gui with MIT License 5 votes vote down vote up
def get_current_frame():
    return cmds.currentTime(query=True) 
Example #15
Source File: ml_animCurveEditor.py    From ml_tools with MIT License 5 votes vote down vote up
def offsetCurrentTimeTo(frame=0, selectionOption=1):

    keySel = _getKeySelection(selectionOption)
    keySel.moveKey(frame-mc.currentTime(query=True)) 
Example #16
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def scaleKey(self, timePivot=0, **kwargs):
        '''
        Wrapper for maya's scaleKey command.
        '''

        if not 'time' in kwargs:
            kwargs['time'] = self.time

        if timePivot == 'current':
            timePivot = self.currentTime

        mc.scaleKey(self.curves, timePivot=timePivot, **kwargs) 
Example #17
Source File: lib.py    From maya-capture-gui with MIT License 5 votes vote down vote up
def list_formats():
    # Workaround for Maya playblast bug where undo would
    # move the currentTime to frame one.
    cmds.currentTime(cmds.currentTime(query=True))
    return cmds.playblast(query=True, format=True) 
Example #18
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def toEnd(self, includeCurrent=False):
        '''
        Sets the keySelection time to the range from the current frame to the last frame.
        Option to include the current frame.
        '''

        t = self.currentTime
        if not includeCurrent:
            t+=self.shortestTime
        self._timeRangeStart = t 
Example #19
Source File: ml_utilities.py    From ml_tools with MIT License 5 votes vote down vote up
def __init__(self, *args):

        #if args are passed in, this has been called from and out of date script. Warn and fail.
        if args:
            print ''
            print "Because of an update to ml_utilities, the tool you're trying to run is deprecated and needs to be updated as well."
            print "Please visit http://morganloomis.com/tools and download the latest version of this tool."
            OpenMaya.MGlobal.displayError('Tool out of date. See script editor for details.')
            return

        self.shortestTime = getFrameRate()/6000.0

        #node variables
        self.nodeSelection = mc.ls(sl=True)
        self._nodes = list()
        self._curves = list()
        self._channels = list()

        #time variables
        self.currentTime = mc.currentTime(query=True)
        self._time = None
        self._timeRangeStart = None
        self._timeRangeEnd = None

        #keyframe command variables
        self.selected = False

        #other housekeeping
        self._curvesCulled = False 
Example #20
Source File: lib.py    From maya-capture-gui with MIT License 5 votes vote down vote up
def list_compressions(format='avi'):
    # Workaround for Maya playblast bug where undo would
    # move the currentTime to frame one.
    cmds.currentTime(cmds.currentTime(query=True))

    cmd = 'playblast -format "{0}" -query -compression'.format(format)
    return mel.eval(cmd) 
Example #21
Source File: lib.py    From pyblish-maya with GNU Lesser General Public License v3.0 5 votes vote down vote up
def maintained_time():
    """Maintain current time during context

    Example:
        >>> with maintained_time():
        ...    cmds.playblast()
        >>> # Time restored

    """

    ct = cmds.currentTime(query=True)
    try:
        yield
    finally:
        cmds.currentTime(ct, edit=True) 
Example #22
Source File: capture.py    From maya-capture with MIT License 5 votes vote down vote up
def _maintained_time():
    """Context manager for preserving (resetting) the time after the context"""

    current_time = cmds.currentTime(query=1)
    try:
        yield
    finally:
        cmds.currentTime(current_time) 
Example #23
Source File: dm2skin.py    From dm2skin with The Unlicense 5 votes vote down vote up
def dm2skin_getVertexLocationList(mesh, frame=0):
    """Gets a list of vertex locations on the given frame."""
    numVerts = cmds.polyEvaluate(mesh, v=True)
    resultList = []
    cmds.currentTime(frame)
    for v in range(0, numVerts):
        pos = cmds.xform(mesh + '.vtx[' + str(v) + ']', q=True, ws=True, t=True)
        resultList.append(np.array([pos[0], pos[1], pos[2], 1.0]))
    return resultList 
Example #24
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def bakeSprings(model=None):
    """Bake the automatic spring animation to animation curves

    Args:
        model (dagNode): The rig top node
    """

    # filters the root node from selection
    if not model:
        model = getRootNode()

    print("Using root: {}".format(model))

    # first clear animation
    clearSprings(model)

    # bake again
    springNodes = getControlers(model, gSuffix=PLOT_GRP_SUFFIX)
    if springNodes:

        start = pm.playbackOptions(q=True, min=True)
        end = pm.playbackOptions(q=True, max=True)
        ct = start
        for i in range(int(end - start) + 1):
            pm.currentTime(int(ct))
            pm.setKeyframe(springNodes, insertBlend=True, attribute='rotate')
            ct += 1 
Example #25
Source File: anim_utils.py    From mgear_core with MIT License 5 votes vote down vote up
def doItByUI(self):
        """Gather UI settings to execute transfer
        """
        startFrame = self.startFrame_value.value()
        endFrame = self.endFrame_value.value()
        onlyKeyframes = self.onlyKeyframes_check.isChecked()

        # based on user input, decide where to flatten animation
        bakeToIk = self.comboBoxSpaces.currentIndex()

        self.bakeAnimation(self.fkControls,
                           self.ikControls,
                           startFrame,
                           endFrame,
                           bakeToIk=bakeToIk,
                           onlyKeyframes=onlyKeyframes)

        # Refresh the viewport by toggling time, refresh/dgdirty do not work
        pm.currentTime(startFrame)
        pm.currentTime(endFrame)
        # set the new space value in the synoptic combobox
        if self.comboObj is not None:
            self.comboObj.setCurrentIndex(self.comboBoxSpaces.currentIndex())

        for c in pyqt.maya_main_window().children():
            if isinstance(c, AbstractAnimationTransfer):
                c.deleteLater() 
Example #26
Source File: maya_warpper.py    From pipeline with MIT License 5 votes vote down vote up
def rewind():
    cmds.currentTime(1)    
    cmds.playbackOptions(minTime=1) 
Example #27
Source File: maya_warpper.py    From pipeline with MIT License 5 votes vote down vote up
def snapshot(path = None, width = 96, height = 96):
    current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
    cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
    #path = "/Users/liorbenhorin/Library/Preferences/Autodesk/maya/2015-x64/scripts/pipeline/thumb.png"
    cmds.playblast(cf = path, fmt="image", frame = cmds.currentTime( query=True ), orn=False, wh = [width,height], p=100, v=False)
    cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
    
    if os.path.isfile(path):
        return path
    else:
        return False 
Example #28
Source File: capture.py    From pyblish-bumpybox with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _maintained_time():
    """Context manager for preserving (resetting) the time after the context"""

    current_time = cmds.currentTime(query=1)
    try:
        yield
    finally:
        cmds.currentTime(current_time) 
Example #29
Source File: mayascene.py    From cross3d with MIT License 5 votes vote down vote up
def currentFrame(self):
		""" returns the current frame
			\return		<float> frame
		"""
		return cmds.currentTime(query=True) 
Example #30
Source File: dm2skin.py    From dm2skin with The Unlicense 5 votes vote down vote up
def createMush(self):
        mesh = self.sourceField.text()
        if not mesh:
            return
        if cmds.objExists(mesh + '_Mush'):
            print(mesh + '_Mush already exists!')
            return
        cmds.currentTime(cmds.playbackOptions(q=True, min=True))
        dup = cmds.duplicate(mesh, inputConnections=True, n=mesh + '_Mush')
        cmds.deltaMush(dup, smoothingIterations=20, smoothingStep=0.5, pinBorderVertices=True, envelope=1)