Esempio n. 1
0
def remove_animation(attr):
    """Remove the animation of an attribute

    Args:
        attr (str): Attribute fullName
    """
    pm.cutKey(attr, clear=True)
Esempio n. 2
0
def snapKey():
    # NOTE 通过命令将 关键帧 吸附
    start = pm.playbackOptions(q=1, min=1)
    end = pm.playbackOptions(q=1, max=1)

    # NOTE 清空关键帧选择避免 snapKey 报错
    pm.selectKey(cl=1)
    pm.snapKey(t=(start, end), tm=1.0)

    # NOTE 获取关键帧曲线 | 区分出驱动关键帧
    anim_list = []
    for sel in pm.ls(sl=1):
        anim_list.extend(sel.listConnections(type="animCurveTA"))
        anim_list.extend(sel.listConnections(type="animCurveTU"))
        anim_list.extend(sel.listConnections(type="animCurveTL"))

    # NOTE 找出前后有关键帧 但是关键帧为小数中间的值进行删除
    remove_dict = {}
    for anim in anim_list:
        for keyframe in range(anim.numKeys()):
            time = anim.getTime(keyframe)
            if not time.is_integer():
                if not remove_dict.has_key(anim):
                    remove_dict[anim] = []
                remove_dict[anim].append(time)

    for anim, times in remove_dict.items():
        for time in times:
            pm.cutKey(anim, clear=1, time=time)
Esempio n. 3
0
def remove_key(attr):
    """Remove the keyframe of an attribute at current frame

    Args:
        attr (str): Attribute fullName
    """
    pm.cutKey(attr, clear=True, time=pm.currentTime())
Esempio n. 4
0
def scale_hierarchy():
    # Select the entire hierarchy of your current selection and store everything in a list
    pm.select(hi=True, r=True)
    selected = pm.ls(sl=True)

    # If the ScaleMe group does not exist, create it
    if not pm.objExists('ScaleMe'):
        # Create the group that you will scale to resize your items
        scale_me = pm.createNode('transform', n='ScaleMe')

        # Iterate through all items, create a locator for each and set the locators to the items...
        # then reverse the constraint relationship so that the locators drive the items. Make all locators children of the ScaleMe group
        for s in selected:
            loc = pm.spaceLocator(n=s + '_ScaleLoc')
            p_con = pm.pointConstraint(s, loc)
            o_con = pm.orientConstraint(s, loc)
            pm.delete(p_con, o_con)
            pm.pointConstraint(loc, s)
            pm.orientConstraint(loc, s)
            pm.parent(loc, scale_me)
    else:
        # Grabbing all applicable joints using the locators attached to them
        items_to_key = [
            item.split('_ScaleLoc')[0]
            for item in pm.listRelatives('ScaleMe', c=True)
        ]

        # Setting a keyframe on each item, then deleting the ScaleMe group (which deletes all constraints with it)
        for item in items_to_key:
            pm.setKeyframe(item, at=['tx', 'ty', 'tz', 'rx', 'ry', 'rz'])
        pm.delete('ScaleMe')

        # Gets rid of all keys on the items that were just resized. You can comment this out if you want to keep the keyframes.
        for item in items_to_key:
            pm.cutKey(item)
 def testLoadStoredKeys(self):
     name = self.storeAnimationAttrs()
     # clear keyframes on the cube
     pm.cutKey(self.cube,at="translateX", cl=1)
     self.store.loadStoredKeys(self.cube)
     keys = pm.keyframe(name + ".translateX", q=1, kc=1)
     eq_(keys,2)
Esempio n. 6
0
def deleteInbetweenRanges(animCurve, deleteRanges):
    '''
    animCurve = pm.PyNode(animCurve) : animCurve to operate on
    deleteRanges = (1,9), (-9,-1) : list of tuples
    '''
    for eachRange in deleteRanges:
        pm.cutKey(animCurve, time=eachRange)
Esempio n. 7
0
def shift_curves(joints, START_FRAME=1, REMOVE_DOUBLES=True):
    connections = []
    for j in joints:
        con = j.listConnections(type='animCurveTA', connections=1)
        connections.extend(con)
    for con in connections:
        crv = con[1]

        keys = pm.keyframe(crv, q=1, tc=1)

        time_change = START_FRAME - keys[0]
        pm.keyframe(crv, tc=time_change, r=1)

        keys = pm.keyframe(crv, q=1, tc=1)
        values = pm.keyframe(crv, q=1, vc=1)

        if REMOVE_DOUBLES:
            ranges = []
            last = values[0] + 1
            for i in range(len(keys)):
                if values[i] == last:
                    ranges.append(keys[i])
                last = values[i]
            for r in ranges:
                pm.cutKey(crv, time=(r, r))
Esempio n. 8
0
def remove_sub_frames(obj_list):
    '''
    Sets a key on every whole frame over the keyed range of all objects, then removes all subframe keys.

    Args:
        obj_list (list<PyNode>): List of all objects to remove sub frames on
    '''
    #pm.select(None)
    #for model_panel in pm.getPanel(type='modelPanel'):
    #    pm.isolateSelect(model_panel, state=True)
    #pm.refresh(su=True)

    try:
        key_frame_list = list(set(pm.keyframe(obj_list, q=True)))
        key_frame_list.sort()
        first_keyframe = get_first_or_default(key_frame_list)
        last_keyframe = get_last_or_default(key_frame_list)

        time_range = (int(first_keyframe), int(last_keyframe))
        current_time = pm.currentTime()
        for frame in xrange(time_range[0], time_range[1] + 1):
            pm.currentTime(frame)
            pm.setKeyframe(obj_list)
    except:
        pass
    finally:
        pm.refresh(su=False)
        for model_panel in pm.getPanel(type='modelPanel'):
            pm.isolateSelect(model_panel, state=False)

    pm.currentTime(current_time)
    pm.select(obj_list, r=True)

    for frame in [x for x in key_frame_list if x % 1 > 0]:
        pm.cutKey(obj_list, t=frame)
Esempio n. 9
0
def dataToCurve(allData, plug):

    if isinstance(allData, dict):
        data = allData['keys']
    else:
        data = allData
        allData = None

    cutKey(plug, t=(data[0]['time'], data[-1]['time']), cl=True, iub=True)
    for key in data:
        setKeyframe(plug, f=key['time'], t=key['time'], v=key['val'])

    for key in data:
        keyTangent(plug,
                   f=(key['time'], ),
                   t=key['time'],
                   ia=key['inAngle'],
                   oa=key['outAngle'],
                   iw=key['inWeight'],
                   ow=key['outWeight'],
                   itt=key['inType'],
                   ott=key['outType'])

    if allData:
        node = plug.listConnections(s=True)[0]
        node.preInfinity.set(allData['preInfinity'])
        node.postInfinity.set(allData['postInfinity'])
Esempio n. 10
0
    def addJointsToCurve(self, *args):
        self.jointsList = []
        self.jointsListGRP = []
        try:
            numOfJoints = pm.intField(self.loadNumJoints, q = True, v = True)
            self.selectedCurve = pm.ls(sl = True)[0]
            incr = float((numOfJoints - 1))
            incr = 1/incr #calculate incrementation
            print incr
            incrTemp = 0.0
            

            for i in range(numOfJoints):
                pm.select(clear = True)
                j = pm.joint(radius = 0.25, n = self.selectedCurve + "Joint")
                self.jointsList.append(j)
                jGRP = pm.group(j, n = j + "GRP")
                self.jointsListGRP.append(jGRP)
                #attach to motion path
                motionPath = pm.pathAnimation(jGRP, self.selectedCurve, fractionMode = True, follow = True )
                pm.setAttr(motionPath +".u", incrTemp)
                pm.cutKey(motionPath)
                incrTemp += incr
                print incrTemp
                if incrTemp >= 1.0:
                    incrTemp = 1.0
                    
            facialAnimations.allJoints.append(self.jointsList)
            self.curvesGRP = pm.group(self.jointsListGRP, n = self.selectedCurve + "_Face_jointsGRP")
        except:
            pass
            print "Curve not selected"
Esempio n. 11
0
def applySetDrivenKeys(ctrl, infos):
    '''
    Create the setDrivenKeys on the ctrl with the specially formatted string
    list from `findSetDrivenKeys`.
    '''

    for info in infos:
        drivenAttr, driveNode, driveAttr, data = info

        node = findFromIds(driveNode)
        cutKey(ctrl.attr(drivenAttr), cl=True)

        #keyData = [KeyData(*d) for d in data]

        if isinstance(data, list):
            setDrivenKeyframe(ctrl,
                              at=[drivenAttr],
                              v=-.14,
                              cd=node.attr(driveAttr),
                              dv=[data[0]['time']])
        else:
            setDrivenKeyframe(ctrl,
                              at=[drivenAttr],
                              v=-.14,
                              cd=node.attr(driveAttr),
                              dv=[data['keys'][0]['time']])

        dataToCurve(data, ctrl.attr(drivenAttr))
Esempio n. 12
0
def alMoveACsegment(startFrame, endFrame):
    lastFrame = 0.0
    preRange = "0:" + str((startFrame - 1))
    allaCurves = pm.ls(type="animCurve")
    refCurves = pm.ls(type="animCurve", referencedNodes=1)
    animCurves = [x for x in allaCurves if x not in refCurves]
    for aCurve in animCurves:
        if (pm.objectType(aCurve) == "animCurveTU") or (
                pm.objectType(aCurve)
                == "animCurveTA") or (pm.objectType(aCurve) == "animCurveTL"):
            pm.setAttr((str(aCurve) + ".ktv"), l=1)
            pm.setAttr((str(aCurve) + ".ktv"), l=0)
            lastFrame = float(pm.findKeyframe(aCurve, which="last"))
            if lastFrame <= endFrame:
                lastFrame = float(endFrame + 2)

            postRange = str((endFrame + 1)) + ":" + str(lastFrame)
            if (pm.getAttr(str(aCurve) + ".pre")
                    == 0) and (pm.getAttr(str(aCurve) + ".pst") == 0):
                pm.setKeyframe(aCurve, insert=1, time=startFrame)
                pm.setKeyframe(aCurve, insert=1, time=endFrame)
                pm.cutKey(aCurve, time=preRange)
                pm.cutKey(aCurve, time=postRange)

#print "\nanimCurve: " + str(aCurve)
            pm.keyframe(aCurve,
                        e=1,
                        iub=True,
                        o='over',
                        r=1,
                        time=(str(startFrame) + ":" + str(endFrame)),
                        tc=(-(startFrame - 1)))
Esempio n. 13
0
    def split_camera(cls):
        """splits one camera to multiple cameras
        """
        selection = pm.ls(sl=1, type=pm.nt.Transform)
        if not selection:
            raise RuntimeError("Please select at least one camera")

        new_cameras = []

        from anima.env.mayaEnv import camera_tools
        for cam in selection:
            cut_info = camera_tools.find_cut_info(cam)

            for cut_in, cut_out in cut_info:
                print(cut_in, cut_out)
                # duplicate the original camera with input graph
                dup_cam = pm.duplicate(cam, un=1)[0]

                # remove all keyframes out of the cut range
                # remove befor
                pm.cutKey(dup_cam, time=(-1000, cut_in - 1))
                # # remove after
                pm.cutKey(dup_cam, time=(cut_out + 1, 100000))

                # rename the new cam
                dup_cam.rename("%s_#" % cam.name())

                new_cameras.append(dup_cam)

            # remove original camera
            pm.delete(cam)

        # select all new cameras
        pm.select(new_cameras)
Esempio n. 14
0
def keys_to_motion_path(objs=None, axis="x", up_axis="y", wuv=(0, 1, 0)):
    if not objs:
        objs = pmc.selected(transforms=True)
    with msu.MayaUndoChunkManager():
        for obj in objs:
            # curve from keys
            keys = sorted(set(pmc.keyframe(obj, q=True)))
            r = int(keys[0]), int(keys[-1]) + 1
            pts = (obj.t.get(t=f) for f in xrange(*r))
            c = pmc.curve(d=3, ep=pts)

            # to set motion path keys, need to link current keys to u param
            curve_keys = dict(
                (k, c.getParamAtPoint(obj.t.get(t=k))) for k in xrange(*r))
            pmc.cutKey(obj, t=r, cl=True)
            mp = pmc.nt.MotionPath()
            c.ws >> mp.geometryPath
            mp.follow.set(True)
            mp.fa.set(axis.upper())
            mp.ua.set(up_axis.upper())
            mp.wu.set(wuv)
            mp.ac >> obj.t
            mp.r >> obj.r
            for t, v in curve_keys.items():
                pmc.setKeyframe(mp.u, t=t, v=v)
            pmc.filterCurve(mp.u, f="simplify", tto=.05)

            # markers clutter and slow
            pmc.delete(mp.pmt.inputs())
Esempio n. 15
0
def vizBlink(sel, firstFrame, duration, offset=0, inv=False):
    for obj in sel:
        if not inv:
            pm.cutKey(obj, at='v')
            onKey = pm.setKeyframe(obj, at='v', t=firstFrame, v=1, s=False)
            offKey = pm.setKeyframe(obj,
                                    at='v',
                                    t=(firstFrame + duration),
                                    v=0,
                                    s=False)
            holdkey = pm.setKeyframe(obj,
                                     at='v',
                                     t=(firstFrame + (2 * duration) + offset),
                                     v=0,
                                     s=False)
            pm.setInfinity(obj.visibility, poi='cycle')
        elif inv:
            pm.cutKey(obj, at='v')
            offKey = pm.setKeyframe(obj, at='v', t=firstFrame, v=0, s=False)
            onKey = pm.setKeyframe(obj,
                                   at='v',
                                   t=(firstFrame + duration),
                                   v=1,
                                   s=False)
            holdkey = pm.setKeyframe(obj,
                                     at='v',
                                     t=(firstFrame + (duration * 2) + offset),
                                     v=1,
                                     s=False)
            pm.setInfinity(obj.visibility, poi='cycle')
Esempio n. 16
0
def keyFlash(obj=None, channel=None, fade=18):
    if obj == None:
        obj = pm.ls(sl=1)[0]
    if channel == None:
        channel = 'translateX'
    current = pm.currentTime(q=1)

    kf = [current - 1, current, current + 1, current + fade]

    value = pm.getAttr('%s.%s' % (obj, channel))
    #see if already keys
    if pm.listConnections('%s.%s' % (obj, channel)) is not []:
        pm.cutKey(obj, at=channel, time=(kf[0], kf[-1]))

    pm.setKeyframe(obj, at=channel, v=0, t=[kf[0]], ott='stepnext')
    pm.setKeyframe(obj, at=channel, v=value, t=[kf[1]], ott='stepnext')
    pm.setKeyframe(obj, at=channel, v=value * 0.75, t=[kf[2]], ott='auto')
    pm.setKeyframe(obj, at=channel, v=0, t=[kf[3]], ott='auto')

    pm.keyTangent(obj,
                  at=channel,
                  a=1,
                  outWeight=1,
                  e=1,
                  t=[kf[2]],
                  outAngle=-10.253096)
Esempio n. 17
0
def popAnimScaleYWiggle(objs, startframe=1, offset=2):
    i = 0
    keyframe1 = startframe
    keyframe2 = keyframe1 + 6
    keyframe3 = keyframe1 + 9
    keyframe4 = keyframe1 + 11
    for obj in objs:
        pm.cutKey(obj)
        endpose_scale = pm.getAttr("%s.scale" % obj)[0]
        endpose_rx = pm.getAttr("%s.rotateX" % obj)
        pm.setKeyframe("%s.scale" % obj, t=keyframe1, v=0)
        pm.setKeyframe("%s.scale" % obj, t=keyframe2, v=endpose_scale * 1.1)
        pm.setKeyframe("%s.scale" % obj,
                       t=keyframe3,
                       v=endpose_scale,
                       itt="linear")

        # rotate
        pm.setKeyframe("%s.rotateX" % obj, t=keyframe2, v=endpose_rx)
        pm.setKeyframe("%s.rotateX" % obj, t=keyframe3, v=endpose_rx + 12)
        pm.setKeyframe("%s.rotateX" % obj, t=keyframe3 + 4, v=endpose_rx - 12)
        pm.setKeyframe("%s.rotateX" % obj, t=keyframe3 + 8, v=endpose_rx)
        if i % offset == 0:
            keyframe1 = keyframe1 + 1
            keyframe2 = keyframe1 + 6
            keyframe3 = keyframe1 + 9
        i = i + 1
Esempio n. 18
0
def popAnimFallTranslateY(objs, startframe=1, height=1300, offset=10):
    i = 0
    keyframe1 = startframe
    keyframe2 = keyframe1 + 6
    keyframe3 = keyframe1 + 9
    keyframe4 = keyframe1 + 11
    for obj in objs:
        pm.cutKey(obj)
        endpose_ty = pm.getAttr("%s.ty" % obj)
        endpose_scale = pm.getAttr("%s.scale" % obj)[0]
        pm.setKeyframe("%s.scale" % obj, t=keyframe1, v=0)
        pm.setKeyframe("%s.scale" % obj, t=keyframe1 + 4, v=endpose_scale)
        pm.setKeyframe("%s.ty" % obj, t=keyframe1, v=endpose_ty + height)
        pm.setKeyframe("%s.ty" % obj,
                       t=keyframe2,
                       v=endpose_ty,
                       itt="linear",
                       ott="linear")
        pm.setKeyframe("%s.ty" % obj,
                       t=keyframe3,
                       v=endpose_ty + (height / 50.0))
        pm.setKeyframe("%s.ty" % obj, t=keyframe4, v=endpose_ty, itt="linear")
        if i % offset == 0:
            keyframe1 = keyframe1 + 1
            keyframe2 = keyframe1 + 6
            keyframe3 = keyframe1 + 9
            keyframe4 = keyframe1 + 11
        i = i + 1
Esempio n. 19
0
    def transfer(self,
                 startFrame,
                 endFrame,
                 onlyKeyframes,
                 ikRot,
                 switchTo=None,
                 *args,
                 **kargs):
        # type: (int, int, bool, str, *str, **str) -> None

        if switchTo is not None:
            if "fk" in switchTo.lower():

                val_src_nodes = self.fkTargets
                key_src_nodes = [self.ikCtrl, self.upvCtrl]
                key_dst_nodes = self.fkCtrls
                if ikRot:
                    key_src_nodes.append(self.ikRotCtl)

            else:

                val_src_nodes = [self.ikTarget, self.upvTarget]
                key_src_nodes = self.fkCtrls
                key_dst_nodes = [self.ikCtrl, self.upvCtrl]
                if ikRot:
                    val_src_nodes.append(self.ikRotTarget)
                    key_dst_nodes.append(self.ikRotCtl)

                # reset roll channel:
                roll_att = self.getChangeRollAttrName()
                pm.cutKey(roll_att, time=(startFrame, endFrame), cl=True)
                pm.setAttr(roll_att, 0)

        else:
            if self.comboBoxSpaces.currentIndex() != 0:  # to FK

                val_src_nodes = self.fkTargets
                key_src_nodes = [self.ikCtrl, self.upvCtrl]
                key_dst_nodes = self.fkCtrls
                if ikRot:
                    key_src_nodes.append(self.ikRotCtl)

            else:  # to IK

                val_src_nodes = [self.ikTarget, self.upvTarget]
                key_src_nodes = self.fkCtrls
                key_dst_nodes = [self.ikCtrl, self.upvCtrl]
                if ikRot:
                    val_src_nodes.append(self.ikRotTarget)
                    key_dst_nodes.append(self.ikRotCtl)

                # reset roll channel:
                roll_att = self.getChangeRollAttrName()
                pm.cutKey(roll_att, time=(startFrame, endFrame))
                pm.setAttr(roll_att, 0)

        self.bakeAnimation(self.getChangeAttrName(), val_src_nodes,
                           key_src_nodes, key_dst_nodes, startFrame, endFrame,
                           onlyKeyframes)
Esempio n. 20
0
    def save_constraint_weights(self, c_rig_button, event_args):
        component_constraint = self.get_space_constraint()
        pm.cutKey(component_constraint)
        weight_alias_list = component_constraint.getWeightAliasList()
        weight_string = "".join(str(x.get())+"," for x in weight_alias_list)

        self.network['addon'].set('no_bake', True)
        self.network['addon'].set('target_weight', weight_string)
Esempio n. 21
0
def _clearKeys(objs, toClear):
    if not toClear:
        return
        
    start = toClear[0] + 1
    end = toClear[-1]
    if start < end:
        #print('clearing', start, end)
        cutKey(objs, t=(start, end), iub=False, cl=True, shape=False)
Esempio n. 22
0
 def build(self):
     '''
     Call to build individual component which requires the component not be built.
     '''
     if not self.built and self.valid():
         if self.bind_joints:
             pm.cutKey(self.bind_joints)
         self._create_rig()
         self.built = True
def autoKey(attr, time):

    ##Get attrs from ui
    easeInFrames = pm.intField("EaseInIntFeild", q=True, v=True)
    holdInFrames = pm.intField("HoldInIntFeild", q=True, v=True)
    holdOutFrames = pm.intField("HoldOutIntFeild", q=True, v=True)
    easeOutFrames = pm.intField("EaseOutIntFeild", q=True, v=True)

    InTangentType = pm.optionMenu("EaseInTangetType_optmenu", q=True, v=True)
    OutTangentType = pm.optionMenu("EaseOutTangetType_optmenu", q=True, v=True)

    pm.cutKey(attr, t=":")

    initKey = pm.setKeyframe(attr,
                             v=1,
                             t=time,
                             inTangentType=InTangentType,
                             outTangentType=OutTangentType)

    if easeInFrames > 0:
        pm.setKeyframe(
            attr,
            v=0,
            t=[time - easeInFrames - holdInFrames],
            outTangentType=InTangentType)  ##ease in @UndefinedVariable
    else:
        initKey

    if holdInFrames > 0:
        pm.setKeyframe(
            attr,
            v=1,
            t=(time - holdInFrames),
            inTangentType=InTangentType,
            outTangentType=InTangentType)  ##inHold @UndefinedVariable
    else:
        initKey

    if holdOutFrames > 0:
        pm.setKeyframe(
            attr,
            v=1,
            t=(time + holdOutFrames),
            inTangentType=OutTangentType,
            outTangentType=OutTangentType)  ##outHold @UndefinedVariable
    else:
        initKey

    if easeOutFrames > 0:
        pm.setKeyframe(
            attr,
            v=0,
            t=[time + easeOutFrames + holdOutFrames],
            inTangentType=OutTangentType)  ##ease out @UndefinedVariable
    else:
        initKey
Esempio n. 24
0
    def delete_parent_key(self, frame):
        """deletes parent keyframes at the given keyframe
        """
        if not self._is_setup:
            return

        pm.cutKey(self._parent_constraint,
                  self._stabilizer_parent,
                  cl=True,
                  time=(frame, frame))
Esempio n. 25
0
    def moveKeys(self, src, dest, attr, axis):

        areThereKeys = pm.keyframe(src,
                                   attribute=attr + axis,
                                   query=True,
                                   valueChange=True)

        if len(areThereKeys) > 0:
            pm.cutKey(src, attribute=attr + axis)
            pm.pasteKey(dest, attribute=attr + axis)
Esempio n. 26
0
    def remove_not_required_animation(self, curve, start, end):
        global_infinity_range = 999999

        pm.cutKey(curve,
                  animation="objects",
                  time=(-global_infinity_range, start - 1))

        pm.cutKey(curve,
                  animation="objects",
                  time=(end + 1, global_infinity_range))
Esempio n. 27
0
def clearControlInbetweens(ctl, deleteRange):
    '''
    ctl = pm.PyNode('JawO_CAU2627')
    deleteRange = (1, 99)
    '''
    allOutputs = ctl.outputs()
    # filter outputs so we only use animCurve nodes
    allAnimOutputs = [output for output in allOutputs if 'animCurve' in output.nodeType(inherited=True)]
    for eachAnimCurve in allAnimOutputs:
        pm.cutKey(eachAnimCurve, float=deleteRange)
Esempio n. 28
0
def clear_vis(sel, vis):
    if pm.keyframe(sel, at='v', q=True):
        pm.cutKey(sel, at='v')
    else:
        pm.warning("No visibility keys to delete!")
    if vis == 0:
        sel.visibility.set(0)
    elif vis == 1:
        sel.visibility.set(1)
    else:
        pass
Esempio n. 29
0
 def cut_key(self):
     """
     Delete animations that exceed the range of frames.
     :return:
     """
     max_time = pm.playbackOptions(query=1, maxTime=1)
     for curve in self.animation_data.keys():
         last_frame = pm.findKeyframe(curve, which='last')
         while last_frame > max_time:
             pm.cutKey(curve, time=last_frame)
             last_frame = pm.findKeyframe(curve, which='last')
def change_intensity(quantity, operator, lights, keyframe):
    """
    Changes the intensity of passed array of Maya Light Transform nodes; may set animation keyframe.
    :param quantity: Amount of intensity to change
    :param operator: Modifying operator value. 0 = fixed quantity, 1 = addition, 2 = multiplication, 3 = add percentage
    :param lights: Array of Light nodeTypes
    :param keyframe: Boolean to define whether to set a keyframe or not
    :return: None
    """

    if not lights:
        pmc.warning(
            'Please select one or more lights in the Light Interface window\'s list'
        )
        return

    # Closure that returns a calculated value according to the selected operator
    def calculate_value(current_value):
        """
        :param current_value: Current intensity value of a specific light
        :return: Lambda operation according to the operator value selected
        """
        fixed = lambda x: quantity
        add = lambda x: x + quantity
        mult = lambda x: x * quantity
        percentage = lambda x: x + (x * quantity / 100.0)

        # Choose an operation based on the passed operator
        operation = {0: fixed, 1: add, 2: mult, 3: percentage}[operator]

        return operation(current_value)

    # Retrieves current frame the user is on
    currentFrame = pmc.currentTime(query=True)

    for light in lights:

        # Get Intensity attribute of this specific light
        new_value = calculate_value(pmc.getAttr('%s.intensity' % light))

        if keyframe is True:
            # cutKey deletes animation found in a certain frame
            pmc.cutKey(light,
                       time=(currentFrame, currentFrame),
                       attribute="intensity")

            # Set a keyframe in the current light
            pmc.setKeyframe(light,
                            time=currentFrame,
                            attribute="intensity",
                            value=new_value)

        # Set Intensity value
        pmc.setAttr('%s.intensity' % light, new_value)
Esempio n. 31
0
    def clearKeys(self):
        """Delete the animation key(s) on the node chennelBox attribute(s).

        :Example:
            from rigIO.channelBox import ChannelBox

            channelBox = ChannelBox('nodeName')
            channelBox.clearKeys()
        """
        for attr in self._filter():
            pm.cutKey(attr)
Esempio n. 32
0
def bdCleanKeyframes():
    start = pm.playbackOptions(q=1,ast=1)
    end = pm.playbackOptions(q=1,aet=1)

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

    for i in range(8,end-10,1):
        if not (i%4):
            print i
            pm.currentTime(i)
            pm.setKeyframe(sel,t=i)
        else:
            pm.cutKey(sel,clear=1,an='objects',iub=0,t=(i,i+1))
Esempio n. 33
0
    def delete_key(self, attr, index):
        '''
        # this delete the key at the given index
        # take the attr from which keys will be removed
        # attr example: 'pCube1.translateX'
        '''
        print attr, index.getValue(), attr, index.getValue()
        
        pm.cutKey('%s' % (attr), index= (index.getValue(),index.getValue()), clear= True)

        
        # reinvoking the create to add the uis for the new keys
        print 'recreating'
        pm.deleteUI(self.temp_layout)
        self.create()
Esempio n. 34
0
def keyAllChildren(op="set", jointsOnly=False): #set, cut, copy, paste
   selectedObjects = mc.ls(sl=True)
   targetObjects = mc.listRelatives( selectedObjects, ad=True ) + selectedObjects
   if(jointsOnly):
      targetObjects = mc.ls(targetObjects, type='joint')
   if(op=="set"):
      py.setKeyframe( targetObjects )
   elif(op=="cut"):
      py.cutKey( targetObjects )
   elif(op=="copy"):
      py.copyKey( targetObjects )
   elif(op=="paste"):
      py.pasteKey( targetObjects )   
   elif(op=="bake"):
      inTime=mc.playbackOptions(q=1,ast=1)
      outTime=mc.playbackOptions(q=1,aet=1)
      mc.bakeResults(targetObjects,simulation=1,sampleBy=1,time=(inTime,outTime))
Esempio n. 35
0
 def stageMousePress(self, event):
     self._startTime = pm.currentTime(q=1)
     self.mouseOrigin[0] = event.x()
     self.mouseOrigin[1] = event.y()
     self.isRecording = True
     for i in range(0,2):
         self._startAttrs[i] = []
         for mAttr in self.attrs[i]:
             self._startAttrs[i].append(pm.getAttr(mAttr))
     if self.recordingMode:
         timeRange = (pm.playbackOptions(q=1,min=1), pm.playbackOptions(q=1,max=1))
         for i in range(0,2):
             for mAttr in self.attrs[i]:
                 pm.cutKey(mAttr.nodeName(), at=mAttr.longName(), time=timeRange, option='keys')
                 pm.select(mAttr.nodeName())
                 pm.recordAttr(at = mAttr.longName())
         pm.play(record=True)
Esempio n. 36
0
    def set_position(self,key_frame, location, rotation, scale, visibility):
        if location is not None:
            pm.setKeyframe(self.object_name, attribute='tx', value=location[0], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='ty', value=location[1], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='tz', value=location[2], time=key_frame)
        if rotation is not None:
            pm.setKeyframe(self.object_name, attribute='rx', value=rotation[0], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='ry', value=rotation[1], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='rz', value=rotation[2], time=key_frame)
        if scale is not None:
            pm.setKeyframe(self.object_name, attribute='sx', value=scale[0], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='sy', value=scale[1], time=key_frame)
            pm.setKeyframe(self.object_name, attribute='sz', value=scale[2], time=key_frame)
        if visibility is not None:
            '''
            
keyTangent -itt auto -ott auto;
'''
            pm.setKeyframe(self.object_name, attribute='v', value=visibility, time=key_frame)
            pm.keyTangent('{}.v'.format(self.object_name), edit=True, itt='auto', ott='auto')
            pm.cutKey(self.object_name.getShape(), attribute='v', clear=True)
            pm.setAttr('{}.v'.format(self.object_name.getShape()), True)
            
            objectShape = None