def keyFullRotation (pObjectName, pStartTime, pEndTime, pTargetAttribute): cmds.cutKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute) cmds.setKeyframe (pObjectName, time = pStartTime, attribute=pTargetAttribute, value=0) cmds.setKeyframe (pObjectName, time = pEndTime, attribute=pTargetAttribute, value=360) cmds.selectKey (pObjectName, time = (pStartTime, pEndTime), attribute=pTargetAttribute, keyframe=True) cmds.keyTangent (inTangentType='linear', outTangentType='linear')
def switch(self, i1, i2, t): """ Exchange two units """ # How to do this? Maybe should not be on this part. u1 = self.units[i1] u2 = self.units[i2] u1r = u1.rotation u2r = u2.rotation if u1r < u2r: r1 = u2r - u1r r2 = 360 - r1 else: r2 = u2r - u1r r1 = 360 - r1 #u1.rotation = r1 #u2.rotation = r2 print(r1) print(r2) u1.rotate(r1, t, t+1, height=3) u2.rotate(2, t, t+1) cmds.setKeyframe(u1.group, attribute='rotateX', t=str(t) + 'sec', value=r1) cmds.setKeyframe(u2.group, attribute='rotateX', t=str(t+1) + 'sec', value=r2)
def elevate(self, height, start, end=None): if end is None: end = start + 1 cmds.setKeyframe(self.group, attribute='translateX', t=str(start) + 'sec', value=0) cmds.setKeyframe(self.group, attribute='translateX', t=str(end) + 'sec', value=height)
def draw(self): circle1 = cmds.circle( nr=(1, 0, 0), c=(0, 0, 0), sw=self.sweep, r=self.start_radius ) circle2 = cmds.circle( nr=(1, 0, 0), c=(0, 0, 0), sw=self.sweep, r=self.end_radius ) l1 = cmds.loft(circle1, circle2) # curves crv = cmds.curve(p=[(0, self.start_radius, 0), (0, self.end_radius, 0)], degree=1) crv2 = cmds.duplicate(crv) cmds.rotate(str(self.sweep) + 'deg', 0, 0, r=True) extrusions = [] for e in [circle1, circle2, crv, crv2]: extrusions.append(cmds.extrude(e, et=0, d=(1,0,0), l=self.height)) cmds.delete(e) pieces = extrusions + [l1] group = cmds.group(*[e[0] for e in pieces]) cmds.move(0,0,0, group+".scalePivot",group+".rotatePivot", absolute=True) cmds.setKeyframe(group, attribute='rotateX', t='0sec', value=self.rotation) return (pieces, group)
def build_crack_distance( self, distance_locator ): obj_distance = {} current_time = cmds.currentTime( query = True ) loc_custon_attrs = cmds.listAttr( ud = True ) for attr in loc_custon_attrs: distance_node = cmds.listConnections( '{0}.{1}'.format( distance_locator, attr ) ) if distance_node: distance_node = distance_node[0] mesh_node = cmds.listConnections( '{0}.point2'.format( distance_node ) ) if mesh_node: mesh_node = mesh_node[0] obj_distance[cmds.getAttr( '{0}.distance'.format( distance_node ) )] = mesh_node for value in sorted( obj_distance ): obj = obj_distance[value] obj_active = '{0}.active'.format( obj ) if cmds.objExists( obj_active ): cmds.setAttr( obj_active, 0 ) cmds.setKeyframe( obj_active, time = current_time ) current_time = current_time + 0.5 cmds.setAttr( obj_active, 1 ) cmds.setKeyframe( obj_active, time = current_time )
def apply(self, attr): obj = attr.node() obj_mel = obj.__melobject__() attr_longName = attr.longName() attrMel = attr.__melobject__() if len(self.times) > 0: for time, value in zip(self.times, self.values): cmds.setKeyframe(obj_mel, time=time, attribute=attr_longName, value=value, breakdown=False, # TODO: Approve hierarchy='none', # TODO: Approve controlPoints=False, # TODO: Approve shape=False) # TODO: Approve # set tangents cmds.keyTangent(attrMel, edit=True, wt=int(self.weightedTangent)) # todo: approve int cast for time, inAngle, outAngle, inWeight, outWeight, inTangentType, outTangentType, lock in zip( self.times, self.inAngles, self.outAngles, self.inWeights, self.outWeights, self.inTangentTypes, self.outTangentTypes, self.locks): fn_keyTangent = functools.partial(cmds.keyTangent, attrMel, edit=True, time=(time, time)) fn_keyTangent(inAngle=inAngle, outAngle=outAngle, inWeight=inWeight, outWeight=outWeight) fn_keyTangent(inTangentType=inTangentType,outTangentType=outTangentType) fn_keyTangent(lock=lock) # TODO: Optimise # set infinity if self.preInfinity != "constant": cmds.setInfinity(obj, attribute=attr_longName, preInfinity=self.preInfinity) if self.postInfinity != "constant": cmds.setInfinity(obj, attribute=attr_longName, postInfinity=self.postInfinity) else: attr.set(self.value)
def cutEarlier(selectionOption=1, setKey=True): keySel = _getKeySelection(selectionOption) keySel.fromBeginning() if setKey and keySel.findKeyframe('previous', time=(keySel._timeRangeEnd,)) < keySel._timeRangeEnd : mc.setKeyframe(keySel.curves, time=keySel._timeRangeEnd) keySel.cutKey()
def findSpeeds(arg): frameRates = {"game": 15, "film": 24, "pal": 25, "ntsc": 30, "show": 48, "palf": 50, "ntscf": 60} first_user_frame = cmds.intField(window_UI["first_frame"], query=True, value=True) last_user_frame = cmds.intField(window_UI["last_frame"], query=True, value=True) start_frame = cmds.playbackOptions(query=True, minTime=True) end_frame = cmds.playbackOptions(query=True, maxTime=True) if first_user_frame < start_frame or last_user_frame > end_frame: return current_frame = first_user_frame fps = frameRates[cmds.currentUnit(query=True, time=True)] timeInterval = 1.0 / fps selectedObjects = cmds.ls(selection=True) attr = "speed" addAttributeToObjects(selectedObjects, attr) prevPos = [] for obj in selectedObjects: prevPos.append(cmds.getAttr(obj + ".translate")[0]) while current_frame < last_user_frame: current_frame += 1 for k in xrange(0, len(selectedObjects)): obj = selectedObjects[k] currentPos = cmds.getAttr(obj + ".translate", time=current_frame)[0] speed = getSpeed(prevPos[k], currentPos, timeInterval) cmds.setKeyframe(obj, at="speed", v=speed, t=current_frame) prevPos[k] = currentPos
def PasteMirrorPose(): # создаю функцию, которая проверяет значение на '-' # и заменяет его на противоположное def MirrorChange(value): if '-' in value: value = value[1:] else: value = '-' + value return value # задаю префиксы, по которым ориентируюсь, правая или левая сторона lPref = 'l_' rPref = 'r_' # paste copied and mirrored keys for setAttrib in setAttribList: splitKey = setAttrib.split() object = splitKey[0] attribute = splitKey[1] value = splitKey[2] # извлекаю префикс из имени объекта objPref = object[0:2] # задаю условия для зеркального отображения объектов if 'rotateY' in attribute: value = MirrorChange(value) if 'rotateZ' in attribute: value = MirrorChange(value) if 'translateX' in attribute: value = MirrorChange(value) if rPref in objPref: object = lPref + object[2:] if lPref in objPref: object = rPref + object[2:] cmds.setAttr(object + '.' + attribute, float(value)) cmds.setKeyframe(locList)
def createBurnin(self,*args): """ Create the burn-in image plane for the playblast """ #Get play blast camera shape node temp = cmds.listRelatives(self.classScopeData['camera'],shapes=True) camShape = temp[0] #Create image plane mel.eval('createImportedImagePlane { "%s" } "%s" "image";'%(camShape,self.classScopeData['image'])) temp = cmds.listConnections(camShape) #If other image planes exist, select the last one if len(temp) > 1: self.imagePlane = temp[len(temp)-1] else: self.imagePlane = temp[0] cmds.setAttr('%s.depth'%self.imagePlane,1) #Key the burn-ins visibility cmds.setKeyframe( self.imagePlane, attribute='alphaGain', t=( self.classScopeData['startTime'] - 1 ),v=0 ) cmds.setKeyframe( self.imagePlane, attribute='alphaGain', t=( self.classScopeData['startTime'] ),v=1 )
def createSlate(self,*args): """ Create the slate image plane for the playblast """ #Setup image plane #Get play blast camera shape node temp = cmds.listRelatives(self.classScopeData['camera'],shapes=True) camShape = temp[0] #Create image plane mel.eval('createImportedImagePlane { "%s" } "%s" "image";'%(camShape,self.classScopeData['slate'])) temp = cmds.listConnections(camShape) #If other image planes exist, select the last one if len(temp) > 1: self.slatePlane = temp[len(temp)-1] else: self.slatePlane = temp[0] #Key the slates visibility. On for 1 frame. cmds.setKeyframe( self.slatePlane, attribute='alphaGain', t=( self.classScopeData['startTime'] - 1 ),v=1 ) cmds.setKeyframe( self.slatePlane, attribute='alphaGain', t=( self.classScopeData['startTime'] ),v=0 )
def animateLegs(indAnt, feetPos): """Animate the legs via Maya keyframe commands """ for leg, footPos in zip(legArray, feetPos): cmds.xform(leg+"IK"+str(indAnt), t=footPos) cmds.setKeyframe(leg+"IK"+str(indAnt),at="translate")
def zbw_stepAll(): sel = cmds.ls(sl=True) keyList = [] keySet = set() allKeys = [] #get timeslider range start startF = cmds.playbackOptions(query=True, min=True) #get end frame endF = cmds.playbackOptions(query=True, max=True) #get all the keyed frames for this in sel: keyList = cmds.keyframe(this, query=True, time=(startF,endF)) for key in keyList: key = int(key) keySet.add(key) #print keyList keySet = set(keyList) for frame in keySet: allKeys.append(frame) allKeys.sort() allKeys.reverse() #print allKeys for object in sel: for thisKey in allKeys: cmds.currentTime(thisKey) cmds.setKeyframe(object, t=thisKey, ott="step")
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)
def connectCommand( uiInstance ): sels = cmds.ls( sl=1 ) selChannels = cmds.channelBox( 'mainChannelBox', q=1, sma=1 ) numItems = uiInstance.layout.count() animNode = cmds.createNode( 'animCurveUU' ) for i in range( 1, numItems-1 ): targetWidget = uiInstance.layout.itemAt( i ).widget() key = targetWidget.lineEdit_key.text() value = targetWidget.lineEdit_value.text() cmds.setKeyframe( animNode, f=float(key), v=float(value) ) cmds.keyTangent( animNode, f=(float(key),float(key)), itt='linear', ott = 'linear' ) if sels and selChannels: cmds.connectAttr( sels[0] + '.' + selChannels[0], animNode + '.input' ) addString = '' if float(key) > 0: addString = 'positive' else: addString = 'negative' animNode = cmds.rename( animNode, selChannels[0] + '_' + addString + '_from_' + sels[0] ) cmds.select( animNode )
def keyCopyObjects( fromList, toList, start, end ): for i in range( len( fromList ) ): fromCtl = fromList[i] toCtl = toList[i] targetMtx = cmds.getAttr( fromCtl+'.m' ) mirrorMtx = getMirrorMatrix_local( targetMtx ) listAttr = cmds.listAttr( fromCtl, k=1 ) if not listAttr: continue for attr in listAttr: times = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), tc=1 ) if not times: continue values = cmds.keyframe( fromCtl+'.'+attr, q=1, t=(start,end), vc=1 ) keyLocks = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), lock=1 ) inAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), ia=1 ) outAngles = cmds.keyTangent( fromCtl+'.'+attr, q=1, t=(start,end), oa=1 ) cmds.cutKey( toCtl+'.'+attr, t=(start+0.01, end-0.01) ) for i in range( len( times ) ): if attr.find( 'translate' ) != -1: value = -values[i] ia = -inAngles[i] oa = -outAngles[i] else: value = values[i] ia = inAngles[i] oa = outAngles[i] cmds.setKeyframe( toCtl+'.'+attr, t=times[i], v=value ) cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=0 ) cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), ia=ia ) cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), oa=oa ) cmds.keyTangent( toCtl+'.'+attr, e=1, t=(times[i],times[i]), lock=keyLocks[i] )
def OnKeyChange( self, *args ): checks = [ cmds.checkBox( self.cXKey, query = True, value = True ), cmds.checkBox( self.cYKey, query = True, value = True ), cmds.checkBox( self.cZKey, query = True, value = True ) ] attribs = [ ".translateX", ".translateY", ".translateZ" ] # ... se quieren cambios? ... sequence = next( ( seq for seq in self.SequenceInfo if seq.GetNode() == self.ActiveNode ), None ) frameInfo = sequence.GetFrameInfo( self.ActiveManip.GetFrame() ) # ... refreshCurve = False frame = self.ActiveManip.GetFrame() + self.StartFrame for i in range( 0, 3 ): if ( checks[ i ] != frameInfo.HasTranslationKeyAxis( i ) ): if ( checks[ i ] ): # ... se crea la key ... cmds.setKeyframe( self.ActiveNode + attribs[ i ], insert = True, time = ( frame, frame ) ) frameInfo.SetTranslationKey( i ) else: # ... se borra la key ... #cmds.selectKey( self.ActiveNode + attribs[ i ], add = True, keyframe = True, time = ( frame, frame ) ) cmds.cutKey( self.ActiveNode + attribs[ i ], time = ( frame, frame ), option = "keys" ) frameInfo.RemoveTranslationKey( i ) refreshCurve = True # ... if ( refreshCurve ): self.CreateCurve()
def insertKeyToAnimLayer(): ''' inserts key to all animcurves in anim layer, wont key if objects has not been keyed but is in anim layer ''' currentLayer = cmds.treeView ('AnimLayerTabanimLayerEditor', q=True, selectItem=True) curves = cmds.animLayer(currentLayer[0], q=True, anc=True) cmds.setKeyframe(curves, i=True)
def updateRot(indAnt, vel, curTri, newTri, comPos, nextLeft, extForceFrame): """Update the rotation of the character """ if np.linalg.norm(extForceFrame) != 0: diff = np.average(newTri, axis=0) - np.average(curTri, axis=0) else: diff = np.average(newTri, axis=0) - comPos velNorm = np.linalg.norm(vel) diffNorm = np.linalg.norm(diff) newVel = velNorm*diff/diffNorm # normal is normalised triN = triangleNorm(curTri, nextLeft) velOnNormal = np.dot(newVel, triN)*triN velOnTri = newVel - velOnNormal # scale matrix for the ant model scaleMatrix = np.matrix([[0.4, 0, 0, 0], [0, 0.4, 0, 0], [0, 0, 0.4, 0], [0, 0, 0, 1]]) rotMat = up.constructRotMat(triN, velOnTri, full=True) mat = np.asarray(rotMat*scaleMatrix).flatten() cmds.xform("antRig"+str(indAnt), m=mat) cmds.setKeyframe('antRig'+str(indAnt), at='rotate') return newVel
def BSplineInterpolate(curveName): keyCount = mc.keyframe(curveName, query=True, keyframeCount=True) keyframes = mc.keyframe(curveName, query=True, timeChange=True, valueChange=True) deBoorPoints = []; for n in range(2): deBoorPoints.append(vector2(keyframes[0], keyframes[1])) for index in range(0, len(keyframes), 2): deBoorPoints.append(vector2(keyframes[index], keyframes[index + 1])) for n in range(2): deBoorPoints.append(vector2(keyframes[-2], keyframes[-1])) basisMatrix = matrix4x4([-1, 3, -3, 1, 3, -6, 3, 0, -3, 0, 3, 0, 1, 4, 1, 0]) for n in range(len(deBoorPoints) - 3): b1 = deBoorPoints[n] b2 = deBoorPoints[n + 1] b3 = deBoorPoints[n + 2] b4 = deBoorPoints[n + 3] timeSteps = 10 for t in range(timeSteps + 1): time = float(t) / float(timeSteps) timeVector = matrix1x4([time ** 3, time ** 2, time, 1]); inputPointsVector = matrix4x1([b1, b2, b3, b4]); output = timeVector * (1.0 / 6.0) * basisMatrix * inputPointsVector; mc.setKeyframe(curveName, time=output.x, value=output.y)
def constructNode( self, timeOffset=0 ): ''' constructs an animCurve node using the data stored on the instance returns the node created ''' animCurveNode = createNode( self[ self.CURVE_TYPE ] ) #massage the time values times = [ t+timeOffset for t in self[ self.TIME ] ] values = self[ self.VALUE ] maxIdxVal = len( values ) - 1 setKeyframe = cmd.setKeyframe for time, value in zip( times, values ): setKeyframe( animCurveNode, t=time, v=value ) #set key data setAttr( '%s.wgt' % animCurveNode, self[ self.WEIGHTED ] ) setAttr( '%s.pre' % animCurveNode, self[ self.PRE_INF ] ) setAttr( '%s.pst' % animCurveNode, self[ self.POST_INF ] ) setAttr( '%s.keyBreakdown[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.BREAKDOWN ] ) setAttr( '%s.keyTanLocked[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.TAN_LOCK ] ) setAttr( '%s.keyWeightLocked[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.WEIGHT_LOCK ] ) setAttr( '%s.kix[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.ITX ] ) setAttr( '%s.kiy[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.ITY ] ) setAttr( '%s.kox[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.OTX ] ) setAttr( '%s.koy[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.OTY ] ) setAttr( '%s.kit[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.ITT ] ) setAttr( '%s.kot[0:%d]' % (animCurveNode, maxIdxVal), *self[ self.OTT ] ) return animCurveNode
def oldKeyArmIKFK(preRoll): #Right Arm #Check initial IKFK State mc.currentTime(0) if mc.getAttr('ten_rig_main_r_arm_switch_CTL.IKFK_Switch') == 0: #Set Arm as FK mc.setAttr('ten_rig_main_l_arm_switch_CTL.IKFK_Switch', 1) if (mc.getAttr('ten_rig_main_l_arm_switch_CTL.IKFK_Switch', keyable=True) or mc.getAttr('ten_rig_main_l_arm_switch_CTL.IKFK_Switch', channelBox=True)): mc.setKeyframe('ten_rig_main_l_arm_switch_CTL.IKFK_Switch'); #Set IKFK at zero mc.setKeyframe('ten_rig_main_r_arm_switch_CTL.IKFK_Switch') #Set IKFK at preRoll mc.currentTime(preRoll) mc.setAttr('ten_rig_main_r_arm_switch_CTL.IKFK_Switch', 1) mc.setKeyframe('ten_rig_main_r_arm_switch_CTL.IKFK_Switch') #Left Arm #Check initial IKFK State mc.currentTime(0) if mc.getAttr('ten_rig_main_l_arm_switch_CTL.IKFK_Switch') == 0: #Set IKFK at zero mc.setKeyframe('ten_rig_main_l_arm_switch_CTL.IKFK_Switch') #Set IKFK at preRoll mc.currentTime(preRoll) mc.setAttr('ten_rig_main_l_arm_switch_CTL.IKFK_Switch', 1) mc.setKeyframe('ten_rig_main_l_arm_switch_CTL.IKFK_Switch')
def BezierInterpolate(curveName): rawKeyCount = mc.keyframe(curveName, query=True, keyframeCount=True) keyframes = mc.keyframe(curveName, query=True, timeChange=True, valueChange=True) if rawKeyCount < 4: print "Not enough control points, key count = " + str(rawKeyCount) + ", must have at least 4" return; keyCount = ((rawKeyCount - 4) // 3) * 3 + 4; curveCount = 1 + ((keyCount - 4) // 3); basisMatrix = matrix4x4([-1, 3, -3, 1, 3, -6, 3, 0, -3, 3, 0, 0, 1, 0, 0, 0]) for index in range(curveCount): p1KeyArrayIndex = 2 * (index * 3); p2KeyArrayIndex = 2 * (index * 3 + 1); p3KeyArrayIndex = 2 * (index * 3 + 2); p4KeyArrayIndex = 2 * (index * 3 + 3); p1 = vector2(keyframes[p1KeyArrayIndex], keyframes[p1KeyArrayIndex + 1]); p2 = vector2(keyframes[p2KeyArrayIndex], keyframes[p2KeyArrayIndex + 1]); p3 = vector2(keyframes[p3KeyArrayIndex], keyframes[p3KeyArrayIndex + 1]); p4 = vector2(keyframes[p4KeyArrayIndex], keyframes[p4KeyArrayIndex + 1]); startTime = int(keyframes[p1KeyArrayIndex]) endTime = int(keyframes[p4KeyArrayIndex]) timeSteps = abs(endTime - startTime) for t in range(timeSteps + 1): time = float(t) / timeSteps timeVector = matrix1x4([time ** 3, time ** 2, time, 1]); inputPointsVector = matrix4x1([p1, p2, p3, p4]); output = timeVector * basisMatrix * inputPointsVector; mc.setKeyframe(curveName, time=output.x, value=output.y)
def _update_flipbook_node(new_page, current_frame): """ Updates the flipbook node with a new page in the enumerator and sets the key for that frame. :param new_page: :type new_page: :returns: None """ # ...: cmds.expression(object=new_page, name="%s_visbility_EXP" % (new_page), string="int $page = %d;\n" "int $current_keyed_frame = flipbook_LOC.pagesToDisplay;\n" "%s.visibility = ($page==$current_keyed_frame)||(visibilityOverride);" % (current_frame, new_page), alwaysEvaluate=True) # We will also be adding another attribute with just integer values. # This will be set here at this point as well. cmds.setKeyframe("flipbook_LOC.pagesToDisplay", value=current_frame, time=current_frame, outTangentType="step") # Return: return
def setKeyByData(namespace, data): #- data format not right.. if not isinstance(data, dict): return #- data is empty.. if len(data) == 0: return #- object not exists.. obj = getObjectReferencedName(namespace, data.get('object', '"')) if not mc.objExists(obj): return #- reading data.. for attr, keydata in data.get('keyData', dict()).iteritems(): #- testing attribute.. #- key it for tm_V, va_V, ia_V, iw_V, oa_V, ow_V in keydata: #- set key mc.setKeyframe(obj, at=attr, t=tm_V, v=va_V) #- fix curve mc.keyTangent('%s.%s'%(obj, attr), l=False) mc.keyTangent(obj, e=True, at=attr, a=True, t=(tm_V, tm_V), ia=ia_V, iw=iw_V, oa=oa_V, ow=ow_V) mc.keyTangent('%s.%s'%(obj, attr), l=True)
def __init__(self, curve_sel, vertex_list, chain_geo): self.curve_sel = curve_sel self.verts = vertex_list self.chain_geo = chain_geo self.find_length = Find_Out() self.link_length = self.find_length.edge_length(self.verts) self.chain_length = self.find_length.curve_length(self.curve_sel) self.link_total = int(self.chain_length/self.link_length) self.motion_path_name = str(self.chain_geo) + '_Path' cmds.pathAnimation(self.chain_geo, name = self.motion_path_name, fractionMode = True, follow= True, followAxis = 'x', upAxis = 'y', worldUpType = 'object', startTimeU = 1, endTimeU = self.link_total, c = self.curve_sel) cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 0.0, t = 1 ) cmds.setKeyframe(self.motion_path_name + '.frontTwist', v = 60.0*self.link_total, t = self.link_total ) cmds.keyTangent(self.motion_path_name + '.uValue', itt = 'linear', ott = 'linear' ) cmds.keyTangent(self.motion_path_name + '.frontTwist', itt = 'linear', ott = 'linear') cmds.snapshot( self.chain_geo, constructionHistory=True, startTime=1, endTime = self.link_total, increment=1, update = 'animCurve', name = str(self.chain_geo) + '_snapShot' ) self.chain_group = cmds.group( em=True, name=str(self.chain_geo) + '_geo_grp' ) self.chain_list = cmds.listRelatives(str(self.chain_geo + '_snapShotGroup')) for dummy_geo in self.chain_list: cmds.delete(icn = True, ch = True) cmds.parent(dummy_geo, self.chain_group)
def set_empty_page(): """Sets the current frame as an empty page. :returns: None. :raises: None. """ # Then group the objects into their own page. The page number is dictated # by the current frame: current_frame = cmds.currentTime(query=True) page_name = "page_%04d" % (current_frame) if not cmds.objExists(page_name): cmds.group(name=page_name, empty=True) # Add the visibility override attribute to the group name: cmds.addAttr(page_name, longName="visibilityOverride", attributeType="bool") cmds.setKeyframe(page_name + ".visibilityOverride", time=1, value=0) # Set the key for this page and insert the page number into the attribute # on the flipbook node: _update_flipbook_node(page_name, current_frame) # Return return
def connectSDK(inPlug, outPlug, keys, name=''): ''' Creates a AnimCurveUU node connecting inPlug to outPlug inPlug - 'node.attribute' for input outPlug - 'node.attribute' for outputs keys - {driverValue:value} return AnimCurveUU node ''' inPlugStr = str(inPlug) outPlugStr = str(outPlug) if not name: try: alias = outPlug.getAlias() except: alias = None if alias: name = outPlugStr.split('.')[0] + '_' + alias + '_SDK_0' else: name = outPlugStr.replace('.', '_') + '_SDK_0' node = mc.createNode('animCurveUU', name=name) for eachKey, eachValue in keys.items(): mc.setKeyframe(node, f=eachKey, v=eachValue) mc.connectAttr(inPlugStr, node+'.input', f=True) mc.connectAttr(node+'.output', outPlugStr, f=True) return node
def testSubD(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testSubDInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3)
def buildGhostAnimation(*args): obj = 'ghost_body1' # get animation start and end points from ui controls animation_start = cmds.intField('animation_start', query=True, value=True) animation_end = cmds.intField('animation_end', query=True, value=True) for current_time in range(animation_start, animation_end + 1): cmds.currentTime(current_time, edit=True) locatorPos = cmds.xform('character_locator', q=1, t=True) x = round(locatorPos[0], 2) z = round(locatorPos[2], 2) if x % 1 == 0.25 or z % 1 == 0.25: cmds.xform(obj, rotation = [0, 11.25, 0]) elif x % 1 == 0.5 or z % 1 == 0.5: cmds.xform(obj, rotation = [0, 22.5, 0]) elif x % 1 == 0.75 or z % 1 == 0.75: cmds.xform(obj, rotation = [0, 33.75, 0]) elif x % 1 == 0 or z % 1 == 0: cmds.xform(obj, rotation = [0, 0, 0]) else: assert False, "Unhandled character position" cmds.setKeyframe([obj])
def run(mode='pose'): """ """ #- copy part sels = cmds.ls(sl=True) data = {} if mode == 'pose': for sel in sels: attrs = cmds.listAttr(sel, keyable=True) if sel[0] in ['l', 'L', 'r', 'R']: result = re.match("^{}+".format(prefix(sel)[0]), sel) selCut = sel[len(result.group(0)):] selRep = prefix(sel)[1] + selCut data[selRep] = {} for attr in attrs: data[selRep][attr] = cmds.getAttr(sel + '.' + attr) else: data[sel] = {} revAttr = ['rotateY'] for attr in attrs: if attr in revAttr: data[sel][attr] = cmds.getAttr(sel + '.' + attr) * -1 else: data[sel][attr] = cmds.getAttr(sel + '.' + attr) #- paste part for sel in sels: for obj in data.keys(): for attr in data[obj].keys(): try: cmds.setAttr(obj + '.' + attr, data[obj][attr]) except: pass elif mode == 'anim': for sel in sels: attrs = cmds.listAttr(sel, keyable=True) if sel[0] in ['l', 'L', 'r', 'R'] and 'root' not in sel.lower(): result = re.match("^{}+".format(prefix(sel)[0]), sel) selCut = sel[len(result.group(0)):] selRep = prefix(sel)[1] + selCut data[selRep] = {} for attr in attrs: data[selRep][attr] = { 'tc': cmds.keyframe(sel + '.' + attr, q=True, tc=True), 'vc': cmds.keyframe(sel + '.' + attr, q=True, vc=True), 'inTangentType': cmds.keyTangent(sel + '.' + attr, inTangentType=True, q=True), 'outTangentType': cmds.keyTangent(sel + '.' + attr, outTangentType=True, q=True), 'inAngle': cmds.keyTangent(sel + '.' + attr, inAngle=True, q=True), 'outAngle': cmds.keyTangent(sel + '.' + attr, outAngle=True, q=True), 'inWeight': cmds.keyTangent(sel + '.' + attr, inWeight=True, q=True), 'outWeight': cmds.keyTangent(sel + '.' + attr, outWeight=True, q=True), 'weightedTangents': cmds.keyTangent(sel + '.' + attr, weightedTangents=True, q=True) } else: data[sel] = {} revAttr = ['rotateY'] for attr in attrs: if attr in revAttr: data[sel][attr] = { 'tc': cmds.keyframe(sel + '.' + attr, q=True, tc=True), 'vc': [ -1 * x for x in cmds.keyframe( sel + '.' + attr, q=True, vc=True) ], 'inTangentType': cmds.keyTangent(sel + '.' + attr, inTangentType=True, q=True), 'outTangentType': cmds.keyTangent(sel + '.' + attr, outTangentType=True, q=True), 'inAngle': cmds.keyTangent(sel + '.' + attr, inAngle=True, q=True), 'outAngle': cmds.keyTangent(sel + '.' + attr, outAngle=True, q=True), 'inWeight': cmds.keyTangent(sel + '.' + attr, inWeight=True, q=True), 'outWeight': cmds.keyTangent(sel + '.' + attr, outWeight=True, q=True), 'weightedTangents': cmds.keyTangent(sel + '.' + attr, weightedTangents=True, q=True) } else: data[sel][attr] = { 'tc': cmds.keyframe(sel + '.' + attr, q=True, tc=True), 'vc': cmds.keyframe(sel + '.' + attr, q=True, vc=True), 'inTangentType': cmds.keyTangent(sel + '.' + attr, inTangentType=True, q=True), 'outTangentType': cmds.keyTangent(sel + '.' + attr, outTangentType=True, q=True), 'inAngle': cmds.keyTangent(sel + '.' + attr, inAngle=True, q=True), 'outAngle': cmds.keyTangent(sel + '.' + attr, outAngle=True, q=True), 'inWeight': cmds.keyTangent(sel + '.' + attr, inWeight=True, q=True), 'outWeight': cmds.keyTangent(sel + '.' + attr, outWeight=True, q=True), 'weightedTangents': cmds.keyTangent(sel + '.' + attr, weightedTangents=True, q=True) } #- paste part for sel in sels: for obj in data.keys(): for attr in data[obj].keys(): # check if data is anim data or pose data if isinstance(data[obj][attr], dict): if not data[obj][attr]['tc'] == None: for i in range(len(data[obj][attr]['tc'])): try: cmds.setKeyframe( obj + '.' + attr, t=data[obj][attr]['tc'][i], v=data[obj][attr]['vc'][i]) cmds.keyTangent( obj + '.' + attr, inTangentType=data[obj][attr] ['inTangentType'][i], outTangentType=data[obj][attr] ['outTangentType'][i], inAngle=data[obj][attr]['inAngle'][i], outAngle=data[obj][attr]['outAngle'] [i], inWeight=data[obj][attr]['inWeight'] [i], outWeight=data[obj][attr]['outWeight'] [i], weightedTangents=data[obj][attr] ['weightedTangents'][i]) except: pass
def move_save(r , h, f ) : cmds.currentTime(f , edit = True ) move_frame(r , h) cmds.setKeyframe("cube" , breakdown = False , hierarchy = "none" , controlPoints = False , shape = False )
def Con_Keyframe_Fn(self, pnCns, Attr_List): for i, Attr in enumerate(Attr_List): if i != 0: cmds.setKeyframe("%s.%s" % (pnCns, Attr))
def printAlgorithmAnimation(step): # Step 1 Animation "Aus dem Regal bewegen" if step == 1: before_rotate = r.getMotorRotation(0) # Paket wird aus dem Regal bewegt for i in range(0, 4): if r.package[0] == 1: if r.package[1] == 2: cmds.move(-.3, 0, 0, 'ikHandle', relative=True) else: cmds.move(-.5, 1, 0, 'ikHandle', relative=True) else: if r.package[1] == 2: cmds.move(-.3, .25, 0, 'ikHandle', relative=True) else: cmds.move(-.5, .4, 0, 'ikHandle', relative=True) after_rotate = r.getMotorRotation(0) # Schnellst moegliche Zeit fuer diese Bewegung wird berechnet min_time = max( abs(before_rotate[1] - after_rotate[1]) / max_speed[1], abs(before_rotate[2] - after_rotate[2]) / max_speed[2], abs(before_rotate[3] - after_rotate[3]) / max_speed[3], abs(before_rotate[4] - after_rotate[4]) / max_speed[4]) # Mit schnellst moeglicher Zeit wird der Roboterarm bewegt cmds.setKeyframe(r.achsname1, at='rotateY', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname2, at='rotateZ', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname3, at='rotateZ', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname4, at='rotateX', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname5, at='rotateZ', t=str(min_time) + 'sec') r.totalpasttime += min_time cmds.currentTime(str(r.totalpasttime) + 'sec', edit=True) # Step 2 Animation "Zur Ausgabe rotieren" if step == 2: rest1 = 0 if cmds.getAttr('achse1.rotateY') < 0: rest1 = -(-180 - cmds.getAttr('achse1.rotateY')) r.setAchse1(-180) else: rest1 = 180 - cmds.getAttr('achse1.rotateY') r.setAchse1(180) rest1_sek = float(rest1) / max_speed[0] cmds.setKeyframe(r.achsname1, at='rotateY', t=str(rest1_sek) + 'sec') cmds.setKeyframe(r.achsname2, at='rotateZ', t=str(r.totalpasttime + .3) + 'sec') cmds.setKeyframe(r.achsname3, at='rotateZ', t=str(r.totalpasttime + .3) + 'sec') cmds.setKeyframe(r.achsname4, at='rotateX', t=str(r.totalpasttime + .3) + 'sec') cmds.setKeyframe(r.achsname5, at='rotateZ', t=str(r.totalpasttime + .3) + 'sec') cmds.delete('ikHandle') cmds.currentTime(str(r.totalpasttime + rest1_sek) + 'sec', edit=True) # Speicherung wie lange die gesamte Animation dauert with open("time_algorithm.conf", "w+") as f: f.write(str(r.totalpasttime + rest1_sek)) # Step 3 Animation "Fuer die Ausgabe rotieren/positionieren" if step == 3: before_rotate = [ cmds.getAttr('achse2.rotateZ'), cmds.getAttr('achse3.rotateZ'), cmds.getAttr('achse4.rotateX'), cmds.getAttr('achse5.rotateZ') ] after_rotate = [-52.2985745581, 34.7935752632, 0.0, -74.1268957397] r.setAchse2(after_rotate[0]) r.setAchse3(after_rotate[1]) r.setAchse4(after_rotate[2]) r.setAchse5(after_rotate[3]) min_time = max( abs(before_rotate[0] - after_rotate[0]) / max_speed[1], abs(before_rotate[1] - after_rotate[1]) / max_speed[2], abs(before_rotate[2] - after_rotate[2]) / max_speed[3], abs(before_rotate[3] - after_rotate[3]) / max_speed[4]) min_time += r.totalpasttime # Mit schnellst moeglicher Zeit wird der Roboterarm bewegt cmds.setKeyframe(r.achsname2, at='rotateZ', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname3, at='rotateZ', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname4, at='rotateX', t=str(min_time) + 'sec') cmds.setKeyframe(r.achsname5, at='rotateZ', t=str(min_time) + 'sec') # Step 4 Export Animation for printing if step == 4: timeproportion = 1 isCombined = False with open("time_algorithm.conf", "r") as f: algorithm_animation_time = float(f.read()) try: with open("time_manual.conf", "r") as f: manual_animation_time = float(f.read()) timeproportion = algorithm_animation_time / manual_animation_time isCombined = True except: SpeedUI("Kombinierung nicht m?glich!") timeseg = float(algorithm_animation_time) / 3 # Erstellung von 4 Roboterarmen an den 4 Zeitpunkten der Animation cmds.currentTime('0sec', edit=True) r1 = newRobot("r1_alg") cmds.currentTime(str(timeseg) + 'sec', edit=True) r2 = newRobot("r2_alg") cmds.currentTime(str(timeseg * 2) + 'sec', edit=True) r3 = newRobot("r3_alg") cmds.currentTime(str(algorithm_animation_time) + 'sec', edit=True) r4 = newRobot("r4_alg") # Kopieren von Regal, Tisch und Platte zum Export in das File cmds.duplicate('Regal', n='Regal_alg') cmds.duplicate('Tisch', n='Tisch_alg') cmds.duplicate('Platte', n='Platte_alg') # Selektion aller Objekte welche exportiert werden sollen # und Verschiebung der Roboterarme auf die zeitlich proportionalen Positionen cmds.select('Regal_alg', r=True) cmds.select('r1_alg', add=True) cmds.move(fill_animation[0] * timeproportion, moveX=True, relative=True) cmds.select('Tisch_alg', r=True) cmds.select('r4_alg', add=True) cmds.move(fill_animation[3] * timeproportion, moveX=True, relative=True) cmds.select('r2_alg', r=True) cmds.move(fill_animation[1] * timeproportion, moveX=True, relative=True) cmds.select('r3_alg', r=True) cmds.move(fill_animation[2] * timeproportion, moveX=True, relative=True) cmds.select('Platte_alg', r=True) cmds.select('Tisch_alg', add=True) cmds.select('Regal_alg', add=True) cmds.select('r1_alg', add=True) cmds.select('r2_alg', add=True) cmds.select('r3_alg', add=True) cmds.select('r4_alg', add=True) # Kombiniert den Manuellen und den algorithmischen Weg if isCombined: cmds.move(5, moveZ=True, relative=True) cmds.file(os.getcwd() + '/PrintRobot_manual.mb', i=True, f=True) cmds.select('Tisch_Frame', r=True) cmds.select('Regal_Frame', add=True) cmds.select('r1', add=True) cmds.select('r2', add=True) cmds.select('r3', add=True) cmds.select('r4', add=True) cmds.move(-5, moveZ=True, relative=True) cmds.select('Platte_Frame', add=True) cmds.select('Tisch_alg', add=True) cmds.select('Regal_alg', add=True) cmds.select('r1_alg', add=True) cmds.select('r2_alg', add=True) cmds.select('r3_alg', add=True) cmds.select('r4_alg', add=True) # Export der Selektion in PrintRobot.mb cmds.file(os.getcwd() + '/PrintRobot_algorithm.mb', type='mayaBinary', exportSelected=True) # Selektion wird nach Export geloescht cmds.delete() SpeedUI("Export abgeschlossen!")
def sceneInfo(self): seqInfo = cmds.textScrollList('shotContent', q=True, si=True)[0] episodeName = cmds.textScrollList('ecfList', q=True, si=True)[0] record = [] for chk in epsInts: if chk[0].find(seqInfo) != -1: record.append(chk) #implement sequence information enviFetch = asiist.getEnvi() for chk in enviFetch: if chk[0] == 'resWidth': resWidth = chk[1] if chk[0] == 'resHeight': resHeight = chk[1] if chk[0] == 'resAspectRatio': resAspectRatio = chk[1] cmds.setAttr('defaultResolution.width', float(resWidth)) cmds.setAttr('defaultResolution.height', float(resHeight)) cmds.setAttr('defaultResolution.deviceAspectRatio', float(resAspectRatio)) #create empty group cmds.group(em=True, n='sceneInfo', p='shotMaster') if not cmds.objExists('char'): cmds.group(em=True, n='char', p='shotMaster') if not cmds.objExists('prop'): cmds.group(em=True, n='prop', p='shotMaster') if not cmds.objExists('sets'): cmds.group(em=True, n='sets', p='shotMaster') #generate data from record duration = 0 for chk in record: duration = duration + int(chk[1]) #additional data to sceneInfo cmds.select('sceneInfo') for chk in asiist.getEnvi(): cmds.addAttr(ln=str(chk[0]), k=True, at='enum', en=str(chk[1])) cmds.setAttr('sceneInfo.' + str(chk[0]), l=True) if chk[0] == 'unit': cmds.currentUnit(time=chk[1]) cmds.addAttr(ln='__________', k=True, at='enum', en='__________') cmds.setAttr('sceneInfo.__________', l=True) cmds.addAttr(ln='episodeName', k=True, at='enum', en=str(episodeName)) cmds.setAttr('sceneInfo.episodeName', l=True) cmds.addAttr(ln='sequenceName', k=True, at='enum', en=str(seqInfo)) cmds.setAttr('sceneInfo.sequenceName', l=True) cmds.addAttr(ln='startFrame', k=True, at='enum', en='101') cmds.setAttr('sceneInfo.startFrame', l=True) cmds.addAttr(ln='endFrame', k=True, at='enum', en=str(100 + (duration))) cmds.setAttr('sceneInfo.endFrame', l=True) cmds.addAttr(ln='key', k=True) cmds.addAttr(ln='___________', k=True, at='enum', en='__________') cmds.setAttr('sceneInfo.___________', l=True) base = 101 for chk in epsInts: if chk[0].find(seqInfo) != -1: #create shot entry cmds.addAttr(ln=chk[0], k=True, at='enum', en=str(chk[1])) cmds.setAttr('sceneInfo.' + chk[0], l=True) #create shot key shotNum = chk[0] shotNum = shotNum[shotNum.rfind('_') + 1:] shotNum = int(shotNum.replace('SH', '')) cmds.setAttr('sceneInfo.key', shotNum) cmds.setKeyframe('sceneInfo', attribute='key', t=base) base = base + (int(chk[1]) - 1) cmds.setAttr('sceneInfo.key', shotNum) cmds.setKeyframe('sceneInfo', attribute='key', t=base) base = base + 1 #cmds.setKeyframe('sceneInfo', attribute='key', t=base) #lock standard channel for object in ['shotMaster', 'sceneInfo', 'char', 'prop', 'sets']: for channel in [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'visibility' ]: cmds.setAttr(object + '.' + channel, l=True, cb=False, k=False) #impose shot range cmds.rangeControl(min=101, max=101 + (int(duration) - 1)) cmds.playbackOptions(min=101, max=101 + (int(duration) - 1)) #insert sound soundName = str(shotNum) if len(soundName) == 1: soundName = '0' + soundName if not os.path.isfile(SOUND_ROOT + '/' + PRJ_NAME + '/' + episodeName + '/SQ' + str(soundName) + '.wav'): cmds.confirmDialog( icn='information', t='Missing File', m='Missing sound file. Skip sound insertion process.', button=['OK']) else: if cmds.objExists('seqSoundtrack'): cmds.delete('seqSoundtrack') ret = mel.eval('doSoundImportArgList ("1", {"' + SOUND_ROOT + '/' + PRJ_NAME + '/' + episodeName + '/SQ' + str(soundName) + '.wav' + '","101.0"});') cmds.rename(ret, 'seqSoundtrack') return
def WalkAnimation(): print 'walking' PelvisTtx = [0.0, 4.0, 8.0, 12.0, 20.0, 24.0] PelvisTty = [0.0, 4.0, 8.0, 16.0, 20.0, 24.0] PelvisTtz = [0.0, 24.0] PelvisTvx = [0.01809184836781906, 0.016717685294681563, -0.0016717796575123401, -0.018, 0.008734702494680788, 0.01809184836781906] PelvisTvy = [-0.040044781654544295, -0.05638604292186571, 0.012150650186155637, -0.0564, 0.0122, -0.040044781654544295] PelvisTvz = [0.0, 0.0] PelvisRtx = [0.0, 4.0, 8.0, 16.0, 20.0, 24.0] PelvisRty = [0.0, 12.0, 24.0] PelvisRtz = [0.0, 12.0, 24.0] PelvisRvx = [0.9431342748637188, 5.524911273740404, 0.0, 5.524911273740404, 0.0, 0.943] PelvisRvy = [-10.632180516807548, 10.632, -10.632180516807544] PelvisRvz = [4.928773690595634, -4.929, 4.928773690595634] L_IK_FootTtx = [0.0, 12.0, 24.0] L_IK_FootTty = [0.0, 12.0, 20.0, 24.0] L_IK_FootTtz = [0.0, 12.0, 24.0] R_IK_FootTtx = [0.0, 12.0, 24.0] R_IK_FootTty = [0.0, 8.0, 12.0, 24.0] R_IK_FootTtz = [0.0, 12.0, 24.0] L_IK_FootTvx = [0.0128, -0.0202, 0.0128] L_IK_FootTvy = [0.0, 0.0, 0.048, 0.0] L_IK_FootTvz = [0.2423613316268693, -0.452, 0.2423613316268693] R_IK_FootTvx = [0.01280566739292261, -0.02016305894801083, 0.01280566739292261] R_IK_FootTvy = [0.0, 0.047998926712581456, 0.0, 0.0] R_IK_FootTvz = [-0.45223226934269134, 0.242, -0.45223226934269134] L_IK_FootRtx = [0.0, 4.0, 16.0, 20.0, 24.0] L_IK_FootRty = [0.0, 12.0, 24.0] L_IK_FootRtz = [0.0, 12.0, 24.0] R_IK_FootRtx = [0.0, 4.0, 8.0, 12.0, 16.0, 24.0] R_IK_FootRty = [0.0, 12.0, 24.0] R_IK_FootRtz = [0.0, 12.0, 24.0] L_IK_FootRvx = [-12.616100254841044, 0.0, 0.0, -12.154, -12.616100254841044] L_IK_FootRvy = [-7.863090889446508, 0.0, -7.863090889446508] L_IK_FootRvz = [1.7538619386382779, 0.0, 1.7538619386382779] R_IK_FootRvx = [0.0, 0.0, -12.154495182541039, -29.18152331857998, 0.0, 0.0] R_IK_FootRvy = [0.0, 7.86300000000002, 0.0] R_IK_FootRvz = [0.0, 1.7539999999999958, 0.0] L_IK_Knee_TwistTtx = [0.0, 12.0, 24.0] L_IK_Knee_TwistTty = [0.0, 12.0, 24.0] L_IK_Knee_TwistTtz = [0.0, 12.0, 24.0] R_IK_Knee_TwistTtx = [0.0, 12.0, 24.0] R_IK_Knee_TwistTty = [0.0, 12.0, 24.0] R_IK_Knee_TwistTtz = [0.0, 12.0, 24.0] L_IK_Knee_TwistTvx = [0.054224433993502706, 0.106, 0.054224433993502706] L_IK_Knee_TwistTvy = [0.0, -1.7053025658242404e-15, 0.0] L_IK_Knee_TwistTvz = [0.35158885438186177, 0.2467322805261363, 0.35158885438186177] R_IK_Knee_TwistTvx = [-0.10595141529585334, -0.054000000000000006, -0.10595141529585334] R_IK_Knee_TwistTvy = [0.0, 0.0, 0.0] R_IK_Knee_TwistTvz = [0.24673228052613833, 0.352, 0.24673228052613833] L_FootRollRtx = [0.0, 4.0, 8.0, 12.0, 24.0] L_FootRollRty = [0.0, 24.0] L_FootRollRtz = [0.0, 24.0] R_FootRollRtx = [0.0, 8.0, 16.0, 20.0, 24.0] R_FootRollRty = [0.0, 24.0] R_FootRollRtz = [0.0, 24.0] R_FootRollRvx = [62.74025947104144, 0.0, 0.0, 50.322, 62.74025947104144] R_FootRollRvy = [0.0, 0.0] R_FootRollRvz = [0.0, 0.0] L_FootRollRvx = [0.0, 0.0, 50.32213879670855, 58.214091501483566, 0.0] L_FootRollRvy = [0.0, 0.0] L_FootRollRvz = [0.0, 0.0] L_ToesRollRtx = [0.0, 12.0, 16.0, 20.0, 24.0] L_ToesRollRty = [0.0, 24.0] L_ToesRollRtz = [0.0, 24.0] R_ToesRollRtx = [0.0, 4.0, 8.0, 24.0] R_ToesRollRty = [0.0, 24.0] R_ToesRollRtz = [0.0, 24.0] L_ToesRollRvx = [0.0, 0.0, 36.431, 0.0, 0.0] L_ToesRollRvy = [0.0, 0.0] L_ToesRollRvz = [0.0, 0.0] R_ToesRollRvx = [0.0, 36.431093251150195, 0.0, 0.0] R_ToesRollRvy = [0.0, 0.0] R_ToesRollRvz = [0.0, 0.0] Spine_1Rtx = [0.0, 4.0, 12.0, 16.0, 24.0] Spine_1Rty = [0.0, 12.0, 24.0] Spine_1Rtz = [0.0, 12.0, 24.0] Spine_1Rvx = [0.0, -4.84800147568847, 0.0, -4.848, 0.0] Spine_1Rvy = [10.632, -10.632, 10.632] Spine_1Rvz = [-4.929, 4.929, -4.929] Spine_2Rtx = [0.0, 6.0, 10.0, 18.0, 22.0, 24.0] Spine_2Rty = [0.0, 24.0] Spine_2Rtz = [0.0, 24.0] Spine_2Rvx = [1.2600000000000013, 6.720753752238523, 0.0, 6.720753752238523, 0.0, 1.2600000000000013] Spine_2Rvy = [0.0, 0.0] Spine_2Rvz = [0.0, 0.0] Spine_3Rtx = [0.0, 8.0, 12.0, 20.0, 24.0] Spine_3Rty = [0.0, 24.0] Spine_3Rtz = [0.0, 24.0] Spine_3Rvx = [0.0, 6.079757007082832, 0.0, 6.079757007082832, 0.0] Spine_3Rvy = [0.0, 0.0] Spine_3Rvz = [0.0, 0.0] Neck_ARtx = [0.0, 6.0, 10.0, 18.0, 22.0, 24.0] Neck_ARty = [0.0, 24.0] Neck_ARtz = [0.0, 24.0] Neck_ARvx = [5.67084375, 0.0, 6.721, 0.0, 6.721, 5.6708437499999995] Neck_ARvy = [0.0, 0.0] Neck_ARvz = [0.0, 0.0] HeadRtx = [0.0, 8.0, 12.0, 20.0, 24.0] HeadRty = [0.0, 24.0] HeadRtz = [0.0, 24.0] HeadRvx = [0.0, -5.13, 0.0, -5.13, 0.0] HeadRvy = [0.0, 0.0] HeadRvz = [0.0, 0.0] L_ShoulderRtx = [0.0, 24.0] L_ShoulderRty = [0.0, 12.0, 24.0] L_ShoulderRtz = [0.0, 24.0] R_ShoulderRtx = [0.0, 12.0, 24.0] R_ShoulderRty = [0.0, 24.0] R_ShoulderRtz = [0.0, 24.0] L_ShoulderRvx = [0.0, 0.0] L_ShoulderRvy = [6.752, -10.18, 6.752] L_ShoulderRvz = [-27.385, -27.385] R_ShoulderRvx = [-10.179924939886178, 6.752254917660859, -10.179924939886178] R_ShoulderRvy = [0.0, 0.0] R_ShoulderRvz = [27.38474327476161, 27.38474327476161] FK_L_UpperArmRtx = [0.0, 24.0] FK_L_UpperArmRty = [0.0, 2.0, 14.0, 24.0] FK_L_UpperArmRtz = [0.0, 24.0] FK_R_UpperArmRtx = [0.0, 24.0] FK_R_UpperArmRty = [0.0, 2.0, 14.0, 24.0] FK_R_UpperArmRtz = [0.0, 24.0] FK_L_UpperArmRvx = [0.0, 0.0] FK_L_UpperArmRvy = [31.696000000000005, 36.346, -26.433, 31.69570370370371] FK_L_UpperArmRvz = [-32.686, -32.686] FK_R_UpperArmRvx = [0.0, 0.0] FK_R_UpperArmRvy = [31.696000000000005, 36.34608086850911, -26.4328908442492, 31.69578666756405] FK_R_UpperArmRvz = [32.68619470854636, 32.68619470854636] FK_L_LowerArmRtx = [0.0, 4.0, 16.0, 24.0] FK_L_LowerArmRty = [0.0, 4.0, 16.0, 24.0] FK_L_LowerArmRtz = [0.0, 4.0, 16.0, 24.0] FK_R_LowerArmRtx = [0.0, 4.0, 16.0, 24.0] FK_R_LowerArmRty = [0.0, 4.0, 16.0, 24.0] FK_R_LowerArmRtz = [0.0, 4.0, 16.0, 24.0] FK_L_LowerArmRvx = [31.319999999999997, 41.52399342360939, -4.782927003193802, 31.31998188806086] FK_L_LowerArmRvy = [5.095, 10.76228332384925, -31.77295552645706, 5.0951596783259365] FK_L_LowerArmRvz = [-2.267, 0.44114944164802233, -10.003244617000254, -2.2667671229259923] FK_R_LowerArmRvx = [4.787492756920226, -3.5979847781576915, 28.74555046224843, 4.787] FK_R_LowerArmRvy = [25.553000000000004, 39.9872450599721, -9.142034133171519, 25.552891358998615] FK_R_LowerArmRvz = [16.867, 17.920113651411693, 13.859361855054962, 16.86724196242166] FK_L_WristRtx = [0.0, 6.0, 18.0, 24.0] FK_L_WristRty = [0.0, 6.0, 18.0, 24.0] FK_L_WristRtz = [0.0, 6.0, 18.0, 24.0] FK_R_WristRtx = [0.0, 6.0, 18.0, 24.0] FK_R_WristRty = [0.0, 6.0, 18.0, 24.0] FK_R_WristRtz = [0.0, 6.0, 18.0, 24.0] FK_L_WristRvx = [-0.999, 1.2753828954336408, -3.273908475061765, -0.9994542375308821] FK_L_WristRvy = [1.224, 23.80421774175543, -21.387492367104528, 1.2244405218732168] FK_L_WristRvz = [7.69, 3.1572405456334316, 12.22399477163508, 7.69049738581754] FK_R_WristRvx = [-2.988, -5.975526246729838, 0.0, -2.9879999999999995] FK_R_WristRvy = [5.119, 25.718631782936257, -16.11966938114741, 5.118957376794449] FK_R_WristRvz = [-6.78, -13.56111854103193, 0.0, -6.7805] global fromFrameNum, toFrameNum, loopADD, stepCheck, stepNum, fpsDesired allTimeLists = [PelvisTtx, PelvisTty, PelvisTtz, PelvisRtx, PelvisRty, PelvisRtz, L_IK_FootTtx, L_IK_FootTty, L_IK_FootTtz, R_IK_FootTtx, R_IK_FootTty, R_IK_FootTtz, L_IK_FootRtx, L_IK_FootRty, L_IK_FootRtz, R_IK_FootRtx, R_IK_FootRty, R_IK_FootRtz, L_IK_Knee_TwistTtx, L_IK_Knee_TwistTty, L_IK_Knee_TwistTtz, R_IK_Knee_TwistTtx, R_IK_Knee_TwistTty, R_IK_Knee_TwistTtz, L_FootRollRtx, L_FootRollRty, L_FootRollRtz, R_FootRollRtx, R_FootRollRty, R_FootRollRtz, L_ToesRollRtx, L_ToesRollRty, L_ToesRollRtz, R_ToesRollRtx, R_ToesRollRty, R_ToesRollRtz, Spine_1Rtx, Spine_1Rty, Spine_1Rtz, Spine_2Rtx, Spine_2Rty, Spine_2Rtz, Spine_3Rtx, Spine_3Rty, Spine_3Rtz, Neck_ARtx, Neck_ARty, Neck_ARtz, HeadRtx, HeadRty, HeadRtz, L_ShoulderRtx, L_ShoulderRty, L_ShoulderRtz, R_ShoulderRtx, R_ShoulderRty, R_ShoulderRtz, FK_L_UpperArmRtx, FK_L_UpperArmRty, FK_L_UpperArmRtz, FK_R_UpperArmRtx, FK_R_UpperArmRty, FK_R_UpperArmRtz, FK_L_LowerArmRtx, FK_L_LowerArmRty, FK_L_LowerArmRtz, FK_R_LowerArmRtx, FK_R_LowerArmRty, FK_R_LowerArmRtz, FK_L_WristRtx, FK_L_WristRty, FK_L_WristRtz, FK_R_WristRtx, FK_R_WristRty, FK_R_WristRtz] if(stepCheck): toFrameNum = fpsDesired / 2 * stepNum + fromFrameNum toFrameNumFILM = toFrameNum * 24 / fpsDesired if(fromFrameNum != 0): print 'treba podesiti da krene kasnije/ranije' for j in range(25): for m, element in enumerate(allTimeLists[j]): allTimeLists[j][m] = element + fromFrameNum else: print 'ne treba nista na pocetku' if(toFrameNumFILM < 24): print 'treba podesiti da se zavrsi ranije' for j in range(25): endTMP = 0 for num in allTimeLists[j]: if(num < toFrameNumFILM): endTMP = endTMP + 1 elif(num >= toFrameNumFILM): endTMP = endTMP + 1 break end = len(allTimeLists[j]) if(end > endTMP): for h in range(end - endTMP): allTimeLists[j].pop() elif(toFrameNumFILM > 24): print 'treba loop unapred' loopADD = True else: print 'ne treba nista na kraju' global pelvis, spine, neck1, neck2, head, hair, shoulder, upArm, lowArm, wrist, thigh, knee, foot, toes, ikHand, ikElbow, ikFoot, ikKnee, fRoll, tRoll, thumbF, finger, lowEyeLid, upEyeLid global spineCount, ikLegs, fkLegs, ikArms, fkArms, thumb mc.currentUnit(t = 'film') LEGbase = 0.607 # new LEG mc.spaceLocator(n = 'p') mc.spaceLocator(n = 'f') mc.matchTransform('p', 'BN_Pelvis', position = True) mc.matchTransform('f', 'BN_R_Ankle', position = True) LEGnew = (mc.getAttr('p.translateY')) - (mc.getAttr('f.translateY')) mc.delete('p', 'f') # constant which allow different characters LEGconst = LEGnew / LEGbase axis = ['x', 'y', 'z'] sides = ['L', 'R'] #pelvis, neck, head keyframes Tt = [PelvisTtx, PelvisTty, PelvisTtz] Tv = [PelvisTvx, PelvisTvy, PelvisTvz] for i, a in enumerate(axis): mc.currentTime(fromFrameNum) for k, t in enumerate(Tt[i]): mc.currentTime(t) mc.setKeyframe(pelvis, attribute = 't' + a, v = Tv[i][k]*LEGconst) Rt = [PelvisRtx, PelvisRty, PelvisRtz, Neck_ARtx, Neck_ARty, Neck_ARtz, HeadRtx, HeadRty, HeadRtz] Rv = [PelvisRvx, PelvisRvy, PelvisRvz, Neck_ARvx, Neck_ARvy, Neck_ARvz, HeadRvx, HeadRvy, HeadRvz] parts = [pelvis, neck1, head] for n, p in enumerate(parts): for i, a in enumerate(axis): mc.currentTime(fromFrameNum) for k, t in enumerate(Rt[n*3+i]): mc.currentTime(t) mc.setKeyframe(p, attribute = 'r' + a, v = Rv[n*3+i][k]) #legs if(fkLegs): mc.setAttr('CTRL_R_LegSwitch.R_IK', 1) mc.setAttr('CTRL_L_LegSwitch.L_IK', 1) Tt = [L_IK_FootTtx, L_IK_FootTty, L_IK_FootTtz, R_IK_FootTtx, R_IK_FootTty, R_IK_FootTtz, L_IK_Knee_TwistTtx, L_IK_Knee_TwistTty, L_IK_Knee_TwistTtz, R_IK_Knee_TwistTtx, R_IK_Knee_TwistTty, R_IK_Knee_TwistTtz] Tv = [L_IK_FootTvx, L_IK_FootTvy, L_IK_FootTvz, R_IK_FootTvx, R_IK_FootTvy, R_IK_FootTvz, L_IK_Knee_TwistTvx, L_IK_Knee_TwistTvy, L_IK_Knee_TwistTvz, R_IK_Knee_TwistTvx, R_IK_Knee_TwistTvy, R_IK_Knee_TwistTvz] parts = [ikFoot, ikKnee] for n, p in enumerate(parts): for s, side in enumerate(sides): for i, a in enumerate(axis): for k, t in enumerate(Tt[n*6+s*3+i]): mc.currentTime(t) mc.setKeyframe('CTRL_' + side + p, attribute = 't' + a, v = Tv[n*6+s*3+i][k]*LEGconst) Rt = [L_IK_FootRtx, L_IK_FootRty, L_IK_FootRtz, R_IK_FootRtx, R_IK_FootRty, R_IK_FootRtz, L_FootRollRtx, L_FootRollRty, L_FootRollRtz, R_FootRollRtx, R_FootRollRty, R_FootRollRtz, L_ToesRollRtx, L_ToesRollRty, L_ToesRollRtz, R_ToesRollRtx, R_ToesRollRty, R_ToesRollRtz] Rv = [L_IK_FootRvx, L_IK_FootRvy, L_IK_FootRvz, R_IK_FootRvx, R_IK_FootRvy, R_IK_FootRvz, L_FootRollRvx, L_FootRollRvy, L_FootRollRvz, R_FootRollRvx, R_FootRollRvy, R_FootRollRvz, L_ToesRollRvx, L_ToesRollRvy, L_ToesRollRvz, R_ToesRollRvx, R_ToesRollRvy, R_ToesRollRvz] parts = [ikFoot, fRoll, tRoll] for n, p in enumerate(parts): for s, side in enumerate(sides): for i, a in enumerate(axis): for k, t in enumerate(Rt[n*6+s*3+i]): mc.currentTime(t) mc.setKeyframe('CTRL_' + side + p, attribute = 'r' + a, v = Rv[n*6+s*3+i][k]) #spine spineHALF = math.floor(spineCount/2)+1 spineHALF = str(spineHALF) spineHALF = spineHALF.split('.')[0] Rt = [Spine_1Rtx, Spine_1Rty, Spine_1Rtz] Rv = [Spine_1Rvx, Spine_1Rvy, Spine_1Rvz] for i, a in enumerate(axis): for k, t in enumerate(Rt[i]): mc.currentTime(t) mc.setKeyframe(spine + '1', attribute = 'r' + a, v = Rv[i][k]) if(spineCount > 2): Rt = [Spine_2Rtx, Spine_2Rty, Spine_2Rtz] Rv = [Spine_2Rvx, Spine_2Rvy, Spine_2Rvz] for i, a in enumerate(axis): for k, t in enumerate(Rt[i]): mc.currentTime(t) mc.setKeyframe(spine + str(spineHALF), attribute = 'r' + a, v = Rv[i][k]) if(spineCount > 1): Rt = [Spine_3Rtx, Spine_3Rty, Spine_3Rtz] Rv = [Spine_3Rvx, Spine_3Rvy, Spine_3Rvz] for i, a in enumerate(axis): for k, t in enumerate(Rt[i]): mc.currentTime(t) mc.setKeyframe(spine + str(spineCount), attribute = 'r' + a, v = Rv[i][k]) #shoulders Rt = [L_ShoulderRtx, L_ShoulderRty, L_ShoulderRtz, R_ShoulderRtx, R_ShoulderRty, R_ShoulderRtz] Rv = [L_ShoulderRvx, L_ShoulderRvy, L_ShoulderRvz, R_ShoulderRvx, R_ShoulderRvy, R_ShoulderRvz] for s, side in enumerate(sides): for i, a in enumerate(axis): for k, t in enumerate(Rt[s*3+i]): mc.currentTime(t) mc.setKeyframe('CTRL_' + side + shoulder, attribute = 'r' + a, v = Rv[s*3+i][k]) #arms if(ikArms): mc.setAttr('CTRL_R_ArmSwitch.R_IK', 0) mc.setAttr('CTRL_L_ArmSwitch.L_IK', 0) Rt = [FK_L_UpperArmRtx, FK_L_UpperArmRty, FK_L_UpperArmRtz, FK_R_UpperArmRtx, FK_R_UpperArmRty, FK_R_UpperArmRtz, FK_L_LowerArmRtx, FK_L_LowerArmRty, FK_L_LowerArmRtz, FK_R_LowerArmRtx, FK_R_LowerArmRty, FK_R_LowerArmRtz, FK_L_WristRtx, FK_L_WristRty, FK_L_WristRtz, FK_R_WristRtx, FK_R_WristRty, FK_R_WristRtz] Rv = [FK_L_UpperArmRvx, FK_L_UpperArmRvy, FK_L_UpperArmRvz, FK_R_UpperArmRvx, FK_R_UpperArmRvy, FK_R_UpperArmRvz, FK_L_LowerArmRvx, FK_L_LowerArmRvy, FK_L_LowerArmRvz, FK_R_LowerArmRvx, FK_R_LowerArmRvy, FK_R_LowerArmRvz, FK_L_WristRvx, FK_L_WristRvy, FK_L_WristRvz, FK_R_WristRvx, FK_R_WristRvy, FK_R_WristRvz] parts = [upArm, lowArm, wrist] for n, p in enumerate(parts): for s, side in enumerate(sides): for i, a in enumerate(axis): for k, t in enumerate(Rt[n*6+s*3+i]): mc.currentTime(t) mc.setKeyframe('CTRL_FK_' + side + p, attribute = 'r' + a, v = Rv[n*6+s*3+i][k])
def keyWall(whichCharacter): whichCharacterOMValue = cmds.optionMenu('whichCharacterOM', q=1, v=1) try: #Save current selection savedtSel = cmds.ls(sl=1) #Select character ctrls set ctrlsWhichCharacter = whichCharacter + 'set_ctrls' toSelect = cmds.select(ctrlsWhichCharacter) #List the selection sel = cmds.ls(sl=1) #Loop: key for sel for i in sel: cmds.setKeyframe(at='translateX') cmds.setKeyframe(at='translateY') cmds.setKeyframe(at='translateZ') cmds.setKeyframe(at='rotateX') cmds.setKeyframe(at='rotateY') cmds.setKeyframe(at='rotateZ') cmds.setKeyframe(at='IKFKSwitch') cmds.setKeyframe(at='footroll') cmds.setKeyframe(at='sideroll') cmds.setKeyframe(at='pivotfoot') cmds.setKeyframe(at='toeTap') cmds.setKeyframe(at='smartBlinkHeight') cmds.setKeyframe(at='smartBlink') cmds.setKeyframe(at='irisScale') cmds.setKeyframe(at='pupilleScale') #Deselect cmds.select(cl=1) #Reselect older selection cmds.select(savedtSel) except Exception as ex: cmds.confirmDialog(t='Error 404 : Not found', m='Their is no ' + whichCharacterOMValue + ' in the scene.', ma='center', b='Close')
def ikSolver(self, currentTime): targetPosMat = np.zeros((len(self.targetList), 3)) endEffectorPosMat = np.zeros((len(self.targetList), 3)) jntPosMat = np.zeros((len(self.jntList), 3)) jntAngleMat = np.zeros((len(self.jntList), 3)) for i in range(len(self.targetList)): targetPosMat[i] = np.array( mc.xform(self.targetList[i], q=True, ws=True, t=True)) endEffectorPosMat[i] = np.array( mc.xform(self.endEffectorList[i], q=True, ws=True, t=True)) for i in range(len(self.jntList)): jntPosMat[i] = np.array( mc.xform(self.jntList[i], q=True, ws=True, t=True)) jntAngleMat[i] = np.array( mc.xform(self.jntList[i], q=True, ws=True, ro=True)) jntLocalAxesMat = np.zeros((len(self.jntList), 3, 3)) for i in range(len(self.jntList)): jntLocalAxesMat[i] = self.getLocalAxes(jntAngleMat[i]) J = self.getJacobian(jntPosMat, jntLocalAxesMat, endEffectorPosMat) J_inverse = self.DampedLeastSquare(J) if currentTime == 1: self.prevTargetPosList = targetPosMat displaceTargetPos = self.getDisplaceError(targetPosMat, endEffectorPosMat) else: displaceTargetPos = self.getDisplaceError(self.prevTargetPosList, targetPosMat) jntAngles = np.dot(J_inverse, displaceTargetPos) #to get fk funtion value f(theta). we need proper way. degX = jntAngles[3 * i] * (180 / self.PI) degY = jntAngles[3 * i + 1] * (180 / self.PI) degZ = jntAngles[3 * i + 2] * (180 / self.PI) mc.xform(self.jntList[i], eu=True, r=True, ro=[degX, degY, degZ]) tempTargetPosMat = np.zeros((len(self.targetList), 3)) for i in range(len(self.targetList)): tempTargetPosMat[i] = np.array( mc.xform(self.endEffectorList[i], q=True, ws=True, t=True)) e = self.getDisplaceError(targetPosMat, tempTargetPosMat) displaceTargetPos = displaceTargetPos + e mc.xform(self.jntList[i], eu=True, r=True, ro=[-degX, -degY, -degZ]) self.prevTargetPosList = targetPosMat #source joint list problem - should match src-target jnt list self.srcJntList = [ u'joint4', u'joint5', u'joint2', u'joint3', u'joint1' ] srcJntAngles = np.zeros((len(self.srcJntList * 3))) for i in range(len(self.srcJntList)): rot = mc.xform(self.srcJntList[i], eu=True, ro=True, r=True, q=True) srcJntAngles[3 * i] = rot[0] * (self.PI / 180.0) srcJntAngles[3 * i + 1] = rot[1] * (self.PI / 180.0) srcJntAngles[3 * i + 2] = rot[2] * (self.PI / 180.0) if self.prevSrcJntAngleList == None: displaceSrcJntAngle = np.zeros(len(self.jntList) * 3) else: displaceSrcJntAngle = srcJntAngles - self.prevSrcJntAngleList tempMat = np.identity(len(self.jntList) * 3, float) - np.dot( J_inverse, J) secondaryJntAngles = np.dot(tempMat, displaceSrcJntAngle) jntAngles = np.dot(J_inverse, displaceTargetPos) + secondaryJntAngles self.prevJntAngleList = jntAngles self.prevSrcJntAngleList = srcJntAngles for i in range(len(self.jntList)): degX = jntAngles[3 * i] * (180.0 / self.PI) degY = jntAngles[3 * i + 1] * (180.0 / self.PI) degZ = jntAngles[3 * i + 2] * (180.0 / self.PI) mc.xform(self.jntList[i], eu=True, r=True, ro=[degX, degY, degZ]) mc.setKeyframe([ 'joint7', 'joint8', 'joint9', 'joint10', 'joint11', 'joint12' ])
import maya.cmds as cmds
def __switch_parent_callback(*args): """ Wrapper function to call mGears change space function Args: list: callback from menuItem """ # creates a map for non logical components controls control_map = {"elbow": "mid", "rot": "orbit", "knee": "mid"} # switch_control = args[0].split("|")[-1].split(":")[-1] switch_control = args[0].split("|")[-1] uiHost = pm.PyNode(switch_control) # UiHost is switch PyNode pointer switch_attr = args[1] switch_idx = args[2] search_token = switch_attr.split("_")[-1].split("ref")[0].split("Ref")[0] print search_token target_control = None # control_01 attr don't standard name ane need to be check attr_split_name = switch_attr.split("_") if len(attr_split_name) <= 2: attr_name = attr_split_name[0] else: attr_name = "_".join(attr_split_name[:-1]) # search criteria to find all the components sharing the name criteria = attr_name + "_id*_ctl_cnx" component_ctl = cmds.listAttr(switch_control, ud=True, string=criteria) target_control_list = [] for comp_ctl_list in component_ctl: # first search for tokens match in all controls. If not token is found # we will use all controls for the switch # this token match is a filter for components like arms or legs for ctl in uiHost.attr(comp_ctl_list).listConnections(): if ctl.ctl_role.get() == search_token: target_control = ctl.stripNamespace() break elif (search_token in control_map.keys() and ctl.ctl_role.get() == control_map[search_token]): target_control = ctl.stripNamespace() break if target_control: target_control_list.append(target_control) else: # token didn't match with any target control. We will add all # found controls for the match. # This is needed for regular ik match in Control_01 for ctl in uiHost.attr(comp_ctl_list).listConnections(): target_control_list.append(ctl.stripNamespace()) # gets root node for the given control namespace_value = args[0].split("|")[-1].split(":") if len(namespace_value) > 1: namespace_value = namespace_value[0] else: namespace_value = "" root = None current_parent = cmds.listRelatives(args[0], fullPath=True, parent=True) if current_parent: current_parent = current_parent[0] while not root: if cmds.objExists("{}.is_rig".format(current_parent)): root = cmds.ls("{}.is_rig".format(current_parent))[0] else: try: current_parent = cmds.listRelatives(current_parent, fullPath=True, parent=True)[0] except TypeError: break if not root or not target_control_list: pm.displayInfo("Not root or target control list for space transfer") return autokey = cmds.listConnections("{}.{}".format(switch_control, switch_attr), type="animCurve") if autokey: for target_control in target_control_list: cmds.setKeyframe("{}:{}".format(namespace_value, target_control), "{}.{}".format(switch_control, switch_attr), time=(cmds.currentTime(query=True) - 1.0)) # triggers switch changeSpace(root, switch_control, switch_attr, switch_idx, target_control_list) if autokey: for target_control in target_control_list: cmds.setKeyframe("{}:{}".format(namespace_value, target_control), "{}.{}".format(switch_control, switch_attr), time=(cmds.currentTime(query=True)))
def keyFullRotation(pObjectName,pStartTime,pEndTime,pTargetAttribute): cmds.cutKey(pObjectName,time=(pStartTime,pEndTime),attribute=pTargetAttribute) cmds.setKeyframe(pObjectName,time=pStartTime,attribute=pTargetAttribute,value=0) cmds.setKeyframe(pObjectName,time=pEndTime,attribute=pTargetAttribute,value=360) cmds.selectKey(pObjectName,time=(pStartTime,pEndTime),attribute=pTargetAttribute,keyframe=True) cmds.keyTangent(inTangentType='linear',outTangentType='linear')
def apply(self, mapping, attributes=None, **kwargs): ''' valid kwargs are: mult [1.0] apply a mutiplier when applying curve values additive [False] clear [True] ''' beginningWeightedTanState = cmd.keyTangent(q=True, g=True, wt=True) ### gather options... additive = kwargs.get(self.kOPT_ADDITIVE, self.kOPT_DEFAULTS[self.kOPT_ADDITIVE]) worldAdditive = kwargs.get( self.kOPT_ADDITIVE_WORLD, self.kOPT_DEFAULTS[self.kOPT_ADDITIVE_WORLD]) clear = kwargs.get(self.kOPT_CLEAR, self.kOPT_DEFAULTS[self.kOPT_CLEAR]) mult = kwargs.get(self.kMULT, self.kOPT_DEFAULTS[self.kMULT]) timeOffset = kwargs.get(self.kOPT_OFFSET, self.offset) #if worldAdditive is turned on, then additive is implied if worldAdditive: additive = worldAdditive #determine the time range to clear clearStart = timeOffset clearEnd = clearStart + self.range #convert the attribute list to a set for fast lookup if attributes: attributes = set(attributes) for obj, tgtObj in mapping.iteritems(): if not tgtObj: continue try: attrDict = self[obj] except KeyError: continue for attr, (weightedTangents, keyList) in attrDict.iteritems(): if attributes: if attr not in attributes: continue attrpath = '%s.%s' % (tgtObj, attr) try: if not cmd.getAttr(attrpath, settable=True): continue except TypeError: continue except RuntimeError: print obj, tgtObj, attrpath raise #do the clear... maya doesn't complain if we try to do a cutKey on an attrpath with no #animation - and this is good to do before we determine whether the attrpath has a curve or not... if clear: cmd.cutKey(attrpath, t=(clearStart, clearEnd), cl=True) #is there an anim curve on the target attrpath already? curveExists = cmd.keyframe(attrpath, index=(0, ), q=True) is not None preValue = 0 if additive: if worldAdditive: isWorld = True #if the control has space switching setup, see if its value is set to "world" - if its not, we're don't treat the control's animation as additive try: isWorld = cmd.getAttr('%s.parent' % obj, asString=True) == 'world' except TypeError: pass #only treat translation as additive if isWorld and attr.startswith('translate'): preValue = cmd.getAttr(attrpath) else: preValue = cmd.getAttr(attrpath) for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList: value *= mult value += preValue if time is None: #in this case the attr value was just a pose... cmd.setAttr(attrpath, value) else: time += timeOffset cmd.setKeyframe(attrpath, t=(time, ), v=value) if weightedTangents: #this needs to be done as two separate commands - because setting the tangent types in the same cmd as setting tangent weights can result #in the tangent types being ignored (for the case of stepped mainly, but subtle weirdness with flat happens too) cmd.keyTangent(attrpath, t=(time, ), ix=ix, iy=iy, ox=ox, oy=oy, l=isLocked, wl=isWeighted) cmd.keyTangent(attrpath, t=(time, ), itt=itt, ott=ott) else: cmd.keyTangent(attrpath, t=(time, ), ix=ix, iy=iy, ox=ox, oy=oy)
global_ctl = i if 'lunchbag' in prop_name: if 'bottom_001_ctl' in i: global_ctl = i print '\t\tFound %d controllers' % len(controllers) print '\t\tFound global controller %s' % global_ctl try: curves = cmds.listConnections(controllers, type='animCurve') print '\t\tFound %d animation curves' % len(curves) except: print '\t\tFound NO animation curves' print '\t\tSetting key on first frame...' cmds.currentTime(frame_s) cmds.setKeyframe() print '\t\tRemoving all keys before start.' cmds.cutKey(time=(-9999, frame_s - 1)) print '\t\tSetting hold key...' cmds.currentTime(frame_s - 1) cmds.setKeyframe() print '\t\tSetting hold key...' cmds.currentTime(frame_s - 10) cmds.setKeyframe() print '\t\tSetting hold key...' cmds.currentTime(frame_s - 11) cmds.setKeyframe()
def load_data(data, threed): suffix = "threed" if threed else "twod" # jnts to ignore to_pass = [5, 4, 9, 10, 12] if threed else [] # locator driver grp if not cmds.objExists("drivers_{0}".format(suffix)): cmds.group(n="drivers_{0}".format(suffix), em=True) for frame, jnt in data.iteritems(): if not cmds.objExists("anim_joint"): cmds.group(n="anim_joint", em=True) anim_grp_prj = cmds.group(n="anim_joint_2d", em=True) cmds.parent(anim_grp_prj, "anim_joint") for jnt_id, trans in jnt.iteritems(): if not int(jnt_id) in to_pass: if not cmds.objExists("anim_jnt_driver_{0}_{1}".format( jnt_id, suffix)): cmds.select(clear=True) jnt = cmds.joint(n="jnt_{0}_{1}".format(jnt_id, suffix), relative=True) cmds.setAttr("{0}.radius".format(jnt), 10) cmds.setAttr("{0}.displayLocalAxis".format(jnt), 1) # match same pos for first frame if threed: cmds.move(trans["translate"][0], trans["translate"][1], trans["translate"][2], jnt) else: cmds.move(trans["translate"][0], trans["translate"][1], jnt) anim_grp_child = cmds.listRelatives("anim_joint", children=True) or [] if not jnt in anim_grp_child: cmds.parent(jnt, "anim_joint") if threed: #create 2d projection jnt_proj = cmds.duplicate( jnt, n="jnt_prj_{0}".format(jnt_id)) cmds.pointConstraint(jnt, jnt_proj, mo=False, skip="z") cmds.setAttr("{0}.translateZ".format(jnt_proj[0]), 0) cmds.parent(jnt_proj, "anim_joint_2d") # driver locator driver = cmds.spaceLocator( n="anim_jnt_driver_{0}_{1}".format(jnt_id, suffix)) # drive jnt with animated locator frim frame 0 cmds.pointConstraint(driver, jnt) #if not driver in cmds.listRelatives("drivers_{0}".format(suffix), children=True) or []: cmds.parent(driver, "drivers_{0}".format(suffix)) # add trans anim values to driver locator cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format( jnt_id, suffix), t=frame, v=trans["translate"][0], at='translateX') cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format( jnt_id, suffix), t=frame, v=trans["translate"][1], at='translateY') if threed: cmds.setKeyframe("anim_jnt_driver_{0}_{1}".format( jnt_id, suffix), t=frame, v=trans["translate"][2], at='translateZ') # hacking 3d-pose-baseline coord. to maya cmds.setAttr("drivers_{0}.rotateX".format(suffix), -110 if threed else -180)
def bakeResult(frameRange=False, selected=False, info=False, skipUD=True, everyFrame=False, bakeAsBreakdowns=False, deleteLocators=False, bakeGrp='ConstraintLocators_grp', smartKey=True): currTime = cmds.currentTime(q=True) sel = cmds.ls(sl=True) print('baking results') timeMin = cmds.playbackOptions(q=1, min=1) timeMax = cmds.playbackOptions(q=1, max=1) if frameRange: print('using timeslider frame range (from ' + str(timeMin) + ' to ' + str(timeMax) + ')') cmds.refresh(suspend=True) try: cmds.undoInfo(openChunk=True) if selected: children = sel else: children = getConstrained(bakeGrp) keyFrameInfo = {} for (i, each) in enumerate(children): print each, '(', i + 1, '/', len(children), ')' keyFrameInfo[each] = {} # Query Keyframes udList = cmds.listAttr(each, ud=1) keyframes = cmds.keyframe(each, query=True, name=True) keyFrameInfo[each]['keyframes'] = keyframes timeList = sorted( list(set(cmds.keyframe(each, query=True, timeChange=True)))) keyFrameInfo[each]['timeList'] = timeList if info: print('keyframes = {}'.format(keyframes)) # cmds.currentTime(timeList[0]) # query associated attributes keyFrameInfo[each]['keyable'] = {} for keyframe in keyframes: connections = cmds.listConnections(keyframe, plugs=1, s=0, d=1) xAttr = connections[0].split('.')[1] if skipUD and xAttr in udList: continue if info: print('keyframe = {}'.format(keyframe)) keyFrameInfo[each]['keyable'][keyframe] = keyframeInfo( keyframe) # Gather the earliest start frame frameList = [] for each in keyFrameInfo: timeList = keyFrameInfo[each]['timeList'] if everyFrame: if info: print('everyFrame') everyFrameMin = timeMin if frameRange else timeList[0] if info: print('everyFrameMin = {0}'.format(everyFrameMin)) everyFrameMax = timeMax if frameRange else timeList[-1] if info: print('everyFrameMax = {0}'.format(everyFrameMax)) timeList = range(int(everyFrameMin), int(everyFrameMax + 1)) if info: print '"{0}" timeList = {1}'.format(each, timeList) keyFrameInfo[each]['timeList'] = timeList frameList = frameList + timeList frameList = sorted(set(frameList)) if info: print 'frameList = {0}'.format(frameList) if info: print 'keyFrameInfo = {0}'.format(keyFrameInfo) if frameRange: frameListCopy = copy.copy(frameList) frameList = [] for frame in frameListCopy: if frame < timeMin: continue if frame > timeMax: break frameList.append(frame) gMainProgressBar = mel.eval('$tmp = $gMainProgressBar') cmds.progressBar(gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True, status='baking frames...', maxValue=len(frameList)) progressBarCancelled = False for frame in frameList: if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True): progressBarCancelled = True break cmds.progressBar(gMainProgressBar, edit=True, step=1, status='frame {0}'.format(frame)) if info: print '\n========================' cmds.currentTime(frame) if info: print 'cmds.currentTime({})'.format(frame) for each in keyFrameInfo: if info: print '\neach = "{}"'.format(each) # check if the current frame is in each timelist if not frame in keyFrameInfo[each]['timeList']: # continue on if it's not continue keyframes = keyFrameInfo[each]['keyframes'] keyable = keyFrameInfo[each]['keyable'] for keyframe in keyframes: if not keyframe in keyFrameInfo[each]['keyable']: continue if not frame in keyFrameInfo[each]['keyable'][keyframe][ 'tList']: if smartKey: if info: print( "smartKey on... cmds.setKeyframe(\"" + each + "\", attribute=\"" + keyFrameInfo[each]['keyable'][keyframe] ['attr'] + "\", breakdown=" + str(bd) + ")") attrVal = cmds.getAttr( each + '.' + keyFrameInfo[each]['keyable'][keyframe]['attr'] ) cmds.setKeyframe(each, attribute=keyFrameInfo[each] ['keyable'][keyframe]['attr'], value=attrVal) continue index = keyFrameInfo[each]['keyable'][keyframe][ 'tList'].index(frame) breakdown = cmds.keyframe(keyframe, query=1, index=(index, index), breakdown=1) bd = True if breakdown else False if info: print("cmds.setKeyframe(\"" + each + "\", attribute=\"" + keyFrameInfo[each]['keyable'][keyframe]['attr'] + "\", breakdown=" + str(bd) + ")") attrVal = cmds.getAttr( each + '.' + keyFrameInfo[each]['keyable'][keyframe]['attr']) # if info: print("cmds.getAttr(\""+each+"."+keyFrameInfo[each]['keyable'][keyframe]['attr']+"\" = "+str(attrVal)+")") cmds.setKeyframe(each, attribute=keyFrameInfo[each]['keyable'] [keyframe]['attr'], breakdown=bd, value=attrVal) if not progressBarCancelled: if deleteLocators: for each in keyFrameInfo: driverConnections = cmds.listConnections( '{0}.message'.format(each), d=True, s=False, plugs=1, type='transform') driverLoc = None for each in driverConnections: if MESSAGEATTR in each: driverLoc = each if driverLoc: plugNode = driverLoc.split('.')[0] if info: print("deleting (\"" + plugNode + "\"...") cmds.delete(plugNode) else: cmds.warning('bake selected cancelled...') except Exception as E: traceback.print_exc(file=sys.stderr) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) cmds.refresh(suspend=False) cmds.currentTime(currTime) cmds.select(sel) cmds.undoInfo(closeChunk=True) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) cmds.refresh(suspend=False) cmds.currentTime(currTime) cmds.select(cl=True) replaceSelect = [] for each in sel: if not cmds.objExists(each): continue replaceSelect.append(each) if len(replaceSelect): cmds.select(replaceSelect) if not selected: bakeGrpChildren = cmds.listRelatives(bakeGrp, children=True) if not bakeGrpChildren: cmds.delete(bakeGrp) cmds.undoInfo(closeChunk=True)
def testAnimLocatorRW(self): name = createLocator() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX') MayaCmds.setKeyframe(name[1], attribute='localPositionY') MayaCmds.setKeyframe(name[1], attribute='localPositionZ') MayaCmds.setKeyframe(name[1], attribute='localScaleX') MayaCmds.setKeyframe(name[1], attribute='localScaleY') MayaCmds.setKeyframe(name[1], attribute='localScaleZ') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionY', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionZ', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localScaleX', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleY', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleZ', value=1.0) self.__files.append(util.expandFileName('testAnimLocatorRW.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW01_14.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') locatorList = MayaCmds.ls(type='locator') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareLocator(locatorList[0], locatorList[1]): self.fail('%s and %s are not the same at frame %d' % (locatorList[0], locatorList[1], t))
def doit(): global voxelSize, cubeSize, cubeDict, allLights, amb, useAmbient, useShadows, disableUndos, showCommands, useVoxCtrl, useCubeCtrl, frameRange, verboseOutput, xmin, xmax, ymin, ymax, zmin, zmax, xLocs, yLocs, zLocs cubeDict = {} shaderDict = {} SGDict = {} if useAmbient: # disable and store all existing lights allLights = cmds.sets("defaultLightSet", q=1) cmds.sets(clear="defaultLightSet") # make an ambient light amb = cmds.ambientLight(i=True, ambientShade=0) else: allLights = None # identify control objects sel = cmds.ls(sl=True) if len(sel) > 0: # filter for polymeshes ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12) cmds.select(cl=1) sel = [] if ctrl == None: print "No meshes found in selection, checking scene..." # check for object or group named "voxelGeo" if cmds.objExists("voxelGeo"): cmds.select("voxelGeo") sel = cmds.ls(sl=1) if len(sel) == 0: # select all dag objects cmds.select(ado=True) sel = cmds.ls(sl=True) if sel == None or sel == []: cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK']) return 0 else: # filter for polymeshes ctrl = cmds.filterExpand(sel, fullPath=0, selectionMask=12) if ctrl == None: cmds.confirmDialog( title='Mesh selection', message= 'No meshes found in scene.', button=['OK']) return 0 if disableUndos: cmds.undoInfo(state=False) if not showCommands: cmds.scriptEditorInfo(sr=True, sw=True, si=True) firstFrame = frameRange[0] lastFrame = frameRange[1] duration = abs(int(lastFrame-firstFrame))+1 # deal with backwards frame ranges if lastFrame < firstFrame: lastFrame -= 1 frameStep = -1 else: lastFrame += 1 frameStep = 1 startTime= cmds.timerX() makeProgBar(duration*len(ctrl)) cmds.progressBar(gMainProgressBar, edit=True, beginProgress=True) s = "s" if duration > 1 else "" print "Voxelizer animating over", duration, "frame%s..."%s print "Press ESC to cancel" resetList = [] directions = [(-1.0, 0.0, 0,0), (0.0, -1.0, 0,0), (0.0, 0.0, -1.0)] cubegroup = cmds.group(em=True, n='cubes') cmds.select(cl=1) #for f in range(firstFrame,lastFrame,frameStep): # for each frame for f in range(int(firstFrame),int(lastFrame),int(frameStep)): # for each frame stepTime= cmds.timerX() if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ): return docancel() cmds.currentTime(f, edit=True, update=True) # get sizes from control objects, if available if useVoxCtrl: voxelSize = round(cmds.getAttr('voxelScaleCtrl.scaleX'), 3) if useCubeCtrl: cubeSize = round(cmds.getAttr('cubeScaleCtrl.scaleX'), 3) # hide visible cubes for x in resetList: cmds.setKeyframe(x, at="scale", v=0, t=f) resetList = [] # for every target control object: for c in ctrl: if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True ): return docancel() cmds.progressBar(gMainProgressBar, edit=True, step=True) # if ctrl object is invisible, skip to the next one if objIsVisible(c) == 0: continue # bake textures into verts cmds.select(c) cmds.polyGeoSampler(sampleByFace=True, computeShadows=useShadows, rs=useShadows) # set ray starting points setLocs(c) locArrays = [xLocs, yLocs, zLocs] # for each axis: for i in range(3): # for every gridpoint: for loc in locArrays[i]: hits = [] # zap a ray through the object rayInt = rayIntersect(c, loc, directions[i]) hits = rayInt[0] hfaces = rayInt[1] for j, x in enumerate(hits): # snap hit locations to cubegrid x = (roundToFraction(x[0], voxelSize), roundToFraction(x[1], voxelSize), roundToFraction(x[2], voxelSize) ) # if location isn't in cubeDict: make a new cube if x not in cubeDict: # add location and new cube to cubeDict cubeDict[x] = cmds.polyCube(sz=1, sy=1, sx=1, cuv=4, d=1, h=1, w=1, ch=1)[0] cube = cubeDict[x] if useShadows: # prevent cubes from casting shadows onto the ctrl objs cmds.setAttr(cube+".castsShadows", 0) cmds.parent(cube, cubegroup) # move cube to location cmds.xform(cube, t=x) # shader coloring method: uses one shader per cube shader = cmds.shadingNode("lambert", asShader=1) # create a shading group shaderSG = cmds.sets(renderable=True, noSurfaceShader=True, empty=True, name=shader+"SG") # connect the shader to the shading group cmds.connectAttr('%s.outColor'%shader, '%s.surfaceShader'%shaderSG, f=True) # add cube to the shaderSG shape = cmds.listRelatives(cube, shapes=1)[0] cmds.sets('%s'%shape, e=True, fe='%s'%shaderSG) shaderDict[cube] = shader SGDict[cube] = shaderSG # set scale key of 0 on the previous frame cmds.setKeyframe(cube, at="scale", v=0, t=(f-1)) cube = cubeDict[x] cubeshape = cmds.listRelatives(cube, shapes=1)[0] # add cube to resetList resetList.append(cube) if len(hfaces) > 0: # check the alpha of the face alpha = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, a=True, cdo=True) if alpha[0] > 0.5: # if more than half opaque # get the color of the face fcolor = cmds.polyColorPerVertex(c+'.f['+str(hfaces[j])+']', q=True, rgb=True, cdo=True, nun=True) cmds.setKeyframe(shaderDict[cube]+'.colorR', v=fcolor[0]) cmds.setKeyframe(shaderDict[cube]+'.colorG', v=fcolor[1]) cmds.setKeyframe(shaderDict[cube]+'.colorB', v=fcolor[2]) # set a scale key cmds.setKeyframe(cube, at="scale", v=cubeSize, t=f, breakdown=0, hierarchy="none", controlPoints=0, shape=0) # if previous frame didn't have a scale key, set it to 0 tempCurTime = cmds.currentTime(q=True)-1 lastKey = cmds.keyframe(cube, at="scale", q=True, t=(tempCurTime,tempCurTime), valueChange=True) if lastKey == None: cmds.setKeyframe(cube, at="scale", v=0, t=(f-1)) if verboseOutput: stepTime = cmds.timerX(st=stepTime) totalTime = cmds.timerX(st=startTime) print "frame:", cmds.currentTime(q=True), "\tkeyed cubes:", len(resetList), "\ttotal cubes:", len(cubeDict) cps = "inf" if stepTime == 0 else round(len(resetList)/stepTime, 2) if useVoxCtrl or useCubeCtrl: print "\t\tvoxelSize:", voxelSize, "\tcubeSize: ", cubeSize print "\t\tstepTime:", round(stepTime, 2), "\ttotal time:", round(totalTime, 2), "\tcubes per second:", cps # restore scene state if useAmbient: if cmds.objExists(amb): cmds.delete(cmds.listRelatives(amb, parent=True)[0]) cmds.sets(allLights, add="defaultLightSet") elif useShadows: # turn the cubes' shadows back on for x in cubeDict: cmds.setAttr(cubeDict[x]+".castsShadows", 1) if not showCommands: cmds.scriptEditorInfo(sr=srState, sw=swState, si=siState) if disableUndos: cmds.undoInfo(state=True) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) totalTime = cmds.timerX(st=startTime) print("Voxelizer finished: "+str(round(totalTime, 2))+ " seconds ("+str(round(totalTime/60, 2)) + " minutes)") #promptSetup() ### End Voxelizer 1.0 ###
def constrainSelected(copyBreakdowns=True, frameRange=False, nodeList=None, info=True, skipUD=True, keyLocOnEveryFrame=True, bakeGrp='ConstraintLocators_grp', smartKey=True): """ """ print 'info = {0}'.format(info) print 'keyLocOnEveryFrame = {0}'.format(keyLocOnEveryFrame) print 'frameRange = {0}'.format(frameRange) locDescriptor = 'Constraint' locSuffix = '_loc' cmds.refresh(suspend=True) locList = [] currTime = cmds.currentTime(q=True) if frameRange: timeMin = cmds.playbackOptions(q=1, min=1) timeMax = cmds.playbackOptions(q=1, max=1) if info: print('timeMin = ' + str(timeMin)) print('timeMax = ' + str(timeMax)) nodeList = nodeList or cmds.ls(sl=True) try: cmds.undoInfo(openChunk=True) if info: print('nodeList = ' + str(nodeList)) if not len(nodeList): raise Exception() if not cmds.objExists(bakeGrp): cmds.createNode('transform', n=bakeGrp) keyFrameInfo = {} for (i, each) in enumerate(nodeList): print each, '(', i + 1, '/', len(nodeList), ')' keyFrameInfo[each] = {} # Query keyframe info udList = cmds.listAttr(each, ud=1) if info: print('udList = ' + str(udList)) keyframes = cmds.keyframe(each, query=True, name=True) keyFrameInfo[each]['keyframes'] = keyframes if keyframes: timeList = sorted( list( set( cmds.keyframe(keyframes, query=True, timeChange=True)))) else: timeList = [cmds.currentTime(q=1)] keyFrameInfo[each]['timeList'] = timeList keyFrameInfo[each]['udList'] = udList if info: print('timeList = ' + str(timeList)) locName = '{}{}{}'.format(each, locDescriptor, locSuffix) if cmds.objExists(locName): foo = 0 if info: print('locName "' + str(locName) + '" already exists...') while cmds.objExists(locName): foo += 1 locName = '{}{}{}{}'.format(each, locDescriptor, foo, locSuffix) if info: print('new locName = "' + str(locName) + '" ') conLoc = cmds.spaceLocator(n=locName)[0] keyFrameInfo[each]['conLoc'] = conLoc if info: print('Created Constraint Locator "' + str(conLoc) + '"') cmds.addAttr(conLoc, at='message', ln=MESSAGEATTR) cmds.connectAttr('{0}.message'.format(each), '{0}.{1}'.format(conLoc, MESSAGEATTR)) locList.append(conLoc) cmds.parent(conLoc, bakeGrp) # Gather the earliest start frame frameList = [] for each in keyFrameInfo: timeList = keyFrameInfo[each]['timeList'] if keyLocOnEveryFrame: if info: print('keyLocOnEveryFrame') keyLocEveryFrameMin = timeMin if frameRange else timeList[0] if info: print('keyLocEveryFrameMin = {0}'.format( keyLocEveryFrameMin)) keyLocEveryFrameMax = timeMax if frameRange else timeList[-1] if info: print('keyLocEveryFrameMax = {0}'.format( keyLocEveryFrameMax)) timeList = range(int(keyLocEveryFrameMin), int(keyLocEveryFrameMax + 1)) if info: print '"{0}" timeList = {1}'.format(each, timeList) keyFrameInfo[each]['timeList'] = timeList frameList = frameList + timeList frameList = sorted(set(frameList)) if info: print 'frameList = {0}'.format(frameList) if info: print 'keyFrameInfo = {0}'.format(keyFrameInfo) if frameRange: frameListCopy = copy.copy(frameList) frameList = [] for frame in frameListCopy: if frame < timeMin: continue if frame > timeMax: break frameList.append(frame) # Iterate through each frame pacList = [] gMainProgressBar = mel.eval('$tmp = $gMainProgressBar') cmds.progressBar(gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True, status='querying frames...', maxValue=len(frameList)) progressBarCancelled = False for frame in frameList: if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True): progressBarCancelled = True break cmds.progressBar(gMainProgressBar, edit=True, step=1, status='frame {0}'.format(frame)) cmds.currentTime(frame) if info: print '\n========================' if info: print 'frame: {0}'.format(frame) for each in keyFrameInfo: if info: print '{}'.format(each) # check if the current frame is in each timelist if not frame in keyFrameInfo[each]['timeList']: # continue on if it's not continue conLoc = keyFrameInfo[each]['conLoc'] keyframes = keyFrameInfo[each]['keyframes'] # check if we've already connected the locator for baking if not 'startFrame' in keyFrameInfo[each]: if info: print '"startFrame" not in keyFrameInfo["{0}"], defining...'.format( each) # store the start frame if we haven't keyFrameInfo[each]['startFrame'] = frame # Setup constraint to constraint locator # with an initial keyframe, so that when # the constraint is made we get a pairblend cmds.delete(cmds.parentConstraint(each, conLoc)) cmds.setKeyframe(conLoc) pacList.append(cmds.parentConstraint(each, conLoc)[0]) # Query additional information for breakdowns settings if copyBreakdowns: if info: print('copyBreakdowns = ' + str(copyBreakdowns)) roVal = cmds.getAttr('{0}.ro'.format(each)) cmds.setAttr('{0}.ro'.format(conLoc), roVal) # query associated attributes keyFrameInfo[each]['keyable'] = {} for keyframe in keyframes: connections = cmds.listConnections(keyframe, plugs=1, s=0, d=1) xAttr = connections[0].split('.')[1] if udList: if skipUD and xAttr in keyFrameInfo[each][ 'udList']: if info: print 'xAttr "{0}" in udList, skipping...'.format( xAttr) continue keyFrameInfo[each]['keyable'][keyframe] = {} keyFrameInfo[each]['keyable'][keyframe][ 'attr'] = xAttr if info: print( 'keyFrameInfo["{0}"]["{1}"][\'attr\'] = {2}' .format( each, keyframe, keyFrameInfo[each] ['keyable'][keyframe]['attr'])) keyFrameInfo[each]['keyable'][keyframe][ 'tList'] = cmds.keyframe(keyframe, query=1, timeChange=1) keyFrameInfo[each]['keyable'][keyframe][ 'vList'] = cmds.keyframe(keyframe, query=1, valueChange=1) # set keys if keyLocOnEveryFrame: if info: print 'keyLocOnEveryFrame' cmds.setKeyframe(conLoc) elif copyBreakdowns: if info: print 'copyBreakdowns' for keyframe in keyFrameInfo[each]['keyable']: if info: print 'keyframe = "{0}"'.format(keyframe) ''' if not keyframe in keyFrameInfo[each]['keyable']: if info: print 'not "{0}" in {1}'.format(keyframe, keyFrameInfo[each]['keyable']) continue ''' if not frame in keyFrameInfo[each]['keyable'][ keyframe]['tList']: if info: print('not "{}" in {}'.format( frame, keyFrameInfo[each]['keyable'] [keyframe]['tList'])) if smartKey: cmds.setKeyframe(conLoc, attribute=keyFrameInfo[each] ['keyable'][keyframe]['attr']) continue index = keyFrameInfo[each]['keyable'][keyframe][ 'tList'].index(frame) breakdown = cmds.keyframe(keyframe, query=1, index=(index, index), breakdown=1) bd = True if breakdown else False cmds.setKeyframe(conLoc, attribute=keyFrameInfo[each] ['keyable'][keyframe]['attr'], breakdown=bd) if info: print('setKeyframe("{}")'.format(conLoc)) else: if info: print 'not keyLocOnEveryFrame or copyBreakdowns' cmds.setKeyframe(conLoc) # clean up cmds.delete(pacList) # Now attach destination nodes to constraint locators if not progressBarCancelled: for each in keyFrameInfo: conLoc = keyFrameInfo[each]['conLoc'] constrainMulti = False try: cmds.orientConstraint(conLoc, each) constrainMulti = True print 'could orient constrain' except: pass try: cmds.pointConstraint(conLoc, each) constrainMulti = True print 'could point constrain' except: pass if not constrainMulti: channels = ['x', 'y', 'z'] for channel in channels: channelList = copy.copy(channels) channelList.pop(channelList.index(channel)) try: cmds.orientConstraint(conLoc, each, skip=channelList) print 'could orient constrain ', channel except: pass try: cmds.pointConstraint(conLoc, each, skip=channelList) print 'could point constrain ', channel except: pass else: cmds.warning( 'constrain selected cancelled, skipping constraining to locators...' ) except Exception as E: traceback.print_exc(file=sys.stderr) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) cmds.refresh(suspend=False) cmds.undoInfo(closeChunk=True) cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) cmds.refresh(suspend=False) cmds.currentTime(currTime) cmds.select(nodeList) cmds.undoInfo(closeChunk=True)
def createController(self): # create controller haindLegControllerName = controllerShape( self.IkHindLegJointList[3].replace( 'ball_JNT', 'hindLeg_CON' ), 'cube', 'blue' ) cmds.move( self.anklePos[0], self.anklePos[1], self.anklePos[2], haindLegControllerName ) hipControllerName = controllerShape( self.IkHindLegJointList[0].replace( 'JNT', 'CON' ), 'cube', 'blue' ) POsnap( hipControllerName, self.IkHindLegJointList[0] ) hipWorldControllerName = controllerShape( self.IkHindLegJointList[0].replace( 'JNT', 'world_CON' ), 'cube', 'blue' ) Psnap( hipWorldControllerName, self.IkHindLegJointList[0] ) kneePVContollerName = cmds.spaceLocator( n=self.IkHindLegJointList[1].replace( 'JNT', 'LOC' ) )[0] kneePVPos = cmds.xform( self.IkHindLegJointList[0], t=True, ws=True, q=True ) cmds.move( kneePVPos[0], kneePVPos[1], kneePVPos[2] + 20, kneePVContollerName ) anklePVContollerName = controllerShape( self.IkHindLegJointList[2].replace( 'JNT', 'CON' ), 'sphere', 'blue' ) anklePVPos = cmds.xform( self.IkHindLegJointList[2], t=True, ws=True, q=True ) cmds.move( anklePVPos[0], anklePVPos[1], anklePVPos[2], anklePVContollerName ) # controller homeNull homeNul( haindLegControllerName ) hipNul = homeNul( hipControllerName ) hipRotZNul = homeNul( hipControllerName, hipNul.replace( 'hip', 'hipRotZ' ) ) hipNulWorldNul = homeNul( hipWorldControllerName ) kneePVNul = homeNul( kneePVContollerName ) homeNul( anklePVContollerName ) # constraints & grouping cmds.parent( self.pivotNulList[0], haindLegControllerName ) cmds.parent( kneePVNul, hipControllerName ) cmds.parent( hipNul, hipWorldControllerName ) if self.side != 'R' : cmds.aimConstraint( haindLegControllerName, hipRotZNul, mo=True, weight=1, aimVector=[ 1, 0, 0 ], upVector=[ 0, 1, 0 ], worldUpType='none', skip=[ 'x', 'y' ] ) else : cmds.aimConstraint( haindLegControllerName, hipRotZNul, mo=True, weight=1, aimVector=[ -1, 0, 0 ], upVector=[ 0, 1, 0 ], worldUpType='none', skip=[ 'x', 'y' ] ) cmds.pointConstraint( hipControllerName, self.IkHindLegJointList[0] ) cmds.pointConstraint( hipControllerName, self.subIkJointList[0] ) cmds.orientConstraint( hipControllerName, self.subIkJointList[0] ) cmds.poleVectorConstraint( anklePVContollerName, self.sRPsName ) cmds.poleVectorConstraint( kneePVContollerName, self.RPsName ) # addAttr & connection cmds.addAttr( haindLegControllerName, longName='auto', at='enum', en='Angle', keyable=True ) cmds.setAttr( '%s.auto' % haindLegControllerName, lock=True ) cmds.addAttr( haindLegControllerName, longName='front', at='double', keyable=True, attributeType='float', min=0, max=1, dv=0.5 ) cmds.addAttr( haindLegControllerName, longName='subController', at='enum', en='Visibility', keyable=True ) cmds.setAttr( '%s.subController' % haindLegControllerName, lock=True ) cmds.addAttr( haindLegControllerName, longName='vis', at='bool', keyable=True ) cmds.setKeyframe( '%s.rz' % hipRotZNul ) cmds.disconnectAttr( 'pairBlend1_inRotateZ1.output', 'pairBlend1.inRotateZ1' ) cmds.delete( 'pairBlend1_inRotateZ1' ) cmds.rename( 'pairBlend1', hipRotZNul.replace( 'NUL', 'PBD' ) ) cmds.connectAttr ( '%s.front' % haindLegControllerName, '%s.blendAim1' % hipRotZNul ) # create foot controller ankleRollCONT = controllerShape( self.anklePivotName.replace( 'PIVOT', 'CON' ), 'cube', 'yellow' ) cvNum = cmds.getAttr( '%s.spans' % ankleRollCONT ) + cmds.getAttr( '%s.degree' % ankleRollCONT ) cmds.select( '%s.cv[0:%s]' % ( ankleRollCONT, cvNum-1 ) ) cmds.scale( 0.5, 0.5, 0.5 ) cmds.select( cl=True ) cmds.parent( '%sShape' % ankleRollCONT, self.anklePivotName, r=True, s=True ) cmds.delete( ankleRollCONT ) ankleRollCON = cmds.rename( self.anklePivotName, self.anklePivotName.replace( 'PIVOT', 'CON' ) ) for x in range( len( self.pivotList ) ): CONT = controllerShape( self.pivotList[x].replace( 'PIVOT', 'CON' ), 'cube', 'yellow' ) cvNum = cmds.getAttr( '%s.spans' % CONT ) + cmds.getAttr( '%s.degree' % CONT ) cmds.select( '%s.cv[0:%s]' % ( CONT, cvNum-1 ) ) cmds.scale( 0.5, 0.5, 0.5 ) cmds.select( cl=True ) cmds.parent( '%sShape' % CONT, self.pivotList[x], r=True, s=True ) cmds.delete( CONT ) ankleRollCON = cmds.rename( self.pivotList[x], self.pivotList[x].replace( 'PIVOT', 'CON' ) ) cmds.connectAttr( '%s.vis' % haindLegControllerName, '%s.visibility' % self.pivotNulList[0] )
def constrain_body(self, reverse=False): root_obj = self.setting_module.root nodes = [] mc_namespace = self.ui.mc_ns_line.text() + ":" _nodes = self._get_nsObjs(mc_namespace) nodes.extend(cmds.ls(_nodes, type="transform")) nodes.extend(cmds.ls(_nodes, type="joint")) f_frame_set = set() l_frame_set = set() for _node in nodes: f_frame_set.add(cmds.findKeyframe(_node, w="first")) l_frame_set.add(cmds.findKeyframe(_node, w="last")) f_frame = min(f_frame_set) l_frame = max(l_frame_set) trans_list = ["translateX", "translateY", "translateZ"] rot_list = ["rotateX", "rotateY", "rotateZ"] for _node in reversed(nodes): for _attr in rot_list: cmds.setKeyframe(str(_node) + "." + _attr, v=0, t=(f_frame - 5)) if _node == root_obj: for _attr in trans_list: cmds.setKeyframe(str(_node) + "." + _attr, v=0, t=(f_frame - 5)) # Constrainパート cmds.currentTime(f_frame - 5) results = {} consts = [] mc_ns = self.ui.mc_ns_line.text() rh_ns = self.ui.rh_ns_line.text() if mc_ns != "": mc_ns = mc_ns + ":" if rh_ns != "": rh_ns = rh_ns + ":" for table_dict in self.table_list: const = table_dict["const"] rh = table_dict["RH"] mc = table_dict["MC"] cmds.setAttr("{}.rotate".format(mc), 0, 0, 0) if mc.split(":")[-1] == "root_MCJNT": cmds.setAttr("{}.translate".format(mc), 0, 0, 0) if reverse == True: if mc.split(":")[-1] in ["ankle_MCJNT_L", "ankle_MCJNT_R"]: print "########################" cmds.parentConstraint("{}ankle_MCJNT_R".format(mc_ns), "{}reverseFoot_ctrl_R".format(rh_ns), mo=True) cmds.parentConstraint("{}ankle_MCJNT_L".format(mc_ns), "{}reverseFoot_ctrl_L".format(rh_ns), mo=True) print "########################" continue const_type, const = self.exec_const(const, rh, mc) consts.extend(const) results.setdefault(const_type, []).append(rh) cmds.currentTime(f_frame) # Bakeパート cmds.cycleCheck(e=False) bakelist = [] # parent if "parent" in results: attrs = trans_list + rot_list bakelist.extend(self._cana_composer(results["parent"], attrs)) # orient if "orient" in results: attrs = rot_list bakelist.extend(self._cana_composer(results["orient"], attrs)) # point if "point" in results: attrs = trans_list bakelist.extend(self._cana_composer(results["point"], attrs)) sampling = float(self.ui.sampling_line.text()) cmds.bakeResults(bakelist, t=(f_frame, l_frame), ral=True, sm=1, sb=sampling) cmds.cycleCheck(e=True) cmds.delete(consts)
def bake_world_space_data(): ''' Bakes extracted data using stored world space dictionary (only translate and rotate) ''' # Store Current Time original_time = cmds.currentTime(q=True) # Last Validation is_valid = True if len(gt_world_space_baker_anim_storage) == 0: is_valid = False cmds.warning( 'Couldn\'t find stored data. Please try extracting it again.') # Bake Keyframes: if is_valid: for key, dict_value in gt_world_space_baker_anim_storage.iteritems(): for key_data in dict_value: try: obj, attr = key.split('.') time = key_data[0] value = key_data[1] cmds.currentTime(time) if attr == 'translate': cmds.xform(obj, ws=True, t=value) cmds.setKeyframe(obj, time=time, attribute='tx') cmds.setKeyframe(obj, time=time, attribute='ty') cmds.setKeyframe(obj, time=time, attribute='tz') if attr == 'rotate': cmds.xform(obj, ws=True, ro=value) cmds.setKeyframe(obj, time=time, attribute='rx') cmds.setKeyframe(obj, time=time, attribute='ry') cmds.setKeyframe(obj, time=time, attribute='rz') except: pass # Reset to Original Time cmds.currentTime(original_time)
def attach(source, target): """ attach( 'anim_ctl', 'spaceA') attach( 'anim_ctl', 'spaceB') """ # Get space transforms space_constrain = get_message_attribute_connections( source, attrName="space_constraint") space_offset = get_message_attribute_connections(source, attrName="space_offset") if not space_constrain: LOG.error('There are no space transforms setup on {}'.format(source)) return # Determine if there's an existing parent constrain on space_constrain node par_con = "" par_cons = get_parent_constraints(space_constrain[0]) # Get world location of space offset space_offset_location = get_world_location(space_offset) # Time current_frame = cmds.currentTime(q=True) first_frame = cmds.playbackOptions(q=True, ast=True) # If there's an existing parent constraint if par_cons: LOG.info('Parent constraint exists') par_con = par_cons[0] # if the target is already active exit if target == get_active_constraint_target(par_con): LOG.error('{} is already active target for {}'.format( target, source)) return target_list = cmds.parentConstraint(par_con, q=True, tl=True) print target_list # reset all targets for i in range(len(target_list)): cmds.setAttr('%s.w%d' % (par_con, i), 0.0) cmds.setKeyframe('%s.w%d' % (par_con, i), ott='step') # if the target is not present in the constraint then add it if target not in target_list: add_target_to_constraint(par_con, target) # set it to 0 in the first frame (since it's new), it's not valid if they are in the first frame if current_frame > first_frame: cmds.setKeyframe('%s.w%d' % (par_con, len(target_list)), ott='step', t=first_frame, v=0.0) # set it to 1 in the current frame target_id = cmds.parentConstraint(par_con, q=True, tl=True).index(target) cmds.setAttr('%s.w%d' % (par_con, target_id), 1.0) cmds.setKeyframe('%s.w%d' % (par_con, target_id), ott='step') print target_id # snap the position of the snap control on the previous position and set the keys of the snap control set_world_location(space_offset[0], space_offset_location) cmds.setKeyframe(space_offset[0], at=['translate', 'rotate'], ott='step') # else if there's not an existing parent constraint else: # Create constraint and set keyframe par_con = create_parent_constraint( space_constrain[0], target, '{}_parcon'.format(space_constrain[0])) cmds.setKeyframe(par_con, at='w0', ott='step') # Snap the position of the space offset transform and set keyframes set_world_location(space_offset[0], space_offset_location) cmds.setKeyframe(space_offset[0], at=['translate', 'rotate'], ott='step') # Set it to 0 on the first frame if current_frame > first_frame: cmds.setKeyframe(par_con, at='w0', ott='step', t=first_frame, v=0.0) cmds.setKeyframe(space_offset[0], at=['translate', 'rotate'], ott='step', t=first_frame, v=0.0) # set keyframes to green cmds.keyframe([space_offset[0], par_con], tds=True) # set the curve step cmds.keyTangent([space_offset[0], par_con], ott='step') return space_constrain
if dialogResuls != None: filePath = dialogResuls[0] qbfile = open(filePath, 'r') for aline in qbfile.readlines(): if aline.startswith('Begin Logger Session'): sessionId = sessionId + 1 currentBoxName = 'cameraProxy' + str(sessionId) cmds.polyCube(name=currentBoxName) values = aline.split(',') if values[0] == 'Log Entry' and currentBoxName != '': frameValue = values[1] positionValues = values[2].split(' ') rotationValues = values[3].split(' ') cmds.setKeyframe(currentBoxName, time=eval(frameValue), attribute='translateX', v=eval(positionValues[0])) cmds.setKeyframe(currentBoxName, time=eval(frameValue), attribute='translateY', v=eval(positionValues[1])) cmds.setKeyframe(currentBoxName, time=eval(frameValue), attribute='translateZ', v=eval(positionValues[2])) cmds.setKeyframe(currentBoxName, time=eval(frameValue), attribute='rotateX', v=eval(rotationValues[0])) cmds.setKeyframe(currentBoxName,
def create(self, *args): img = cmds.iconTextButton("TempCustomPivotBtn", query=True, image=True) onOff = (img[-10:-4] == "active") if onOff: self.clear() cmds.select(self.sel) return cmds.undoInfo(openChunk=True) cmds.undoInfo(closeChunk=True) cmds.undoInfo(openChunk=True) cmds.undoInfo(closeChunk=True) cmds.undoInfo(openChunk=True) cmds.undoInfo(closeChunk=True) cmds.undoInfo(openChunk=True) self.clear() getCurves = animMod.getAnimCurves() animCurves = getCurves[0] getFrom = getCurves[1] if animCurves: keyTimes = animMod.getTarget("keyTimes", animCurves, getFrom) self.sel = cmds.ls(selection=True) if not self.sel: return cmds.iconTextButton( "TempCustomPivotBtn", edit=True, image=uiMod.getImagePath( "specialTools_create_temp_custom_pivot_active"), highlightImage=uiMod.getImagePath( "specialTools_create_temp_custom_pivot_active")) targetObj = self.sel[-1] aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CTRLS, self.sel) currentFrame = cmds.currentTime(query=True) aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CURRENTFRAME, currentFrame) locators = [] for loopSel in self.sel: nameSpace = utilMod.getNameSpace([loopSel]) loopSelName = "%s_%s" % (nameSpace[0][0], nameSpace[1][0]) locatorName = "tempCustomPivot_%s" % loopSelName locator = animMod.createNull(locatorName) locators.append(locator) G.aToolsBar.align.align([locator], loopSel) locatorGroup = "tempCustomPivot_group" animMod.group(name=locatorGroup) G.aToolsBar.align.align([locatorGroup], targetObj) with G.aToolsBar.createAToolsNode: cmds.parent(locators, locatorGroup) cmds.select(locatorGroup, replace=True) locators.append(locatorGroup) aToolsMod.saveInfoWithScene(self.STORE_NODE, self.LOCATORS, locators) #parent ctrls to locator constraints = [ "%s_tempCustomPivot_constraint" % loopConstraint for loopConstraint in self.sel ] aToolsMod.saveInfoWithScene(self.STORE_NODE, self.CONSTRAINTS, constraints) for n, loopSel in enumerate(self.sel): with G.aToolsBar.createAToolsNode: cmds.parentConstraint(locators[n], loopSel, name=constraints[n], maintainOffset=True) constraintNode = "%s.blendParent1" % loopSel if not cmds.objExists(constraintNode): continue cmds.setKeyframe(constraintNode) if keyTimes: for loopTime in keyTimes[0]: cmds.setKeyframe("%s.tx" % locatorGroup, time=(loopTime, loopTime)) if loopTime != currentFrame: cmds.setKeyframe(constraintNode, time=(loopTime, loopTime), value=0) #enter edit mode cmds.setToolTo(cmds.currentCtx()) cmds.ctxEditMode() #scriptjob cmds.scriptJob(runOnce=True, killWithScene=True, event=('SelectionChanged', self.scriptJob_SelectionChanged))
import maya.cmds as cmds cmds.setAttr('persp1.translateX', 9.453) cmds.setAttr('persp1.translateY', 1.983) cmds.setAttr('persp1.translateZ', 18.285) cmds.setAttr('persp1.rotateX', 5.062) cmds.setAttr('persp1.rotateY', 1113) cmds.setAttr('persp1.rotateZ', 0) for s in range(0, 10): cmds.setAttr('pSphere2.scaleY', 1 - ((s % 10) * 0.1)) cmds.setAttr('pSphere1.scaleY', 1 - ((s % 10) * 0.1)) cmds.setKeyframe('pSphere2', 'pSphere1', attribute='scaleY', t=s) for s in range(10, 20): cmds.setAttr('pSphere2.scaleY', 0 + ((s % 10) * 0.1)) cmds.setAttr('pSphere1.scaleY', 0 + ((s % 10) * 0.1)) cmds.setKeyframe('pSphere2', 'pSphere1', attribute='scaleY', t=s) for s in range(20, 40): cmds.setAttr('pCylinder1.rotateZ', -20 + ((s % 20) * 4)) cmds.setAttr('pSphere4.rotateZ', -14.894 - ((s % 20) * 50)) cmds.setAttr('pSphere3.rotateZ', -14.894 - ((s % 20) * 50)) cmds.setKeyframe('pCylinder1', attribute='rotateZ', t=s) cmds.setKeyframe('pSphere4', 'pSphere3', attribute='rotateZ', t=s) for s in range(40, 70): cmds.setAttr('pCylinder1.translateY', 4.618 + ((s % 40))) cmds.setAttr('pSphere1.translateY', 4.537 + ((s % 40))) cmds.setAttr('pSphere2.translateY', 4.537 + ((s % 40)))
def Con_Keyframe_Fn(self,pnCns,Attr_List): for i,Attr in enumerate(Attr_List): if i != 0: cmds.setKeyframe ("cam_grp_pointConstraint1.w1")
def testStaticMeshAnimColor(self): MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.polyColorPerVertex(r=0.0, g=1.0, b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=0.0, g=0.0, b=1.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.polyColorPerVertex(r=1.0, g=1.0, b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=1.0, g=0.0, b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) self.__files.append(util.expandFileName('animColorSets.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0.444444447756) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 1) self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 0)
def IdleAnimation(): if(IDLEposing): IDLEpose() global fromFrameNum, toFrameNum, loopADD, fpsDesired HipsTtX = [0.0, 13.5, 27.0, 82.5, 110.25, 138.0, 144.0, 156.0, 168.0, 180.0, 192.0, 209.25, 217.875, 226.5, 243.75, 261.0, 288.0, 315.0, 321.0, 349.5, 363.75, 370.875, 378.0, 477.0, 500.0] HipsTtY = [0.0, 33.0, 48.0, 72.0, 114.0, 123.0, 177.0, 264.0, 279.0, 294.0, 318.0, 375.0, 393.0, 396.0, 453.0, 500.0] HipsTtZ = [0.0, 43.5, 65.25, 76.125, 87.0, 102.0, 124.5, 135.75, 147.0, 158.25, 169.5, 180.75, 192.0, 211.5, 221.25, 231.0, 252.0, 264.0, 298.5, 333.0, 339.0, 348.0, 357.0, 387.75, 403.125, 410.8125, 418.5, 433.875, 449.25, 464.625, 480.0, 490.0, 500.0] HipsTvX = [0.17779485881328583, 0.18752059530466797, 0.2009551344376344, -0.0735133182831529, -0.22100100769524234, -0.3282756494652284, -0.3224179744720459, -0.37428250908851624, -0.4851997196674347, -0.6094918251037598, -0.6346231698989868, -0.514301427640021, -0.4467938421003054, -0.3645054157823324, -0.2612109170295297, -0.23870888352394104, -0.355541721713962, -0.39751530008972, -0.3985836661553808, -0.43591747228390515, -0.5022106756587338, -0.5285275414912446, -0.5376094683580722, 0.3587857484817505, 0.17779485881328583] HipsTvY = [98.2432861328125, 98.25767124720981, 98.25446319580078, 98.26216704757125, 98.23657386504937, 98.23868560791016, 98.18712615966797, 98.29048873163418, 98.26807403564453, 98.26515831266131, 98.27314211527505, 98.18214632707156, 98.19028112825262, 98.19105529785156, 98.26376342773438, 98.2432861328125] HipsTvZ = [-0.4100062847137451, -0.24446356572406283, -0.023791488840410425, 0.062385208092899526, 0.06793052840914164, 0.05239826440811157, 0.14909910410642624, 0.18939124466851356, 0.21213829517364502, 0.23913892824202784, 0.323179729282856, 0.43452210584655415, 0.4574851393699646, 0.301368131759268, 0.24785943173766306, 0.24008075649641, 0.2732388474323132, 0.27188771963119507, 0.4058982297447148, 0.5125252216983912, 0.5113953351974487, 0.5283292531967163, 0.528292179107666, 0.3083632541820405, 0.0311279170564377, -0.09514799168209695, -0.21084582246839956, -0.40345653597614733, -0.51361380610615, -0.5914320640149527, -0.6361932754516602, -0.550125777721405, -0.4100062847137451] Rtx = [0.0, 28.5, 42.75, 49.875, 57.0, 68.25, 79.5, 90.75, 102.0, 108.0, 129.0, 139.5, 144.75, 150.0, 155.25, 160.5, 171.0, 181.5, 192.0, 231.0, 234.75, 238.5, 246.0, 263.25, 271.875, 280.5, 289.125, 297.75, 306.375, 315.0, 337.5, 343.125, 348.75, 354.375, 360.0, 400.5, 410.625, 420.75, 430.875, 441.0, 468.0, 472.0, 476.0, 484.0, 500.0] Rty = [0.0, 3.0, 7.875, 12.75, 22.5, 32.25, 42.0, 48.0, 52.5, 57.0, 61.5, 66.0, 69.0, 73.5, 78.0, 82.5, 87.0, 96.0, 105.0, 121.5, 138.0, 142.875, 147.75, 152.625, 155.0625, 157.5, 162.375, 167.25, 177.0, 198.75, 209.625, 220.5, 231.375, 242.25, 264.0, 270.0, 301.5, 333.0, 369.0, 375.0, 381.0, 387.0, 393.0, 399.0, 444.0, 466.5, 477.75, 489.0, 500.0] Rtz = [0.0, 3.0, 6.0, 15.0, 33.0, 51.0, 61.5, 72.0, 93.0, 135.0, 156.0, 177.75, 199.5, 221.25, 243.0, 271.5, 300.0, 321.0, 342.0, 363.0, 387.0, 415.25, 443.5, 471.75, 478.8125, 485.875, 500.0] Rvx = [-3.459852933883667, -3.3072674870491032, -3.176591850817203, -3.0825127395801246, -3.07987642288208, -3.22169135697186, -3.3993495255708694, -3.5094699412584305, -3.5606977939605713, -3.559291362762451, -3.692271232604981, -3.8295076936483383, -3.9137303754687323, -4.017697811126709, -4.0973897092044345, -4.128383785486221, -4.197817325592041, -4.2483763694763175, -4.316548824310303, -3.942728281021118, -3.9687414783984427, -3.9942632317543025, -3.9991328716278076, -3.926121961325408, -3.9024378501344463, -3.802559673786164, -3.720135221956298, -3.6284290980547667, -3.5285610260907556, -3.5282745361328125, -3.7624221891164775, -3.890642332611606, -4.048165224492551, -4.1375120636075735, -4.147119522094727, -3.9508220106363305, -3.8748749443329875, -3.762465771287679, -3.582578553818166, -3.5687813758850098, -3.8114373683929443, -3.749022960662842, -3.6738564968109126, -3.5961985588073726, -3.459852933883667] Rvy = [-5.428574085235596, -5.429776191711426, -5.464799016037511, -5.55895686494974, -5.76318071230855, -5.900301446019517, -5.919962774965807, -5.9206414222717285, -5.93696716427803, -5.921253681182861, -5.9002445936203, -5.902807235717773, -5.888182163238525, -5.8291606307029715, -5.711162567138672, -5.551192641258239, -5.371066093444824, -5.142420291900635, -5.088422775268555, -5.278287128282444, -5.358760306604535, -5.285179398731328, -5.192776870766908, -5.060915844826717, -4.985991182575158, -4.9078199565410605, -4.79939656531452, -4.7610757600463645, -4.720608084550551, -4.861498888220405, -4.939804805868713, -5.029376111924648, -5.14065934223968, -5.205549111566794, -5.209500152623212, -5.201642036437988, -5.485459406337823, -5.567963123321533, -5.215297222137451, -5.228514229129843, -5.243098384471413, -5.254955123984125, -5.243727177576302, -5.262018954740371, -5.627600338527134, -5.46442405575305, -5.368713822153452, -5.34763541845469, -5.428574085235596] Rvz = [-2.9911160469055176, -2.9928882122039795, -2.9908785820007324, -2.989689588546753, -3.0356638431549072, -3.068981409072876, -3.002770761332297, -2.9430974031992263, -2.763348609776853, -2.6338381805708484, -2.673411821239788, -2.584677147679032, -2.450161037634943, -2.3980438846629113, -2.362424612045288, -2.461025772027432, -2.534801226124125, -2.505805730819702, -2.6102686353303763, -2.6427693367004395, -2.5919349193573, -2.7329156929069756, -2.8143385203904536, -2.8868817113264407, -2.9342009524940953, -2.9602950462468645, -2.9911160469055176] ArmsRtx = [0.0, 3.0, 11.25, 19.5, 36.0, 43.5, 47.25, 51.0, 54.0, 58.5, 63.0, 75.0, 84.0, 88.5, 93.0, 102.0, 111.0, 144.0, 151.5, 155.25, 159.0, 163.5, 168.0, 171.0, 179.25, 183.375, 187.5, 191.625, 195.75, 199.875, 204.0, 220.5, 237.0, 240.0, 252.0, 269.625, 287.25, 296.0625, 304.875, 309.28125, 313.6875, 322.5, 331.3125, 335.71875, 337.921875, 340.125, 344.53125, 348.9375, 353.34375, 357.75, 393.0, 396.375, 399.75, 406.5, 413.25, 416.625, 420.0, 426.75, 433.5, 447.0, 473.5, 486.75, 500.0] ArmsRty = [0.0, 30.0, 55.5, 81.0, 108.0, 120.0, 141.0, 183.0, 210.0, 270.0, 348.0, 426.0, 463.0, 500.0] ArmsRtz = [0.0, 24.0, 42.0, 46.5, 51.0, 55.5, 60.0, 63.0, 72.0, 81.0, 94.5, 101.25, 108.0, 113.25, 118.5, 129.0, 138.0, 142.5, 147.0, 150.0, 252.0, 255.0, 264.0, 280.875, 297.75, 314.625, 323.0625, 331.5, 339.9375, 344.15625, 348.375, 356.8125, 361.03125, 365.25, 369.46875, 373.6875, 382.125, 399.0, 408.375, 417.75, 436.5, 455.25, 474.0, 500.0] ArmsRvx = [14.696393966674805, 14.683956146240234, 14.589741982519627, 14.539034843444822, 14.508481025695799, 14.573204278945921, 14.589449927210808, 14.567172050476074, 14.573321342468263, 14.613119781017305, 14.612019538879396, 14.580472946166994, 14.755029069900512, 14.90908973264694, 15.013168248176573, 15.102417178153996, 15.107366561889648, 14.980143547058105, 15.04130208492279, 15.064428016543387, 15.050728797912596, 15.01063358783722, 15.00830078125, 15.000904083251951, 14.887253042538324, 14.792230348605065, 14.64637211422682, 14.466676157440226, 14.362500167665285, 14.279128948680162, 14.181788893019707, 13.912285493060484, 13.887174606323242, 13.877899169921875, 13.866764444580067, 13.99433328050395, 14.119301445224893, 14.168557734797973, 14.275942387520162, 14.355731188232825, 14.410879196153525, 14.482654170163034, 14.63298543533977, 14.724944110488774, 14.785129346152559, 14.874119049950117, 15.02308235241596, 15.06902795045495, 15.074395629087238, 15.101098716850576, 15.285305629373527, 15.21556884337512, 15.159940492560024, 15.025511155998947, 14.836986242022569, 14.748274388239864, 14.664523022281793, 14.540925806567216, 14.506900751218026, 14.491443634033203, 14.603954076766964, 14.668143555521963, 14.696393966674805] ArmsRvy = [6.138768672943115, 6.160321235656738, 6.124497828423046, 6.112393379211426, 6.126261855390939, 6.121921566225887, 6.128090589804135, 6.116992473602295, 6.128780841827393, 6.09617280960083, 6.133551972930342, 6.187722664722027, 6.146836555180271, 6.138768672943115] ArmsRvz = [14.900257110595705, 14.989876456930611, 14.898343368557619, 14.840866263258503, 14.757704198310002, 14.709761652553368, 14.71494197845459, 14.697582244873047, 14.64612928181681, 14.663432207695275, 14.957966160545293, 15.020994551827302, 15.008961615882127, 14.973911670493544, 14.968881726264952, 14.9664312776903, 14.970444679260254, 14.943714380264284, 14.957403182983398, 14.955492019653319, 14.151723861694336, 14.146367073059082, 14.146729221427957, 14.275032481557885, 14.353107295630942, 14.49930505229019, 14.591430860072094, 14.717206958907704, 14.930823182979315, 15.029528533958906, 15.083471822860004, 15.13192010909238, 15.193725110862673, 15.28104424762414, 15.371352550050576, 15.422538384838996, 15.466372599124623, 15.509959384570992, 15.458869024417957, 15.32128171250963, 15.01405720655155, 14.893473285597622, 14.875975984025917, 14.900257110595705] allTimeLists = [HipsTtX, HipsTtY, HipsTtZ, Rtx, Rty, Rtz, ArmsRtx, ArmsRty, ArmsRtz] toFrameNumNTSCF = toFrameNum * 60 / fpsDesired if(fromFrameNum != 0): print 'treba podesiti da krene kasnije/ranije' for j in range(9): for m, element in enumerate(allTimeLists[j]): allTimeLists[j][m] = element + fromFrameNum else: print 'ne treba nista na pocetku' if(toFrameNumNTSCF < 500): print 'treba podesiti da se zavrsi ranije' for j in range(9): endTMP = 0 for num in allTimeLists[j]: if(num < toFrameNumNTSCF): endTMP = endTMP + 1 elif(num >= toFrameNumNTSCF): endTMP = endTMP + 1 break end = len(allTimeLists[j]) if(end > endTMP): for h in range(end - endTMP): allTimeLists[j].pop() elif(toFrameNumNTSCF > 500): print 'treba loop unapred' loopADD = True else: print 'ne treba nista na kraju' global pelvis, spine, neck1, neck2, head, hair, shoulder, upArm, lowArm, wrist, thigh, knee, foot, toes, ikHand, ikElbow, ikFoot, ikKnee, thumbF, finger, lowEyeLid, upEyeLid global spineCount, ikLegs, fkLegs, ikArms, fkArms, thumb mc.currentUnit(t = 'ntscf') LEGbase = 0.607 #new LEG mc.spaceLocator(n = 'p') mc.spaceLocator(n = 'f') mc.matchTransform('p', 'BN_Pelvis', position = True) mc.matchTransform('f', 'BN_R_Ankle', position = True) LEGnew = (mc.getAttr('p.translateY')) - (mc.getAttr('f.translateY')) mc.delete('p', 'f') #constant which allow different characters LEGconst = LEGnew / LEGbase hipsTt = [HipsTtX, HipsTtY, HipsTtZ] hipsTv = [HipsTvX, HipsTvY, HipsTvZ] axis = ['x', 'y', 'z'] for i, a in enumerate(axis): mc.currentTime(fromFrameNum) tav = mc.getAttr(pelvis + '.t' + a) if(tav == 0): tav = 0.001 difference = tav/hipsTv[i][0] for k, t in enumerate(hipsTt[i]): mc.currentTime(t) mc.setKeyframe(pelvis, attribute = 't' + a, v = hipsTv[i][k]*difference) bodyParts = [pelvis, neck1, head] pRt = [Rtx, Rty, Rtz] pRv = [Rvx, Rvy, Rvz] #pelvis, neck, head for p in bodyParts: for i, a in enumerate(axis): mc.currentTime(fromFrameNum) rav = mc.getAttr(p + '.r' + a) if(rav == 0): rav = 0.001 difference = rav/pRv[i][0] for k, t in enumerate(pRt[i]): mc.currentTime(t) mc.setKeyframe(p, attribute = 'r' + a, v = pRv[i][k]*difference) #spine for bn in range(spineCount): for i, a in enumerate(axis): mc.currentTime(fromFrameNum) rav = mc.getAttr(spine + str(bn+1) + '.r' + a) if(rav == 0): rav = 0.001 difference = rav/pRv[i][0] for k, t in enumerate(pRt[i]): mc.currentTime(t) mc.setKeyframe(spine + str(bn+1), attribute = 'r' + a, v = pRv[i][k]*difference) #Arms bodyParts = [shoulder, upArm, lowArm, wrist] ApRt = [ArmsRtx, ArmsRty, ArmsRtz] ApRv = [ArmsRvx, ArmsRvy, ArmsRvz] axis = ['x', 'y', 'z'] sides = ['L', 'R'] pTMP = '' for side in sides: for p in bodyParts: for i, a in enumerate(axis): if(p == shoulder): mc.currentTime(fromFrameNum) rav = mc.getAttr('CTRL_'+ side + p + '.r' + a) if(rav == 0): rav = 0.01 difference = rav/ApRv[i][0] for k, t in enumerate(ApRt[i]): mc.currentTime(t) mc.setKeyframe('CTRL_'+ side + p, attribute = 'r' + a, v = ApRv[i][k]*difference) else: mc.currentTime(0) rav = mc.getAttr('CTRL_FK_'+ side + p + '.r' + a) if(rav == 0): rav = 0.01 difference = rav/ApRv[i][0] for k, t in enumerate(ApRt[i]): mc.currentTime(t) mc.setKeyframe('CTRL_FK_'+ side + p, attribute = 'r' + a, v = ApRv[i][k]*difference)
def Con_Keyframe_Fn(self,pnCns,Attr_List): for Attr in Attr_List cmds.setKeyframe ("cam_grp_pointConstraint1.w1") def Batch_Position_Fn(self): ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: Base_Curve = self.Attr["Add_Crv_LE"] CamGrp = child.Attr["Add_CamGrp_LE"] if not cmds.objExists(Base_Curve): continue if not cmds.objExists(CamGrp): continue cmds.setAttr("%s.tx" % CamGrp,0) cmds.setAttr("%s.ty" % CamGrp,0) cmds.setAttr("%s.tz" % CamGrp,0) cmds.setAttr("%s.rx" % CamGrp,0) cmds.setAttr("%s.ry" % CamGrp,0) cmds.setAttr("%s.rz" % CamGrp,0) cmds.xform( CamGrp,cp=1 ) cmds.delete(cmds.parentConstraint( Base_Curve,CamGrp )) Target_Curve = child.Attr["Add_Crv_LE"] if not cmds.objExists(Target_Curve): continue cmds.xform( Target_Curve,cp=1 ) # Note 解除曲线的锁定 cmds.setAttr("%s.tx" % Target_Curve,lock=False) cmds.setAttr("%s.ty" % Target_Curve,lock=False) cmds.setAttr("%s.tz" % Target_Curve,lock=False) cmds.setAttr("%s.rx" % Target_Curve,lock=False) cmds.setAttr("%s.ry" % Target_Curve,lock=False) cmds.setAttr("%s.rz" % Target_Curve,lock=False) cmds.delete(cmds.parentConstraint( Base_Curve,Target_Curve )) cmds.headsUpMessage(u"位置匹配完成") def Batch_Keyframe_Fn(self): ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: Path = child.Attr["Add_Motion_Path_LE"] if cmds.objExists(Path): offset = cmds.keyframe(Path,q=1)[0] cmds.keyframe("%s.uValue"% Path,e=1,iub=1,r=1,o="over",tc=-offset) def Select_Path_Fn(self): cmds.select(cl=1) ChildrenList = self.Item_Layout.children() for i,child in enumerate(ChildrenList): if i != 0: if cmds.objExists(child.Attr["Add_Motion_Path_LE"]): cmds.select(child.Attr["Add_Motion_Path_LE"],add=1) def Item_Add_Fn(self): self.Cam_Item_Num += 1 return Cam_Item(self,self.MainWindow) def Item_Clear_Fn(self): self.Attr["Add_Crv_LE"] = "" self.Attr["Add_Motion_Path_LE"] = "" self.Attr["Name"] = "" for i,child in enumerate(self.Item_Layout.children()): if i != 0: child.deleteLater() def Scroll_Fn(self): self.Scroll_Offset = self.Cam_Item_Scroll.verticalScrollBar().value()
i++ for itr in xrange(0,1): for tx in xrange(0,900): #creates the movement throught the y posy = y + v0y*(tx-1) + g*(tx-1)*(tx-1)/2 #Makes sure the ball bounces when it hits its initial height if posy <= y + v0y*(1-1) + g*(1-1)*(1-1)/2: posy = y + v0y*(dx-1) + g*(dx-1)*(dx-1)/2 dx+=1 #This sets the ground limit for each ball so it continues to bounce to infinity if y + v0y*(dx-1) + g*(dx-1)*(dx-1)/2<= y + v0y*(1-1) + g*(1-1)*(1-1)/2: dx=1 #Creates the movement across the x posx = x + v0x*((itr*0) + tx-1) #this sets the keyframes based on tx cmds.setKeyframe( ball, attribute="translateY", value=posy, t= tx ) cmds.setKeyframe( ball, attribute="translateX", value=posx, t= tx ) #these parameters slightly change how high, far and fast the next ball bounces v0y+= .01 v0x+=.001 g+=-.001 cmds.play()