def createPathLocators(*argv): oPathLoc = cmds.spaceLocator(n='pathLocator') oStopLoc = cmds.spaceLocator(n='stopLocator') oPathLocGrp = cmds.group(oPathLoc,n='pathLocatorGrp') cmds.group(oStopLoc,n='stopLocatorGrp') cmds.pathAnimation( oPathLocGrp, stu=0, etu=1000, fa='x', ua='y', bank=True, fm = True,c='pathCurve' ) cmds.parentConstraint(oPathLoc,oStopLoc,cmds.ls('*:Master_Anim')[0])
def locOnCurve(curve, intLoc=1, n='locator', upObject='', start=False, end=False, *args): locList = [] curveLength = cmds.getAttr('{0}.maxValue'.format(curve)) step = curveLength / float(intLoc - 1) if end else curveLength / float(intLoc + 1) distance = 0 if start else step i = 1 for loc in range(intLoc): # loc = cmds.spaceLocator(n='{0}_{1}'.format(n, i))[0] loc = cmds.group(n='{0}_{1}'.format(n, i), em=True) mp = setOnMotionPath(selected=loc, name='{}_motionPath'.format(loc), curve=curve, uValue=distance) if upObject: cmds.pathAnimation(mp, e=True, wut='objectRotation', wuo=upObject) distance += step i += 1 locList.append(loc) return locList
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 create_path_animation(node, curve, frame_range, follow=True, step=1): path_node = "{}_temp_path".format(node) locator_name = "{}_temp_loc".format(node) plugs = [] if cmds.objExists(path_node): cmds.delete(path_node) if cmds.objExists(locator_name): cmds.delete(locator_name) locator = cmds.duplicate(node, name=locator_name, returnRootsOnly=True)[0] start_frame, end_frame = frame_range cmds.pathAnimation(locator, curve=curve, name=path_node, startTimeU=start_frame, endTimeU=end_frame, worldUpType="object", upAxis="y", follow=follow, followAxis="x") # Bake anim # depend_node = maya_api_utils.get_dependency_node(locator) # plugs += [ # depend_node.findPlug(attr) for attr in constants.ATTRIBUTES_TO_BAKE # ] # keys_utils.bake_animation(plugs, frame_range=frame_range, step=step) # keys_utils.copy_keys(source=locator, target=node) cmds.delete(path_node) cmds.delete(locator)
def _finalize(self): """ Finalize rig. """ # connect cmds.parent(self.fk_group, self.pos_group) cmds.parentConstraint(self.fk_controls[0], self.dynamic_control) for item in (self.fk_group, self.dynamic_joints[0]): cmds.parentConstraint(self.parent_control, item, mo=True) for count, control in enumerate(self.controls): cmds.parentConstraint(self.dynamic_joints[count], control, mo=True) # connect motion path to prevent flipping cmds.select(cl=True) cmds.select(self.motion_parent) cmds.select(self.curve, add=True) cmds.pathAnimation(su=self.start_frame, eu=self.end_frame) # lock and hide attributes on dynamic control for attr in ATTRS: cmds.setAttr("{0}.{1}".format(self.dynamic_control, attr), l=True, k=False, cb=False) self._create_meta_data()
def create_moon(): """ create the moon """ n = 'moon' moon_time_period = 0.0748 cmds.sphere(name=n, axis=[0, 1.0, 0], radius=moon_radius * 0.025) cmds.setAttr(n + 'Shape.castsShadows', 0) cmds.setAttr(n + 'Shape.receiveShadows', 0) cmds.select(n) create_texture(n) cmds.circle(radius=0.25, normalY=1, normalZ=0, name=n + '_orbit') cmds.parent('moon_orbit', 'earth') cmds.select(n, n + '_orbit') cmds.pathAnimation(name=n + '_path', fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, bank=False, startTimeU=1, endTimeU=int(moon_time_period * 10000 / time_period[3] / 2)) cmds.selectKey(clear=True) cmds.selectKey(n + '_path', keyframe=True, time=(1, int(moon_time_period * 10000 / time_period[3] / 2))) cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.setInfinity(postInfinite='cycle') animate_rotation('moon', int(moon_time_period * 10000 / time_period[3] / 2))
def createPathLocators(*argv): oPathLoc = cmds.spaceLocator(n='pathLocator') oStopLoc = cmds.spaceLocator(n='stopLocator') oPathLocGrp = cmds.group(oPathLoc, n='pathLocatorGrp') cmds.group(oStopLoc, n='stopLocatorGrp') cmds.pathAnimation(oPathLocGrp, stu=0, etu=1000, fa='x', ua='y', bank=True, fm=True, c='pathCurve') cmds.parentConstraint(oPathLoc, oStopLoc, cmds.ls('*:Master_Anim')[0])
def attach(up='', reverse=False): # select control and path namespace sel = cmds.ls(sl=True) path = sel[len(sel) - 1] path = path.split(':')[0] + ':path' up = path.split(':')[0] + ':up' print path # remove path from list sel.remove(sel[len(sel) - 1]) i = 0 mlt = 1.0 / len(sel) s = 0.0 e = 0.3 locs = [] for ct in sel: cmds.select(ct) loc = cn.locatorOnSelection(constrain=False) locs.append(loc[0]) min = cmds.playbackOptions(q=True, minTime=True) max = cmds.playbackOptions(q=True, maxTime=True) cmds.parentConstraint(loc, ct, mo=True) # add world up object to path if not reverse: cmds.pathAnimation(loc, c=path, startTimeU=min, endTimeU=max, startU=s, endU=e, follow=True, wut='object', wuo=up) else: cmds.pathAnimation(loc, c=path, startTimeU=min, endTimeU=max, startU=e, endU=s, follow=True, wut='object', wuo=up) i = i + 1 s = s + mlt e = e + mlt cmds.select(clear=True) grp = cmds.group(name='__PATH_GRP__#', em=True) cmds.parent(locs, grp) cmds.select(locs)
def _finalize(self): """ Finalize rig. """ # connect cmds.parent(self.fk_group, self.pos_group) cmds.parentConstraint(self.fk_controls[0], self.dynamic_control) for item in (self.fk_group, self.dynamic_joints[0]): cmds.parentConstraint(self.parent_control, item, mo=True) for count, control in enumerate(self.controls): cmds.parentConstraint(self.dynamic_joints[count], control, mo=True) # connect motion path to prevent flipping cmds.select(cl=True) cmds.select(self.motion_parent) cmds.select(self.curve, add=True) cmds.pathAnimation(su=self.start_frame, eu=self.end_frame) # lock and hide attributes on dynamic control for attr in ATTRS: cmds.setAttr("{0}.{1}".format(self.dynamic_control, attr), l=True, k=False, cb=False) # create metadata self._create_meta_data()
def generateSpider(input_namespace, startTime, endTime): ''' this function attaches all curves together, without replacing the orignal curves, using it as a motion path for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on the controller that appears with the spider rig, controlling the length of its steps as it walks. ''' filePath = cmds.internalVar( usd=True ) + 'SpiderGen/spider.ma' #the file path at which the spider model should exist fileExists = cmds.file(filePath, q=True, ex=True) #queries whether the file exists if fileExists is True: #selects all of the spiralling curves and connects them, providing a 'path' for the spiders movement. cmds.select(str(input_namespace) + 'curve_spiral*') curves = cmds.ls(selection=True) path = cmds.attachCurve(curves, n=str(input_namespace) + 'spiderpath', rpo=False) cmds.rebuildCurve(path, rt=3) cmds.hide(path) cmds.file(filePath, i=True) #renames the spider and it's callable controllers so that they are using the current 'namespace'. cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG') cmds.rename('SCALE_HANDLE', str(input_namespace) + 'CONTROLLER_ScaleMe') cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER') #selects the scale controller and the path and connects them to a path animation. cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path) cmds.pathAnimation(stu=startTime, etu=endTime, f=True, fa='x', ua='y', name=str(input_namespace) + 'motionpath') #creates a command that links the controller rotation to the 'length' of the animation. command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str( input_namespace) + 'motionpath_uValue.output * ' + str( (endTime - startTime) / 10) #creates an expression of that command which is used for moving the legs as the spider moves around the path. cmds.expression(name=str(input_namespace) + 'leg_movement', alwaysEvaluate=True, s=command) else: #an error window for if the file is not found cmds.confirmDialog( title='Error', message='Spider Model not found, please ensure it located at: ' + str(filePath), button=['OK'], cancelButton='OK') return fileExists #so that the grouping functions know not to expect the spider model or motionpath
def nodesAlongCurve(crv=None, numNodes=6, name='', followAxis='x', upAxis='y', upNode=None, upVec=None): ''' creates a motionPath node for each in numNodes and connects its parameter to the supplied curve attaches an empty group to each motionpath node returns a dictionary with keys for the motionPath nodes and the groups along the curve as well as the rootGrp upVec can be passed as an attribute eg translation which worldUpVector of motionpath node can be connected to ''' # Validation of args if not crv: if len(cmds.ls(sl=1)) == 1: crv = cmds.ls(sl=1)[0] else: return common.showDialog( 'Argument Error', 'Please supply or select a nurbs curve' ) upDict = {'x':(1.0, 0.0, 0.0), 'y':(0.0, 1.0, 0.0), 'z':(0.0, 0.0, 1.0)} #rootGrp = cmds.group(empty=1, name='%s_pathNodes_grp' % name) #cmds.setAttr('%s.inheritsTransform' % rootGrp, 0) returnDict={'mpNodes':[], 'grps':[]} for i in range( numNodes ): n = cmds.group(empty=1, name='%s_%s_grp' % (name, i+1)) #cmds.parent(n, rootGrp) mp = cmds.pathAnimation(n, fm=1, f=1, fa=followAxis, ua=upAxis, wu=upDict[upAxis], curve=crv, name='%s_%s_mp' % (name, i+1)) if upNode: cmds.pathAnimation(mp, e=1, wut='objectrotation', wuo=upNode) elif upVec: cmds.connectAttr(upVec, '%s.worldUpVector' % mp) # Delete all the crap that comes with the motion path node mpAnim = cmds.listConnections( '%s.uValue' % mp, d=False, s=True, type='animCurve' ) adlX = cmds.listConnections( '%s.xCoordinate' % mp, d=True, s=False, type='addDoubleLinear' ) cmds.delete(adlX) adlY = cmds.listConnections( '%s.yCoordinate' % mp, d=True, s=False, type='addDoubleLinear' ) cmds.delete(adlY) adlZ = cmds.listConnections( '%s.zCoordinate' % mp, d=True, s=False, type='addDoubleLinear' ) cmds.delete(adlZ) cmds.delete(mpAnim) # Manually connect up the position cmds.connectAttr('%s.xCoordinate' % mp, '%s.tx' % n, f=1) cmds.connectAttr('%s.yCoordinate' % mp, '%s.ty' % n, f=1) cmds.connectAttr('%s.zCoordinate' % mp, '%s.tz' % n, f=1) if numNodes != 1: cmds.setAttr('%s.uValue' % mp, (1.0 / (numNodes-1))*i) else: cmds.setAttr('%s.uValue' % mp, 0.5) returnDict['mpNodes'].append(mp) returnDict['grps'].append(n) return returnDict
def animateCurve(start, finish): """ This function will create an emitter and attach it to a curve with a start and finish animation point. """ #start = mc.intFieldGrp(strnfin,query=True,value1=True) #finish = mc.intFieldGrp(strnfin,query=True,value2=True) curvetoAnimate = mc.ls(selection=True) emitterforAnimation = createEmitter() #mc.select(emitterforAnimation, curvetoAnimate) mc.select(emitterforAnimation, add=True) mc.select(curvetoAnimate, add=True) mc.pathAnimation(stu = start,etu = finish)
def generateSpider(input_namespace, startTime, endTime): ''' this function attaches all curves together, without replacing the orignal curves, using it as a motion path for an animated spider. the animated spider is imported, and a simple expression links the U value of the motion path to a rotation attribute on the spider rig, controlling its walk cycle. there is also a custom attribute on the controller that appears with the spider rig, controlling the length of its steps as it walks. ''' filePath = cmds.internalVar(usd=True) + 'SpiderGen/spider.ma' fileExists = cmds.file(filePath, q=True, ex=True) if fileExists is True: cmds.select(str(input_namespace) + 'curve_spiral*') curves = cmds.ls(selection=True) path = cmds.attachCurve(curves, n=str(input_namespace) + 'spiderpath', rpo=False) cmds.rebuildCurve(path, rt=3) cmds.hide(path) cmds.file(filePath, i=True) cmds.rename('SPIDER_RIG', str(input_namespace) + 'SPIDER_RIG') cmds.rename('SCALE_HANDLE', str(input_namespace) + 'CONTROLLER_ScaleMe') cmds.rename('CONTROLLER', str(input_namespace) + 'CONTROLLER') cmds.select(str(input_namespace) + 'CONTROLLER_ScaleMe', path) cmds.pathAnimation(stu=startTime, etu=endTime, f=True, fa='x', ua='y', name=str(input_namespace) + 'motionpath') command = str(input_namespace) + 'CONTROLLER.rotateX = ' + str( input_namespace) + 'motionpath_uValue.output * ' + str( (endTime - startTime) / 10) cmds.expression(name=str(input_namespace) + 'leg_movement', alwaysEvaluate=True, s=command) else: cmds.confirmDialog( title='Error', message='Spider Model not found, please ensure it located at: ' + str(filePath), button=['OK'], cancelButton='OK') return fileExists
def build(self): self.tangentCrv = rt_curve.TangentCurve(points=cmds.ls(sl=1), name=self.name) self.main_grp = cmds.group(empty=1, name='%s_grp' % self.name) cmds.parent(self.tangentCrv.dnt_grp, self.main_grp) # Ctrls self.ctrls = [] for loc in self.tangentCrv.cv_locs: ctrl = rt_controls.circleBumpCtrl(radius=10, name=loc.replace('loc', 'ctrl'), axis='y') common.align(ctrl, loc, orient=0) cmds.parent(loc, ctrl) cmds.parent(ctrl, self.main_grp) common.insertGroup(ctrl) cmds.addAttr(ctrl, ln='tangentWeight', at="float", minValue=0.0, maxValue=1.0, keyable=1, hidden=0, defaultValue=0.25 ) cmds.connectAttr('%s.tangentWeight' % ctrl, '%s.tangentWeight' % loc) self.ctrls.append(ctrl) # set up stretch blending cmds.addAttr(self.ctrls[-1], ln='stretch', at="float", minValue=0.0, maxValue=1.0, keyable=1, hidden=0, defaultValue=1.0 ) cmds.addAttr(self.ctrls[-1], ln='stretchValue', at="float", keyable=0, hidden=0) info = cmds.createNode('curveInfo', name='%s_crvInfo' % self.name) cmds.connectAttr('%s.worldSpace[0]' % self.tangentCrv.crv, '%s.inputCurve' % info) stretch_md = cmds.createNode('multiplyDivide', name='%s_stretch_md' % self.name) cmds.connectAttr('%s.arcLength' % info, '%s.input2X' % stretch_md) cmds.setAttr('%s.input1X' % stretch_md, cmds.getAttr('%s.input2X' % stretch_md)) cmds.setAttr('%s.operation' % stretch_md, 2) cmds.connectAttr('%s.outputX' % stretch_md, '%s.stretchValue' % self.ctrls[-1]) # Nodes along curve self.pathNodes = rt_curve.nodesAlongCurve(crv=self.tangentCrv.crv, numNodes=self.numCtrls, name=self.name) for i in range(len(self.pathNodes['mpNodes'])): mp = self.pathNodes['mpNodes'][i] if i == 0: cmds.pathAnimation(mp, e=1, wut='objectrotation', wuo=self.ctrls[0]) else: cmds.pathAnimation(mp, e=1, wut='objectrotation', wuo=self.pathNodes['grps'][i-1]) # Add stretching functionality blend = cmds.createNode('blendTwoAttr', name=mp.replace('mp', 'stretch_blend')) cmds.connectAttr('%s.stretch' % self.ctrls[-1], '%s.attributesBlender' % blend) uc = cmds.createNode('unitConversion', name=mp.replace('mp', 'stretch_uc')) cmds.connectAttr('%s.stretchValue' % self.ctrls[-1], '%s.input' % uc) cmds.setAttr('%s.conversionFactor' % uc, cmds.getAttr('%s.uValue' % mp)) cmds.connectAttr('%s.output' % uc, '%s.input[0]' % blend) cmds.setAttr('%s.input[1]' % blend, cmds.getAttr('%s.uValue' % mp)) cmds.connectAttr('%s.output' % blend, '%s.uValue' % mp) cmds.parent(self.pathNodes['grps'][i], self.tangentCrv.dnt_grp)
def createPathLocators(*argv): counter = '' if len(cmds.ls('pathLocator?',type='transform')) > 0: counter = len(cmds.ls('pathLocator?',type='transform'))+1 print counter oPathLoc = cmds.spaceLocator(n='pathLocator'+str(counter)) oStopLoc = cmds.spaceLocator(n='stopLocator'+str(counter)) oPathLocGrp = cmds.group(oPathLoc,n='pathLocatorGrp'+str(counter)) oStopGrp = cmds.group(oStopLoc,n='stopLocatorGrp'+str(counter)) counter = '' if len(cmds.ls('pathCurve?',l=True)) > 0: counter = len(cmds.ls('pathCurve?',l=True)) cmds.pathAnimation( oPathLocGrp, stu=0, etu=1000, fa='x', ua='y', bank=True, fm = True,c=('pathCurve' + str(counter)) ) cmds.parentConstraint(oPathLoc,oStopLoc,cmds.ls('*:Master_Anim')[0]) cmds.setAttr(cmds.ls('Master_Anim_parentConstraint*',l=True)[0] + '.stopLocatorW1',0)
def createJntAlongCurve(): curveSelected = mc.ls(s1 = True)[0] jointAmount = mc.IntField(jntAmountIF, q = True, v = True) previousJnt = "" rootJnt = "" for i in range(0, jointAmount): mc.select(c1 = True) newJnt = mc.joint() mothionPath = mc.pathAnimation( newJnt, c = curveSelected, fractionMode = True ) mc.cutKey(mothionPath + ".u", time = ()) mc.setAttr(mouthPath + ".u", i * (1.0/(jointAmount -1))) mc.delete(newJnt + ".tx", icn = True) mc.delete(newJnt + ".ty", icn = True) mc.delete(newJnt + ".tz", icn = True) mc.delete(mothionPath) if i == 0: previousJnt = newJnt rootJnt = newJnt continue mc.parent(newJnt, previousJnt) previousJnt = newJnt
def CreatJntAlngCrv(): selCrv = cmds.ls(sl=1, type='transform') Name = cmds.textFieldGrp(NameTextFG, q=1, tx=1) IKCtlAmnt = cmds.intSliderGrp(IKCtlintSG, q=1, v=1) JntNum = cmds.intSliderGrp(JntNumintSG, q=1, v=1) jntAmnt = (JntNum * (IKCtlAmnt - 1)) + 1 for k in selCrv: cmds.setAttr(k + '.visibility', 0) cmds.rebuildCurve(k, ch=0, rpo=1, rt=0, end=1, kr=1, kcp=0, kep=1, kt=0, s=jntAmnt - 1, d=3, tol=0.01) ## Rebuild Crv ## preJnt = "" rootJnt = "" for x in range(len(selCrv)): for i in range(0, jntAmnt): cmds.select(cl=True) newJnt = cmds.joint(n=Name + str(x + 1) + '_joint1') motionPath = cmds.pathAnimation(newJnt, c=selCrv[x], fractionMode=True) cmds.cutKey(motionPath + ".u", time=()) cmds.setAttr(motionPath + ".u", i * (1.0 / (jntAmnt - 1))) cmds.delete(newJnt + ".tx", icn=True) cmds.delete(newJnt + ".ty", icn=True) cmds.delete(newJnt + ".tz", icn=True) cmds.delete(motionPath) if i == 0: preJnt = newJnt rootJnt = newJnt continue cmds.parent(newJnt, preJnt) preJnt = newJnt cmds.joint(rootJnt, e=True, oj="xyz", sao="yup", ch=True, zso=True) # ---- Orient Joint----# selJnt = cmds.ls(Name + "*_joint1", type='joint') for a in range(len(selCrv)): # ---- Orient the End Joint----# # print a, SelHi_(selJnt)[a][-1] endJnt = SelHi_(selJnt)[a][-1] cmds.joint(endJnt, e=1, oj="none", ch=1, zso=1)
def sweepPipe(circle, pipeCurve): numberOfCVs = cmds.getAttr('%s.cp' % pipeCurve[0], size=1) motionPath = cmds.pathAnimation("%s" % circle[0], curve=pipeCurve[0], follow=True, startTimeU=1, endTimeU=numberOfCVs) cmds.selectKey("%s.uValue" % motionPath) cmds.keyTangent( itt="linear", ott="linear") pipeSweep = cmds.snapshot(circle, startTime=1, endTime=numberOfCVs) return pipeSweep
def doReplicate(): the_name = cmd.textFieldGrp("name", query=True, text=True) the_incr = cmd.floatSliderGrp("incr", query=True, value=True) selection = cmd.ls(selection=True, long=True) element = selection[0] curve = selection[1] # Build motion path the_motion_path = cmd.pathAnimation(element, curve=curve, fractionMode=True, follow=True, followAxis="z", upAxis="y", startTimeU=1, endTimeU=100) # Flat animation curves cmd.keyTangent(the_motion_path, inTangentType="linear", outTangentType="linear") # Create animation snapshot the_snapshot = cmd.snapshot(element, name=the_name, endTime=100, increment=the_incr)
def getPointOnCurve(crv, parameter, inverse=0): """ Gets position and rotation of point on curve using motion path """ poc_loc = cmds.spaceLocator(name='Poc_Temp_Loc') mPath_Crv = cmds.duplicate(crv, name='mPath_Temp_Crv')[0] cmds.delete(mPath_Crv, ch=1) mPath = cmds.pathAnimation(poc_loc, mPath_Crv, n='mPath_Temp', fractionMode=1, followAxis='x', upAxis='y', worldUpType="vector", inverseUp=inverse, inverseFront=inverse) cmds.disconnectAttr(mPath + '_uValue.output', mPath + '.uValue') cmds.setAttr(mPath + '.uValue', parameter) tr = cmds.xform(poc_loc, q=1, t=1) rt = cmds.xform(poc_loc, q=1, ro=1) point = [] point.append(tr) point.append(rt) cmds.delete(mPath + '_uValue', mPath, poc_loc, mPath_Crv) # point = [[t.x, t.y, t.z], [r.x, r.y, r.z]] return point
def __init__(self, curve, objects, pointsCount, useTips = False, keepConnected = True, tangent = False,rand = False, groupit = False, animated = False ): """creates objects allong curve, curve: Curve Class object that handles the curve objects: Array of one o more transforms objects to position allong curve pointsCount: Amount of points in the curve useTips: is to position objects in the curve keepConnected: Keep pointOnCurveInfo connected between transform and curve tangent: Manage rotation on objects also rand: Place the objects in random order animated: Add speed attribute to move objects along curve""" self._nodes = [] self._curve = curve if useTips: val = -1 else: val = 1 startParam = 1.0 / ( pointsCount + val ) param = 0 objsIter = it.bicycle( objects ) grp = mn.Node( curve.name + '_grp' ) if groupit: grp = mn.Node( mc.group( n = grp.name, em = True ) ) if animated: grp.a.laps.add( k = True ) with undo.Undo(): for p in range( pointsCount ): #place transform in param point if not useTips: param += startParam if rand: baseobj = random.choice( objects ) else: baseobj = objsIter.next() obj = baseobj.duplicate() self._nodes.append( obj ) if groupit: obj.parent = grp pcurveNode = mn.Node( mc.pathAnimation( obj.name, su=0.5, c=curve.name, fm = True, follow=tangent, followAxis = 'z', upAxis = 'y', worldUpType = 'object', worldUpObject = curve.parent.name ) ) animCurve = pcurveNode.a.uValue.input.node animCurve.delete() if keepConnected: obj.a.parameter.add( k = True ) obj.a.parameter.v = param obj.a.parameter.min = 0 obj.a.parameter.max = 1 obj.a.parameter >> pcurveNode.a.uValue else: if param > 1.0: param = 1 pcurveNode.a.uValue.v = param t = obj.a.t.v r = obj.a.r.v pcurveNode.delete() obj.a.t.v = t[0] obj.a.r.v = r[0] if useTips: param += startParam if animated: cmd = obj.a.parameter.fullname + ' = ( abs( ' + str( obj.a.parameter.v ) + ' + ' + grp.a.laps.fullname + ' ) ) % 1;' mc.expression( s=cmd )
def pathFollow (curve , control, objectArray, NameConv = None): if not NameConv: NameConv = RMNameConvention.RMNameConvention() controlAttr = cmds.listAttr(control) if "Percent" not in controlAttr: cmds.addAttr(control,at="float", ln = "Percent", h = 0, k = 1) if "Stretch" not in controlAttr: cmds.addAttr(control,at="float", ln = "Stretch", hnv = 1, hxv = 0, h = 0, k = 1, smn = 0) numberOfElements = len(objectArray) sumPath = [] multiplyDivide = [] index = 0 for eachObject in objectArray: motionPath = cmds.pathAnimation(eachObject, c = curve , follow = True , worldUpType = "scene", name = "motionpath%s"%index) motionPath = NameConv.RMRenameNameInFormat(motionPath) multDivFactor = cmds.shadingNode('multiplyDivide', asUtility = True, name = "factor%s"%index) multDivFactor = NameConv.RMRenameNameInFormat(multDivFactor) cmds.connectAttr("%s.Stretch"%control ,"%s.input1X"%multDivFactor) cmds.setAttr("%s.input2X"%multDivFactor, float(index)/float(len(objectArray))) cmds.setAttr("%s.operation"%multDivFactor, 1) multiplyDivide.append(multDivFactor) addition = cmds.shadingNode('plusMinusAverage', asUtility = True, name = "Addition%s"%index) addition = NameConv.RMRenameNameInFormat(addition) cmds.connectAttr("%s.outputX"%multDivFactor ,"%s.input1D[0]"%addition) cmds.connectAttr("%s.Percent"%control ,"%s.input1D[1]"%addition) cmds.connectAttr("%s.output1D"%addition,"%s.uValue"%motionPath, force = True) index+=1
def get_point_on_curve(crv, parameter, inverse=0): """ Gets position and rotation of point on curve using motion path :param crv: :param parameter: :param inverse: :return translation and rotation list: """ poc_loc = cmds.spaceLocator(name='Poc_Temp_Loc') m_path_crv = cmds.duplicate(crv, name='mPath_Temp_Crv')[0] cmds.delete(m_path_crv, ch=1) m_path = cmds.pathAnimation(poc_loc, m_path_crv, n='mPath_Temp', fractionMode=1, followAxis='x', upAxis='y', worldUpType='vector', inverseUp=inverse, inverseFront=inverse) cmds.disconnectAttr(m_path + '_uValue.output', m_path + '.uValue') cmds.setAttr(m_path + '.uValue', parameter) tr = cmds.xform(poc_loc, q=1, t=1) rt = cmds.xform(poc_loc, q=1, ro=1) point = [tr, rt] cmds.delete(m_path + '_uValue', m_path, poc_loc, m_path_crv) # point = [[t.x, t.y, t.z], [r.x, r.y, r.z]] return point
def createJointAlongCurve(curve, jointCount=2, jointName=''): joints = [] if cmds.objExists(curve): if jointCount < 2: jointCount = 2 preParent = None for i in range(0, jointCount): cmds.select(cl=True) if jointName == '': curJoint = cmds.joint() else: curJoint = cmds.joint(n=jointName + str(i)) motionPath = cmds.pathAnimation(curJoint, c=curve, fractionMode=True) cmds.cutKey(motionPath + '.u', time=()) cmds.setAttr(motionPath + '.u', i * (1.0 / (jointCount - 1))) cmds.delete(curJoint + '.tx', icn=True) cmds.delete(curJoint + '.ty', icn=True) cmds.delete(curJoint + '.tz', icn=True) cmds.delete(motionPath) if preParent: cmds.parent(curJoint, preParent) preParent = curJoint joints.append(curJoint) cmds.joint(joints[0], e=True, oj='xyz', sao='yup', ch=True, zso=True) else: cmds.warning('Cannot find curve:' + curve) return joints
def buildGuideSpline(self): cPoints = [] for marker in self.totalMarkerList: markerPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) cPoints.append(markerPos) nameStart = nameBase(self.totalMarkerList[0].getName(), self.searchString, "loc", "cv") guideSplineName = nameStart + "ribbonGuideSpline" self.guideSpline = cmds.curve(editPoint = cPoints, degree=3, name=guideSplineName) #Need to add Naming Convention here self.tempGuideParts.append(self.guideSpline) for i, marker in enumerate(self.totalMarkerList): locPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) newPara = cmds.closestPointOnCurve(self.guideSpline, ip=locPos, paramU=True) newParaVal = cmds.getAttr(newPara + ".paramU") cmds.delete(newPara) # print "new ParaVal : ", newParaVal ##Now Create a new Locator and add it to the precise parameter position nameStart = nameRebuild(marker.getName(), self.searchString, "loc", "loc",nameAddition = "tempRibbonGuide") newAlignedLoc = cmds.spaceLocator(name = nameStart) # guideSplineName = nameStart + "ribbonGuideSpline" #Need naming convention self.tempGuideParts.append(newAlignedLoc[0]) mPath = cmds.pathAnimation(newAlignedLoc, follow=True, c=self.guideSpline) uAnimNode = cmds.listConnections(mPath + ".uValue", source=True) cmds.delete(uAnimNode) cmds.setAttr(mPath + ".uValue", newParaVal) self.totalMarkerList[i].setAlignedMarker(newAlignedLoc[0]) self.totalMarkerList[i].setUParameter(newParaVal)
def motionPath(itemList, curvePath, upObject, frontAxis, invertFront, upAxis, invertUp, cycleAttributeName): attributeList = [cycleAttributeName, 'frontTwist', 'upTwist', 'sideTwist'] for attr in attributeList: if not ma.objExists(upObject + '.' + attr): ma.addAttr(upObject, ln=attr, at='double') ma.setAttr(upObject + '.' + attr, e=1, k=1, cb=0) #calculate current sceneUnitMultiplier sceneUnitDict = { 'cm': 1.0, 'mm': 10.0, 'm': 0.01, 'km': 9.999969839999708e-6, 'in': 0.393701, 'ft': 0.0328083, 'yd': 0.0109361, 'mi': 6.213693181818e-6 } sceneUnitMultiplier = sceneUnitDict.get(ma.currentUnit(l=1, q=1)) offset = 1.0 / float(len(itemList)) if len(itemList) > 1 else 0.5 for i in range(0, len(itemList)): #create motionpath path = ma.pathAnimation(itemList[i], c=curvePath, n=itemList[i] + '_' + pathSuffix, fm=1, f=1, fa=frontAxis, ua=upAxis, wut='object', wuo=upObject, iu=invertUp, inverseFront=invertFront, b=0) ma.cutKey(path) driven = path + '.' + 'uValue' #setDrivenKeys ma.setDrivenKeyframe(driven, cd=upObject + '.' + attributeList[0], dv=i * offset, v=0, itt='linear', ott='linear') ma.setDrivenKeyframe(driven, cd=upObject + '.' + attributeList[0], dv=(i * offset) + 1, v=sceneUnitMultiplier, itt='linear', ott='linear') ma.setInfinity(driven, pri='cycle', poi='cycle') for attr in attributeList: if attr != attributeList[0]: ma.connectAttr(upObject + '.' + attr, path + '.' + attr) #cleanup convertDoubleLinear(path)
def dynChain(direction): geomlist=cmds.ls(sl=1) sortlist={} sortedgeom=[] curvepnts=[] #dicoloc={} dicojnt={} jntlist=[] sortlistpointcurve={} mycurvedefinition='curve -d 3' if cmds.objExists('locs')== 0: cmds.group(em=1,n='locs') if cmds.objExists('jnts')== 0: cmds.group(em=1,n='jnts') for each in geomlist: cmds.xform(each,cp=1) translations=cmds.xform(each,q=1,ws=1,rp=1) cmds.xform(each,t=(translations[0]*-1,translations[1]*-1,translations[2]*-1)) cmds.makeIdentity(each,a=1) cmds.xform(each,t=(translations[0],translations[1],translations[2])) sortlist[translations[direction]]=each sortlistpointcurve[translations[direction]]=str(translations) sortedlist=sorted(sortlist) sortedcoords=sorted(sortlistpointcurve) for each in sortedcoords: curvepnts.append(sortlistpointcurve[each]) for each in sortedlist: sortedgeom.append(sortlist[each]) for each in curvepnts: mycurvedefinition+=' -p '+each mycurvedefinition = mycurvedefinition.translate(None, '[],') mycurve=mel.eval(mycurvedefinition) for each in sortedgeom: cmds.select(each) jnt=cmds.joint(n=each.replace('geom_','jnt_')) jntlist.append(jnt) #loc=cmds.spaceLocator() #cmds.parent(loc,jnt,r=1) #cmds.parent(loc,'locs') cmds.parent(jnt,'jnts') #cmds.parentConstraint(loc,jnt,mo=0) #tupple=(each,jnt) dicojnt[jnt]=each #dicoloc[loc[0]]=jnt cmds.select(pouet) mel.eval('makeCurvesDynamic 2 { "0", "0", "1", "1", "0"}') myfol=cmds.listConnections(mycurve) myfolshape=cmds.listRelatives(myfol) outfol=cmds.listConnections(myfolshape[0],d=1) for each in jntlist: motionpathname=cmds.pathAnimation(each,c=outfol[-1],fm=0, f=1, fa='x', ua='z',wut= "object", wu=( 0 ,0 ,1)) uvalue= float(jntlist.index(each)-1) mel.eval('source generateChannelMenu.mel;') cmds.delete(motionpathname+'_uValue') cmds.setAttr(motionpathname+'.uValue',uvalue) for each in dicojnt: cmds.skinCluster(each, dicojnt[each],tsb=1)
def matchPathToKeyframes(targets,origCurves,start=False,end=False,increment=1): # match a path animation as closely as possible to original keyframed animation. # duplicate curve and loft into a surface. # create locator at target's pivot. attach to original curve. # create pointOnSurfaceInfo, use lofted surface.create as input, use locatorShape.worldPosition as reference pos. # per each increment, find the result.u of the pointOnSurfaceInfo, then set the motion path uValue to this value. # return motion path. if not start: start = cmds.playbackOptions(q=1,min=1) if not end: end = cmds.playbackOptions(q=1,max=1) pointOnSurfaces = [] motionPaths = [] surfaces = [] dupeCurves = [] newLocs = [] outLocs = [] for k,i in enumerate(targets): origShape = cmds.listRelatives(origCurves[k],s=1)[0] dupeCurve = cmds.duplicate(origCurves[k])[0] dupeShape = cmds.listRelatives(dupeCurve,s=1)[0] origTy = cmds.getAttr(dupeCurve+'.ty') origDeg = cmds.getAttr(dupeShape+'.degree') cmds.setAttr(dupeCurve+'.ty',origTy+0.001) loft = cmds.loft(origShape,dupeShape,po=0,d=origDeg) surface = cmds.listConnections(loft,type='nurbsSurface')[0] newLoc = cmds.spaceLocator()[0] newLocShape = cmds.listRelatives(newLoc,s=1)[0] cmds.pointConstraint(i,newLoc) pointOnSurface = cmds.createNode('closestPointOnSurface') cmds.connectAttr(newLocShape+'.worldPosition',pointOnSurface+'.inPosition') cmds.connectAttr(surface+'.create',pointOnSurface+'.inputSurface') outLoc = cmds.spaceLocator()[0] motionPath = cmds.pathAnimation(outLoc,c=origCurves[k],stu=start,etu=end) cmds.cutKey(motionPath,cl=1,time=(0,9999999),at='uValue') pointOnSurfaces.append(pointOnSurface) motionPaths.append(motionPath) surfaces.append(surface) dupeCurves.append(dupeCurve) newLocs.append(newLoc) outLocs.append(outLoc) # for each frame, check pointOnSurface.result.u and key motionPath.uValue to match for f in range(start,end,increment): cmds.currentTime(f) for k,i in enumerate(targets): u = cmds.getAttr(pointOnSurfaces[k]+'.result.v') if u == 1.0: u = 0.999999 cmds.setKeyframe(motionPaths[k],at='uValue',v=u) # cleanup cmds.delete(surfaces) cmds.delete(dupeCurves) cmds.delete(pointOnSurfaces) cmds.delete(newLocs) return outLocs
def addBlossMesh(self): for blossCurve in self.allBlossCurves: #Names trunk startIdx = len("blossom_curve_") blossMesh = "blossom_" + blossCurve[startIdx:] + "_" + str( self.blossVal) #Adds blossom mesh #import os #pathVar = os.path.dirname(__file__) # This stores the current working directory #cmds.file( pathVar+"/blossom_geo.mb", i=True ) #bloss_file = cmds.file( pathVar+"/lotus_OBJ_low.obj", i=True ) #cmds.rename( "polySurface1", blossMesh ) cmds.duplicate(self.blossMesh, name=blossMesh) # Places the blossom to the right position and rotates it according to the last branch orientation cmds.select(blossMesh) yMax = cmds.xform( boundingBox=True, q=True)[4] #values returned as: xmin ymin zmin xmax ymax zmax scale = [self.length / yMax for i in range(3)] cmds.select(clear=True) cmds.select(blossMesh) cmds.scale(0.5 * scale[0], 0.5 * scale[1], 0.5 * scale[2]) #move polygon to branch end and align with normal cmds.select(clear=True) cmds.select(blossMesh, tgl=True) points = cmds.getAttr(blossCurve + '.cv[0:2]') start = points[0] cmds.move(start[0], start[1], start[2]) cmds.select(clear=True) cmds.select(blossMesh, tgl=True) cmds.select(blossCurve, add=True) cmds.pathAnimation(follow=True, followAxis='y', upAxis='z', startTimeU=True) self.allBlossoms.append(blossMesh) cmds.parent(blossMesh, self.blossGroup)
def create_turntable(self): """Automatically creates 360 degree turntable with lights relative to object size""" # Creates object selection which selects current object in panel view objectSelection = cmds.ls(sl=True) bBox = cmds.exactWorldBoundingBox(objectSelection) objectDistance = cmds.shadingNode('distanceBetween', asUtility=True) locator1 = cmds.spaceLocator() locatorShape1 = cmds.listRelatives(locator1[0], shapes=True) locator2 = cmds.spaceLocator() locatorShape2 = cmds.listRelatives(locator2[0], shapes=True) #Creates ground cylinder for selected object. objectGround = cmds.polyCylinder(axis=[0, 1, 0], height=bBox[4] / 10.0, radius=bBox[3] * 2.5, subdivisionsX=30, subdivisionsZ=1, n='turntableGround') cmds.setAttr(objectGround[0] + '.translateY', bBox[1] - (bBox[4] / 10.0) / 2) cmds.parent(locator2[0], objectSelection[0]) cmds.setAttr(locator1[0] + '.translateX', 0) cmds.setAttr(locator1[0] + '.translateY', 0) cmds.setAttr(locator1[0] + '.translateZ', 0) cmds.setAttr(locator2[0] + '.translateX', 0) cmds.setAttr(locator2[0] + '.translateY', 0) cmds.setAttr(locator2[0] + '.translateZ', 0) cmds.connectAttr(locatorShape1[0] + '.worldPosition', objectDistance + '.point1') cmds.connectAttr(locatorShape2[0] + '.worldPosition', objectDistance + '.point2') #Creates nurb circle for the turntable and adjusts position based on object selected. cameraCircle = cmds.circle(radius = bBox[3] * 9, sections = 50) cmds.setAttr(cameraCircle[0] + '.rotateX', 90) cmds.reverseCurve(cameraCircle[0]) cmds.setAttr(cameraCircle[0] + '.translateY', bBox[1] - (bBox[4] / 10.0) / 2) cmds.select(cameraCircle, r=True) cmds.move(0, 5, 0) #Creates turntable camera and groups the camera, circle, and ground. cmds.camera(n='turntableCamera') cmds.group('nurbsCircle1', 'turntableCamera1', 'turntableGround', n='cameraSetup') # Creates a path animation based on the objects 'turntableCamera1' and 'cameraCircle' cmds.pathAnimation('turntableCamera1', cameraCircle[0], fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, inverseFront=False, bank=False, startTimeU=1, endTimeU=120) cmds.delete('locator1', 'locator2')
def attachToMotionpath(obj, crv, crv_param, obj_up): obj = obj crv = crv crv_param = crv_param/8.0 obj_up = obj_up if obj_up: mpath = mc.pathAnimation( obj, c=crv, fractionMode = True, follow = True, followAxis = "x", upAxis = "y", worldUpType = "object", worldUpObject = obj_up, inverseUp = False, inverseFront = False, bank = False, startTimeU = 1, endTimeU = 1 ) else: mpath = mc.pathAnimation( obj, c=crv, fractionMode = True, follow = True, followAxis = "x", upAxis = "y", worldUpType = "scene", inverseUp = False, inverseFront = False, bank = False, startTimeU = 1, endTimeU = 1 ) #break the motions path's time values and set to crv_param mc.delete(mpath+"_uValue") tmp_value = (mpath+".uValue") mc.setAttr(tmp_value, crv_param)
def addTrunkMesh(self): for curve in self.allBranchCurves: #Names trunk startIdx = len(self.name) + len("_curve_") trunkName = self.name + "_trunk_" + curve["name"][startIdx:] #Creates cylinder and moves it to the origin pt cmds.polyCylinder(name=trunkName, subdivisionsX=20, subdivisionsY=1, r=curve["baseRad"]) cmds.move(-1, trunkName + ".scalePivot", trunkName + ".rotatePivot", moveY=True, relative=True) #move polygon to start and align with normal cmds.select(clear=True) cmds.select(trunkName, tgl=True) cmds.select(curve["name"], add=True) cmds.pathAnimation(follow=True, followAxis='y', upAxis='z', startTimeU=True) #Selects the face to scale and extrude cmds.select(clear=True) cmds.select(trunkName + ".f[26]") #get Scale of decreased radius scale = [curve["tipRad"] / curve["baseRad"] for i in range(3)] #extrudes along curve cmds.polyExtrudeFacet(inputCurve=curve["name"], d=1, localScale=scale) cmds.parent(trunkName, self.trunkGroup) self.allTrunks.append(trunkName)
def createSpiralCurve(self, baseCurve, numRounds, radius, profileScale): surfaceCV = float(numRounds+2)*(float(numRounds+2)/2.0) # duplicate curve and get the maxValue cmds.select(baseCurve, r=True) curveMaxValue = cmds.getAttr(baseCurve+".maxValue") cmds.rebuildCurve(ch=0, rpo=1, rt=0, end=1, kr=2, kcp=0, kep=1, kt=0, s=0, d=3) # create a circle profile profile = cmds.circle(nr=[0, 1, 0], c=[0, 0, 0], r=radius) # put it at the start of the baseCurve cmds.pathAnimation(profile, fm=True, f=True, fa="y", ua="x", wut=4, wu=[0, 1, 0], c=baseCurve) # extrude the profile extrudesurface = cmds.extrude(profile[0], baseCurve, et=2, sc=profileScale) # curve on surface curveonsurface = cmds.curveOnSurface(extrudesurface, append=False, uv=(0, 0)) y = 0.0 for i in range(int(surfaceCV)): y += curveMaxValue/surfaceCV x = math.fmod(y*2*surfaceCV/curveMaxValue, 8) #print x, y cmds.curveOnSurface(curveonsurface, append=True, uv=(x, y)) # duplicate the created curve cmds.duplicateCurve(ch = False) cmds.rename("duplicated_"+baseCurve) spiralCurve = cmds.ls(sl = True) cmds.rebuildCurve(ch=0, rpo=1, rt=0, end=1, kr=2, kcp=0, kep=1, kt=0, s=0, d=3) # create wire #cmds.wire(spiralCurve, dds = [(0, 100)], gw = True, en = 1.0, ce = 0.0, li = 0.0, w = baseCurve) #cmds.pickWalk(d = "up") cmds.select(spiralCurve, r = True) arcCurveGroup = cmds.group(n = "spiralCurveWire"+baseCurve+"___GRP") #delete unused nodes cmds.delete(profile) cmds.delete(extrudesurface[0]) #print "spiral curve created." return spiralCurve, arcCurveGroup
def pathMode(path): nameBuilder_locator = path + "_loc" nameBuilder_joint = path + "_jnt" locatorList = [] for p in range(1, pointsNumber): if p == 1: locator = cmds.spaceLocator(n=nameBuilder_locator + str(p)) motionPath = cmds.pathAnimation(locator[0], c=path, f=True) deleteConnection(motionPath + '.u') cmds.setAttr(motionPath + '.uValue', 0) locatorList.append(locator[0]) #joint locator = cmds.spaceLocator(n=nameBuilder_locator + str(p)) motionPath = cmds.pathAnimation(locator[0], c=path, f=True) deleteConnection(motionPath + '.u') cmds.setAttr(motionPath + '.uValue', spacing * p) locatorList.append(locator[0]) #joint # -gruppa i locator return locatorList
def emitCurve(sourceCurve,curveStart,duration,particleList,maxDistance,minDistance,emitTime,lifeTime,lifeTimeVar,fadeOut,turbulenceAmp,turbulencePer,drift): ''' Emits particles from a curve sourceCurve : Name of the curve particles will emit from curveStart : Frame to start emission duration : Number of frames to emit for particleList : List containing names of all the particles to be animatied maxDistance : Maximum distance particles will be emitted from at the middle of the curve minDistance : Maximum distance particles will be emitted from at the start and end of the curve emitTime : Number of frames particles will be affected by the emission force lifeTime : Average lifetime of a particle lifeTimeVar : Variation from average lifetime as a percentage fadeOut : Number of frames to scale down particles at the end of their lifetime turbulenceAmp : Amplitude of the turbulence animation graph turbulencePer : Period of the turbulence animation graph drift : Distance a particle will drift 10 frames. Contains (x,y,z) Updates the progress window and assigns all the elements in particleList to the class particles. Creates a locator and keys it to follow the curve linearly over the emission time. At the emit time, copies the coordinates of the locator and moves particle to that location and add a random rotation. The distance is calculated depending on the time the particle is emitted. Runs the relevant class specific procedures to animate the particle. ''' cmds.progressWindow(e=1,progress=0,status='Animating Particles...') for i in range(0,len(particleList)): particleList[i]=particles(particleList[i]) count=0 [emitter] = [cmds.spaceLocator(n='emitter')[0]] motionPath = cmds.pathAnimation(fm=1, stu=curveStart,etu=curveStart+duration,c=sourceCurve) cmds.keyTangent(motionPath,at='uValue',itt='Linear',ott='Linear') for x in particleList: launchTime=random.uniform(0,duration) [(emitX,emitY,emitZ)]=cmds.getAttr(emitter+'.translate',t=curveStart+launchTime) cmds.move(emitX,emitY,emitZ,x.name) cmds.rotate(random.uniform(0,360),random.uniform(0,360),random.uniform(0,360),x.name) if launchTime/duration <=0.5: distance=(launchTime/duration)*2*(maxDistance-minDistance)+minDistance else: distance=(1-(launchTime/duration))*2*(maxDistance-minDistance)+minDistance x.born = int(curveStart+launchTime+random.randint(-1,1)) x.explode(x.born,emitTime,distance) x.drift(x.born,drift,turbulenceAmp*random.random(),turbulencePer+random.randint(-2,2)) x.lifeTime=int(lifeTime+random.uniform(-lifeTime*lifeTimeVar*0.01,lifeTime*lifeTimeVar*0.01)) x.fadeOut=random.randint(fadeOut-2,fadeOut+2) x.bake() cmds.keyframe(x.name,at='visibility',a=1,vc=0) count+=1 cmds.progressWindow(e=1,progress=int((100.0/len(particleList))*count)) for x in particleList: x.birth() x.death() return
def attach(up='', reverse=False): # select control and path namespace sel = cmds.ls(sl=True) path = sel[len(sel) - 1] path = path.split(':')[0] + ':path' # remove path from list sel.remove(sel[len(sel) - 1]) i = 0 mlt = 1.0 / len(sel) s = 0.01 e = 0.3 locs = [] for ct in sel: cmds.select(ct) loc = cn.locatorOnSelection(constrain=False, X=8) locs.append(loc[0]) min = cmds.playbackOptions(q=True, minTime=True) max = cmds.playbackOptions(q=True, maxTime=True) cmds.parentConstraint(loc, ct, mo=True) # add world up object to path if not reverse: m = cmds.pathAnimation(loc, c=path, startTimeU=min, endTimeU=max, startU=s, endU=e, follow=True, wut='object', wuo=up) else: m = cmds.pathAnimation(loc, c=path, startTimeU=min, endTimeU=max, startU=e, endU=s, follow=True, wut='object', wuo=up) # parametric off cmds.setAttr(m + '.fractionMode', True) # fix value for parametric off option crv = cmds.findKeyframe(m, c=True)[0] frm = cmds.keyframe(crv, q=True) cmds.keyframe(crv, vc=s, time=(frm[0], frm[0])) cmds.keyframe(crv, vc=e, time=(frm[1], frm[1])) # i = i + 1 s = s + mlt e = e + mlt cmds.select(clear=True) grp = cmds.group(name='__PATH_GRP__#', em=True) cmds.parent(locs, grp) cmds.select(locs) return locs
def joint2Curve(prefix, partName, curve, numJnt=2, addSlaveAttr=True, zeroRot=True): """ create joints along the curve :param prefix: str, prefix of the joint :param partName: str, rig part name of the joint :param curve: str, along the curve :param numJnt: int, number of the joints :param addSlaveAttr: bool, whether add slave joint attr :param zeroRot: bool, whether zero the rotation of the joint :return: list(str), return the create joint list """ if numJnt < 2: cmds.error('The numJnt must be larger than 2!') return eachADD = 1.0 / (len(range(numJnt)) - 1) jointList = [] cmds.select(cl=1) for i in range(numJnt): newJnt = createJoint(prefixName=prefix + partName, jointNum=str(i), slaveAttr=addSlaveAttr) motionPath = cmds.pathAnimation(curve, newJnt, n=prefix + partName + '_motionPath', fractionMode=1, follow=1, followAxis='x', upAxis='z', worldUpType='scene', inverseUp=0, inverseFront=0, bank=0) cmds.cutKey(motionPath + '.u', time=()) cmds.setAttr(motionPath + '.uValue', eachADD * float(i)) for attr in ['t', 'r']: for axis in ['x', 'y', 'z']: cmds.delete(newJnt + '.%s%s' % (attr, axis), icn=1) cmds.delete(motionPath) cmds.select(cl=1) jointList.append(newJnt) if zeroRot: cmds.setAttr(newJnt + '.r', 0, 0, 0) return jointList
def attachToMotionPath(nodeName, curveName, mopName, uValue): """ Simple function to attach a node in a motion path curve. Sets the u position based to given uValue. Returns the created motion path node. """ moPath = cmds.pathAnimation(nodeName, curve=curveName, fractionMode=True, name=mopName) cmds.delete( cmds.listConnections(moPath + ".u", source=True, destination=False)[0]) cmds.setAttr(moPath + ".u", uValue) return moPath
def RMJointsOnCurve(self, JointNumber,curve = None, JointUpNodeMode = "single", UpVectorArray = None, UpVectorType = "object"): ''' JointUpNodeMode : valid values are "single","multiShape" UpVectorType : valid values are "object","array","world" ''' degree = cmds.getAttr (curve+".degree") spans = cmds.getAttr (curve+".spans") form = cmds.getAttr (curve+".form") # Form (open = 0, closed = 1, periodic = 2) UpVectorObject = None if UpVectorType == "object": UpVectorObject = cmds.group(empty=True,name = self.NameConv.RMUniqueName ("Character_MD_UpVector_grp_rig")) jointArray=[] for Num in range(0,JointNumber): cmds.select(cl=True) Newjoint = cmds.joint(name = self.NameConv.RMUniqueName ("Character_MD_LaceJoint_jnt_rig")) jointArray.append(Newjoint) step = 0.0 if form == 0 or form ==1: step = float(spans) / (JointNumber-1) else: step = float(spans) /(JointNumber) jointCount = 0 for eachJoint in jointArray: if UpVectorType=="world": motionPath = cmds.pathAnimation(eachJoint, c = curve , follow = True , worldUpType = "scene") elif UpVectorType == "object": motionPath = cmds.pathAnimation(eachJoint, c = curve , follow = True , worldUpObject = UpVectorObject , worldUpType = "objectrotation") elif UpVectorType == "array": motionPath = cmds.pathAnimation(eachJoint, c = curve , follow = True , worldUpObject = UpVectorArray[jointCount] , worldUpType = "object") cmds.setKeyframe (motionPath , v = (step * jointCount) , at = "uValue") jointCount+=1 return {"Joints":jointArray,"UpVector":UpVectorObject}
def pathFollow(curve, control, objectArray, NameConv=None): if not NameConv: NameConv = nameConvention.NameConvention() controlAttr = cmds.listAttr(control) if "Percent" not in controlAttr: cmds.addAttr(control, at="float", ln="Percent", h=0, k=1) if "Stretch" not in controlAttr: cmds.addAttr(control, at="float", ln="Stretch", hnv=1, hxv=0, h=0, k=1, smn=0) numberOfElements = len(objectArray) sumPath = [] multiplyDivide = [] index = 0 for eachObject in objectArray: motionPath = cmds.pathAnimation(eachObject, c=curve, follow=True, worldUpType="scene", name="motionpath%s" % index) motionPath = NameConv.rename_name_in_format(motionPath, {'name': motionPath}) multDivFactor = cmds.shadingNode('multiplyDivide', asUtility=True, name="factor%s" % index) multDivFactor = NameConv.rename_name_in_format(multDivFactor, {'name': multDivFactor}) cmds.connectAttr("%s.Stretch" % control, "%s.input1X" % multDivFactor) cmds.setAttr("%s.input2X" % multDivFactor, float(index) / float(len(objectArray))) cmds.setAttr("%s.operation" % multDivFactor, 1) multiplyDivide.append(multDivFactor) addition = cmds.shadingNode('plusMinusAverage', asUtility=True, name="Addition%s" % index) addition = NameConv.rename_name_in_format(addition, {'name': addition}) cmds.connectAttr("%s.outputX" % multDivFactor, "%s.input1D[0]" % addition) cmds.connectAttr("%s.Percent" % control, "%s.input1D[1]" % addition) cmds.connectAttr("%s.output1D" % addition, "%s.uValue" % motionPath, force=True) index += 1
def createPathLocators(*argv): counter = '' if len(cmds.ls('pathLocator?', type='transform')) > 0: counter = len(cmds.ls('pathLocator?', type='transform')) + 1 print counter oPathLoc = cmds.spaceLocator(n='pathLocator' + str(counter)) oStopLoc = cmds.spaceLocator(n='stopLocator' + str(counter)) oPathLocGrp = cmds.group(oPathLoc, n='pathLocatorGrp' + str(counter)) oStopGrp = cmds.group(oStopLoc, n='stopLocatorGrp' + str(counter)) counter = '' if len(cmds.ls('pathCurve?', l=True)) > 0: counter = len(cmds.ls('pathCurve?', l=True)) cmds.pathAnimation(oPathLocGrp, stu=0, etu=1000, fa='x', ua='y', bank=True, fm=True, c=('pathCurve' + str(counter))) cmds.parentConstraint(oPathLoc, oStopLoc, cmds.ls('*:Master_Anim')[0]) cmds.setAttr( cmds.ls('Master_Anim_parentConstraint*', l=True)[0] + '.stopLocatorW1', 0)
def create_orbit_animation(i): # i'm offsetting the frames by 1500 (i may increase this) so that I can do the first part of the script # this creates orbits and animates them from frame 1500 to 11500 cmds.circle(radius=i * 2 + 5, normalY=1, normalZ=0, name=names[i] + '_orbit') cmds.select(names[i] + '_orbit') cmds.setAttr(names[i] + '_orbit.rotateY', int(i * 90 / 8)) cmds.select(names[i], names[i] + '_orbit') # cmds.pathAnimation(name=names[i]+'_path', fractionMode=True, follow=True, followAxis='x', upAxis='y', worldUpType='vector', worldUpVector=[0, 1, 0], inverseUp=False, bank=False, startTimeU=1500, endTimeU=1500+int(time_period[i]*10000/time_period[3]/2)) cmds.pathAnimation(name=names[i] + '_path', fractionMode=True, follow=False, startTimeU=1500, endTimeU=1500 + int(time_period[i] * 10000 / time_period[3] / 2)) cmds.selectKey(clear=True) cmds.selectKey(names[i] + '_path', keyframe=True, time=(1500, 1500 + int(time_period[i] * 10000 / time_period[3] / 2))) cmds.keyTangent(inTangentType='linear', outTangentType='linear') cmds.setInfinity(postInfinite='cycle')
def _attach_to_curve(self, child, cv): """ @note: attach to curve using motion path @param child: object to be attached @param cv: cv index @param fm: fraction mode, allows U values 0 to 1 @return: """ # attach to motion path # @param: fm = fraction mode motion_path = mc.pathAnimation(child, str(self.name), fm=True) # break U value connection of motion path pm.disconnectAttr('{}_uValue.output'.format(motion_path)) # set U value spacing = 1.0 / (self.cvs - 1) u_position = spacing * cv pm.setAttr('{}.uValue'.format(motion_path), u_position)
def dominoAlongPath(path,main,dist): y = 1 x = 2000 uValue = dist cmds.group( em=True, name=path + '_grp' ) cmds.parent(path, path + '_grp' ) try: while y <= x: dominObj = cmds.duplicate(main,rr=True,un=True) cmds.parent(dominObj,path + '_grp') motionObj = cmds.pathAnimation(dominObj, startTimeU=int(y),endTimeU=int(x),fa='X',ua="Y",follow=True,fractionMode=True,followAxis="X",c=curve) cmds.cutKey( motionObj, time=(y,x), attribute='uValue' ) cmds.setAttr(motionObj+".uValue",uValue) uValue = uValue + uValueStart y = y + 1 except: pass
def putOnCurve(selList, numberObj, stepObj, selFrontAxis, selFrontNegativ, selUpAxis, selUpNegativ): """ Creates objects and links them to the selected curve accepts arguments: @selList[list] - list of selected objects @numberObj[int] - number of objects @stepObj[float] - step @selFrontAxis[string] - selected front axis @selFrontNegativ[bool] - positive or negative front axis @selUpAxis[string] - selected up axis @selUpNegativ[bool] - positive or negative up axis return arguments: @newObjList[list] - list of created objects """ newObjList = [] value = 0 while numberObj > 0: obj = mc.duplicate(selList[2], rr=1) mpNode = mc.pathAnimation(selList[0], obj, follow=1, followAxis=selFrontAxis.lower(), upAxis=selUpAxis.lower(), worldUpType="object", worldUpObject=selList[1], inverseFront=selFrontNegativ, inverseUp=selUpNegativ, bank=0, startTimeU=0, endTimeU=1) conList = mc.listConnections("{}.u".format(mpNode), s=1) mc.delete(conList[0]) mc.setAttr("{}.u".format(mpNode), value) value += stepObj numberObj -= 1 newObjList.append(obj) return newObjList
def preBake(self): self.bakeTempLocator() points = [] ks = [0] k = -1 mc.refresh(su=not self.showBake) for i in range(self.startTime, self.endTime + 1): mc.currentTime(i) points.append(self._bakedLoc.p_position) ks.append(min(max(k, 0), self.endTime - self.startTime - 2)) k = k + 1 mc.refresh(su=False) ks.append(ks[-1]) self.motionCurve = cgmMeta.asMeta( mc.curve(name='motionCurve', d=3, p=points, k=ks)) mc.rebuildCurve(self.motionCurve.mNode, ch=False, rpo=True, rt=0, end=1, kr=0, kcp=1, kep=1, kt=0, s=4, d=3, tol=3.28084e-06) mc.cutKey(self.obj.mNode, at=['tx', 'ty', 'tz'], clear=True) self.motionPath = cgmMeta.asMeta( mc.pathAnimation(self.obj.mNode, self.motionCurve.mNode, fractionMode=False, follow=False, startTimeU=self.startTime, endTimeU=self.endTime))
def buildGuideSpline(self): cPoints = [] for marker in self.totalMarkerList: markerPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) cPoints.append(markerPos) nameStart = nameBase(self.totalMarkerList[0].getName(), self.searchString, "loc", "cv") guideSplineName = nameStart + "ribbonGuideSpline" self.guideSpline = cmds.curve( editPoint=cPoints, degree=3, name=guideSplineName) #Need to add Naming Convention here self.tempGuideParts.append(self.guideSpline) for i, marker in enumerate(self.totalMarkerList): locPos = cmds.xform(marker.getName(), t=True, q=True, ws=True) newPara = cmds.closestPointOnCurve(self.guideSpline, ip=locPos, paramU=True) newParaVal = cmds.getAttr(newPara + ".paramU") cmds.delete(newPara) # print "new ParaVal : ", newParaVal ##Now Create a new Locator and add it to the precise parameter position nameStart = nameRebuild(marker.getName(), self.searchString, "loc", "loc", nameAddition="tempRibbonGuide") newAlignedLoc = cmds.spaceLocator(name=nameStart) # guideSplineName = nameStart + "ribbonGuideSpline" #Need naming convention self.tempGuideParts.append(newAlignedLoc[0]) mPath = cmds.pathAnimation(newAlignedLoc, follow=True, c=self.guideSpline) uAnimNode = cmds.listConnections(mPath + ".uValue", source=True) cmds.delete(uAnimNode) cmds.setAttr(mPath + ".uValue", newParaVal) self.totalMarkerList[i].setAlignedMarker(newAlignedLoc[0]) self.totalMarkerList[i].setUParameter(newParaVal)
def rsObjectsInPath(l_curves, i_number=3, i_type=0, b_consPos=True, b_consOri=True, b_orientWorld=True, b_parentHierarchy=False, b_selectNewObjs=True, o_toCurve=None, i_instance=0, i_loft=0): l_selIn = cmds.ls(sl=True, o=False) cmds.select(cl=True) l_list = [] try: if cmds.objExists(l_curves): l_list.append(l_curves) except: pass for o_obj in l_curves: if cmds.objExists(o_obj): l_list.append(o_obj) if len(l_list) == 0: cmds.warning("Wrong input argument") return False l_curves = l_list d_type = {0: "group", 1: "spaceLocator", 2: "joint", 3: "Scene object"} l_targets = [] l_objReturns = [] for o_obj in l_curves: if cmds.objExists(o_obj): l_shapes = cmds.listRelatives(o_obj, s=True) for o_shape in l_shapes: if cmds.nodeType(o_shape) == "nurbsCurve" or cmds.nodeType(o_shape) == "bezierCurve": l_targets.append(o_shape) else: cmds.warning("%s > A Does not exist" % (o_obj)) if len(l_targets) > 0: l_loft = [] for o_target in l_targets: l_tmpObjReturns = [] i_openCloseVal = cmds.getAttr("%s.f" % (o_target)) if i_openCloseVal == 0: f_div = 1.00 / (i_number - 1) else: f_div = 1.00 / i_number l_uValues = [] for z in range(i_number): l_uValues.append(f_div * z) for z in range(i_number): o_obj = None if i_type != 3: if i_type in d_type: if i_type == 0: o_obj = cmds.group(em=True) if i_type == 1: o_obj = cmds.spaceLocator()[0] if i_type == 2: o_obj = cmds.joint() else: cmds.warning("Type not recognized") break else: if cmds.objExists(o_toCurve): if i_instance == 0: o_obj = cmds.duplicate(o_toCurve)[0] else: o_obj = cmds.instance(o_toCurve)[0] else: cmds.warning("%s > B Does not exist" % (o_toCurve)) break l_objReturns.append(o_obj) l_tmpObjReturns.append(o_obj) o_path = cmds.pathAnimation(o_obj, o_target, f=b_consOri, fractionMode=True, followAxis="y", upAxis="z", worldUpType="vector") o_incomingConnection = cmds.listConnections("%s.uValue" % (o_path), destination=False, source=True)[0] cmds.cycleCheck(e=0) cmds.delete(o_incomingConnection) cmds.cycleCheck(e=1) cmds.setAttr("%s.uValue" % (o_path), l_uValues[z]) if not b_consOri and not b_consPos: o_incoming = cmds.listConnections("%s.rotateX" % (o_obj), destination=False, source=True)[0] cmds.cycleCheck(e=0) cmds.delete(o_incoming) cmds.cycleCheck(e=1) if b_consOri and not b_consPos: o_incomingX = cmds.listConnections("%s.translateX" % (o_obj), plugs=True, destination=False, source=True)[0] o_incomingY = cmds.listConnections("%s.translateY" % (o_obj), plugs=True, destination=False, source=True)[0] o_incomingZ = cmds.listConnections("%s.translateZ" % (o_obj), plugs=True, destination=False, source=True)[0] cmds.disconnectAttr(o_incomingX, "%s.translateX" % (o_obj)) cmds.disconnectAttr(o_incomingY, "%s.translateY" % (o_obj)) cmds.disconnectAttr(o_incomingZ, "%s.translateZ" % (o_obj)) if not b_consOri and b_consPos: o_incomingX = cmds.listConnections("%s.rotateX" % (o_obj), plugs=True, destination=False, source=True)[0] o_incomingY = cmds.listConnections("%s.rotateY" % (o_obj), plugs=True, destination=False, source=True)[0] o_incomingZ = cmds.listConnections("%s.rotateZ" % (o_obj), plugs=True, destination=False, source=True)[0] cmds.disconnectAttr(o_incomingX, "%s.rotateX" % (o_obj)) cmds.disconnectAttr(o_incomingY, "%s.rotateY" % (o_obj)) cmds.disconnectAttr(o_incomingZ, "%s.rotateZ" % (o_obj)) cmds.setAttr("%s.follow" % (o_path), b_consOri) if not b_consOri and b_orientWorld: cmds.setAttr("%s.rotateX" % (o_obj), 0) cmds.setAttr("%s.rotateY" % (o_obj), 0) cmds.setAttr("%s.rotateZ" % (o_obj), 0) cmds.select(cl=True) o_loft = "" if i_loft > 0: if i_loft == 1: o_loftPoly = cmds.loft(l_tmpObjReturns, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=1, rsn=True) o_outcoming = cmds.listConnections("%s.outputSurface" % (o_loftPoly[1]), plugs=False, destination=True, source=False)[0] o_loft = o_loftPoly[1] l_loft.append(o_loftPoly[0]) cmds.setAttr("%s.polygonType" % (o_outcoming), 1) cmds.setAttr("%s.format" % (o_outcoming), 2) cmds.setAttr("%s.uType" % (o_outcoming), 3) cmds.setAttr("%s.uNumber" % (o_outcoming), 1) cmds.setAttr("%s.vType" % (o_outcoming), 3) cmds.setAttr("%s.vNumber" % (o_outcoming), 1) if i_loft == 2: cmds.loft(l_tmpObjReturns, ch=1, u=1, c=0, ar=1, d=3, ss=1, rn=0, po=0, rsn=True) if i_loft > 2: cmds.warning("Loft type not recognized") cmds.select(cl=True) if b_parentHierarchy: if not b_consPos and not b_consOri: l_tmpObjReturns.reverse() for z in range(len(l_tmpObjReturns) - 1): cmds.parent(l_tmpObjReturns[z], l_tmpObjReturns[z + 1]) else: cmds.warning("Objects cannot be in hierarchy, , they have transformations constraints") cmds.select(cl=True) if b_selectNewObjs: if l_objReturns != []: cmds.select(l_objReturns) if len(l_loft) > 0: cmds.select(l_loft, add=True) else: if l_selIn != []: cmds.select(l_selIn) else: if l_selIn != []: cmds.select(l_selIn) return(l_objReturns, l_targets, l_loft)
def macroControls(self, medLeadCurve, mainName,controllerType, childControllers,microLeadCurve, childCurve, parentCurve,size, colour, nrx, nry, nrz, getNum, medLeadCurveNum): CVbucketList=[] collectJack=[] for eachCurve in medLeadCurve: getCurve=ls(eachCurve)[0] for index, eachCV in enumerate(getCurve.cv): transformWorldMatrix=eachCV.getPosition() rotateWorldMatrix=[0.0, 0.0, 0.0] tempname=mainName+str(index)+"none" tempgrpname=mainName+str(index)+"none_grp" tempsize, tempcolour= 6, 6 getClass.JackI(tempname, tempgrpname, tempsize, transformWorldMatrix, rotateWorldMatrix, tempcolour) collectJack.append(tempname) for eachCV, eachJack in map(None, getCurve.cv, xrange(len(collectJack) - 1)): # transformWorldMatrixNext=next_item.getPosition() try: current_item, next_item =collectJack[eachJack], collectJack[eachJack + 1] except: pass getNum=re.sub("\D", "", str(eachCV)) getNum=int(getNum) getNum="%02d" % (getNum,) aname=controllerType.split("_grp")[0]+"_Ctrl" name=mainName+str(getNum)+aname grpname= mainName+str(getNum)+controllerType CVbucketList.append(eachCV) transformWorldMatrix=eachCV.getPosition() rotateWorldMatrix=[0.0, 0.0, 0.0] select(eachCV, r=1) getNewClust=cmds.cluster() getClass.buildCtrl(eachCV, name, grpname,transformWorldMatrix, rotateWorldMatrix, size, colour, nrx, nry, nrz) getNewCtrl=cmds.ls(sl=1, fl=1) try: cmds.select(next_item, r=1) cmds.select(grpname, add=1) cmds.aimConstraint(offset=[0,0, 0], weight=1, aimVector=[1, 0, 0] , upVector=[0, 1, 0] ,worldUpType="vector" ,worldUpVector=[0, 1, 0]) cmds.delete(next_item+"_grp") except: pass cmds.parentConstraint(ls(name), getNewClust, mo=0, w=1) cmds.parent(grpname, mainName+"_Rig") cmds.parent(getNewClust, mainName+"_Rig") CVbucketbuckList=[] for each in microLeadCurve: for eachCV, eachCtrlGro in map(None, each.cv, childControllers): CVbucketbuckList.append(eachCV) CVbucketbuckList=CVbucketbuckList[:1]+CVbucketbuckList[2:] CVbucketbuckList=CVbucketbuckList[:-2]+CVbucketbuckList[-1:] medLeadCurve=ls(medLeadCurve) #attach controllers to new parent curve for each in medLeadCurve: for eachItemCV, eachCtrlGro in map(None, CVbucketbuckList, childControllers): pgetCVpos=eachCtrlGro.getTranslation() getpoint=each.closestPoint(pgetCVpos, tolerance=0.001, space='preTransform') getParam=each.getParamAtPoint(getpoint, space='preTransform') select(eachCtrlGro, r=1) select(medLeadCurve[0], add=1) motionPath=cmds.pathAnimation(fractionMode=1, follow=1, followAxis="x", upAxis="y", worldUpType="vector", worldUpVector=[0, 1, 0], inverseUp=0, inverseFront=0, bank=0) disconnectAttr(motionPath+"_uValue.output", motionPath+".uValue") getpth=str(motionPath) setAttr(motionPath+".fractionMode", False) setAttr(motionPath+".uValue", getParam)
def followCurve(sourceCurve,curveStart,duration,particleList,maxDistance,minDistance,nose,tail,length,turbulenceAmp,turbulencePer): ''' Creates a trail of particles following the source curve sourceCurve : Name of the curve particles will emit from curveStart : Frame to start emission duration : Number of frames to emit for particleList : List containing names of all the particles to be animatied maxDistance : Maximum distance particles will be emitted from the curve at the middle of the trail minDistance : Maximum distance particles will be emitted from the curve at the nose and tail of the trail nose : Number of frames to taper the front of the trail tail : Number of frames to taper the end of the trail length : Length of the trail in frames emitTime : Number of frames particles will be affected by the emission force turbulenceAmp : Amplitude of the turbulence animation graph turbulencePer : Period of the turbulence animation graph Updates the progress window and assigns all the elements in particleList to the class particles. Particle assigned to the source curve as a motion path and this motion is baked here as Maya doesn't correctly combine animation layers when motion paths are used. The particle offset calculated and keyed. Turbulence is added and visibility is temporarily set to 'off' to speed up processing of subsequent particles. After all particles are animated, birth and death are keyed. ''' cmds.progressWindow(e=1,progress=0,status='Animating Particles...') for i in range(0,len(particleList)): particleList[i]=particles(particleList[i]) count=0 for x in particleList: launch = random.uniform(0,length) x.born = curveStart+int(launch) x.lifeTime = duration+random.randint(-(length/4),(length/4)) motionPath = cmds.pathAnimation(x.name, fm=1, stu=curveStart+launch, etu=x.born+x.lifeTime, c=sourceCurve) cmds.keyTangent(motionPath,at='uValue',itt='Linear',ott='Linear') cmds.bakeResults(x.name,at=['translateX','translateY','translateZ'],t=(x.born,x.born+x.lifeTime+1),sm=1,dic=1,pok=0,sac=1,sb=1,ral=1,bol=0,mr=0,s=1) if launch<nose: distance = ((launch/float(nose))*(maxDistance-minDistance))+minDistance elif length-launch<tail: distance = (((length-launch)/float(tail))*(maxDistance-minDistance))+minDistance else: distance = maxDistance a = 'AnimLayerOffset' cmds.select(x.name) if cmds.animLayer(a,exists=True,q=True)==False: cmds.animLayer(a,aso=1) else: cmds.animLayer(a, e=1,aso=1) cmds.setKeyframe(x.name,at='translateX',t=x.born, v=random.uniform(-distance,distance),al=a,nr=1) cmds.setKeyframe(x.name,at='translateY',t=x.born, v=random.uniform(-distance,distance),al=a,nr=1) cmds.setKeyframe(x.name,at='translateZ',t=x.born, v=random.uniform(-distance,distance),al=a,nr=1) cmds.setKeyframe(x.name,at='rotateX',t=x.born, v=random.uniform(0,360),al=a,nr=1) cmds.setKeyframe(x.name,at='rotateY',t=x.born, v=random.uniform(0,360),al=a,nr=1) cmds.setKeyframe(x.name,at='rotateZ',t=x.born, v=random.uniform(0,360),al=a,nr=1) x.drift(x.born,(0,0,0),turbulenceAmp*random.random(),turbulencePer+random.randint(-2,2)) x.bake() cmds.keyframe(x.name,at='visibility',a=1,vc=0) count+=1 cmds.progressWindow(e=1,progress=int((100.0/len(particleList))*count)) for x in particleList: x.fadeOut = 0 x.birth() x.death() return
def import2dTrack(): """ """ # Get UI Elements perspCamListUI = 'importTrack_camListTSL' fileUI = 'importTrack_fileTFB' pixelWidthUI = 'importTrack_widthFFG' pixelHeightUI = 'importTrack_heightFFG' pointNameUI = 'importTrack_nameTFG' # Get UI Values w = cmds.floatFieldGrp(pixelWidthUI, q=True, v1=True) h = cmds.floatFieldGrp(pixelHeightUI, q=True, v1=True) cam = cmds.textScrollList(perspCamListUI, q=True, si=True)[0] filePath = cmds.textFieldButtonGrp(fileUI, q=True, text=True) pointName = cmds.textFieldGrp(pointNameUI, q=True, text=True) # Ensure Camera Transform is Selected if cmds.objectType(cam) == 'camera': cam = cmds.listRelatives(cam, p=True)[0] # Check Track File Path if not os.path.isfile(filePath): raise Exception('Invalid file path "' + filePath + '"!') # Build Track Point Scene Elements point = cmds.spaceLocator(n=pointName)[0] plane = cmds.nurbsPlane(ax=(0, 0, 1), w=1, lr=1, d=1, u=1, v=1, ch=1, n=pointName + 'Plane')[0] print plane # Position Track Plane plane = cmds.parent(plane, cam)[0] cmds.setAttr(plane + '.translate', 0, 0, -5) cmds.setAttr(plane + '.rotate', 0, 0, 0) for attr in ['.tx', '.ty', '.rx', '.ry', '.rz']: cmds.setAttr(plane + attr, l=True) # Add FOV Attributes if not cmds.objExists(cam + '.horizontalFOV'): cmds.addAttr(cam, ln='horizontalFOV', at='double') if not cmds.objExists(cam + '.verticalFOV'): cmds.addAttr(cam, ln='verticalFOV', at='double') # Create FOV Expression expStr = '// Get Horizontal and Vertical FOV\r\n\r\n' expStr += 'float $focal =' + cam + '.focalLength;\r\n' expStr += 'float $aperture = ' + cam + '.horizontalFilmAperture;\r\n\r\n' expStr += 'float $fov = (0.5 * $aperture) / ($focal * 0.03937);\r\n' expStr += '$fov = 2.0 * atan ($fov);\r\n' expStr += cam + '.horizontalFOV = 57.29578 * $fov;\r\n\r\n' expStr += 'float $aperture = ' + cam + '.verticalFilmAperture;\r\n\r\n' expStr += 'float $fov = (0.5 * $aperture) / ($focal * 0.03937);\r\n' expStr += '$fov = 2.0 * atan ($fov);\r\n' expStr += cam + '.verticalFOV = 57.29578 * $fov;\r\n\r\n' expStr += '// Scale plane based on FOV\r\n\r\n' expStr += 'float $dist = ' + plane + '.translateZ;\r\n' expStr += 'float $hfov = ' + cam + '.horizontalFOV / 2;\r\n' expStr += 'float $vfov = ' + cam + '.verticalFOV / 2;\r\n\r\n' expStr += 'float $hyp = $dist / cos(deg_to_rad($hfov));\r\n' expStr += 'float $scale = ($hyp * $hyp) - ($dist * $dist);\r\n' expStr += plane + '.scaleX = (sqrt($scale)) * 2;\r\n\r\n' expStr += 'float $hyp = $dist / cos(deg_to_rad($vfov));\r\n' expStr += 'float $scale = ($hyp * $hyp) - ($dist * $dist);\r\n' expStr += plane + '.scaleY = (sqrt($scale)) * 2;' cmds.expression(s=expStr, o=plane, n='planeFOV_exp', ae=1, uc='all') # Open Track Data File count = 0 f = open(filePath, 'r') # Build Track Path Curve crvCmd = 'curveOnSurface -d 1 ' for line in f: u, v = line.split() crvCmd += '-uv ' + str(float(u) * (1.0 / w)) + ' ' + str(float(v) * (1.0 / h)) + ' ' count += 1 crvCmd += plane print crvCmd path = mel.eval(crvCmd) # Close Track Data File f.close() # Rebuild Curve cmds.rebuildCurve(path, fitRebuild=False, keepEndPoints=True, keepRange=True, spans=0, degree=3) # Attach Track Point to Path motionPath = cmds.pathAnimation(point, path, fractionMode=False, follow=False, startTimeU=1, endTimeU=count) exp = cmds.listConnections(motionPath + '.uValue') if exp: cmds.delete(exp) cmds.setKeyframe(motionPath, at='uValue', t=1, v=0) cmds.setKeyframe(motionPath, at='uValue', t=count, v=count - 1)
def fastAnimation( win ): objList = cmds.ls( 'my*' ) if objList > 0: cmds.delete( objList ) nice_try = cmds.polySphere( name='mySun', sx=True, sy=True ) cmds.move( 0, 0, 0, nice_try ) cmds.scale( 8, 8, 8, nice_try ) orbitOfMercury=cmds.circle( nr=(0, 1, 0 ), c=(0, 0, 0),r=11.5 ,name='myOrbitMercury' ) setVis( 'myOrbitMercury.visibility' ) orbitOfVenus=cmds.circle( nr=(0, 1, 0 ), c=(0, 2, 0),r=15.5 ,name='myOrbitVenus' ) setVis( 'myOrbitVenus.visibility' ) orbitOfEarth=cmds.circle( nr=(0, 1, 0 ), c=(0, 4, 0),r=20.5 ,name='myOrbitEarth' ) setVis( 'myOrbitEarth.visibility' ) orbitOfMars=cmds.circle( nr=(0, 1, 0 ), c=(0, 6, 0),r=25.5 ,name='myOrbitMars' ) setVis( 'myOrbitMars.visibility' ) orbitOfJupiter=cmds.circle( nr=(0, 1, 0 ), c=(0, 8, 0),r=35.5 ,name='myOrbitJupiter' ) setVis( 'myOrbitJupiter.visibility' ) orbitOfSaturn=cmds.circle( nr=(0, 1, 0 ), c=(0, 10, 0),r=45.5 ,name='myOrbitSaturn' ) setVis( 'myOrbitSaturn.visibility' ) orbitOfUranus=cmds.circle( nr=(0, 1, 0 ), c=(0, 12, 0),r=53 ,name='myOrbitUranus' ) setVis( 'myOrbitUranus.visibility' ) orbitOfNeptune=cmds.circle( nr=(0, 1, 0 ), c=(0, 14, 0),r=60.5 ,name='myOrbitNeptune' ) setVis( 'myOrbitNeptune.visibility' ) orbitOfPluto=cmds.circle( nr=(0, 1, 0.2 ), c=(0, 16, 0),r=67 ,name='myOrbitPluto' ) setVis( 'myOrbitPluto.visibility' ) planetMercury=cmds.polySphere( name='myPlanetMercury', sx=True, sy=True ) cmds.scale( 0.9, 0.9, 0.9, planetMercury ) planetVenus=cmds.polySphere( name='myPlanetVenus', sx=True, sy=True ) cmds.scale( 1.5, 1.5, 1.5, planetVenus ) planetEarth=cmds.polySphere( name='myPlanetEarth', sx=True, sy=True ) cmds.scale( 1.5, 1.5, 1.5, planetEarth ) planetMars=cmds.polySphere( name='myPlanetMars', sx=True, sy=True ) cmds.scale( 1.2, 1.2, 1.2, planetMars ) planetJupiter=cmds.polySphere( name='myPlanetJupiter', sx=True, sy=True ) cmds.scale( 4.5, 4.5, 4.5, planetJupiter ) planetSaturn=cmds.polySphere( name='myPlanetSaturn', sx=True, sy=True ) cmds.scale( 3.4, 3.4, 3.4, planetSaturn ) planetUranus=cmds.polySphere( name='myPlanetUranus', sx=True, sy=True ) cmds.scale( 2.5, 2.5, 2.5, planetUranus ) planetNeptune=cmds.polySphere( name='myPlanetNeptune', sx=True, sy=True ) cmds.scale( 2.5, 2.5, 2.5, planetNeptune ) planetPluto=cmds.polySphere( name='myPlanetPluto', sx=True, sy=True ) cmds.scale( 0.8, 0.8, 0.8, planetPluto ) mtpMercury = cmds.pathAnimation( planetMercury, orbitOfMercury, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=88 ) mtpVenus = cmds.pathAnimation( planetVenus, orbitOfVenus, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=25 ) mtpEarth = cmds.pathAnimation( planetEarth, orbitOfEarth, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=65 ) mtpMars = cmds.pathAnimation( planetMars, orbitOfMars, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=200 ) mtpJupiter = cmds.pathAnimation( planetJupiter, orbitOfJupiter, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=150 ) mtpSaturn = cmds.pathAnimation( planetSaturn, orbitOfSaturn, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=300 ) mtpUranus = cmds.pathAnimation( planetUranus, orbitOfUranus, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=800 ) mtpNeptune = cmds.pathAnimation( planetNeptune, orbitOfNeptune, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=6500 ) mtpPluto = cmds.pathAnimation( planetPluto, orbitOfPluto, f=True, fa='x', fm=True, ua='y', stu=1.0, etu=4800 ) linear_cycle( mtpMercury ) linear_cycle( mtpVenus ) linear_cycle( mtpEarth ) linear_cycle( mtpMars ) linear_cycle( mtpJupiter ) linear_cycle( mtpSaturn ) linear_cycle( mtpUranus ) linear_cycle( mtpNeptune ) linear_cycle( mtpPluto ) cmds.playbackOptions( max=4800 ) pmc.deleteUI(win)
for curveParticleId in allParticleDictionary.keys(): #print sorted(allParticleDictionary[curveParticleId].keys()) #print curveParticleId pointList = [] sortedKeyFrameList = sorted(allParticleDictionary[curveParticleId].keys()) if len(sortedKeyFrameList) > 1: for keyFrame in sortedKeyFrameList: pointList.append(allParticleDictionary[curveParticleId][keyFrame]) curveName = "partiCurve" + str(curveParticleId) curveObj = mc.curve(name = curveName, p = pointList) locName = "locatorName" + str(curveParticleId) locObj = mc.spaceLocator(name = locName) mc.pathAnimation(locObj, stu=sortedKeyFrameList[0], etu=sortedKeyFrameList[-1] ,c=curveObj) #For every locator we create, make a bubble and attach that to the locator in worldspace and parent in underneath makeBubble = mc.polyCube(name="bubble" + str(curveParticleId), w=.1, h=.1, d=.1, sx=5, sy=5, sz=5) mc.sculpt(makeBubble, maxDisplacement=.1) mc.delete(makeBubble, ch=True) getPos = mc.xform(locObj, ws=True, q=True, translation=True) mc.xform(makeBubble[0], t=(getPos[0], getPos[1], getPos[2])) mc.parent(makeBubble[0], locObj) randBubbleSize = random.uniform(.4,.6)#This is what will give our bubbles the random size mc.scale(randBubbleSize, randBubbleSize, randBubbleSize, makeBubble[0]) #Create nCloth for each bubble and set the collide strength to turn on when the bubble moves, never before. mc.select(makeBubble[0]) mc.nClothCreate()