def splashDiscParticleExpressionBeforeDynamics(splashDiscParticle="",oceanShader=""): """ send splashDiscParticle and oceanShader to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @param oceanShader: Name of shader @type oceanShader: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "float $particleFoamEmission = 0.8; \n" newExp += "float $particleWakeEmission = 0.01;\n" newExp += "vector $pos = %s.position;\n"%splashDiscParticle newExp += "vector $vel = %s.velocity;\n"%splashDiscParticle newExp += "float $px = $pos.x;\n" newExp += "float $pz = $pos.z;\n" newExp += "float $disp[] = `colorAtPoint -u $px -v $pz %s`;\n"%oceanShader newExp += "\nif( $vel.y < 0 && $pos.y < ($disp[0]-.2) ){\n\t" newExp += "%s.lifespanPP = 0;\n\t"%splashDiscParticle newExp += "int $vox[] = `fluidVoxelInfo -objectSpace false -cb -voxel $px 0 $pz OceanWakeTexture1`;\n\t" newExp += "if( size($vox) > 0){\n\t\t" newExp += "setFluidAttr -at density -ad -xi $vox[0] -yi $vox[1] -zi $vox[2] -fv $particleWakeEmission OceanWakeTexture1;\n\t" newExp += "}\n\t" newExp += "$vox = `fluidVoxelInfo -objectSpace false -cb -voxel $px 0 $pz OceanWakeFoamTexture1`;\n\t" newExp += "if( size($vox) > 0){\n\t\t" newExp += "setFluidAttr -at temperature -ad -xi $vox[0] -yi $vox[1] -zi $vox[2] -fv $particleFoamEmission OceanWakeFoamTexture1;\n\t}\n" newExp += "}" cmds.dynExpression(splashDiscParticle,string=newExp,runtimeBeforeDynamics=True) return newExp
def updateParticleBucket(self,emitSurfPtcsShape): '''update the settings of the particle system passed to the proc''' randSeed = cmds.getAttr(emitSurfPtcsShape+'.randSeed') scaleMin = cmds.getAttr(emitSurfPtcsShape+'.scaleMin') scaleMax = cmds.getAttr(emitSurfPtcsShape+'.scaleMax') dressType = cmds.getAttr(emitSurfPtcsShape+'.dressType') if dressType == 'all': instSize = str(len(cmds.listRelatives('dressExampleGrp', c = True, f = True))) #build the strings that set the on creation expression createExp = 'seed('+str(randSeed)+'+id);\ngoalU = parentU;\ngoalV = parentV;\n' createExp +=emitSurfPtcsShape+'.indexPP = floor(rand('+instSize+'));\n' createExp +=emitSurfPtcsShape+'.scalePP = rand('+str(scaleMin)+','+str(scaleMax) createExp +=');\n'+emitSurfPtcsShape+'.aimRotOffPP = <<rand(-1.0,1.0),0.0,rand(-1.0,1.0)>>;\n' createExp +=emitSurfPtcsShape+'.surfRotOffPP = <<0.0,sin(id*rand(50)),cos(id * rand(5))>>;\n' print createExp #build the strings that set the run on dynamics expression rbdExp = emitSurfPtcsShape+'.surfRotPP = '+emitSurfPtcsShape+'.surfRotOffPP;\n' rbdExp +=emitSurfPtcsShape+'.aimRotPP = '+emitSurfPtcsShape+'.aimRotOffPP;\n' print rbdExp #update the per particle expressions cmds.dynExpression(emitSurfPtcsShape, s = str(createExp), c = 1) cmds.dynExpression(emitSurfPtcsShape, s = str(rbdExp), rbd = 1) return
def objectNameParticleExpressionBeforeDynamics(objectNameParticle="", oceanShader=""): """ send objectParticle and oceanShader to make custom expression on objectParticle @param objectNameParticle: Name of Object @type objectNameParticle: String -------------------------------------------- @param oceanShader: Name of shader @type oceanShader: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "%s.lifespanPP = rand(2,4);\n" % objectNameParticle newExp += "vector $pos = %s.position;\n" % objectNameParticle newExp += "float $px = $pos.x;\n" newExp += "float $pz = $pos.z;\n" newExp += "float $disp[] = `colorAtPoint -u $px -v $pz %s`;\n" % oceanShader newExp += "if( $pos.y > $disp[0]-0.2 ){\n" newExp += "\n\t%s.lifespanPP = 0;\n" % objectNameParticle newExp += "}\n" cmds.dynExpression(objectNameParticle, string=newExp, runtimeBeforeDynamics=True) return newExp
def createParticleSystem_2(): # Creates a point emitter, with a collide plane and some PP attributes cmds.playbackOptions(maxTime=180) emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0),rate=20)[0] # nParticle creation depends on an optionVar value, make sure we use the default one cmds.optionVar( sv=("NParticleStyle","Points") ) particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_2") cmds.setAttr('%s.lfm' % particleSystemShape, 2.0) # random range cmds.setAttr('%s.lifespan' % particleSystemShape, 3) cmds.setAttr('%s.lifespanRandom' % particleSystemShape, 4) cmds.setAttr('%s.friction' % particleSystemShape, 0.01) cmds.setAttr('%s.bounce' % particleSystemShape, 0.5) cmds.setAttr('%s.rotationFriction' % particleSystemShape, 0.98) cmds.setAttr('%s.pointMass' % particleSystemShape, 4) cmds.setAttr('%s.computeRotation' % particleSystemShape, True) cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius cmds.setAttr('%s.selfCollide' % particleSystemShape, True) cmds.connectDynamic( particleSystemShape, em=emitter) # add Custom Attributes # rgb if not cmds.objExists( "%s.rgbPP" % particleSystemShape): cmds.addAttr( particleSystemShape ,ln="rgbPP",dt="vectorArray") else: # Disconnect possible thing in rgbPP input = cmds.connectionInfo("%s.rgbPP" % particleSystemShape,sourceFromDestination=True) if input: cmds.disconnectAttr(input,"%s.rgbPP" % particleSystemShape) cmds.dynExpression( particleSystem, s="\nfloat $r = rand(1.0);float $g = rand(1.0);float $b = rand(1.0);\n%s.rgbPP = <<$r,$g,$b>>;" % particleSystemShape, c=True) # radius if not cmds.objExists( "%s.radiusPP" % particleSystemShape): cmds.addAttr( particleSystemShape, ln="radiusPP",dt="doubleArray") cmds.dynExpression( particleSystem, s="seed(%s.id);\n%s.radiusPP = .2 + time * .2 * rand(.2,1.5)" % (particleSystemShape,particleSystemShape), runtimeAfterDynamics=True) # rotatePP (enabled by "compute rotation", the attribute would be created by attribut editor's first constrcution in a gui maya) if not cmds.objExists( "%s.rotationPP" % particleSystemShape): cmds.addAttr( particleSystemShape, ln="rotationPP",dt="vectorArray") # add collision plane plane = cmds.polyPlane( w=30,h=30,sx=10,sy=10,ax=[0, 1, .5], cuv=2) cmds.select(plane[0]) maya.mel.eval("makePassiveCollider") cmds.select(clear=True) cmds.setAttr( "nRigidShape1.friction", 0.25) cmds.setAttr( "nRigidShape1.stickiness", 0.0) return particleSystem, particleSystemShape
def createParticleSystem_2(): # Creates a point emitter, with a collide plane and some PP attributes cmds.playbackOptions(maxTime=180) emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0), rate=20)[0] # nParticle creation depends on an optionVar value, make sure we use the default one cmds.optionVar(sv=("NParticleStyle", "Points")) particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_2") cmds.setAttr('%s.lfm' % particleSystemShape, 2.0) # random range cmds.setAttr('%s.lifespan' % particleSystemShape, 3) cmds.setAttr('%s.lifespanRandom' % particleSystemShape, 4) cmds.setAttr('%s.friction' % particleSystemShape, 0.01) cmds.setAttr('%s.bounce' % particleSystemShape, 0.5) cmds.setAttr('%s.rotationFriction' % particleSystemShape, 0.98) cmds.setAttr('%s.pointMass' % particleSystemShape, 4) cmds.setAttr('%s.computeRotation' % particleSystemShape, True) cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius cmds.setAttr('%s.selfCollide' % particleSystemShape, True) cmds.connectDynamic(particleSystemShape, em=emitter) # add Custom Attributes # rgb if not cmds.objExists("%s.rgbPP" % particleSystemShape): cmds.addAttr(particleSystemShape , ln="rgbPP", dt="vectorArray") else: # Disconnect possible thing in rgbPP input = cmds.connectionInfo("%s.rgbPP" % particleSystemShape, sourceFromDestination=True) if input: cmds.disconnectAttr(input, "%s.rgbPP" % particleSystemShape) cmds.dynExpression(particleSystem, s="\nfloat $r = rand(1.0);float $g = rand(1.0);float $b = rand(1.0);\n%s.rgbPP = <<$r,$g,$b>>;" % particleSystemShape, c=True) # radius if not cmds.objExists("%s.radiusPP" % particleSystemShape): cmds.addAttr(particleSystemShape, ln="radiusPP", dt="doubleArray") cmds.dynExpression(particleSystem, s="seed(%s.id);\n%s.radiusPP = .2 + time * .2 * rand(.2,1.5)" % (particleSystemShape, particleSystemShape), runtimeAfterDynamics=True) # rotatePP (enabled by "compute rotation", the attribute would be created by attribut editor's first constrcution in a gui maya) if not cmds.objExists("%s.rotationPP" % particleSystemShape): cmds.addAttr(particleSystemShape, ln="rotationPP", dt="vectorArray") # add collision plane plane = cmds.polyPlane(w=30, h=30, sx=10, sy=10, ax=[0, 1, .5], cuv=2) cmds.select(plane[0]) maya.mel.eval("makePassiveCollider") cmds.select(clear=True) cmds.setAttr("nRigidShape1.friction", 0.25) cmds.setAttr("nRigidShape1.stickiness", 0.0) return particleSystem, particleSystemShape
def splashDiscParticleExpressionCreation(splashDiscParticle=""): """ send splashDiscParticle to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "%s.lifespanPP = rand(2,3);\n"%splashDiscParticle newExp += "%s.spriteTwistPP = rand(360);"%splashDiscParticle cmds.dynExpression(splashDiscParticle,string=newExp,creation=True) return newExp
def splashDiscParticleExpressionCreation(splashDiscParticle=""): """ send splashDiscParticle to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "%s.lifespanPP = rand(2,3);\n" % splashDiscParticle newExp += "%s.spriteTwistPP = rand(360);" % splashDiscParticle cmds.dynExpression(splashDiscParticle, string=newExp, creation=True) return newExp
def _setupRear_ParticleExpressions(particleShapeName = '', type = 'splash', boatWorldCtrl = '', boatName = '', rearAnimatable = ''): """ Setup the expressions for the rearEmitter nParticleShape node @param particleShapeName: The name of the nParticleShape node @param boatWorldCtrl: The name of the boatWorldCtrl curve @param boatName: The name of the boat should be stripped : @type particleShapeName: String @type boatWorldCtrl: String @type boatName: String """ if type == 'splash': ############################ ## Creation expStringList = [ '%s.lifespanPP = rand(%s.lifespanMin, %s.lifespanMax);\n' %(particleShapeName, rearAnimatable, rearAnimatable), '%s.twistSpeedPP = rand(%s.twistSpeedMin, %s.twistSpeedMax);\n' %(particleShapeName, rearAnimatable, rearAnimatable), '%s.spriteStartSizePP = rand(%s.spriteStartSizeMin, %s.spriteStartSizeMax);\n' %(particleShapeName, rearAnimatable, rearAnimatable), '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP;\n' %(particleShapeName, particleShapeName, particleShapeName), '%s.spriteTwistPP = rand(%s.twistAngleMin, %s.twistAngleMax);\n' %(particleShapeName, rearAnimatable, rearAnimatable), ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sprite_settings' % particleShapeName) ## Build new expression cmds.dynExpression( particleShapeName, n = "%s_sprite_settings" % particleShapeName, creation = True, string = utils.processExpressionString(expStringList) ) ############################ ## Runtime Before Dynamics expStringList = [ '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP * %s.scaleOverLifeRamp;\n' %(particleShapeName, particleShapeName, particleShapeName, particleShapeName), '%s.spriteScaleXPP = %s.spriteScaleYPP;\n' %(particleShapeName, particleShapeName), '%s.spriteTwistPP += (%s.twistSpeedPP * %s.twistRateOverLife);\n' %(particleShapeName, particleShapeName, particleShapeName), '\n', ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sprite_settings' % particleShapeName) ## Build new expression cmds.dynExpression( particleShapeName, n = "%s_sprite_settings" % particleShapeName, rbd = True, string = utils.processExpressionString(expStringList) ) ## Connect some attrs to animatable group attrs = ['inheritFactor', 'conserve', 'drag', 'damp'] for att in attrs: if not cmds.isConnected( '%s.%s' %(rearAnimatable, att), '%s.%s' %(particleShapeName, att) ): cmds.connectAttr('%s.%s' %(rearAnimatable, att), '%s.%s' %(particleShapeName, att), force = True)
def __run(self, *args, **kwargs): pos = kwargs.get("position", []) col = kwargs.pop("color", []) particle = cmds.particle(**kwargs)[1] if col and len(col) == len(pos): cmds.addAttr(particle, ln="rgbPP", dt="vectorArray") cmds.addAttr(particle, ln="rgbPP0", dt="vectorArray") color_exp = "vector $vectorList[] = {%s};" % (",".join( map(lambda x: "<<{},{},{}>>".format(x[0], x[1], x[2]), col))) color_exp += "\nint $id = id;\n%s.rgbPP = $vectorList[$id];" % ( particle) cmds.dynExpression(particle, c=1, s=color_exp) return particle
def splashDiscParticleExpressionAfterDynamics(splashDiscParticle=""): """ send splashDiscParticle to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "vector $appear = %s.position;\n"%splashDiscParticle newExp += "if ($appear.y < -0.25){\n\t" newExp += "%s.lifespanPP = 0;\n"%splashDiscParticle newExp += "}" cmds.dynExpression(splashDiscParticle,string=newExp,runtimeAfterDynamics=True) return newExp
def splashDiscParticleExpressionAfterDynamics(splashDiscParticle=""): """ send splashDiscParticle to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "vector $appear = %s.position;\n" % splashDiscParticle newExp += "if ($appear.y < -0.25){\n\t" newExp += "%s.lifespanPP = 0;\n" % splashDiscParticle newExp += "}" cmds.dynExpression(splashDiscParticle, string=newExp, runtimeAfterDynamics=True) return newExp
def cleanerUpLoad(): '''{'del_path':'Dynamics/QS/cleanerUpLoad()', 'icon':':/SP_TrashIcon.png', 'usage':'$fun()', 'help':'删除指定脚本,所有粒子表达式', } ''' #Delete 'QS_VFX*' nodes node = cmds.ls('QS_VFX*') if node != []: cmds.delete(node) print 'Deleted %s node' % (node) #Delete 'All expressions of particles for parShape in cmds.ls(type='particle'): cmds.dynExpression(parShape, s='', c=True, rbd=True, rad=True) print 'Deleted all expressions of particles' #Delete inputForce attributes for particle nodes addInputForceAttrForPar(cmds.ls(exactType='particle'))
def _build_nParticleExpressions(self, particleShapeName = '', animatable = ''): """ Setup the expressions for the sideEmitter's nParticleShape node @param particleShapeName: The name of the nParticleShape node @param boatWorldCtrl: The name of the boatWorldCtrl curve @param speedObject: The name of the boat should be stripped : @type particleShapeName: String @type boatWorldCtrl: String @type speedObject: String """ ## Creation expStringList = [ '%s.lifespanPP = rand(%s.lifespanMin, %s.lifespanMax);' %(particleShapeName, animatable, animatable), '%s.twistSpeedPP = rand(%s.twistSpeedMin, %s.twistSpeedMax);' %(particleShapeName, animatable, animatable), '%s.spriteStartSizePP = rand(%s.spriteStartSizeMin, %s.spriteStartSizeMax);' %(particleShapeName, animatable, animatable), '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP;' %(particleShapeName, particleShapeName, particleShapeName), '%s.spriteTwistPP = rand(%s.twistAngleMin, %s.twistAngleMax);' %(particleShapeName, animatable, animatable), ] ## Build new expression cmds.dynExpression( particleShapeName, name = "%s_expression" % particleShapeName, creation = True, string = self.processExpressionString(expStringList) ) ## Runtime Before Dynamics expStringList = [ '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP * %s.scaleOverLifeRamp;' %(particleShapeName, particleShapeName, particleShapeName, particleShapeName), '%s.spriteScaleXPP = %s.spriteScaleYPP;' %(particleShapeName, particleShapeName), '%s.spriteTwistPP += (%s.twistSpeedPP * %s.twistRateOverLife);' %(particleShapeName, particleShapeName, particleShapeName), '', ] ## Build new expression cmds.dynExpression( particleShapeName, name = "%s_expression" % particleShapeName, rbd = True, string = self.processExpressionString(expStringList) ) ## Connect some attrs to animatable group attrs = ['inheritFactor', 'conserve', 'drag', 'damp'] for att in attrs: if not cmds.isConnected( '%s.%sSprite' %(animatable, att), '%s.%s' %(particleShapeName, att) ): cmds.connectAttr('%s.%sSprite' %(animatable, att), '%s.%s' %(particleShapeName, att), force = True)
def splashDiscParticleExpressionBeforeDynamics(splashDiscParticle="", oceanShader=""): """ send splashDiscParticle and oceanShader to make custom expression on splashDiscParticle @param splashDiscParticle: Name of SplashDiscParticle @type splashDiscParticle: String -------------------------------------------- @param oceanShader: Name of shader @type oceanShader: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "float $particleFoamEmission = 0.8; \n" newExp += "float $particleWakeEmission = 0.01;\n" newExp += "vector $pos = %s.position;\n" % splashDiscParticle newExp += "vector $vel = %s.velocity;\n" % splashDiscParticle newExp += "float $px = $pos.x;\n" newExp += "float $pz = $pos.z;\n" newExp += "float $disp[] = `colorAtPoint -u $px -v $pz %s`;\n" % oceanShader newExp += "\nif( $vel.y < 0 && $pos.y < ($disp[0]-.2) ){\n\t" newExp += "%s.lifespanPP = 0;\n\t" % splashDiscParticle newExp += "int $vox[] = `fluidVoxelInfo -objectSpace false -cb -voxel $px 0 $pz OceanWakeTexture1`;\n\t" newExp += "if( size($vox) > 0){\n\t\t" newExp += "setFluidAttr -at density -ad -xi $vox[0] -yi $vox[1] -zi $vox[2] -fv $particleWakeEmission OceanWakeTexture1;\n\t" newExp += "}\n\t" newExp += "$vox = `fluidVoxelInfo -objectSpace false -cb -voxel $px 0 $pz OceanWakeFoamTexture1`;\n\t" newExp += "if( size($vox) > 0){\n\t\t" newExp += "setFluidAttr -at temperature -ad -xi $vox[0] -yi $vox[1] -zi $vox[2] -fv $particleFoamEmission OceanWakeFoamTexture1;\n\t}\n" newExp += "}" cmds.dynExpression(splashDiscParticle, string=newExp, runtimeBeforeDynamics=True) return newExp
def init(WeatherUI,self): c.select('emitPlane'); c.emitter(n='rainEmitter',type='surf',r=300,sro=0,nuv=0,cye='none',cyi=1,spd=1,srn=0,nsp=1,tsp=0,mxd=0,mnd=0,dx=0,dy=-1,dz=0,sp=1); c.particle(n='rainParticle'); c.select(cl=True); c.setAttr( "rainParticle|rainParticleShape.particleRenderType", 6); # rainParticleShape/render Attributes c.gravity(n='rainGravity'); c.select(cl=True); c.connectDynamic('rainParticle',em='rainEmitter'); c.connectDynamic('rainParticle',f='rainGravity'); c.addAttr('rainParticleShape', ln='rgbPP', dt='vectorArray' ); c.dynExpression('rainParticleShape', s='rainParticleShape.rgbPP = <<0, 0, 1.0>>', c=1); c.select(cl=True); c.setAttr("particleCloud1.color", 1, 1, 1, type="double3"); #instead of particleCloud1? #sets the collision event and particle spawning c.particle( name='rainCollisionParticle' , inherit=True); c.connectDynamic('rainCollisionParticle',f='rainGravity'); c.select(cl=True); c.setAttr( "rainCollisionParticle|rainCollisionParticleShape.particleRenderType", 6); # rainParticleShape/render Attributes c.setAttr('rainCollisionParticle.inheritFactor', 1); c.event( 'rainParticle', em=2, die=True, target='rainCollisionParticle', spread=0.5, random=True, count=0, name='rainParticleCollideEvent' ); c.floatSliderGrp('rainIntens',en=True, e=True);
def init(WeatherUI,self): c.select('emitPlane'); c.emitter(n='snowEmitter',type='surf',r=300,sro=0,nuv=0,cye='none',cyi=1,spd=1,srn=0,nsp=1,tsp=0,mxd=0,mnd=0,dx=0,dy=-1,dz=0,sp=1); c.particle(n='snowParticle'); c.select(cl=True); c.setAttr( "snowParticle|snowParticleShape.particleRenderType", 8); # 1 ist for 8 c.gravity(n='snowGravity',m=0.5); c.select(cl=True); c.connectDynamic('snowParticle',em='snowEmitter'); c.connectDynamic('snowParticle',f='snowGravity'); c.addAttr('snowParticleShape', ln='rgbPP', dt='vectorArray' ); c.dynExpression('snowParticleShape', s='snowParticleShape.rgbPP = <<1.0, 1.0, 1.0>>', c=1); c.addAttr('snowParticleShape', ln='radius', at='float', min=0, max=20, dv=1); c.setAttr('snowParticleShape.radius', 0.3); c.setAttr("particleCloud1.color", 1, 1, 1, type="double3"); c.setAttr('snowParticleShape.lifespanMode', 2); c.setAttr('snowParticleShape.lifespan', 30) c.select(cl=True); c.floatSliderGrp('snowIntens', en=True, e=True);
def objectNameParticleExpressionBeforeDynamics(objectNameParticle="",oceanShader=""): """ send objectParticle and oceanShader to make custom expression on objectParticle @param objectNameParticle: Name of Object @type objectNameParticle: String -------------------------------------------- @param oceanShader: Name of shader @type oceanShader: String -------------------------------------------- @return: 0-ExpressionText """ newExp = "" newExp += "%s.lifespanPP = rand(2,4);\n"%objectNameParticle newExp += "vector $pos = %s.position;\n"%objectNameParticle newExp += "float $px = $pos.x;\n" newExp += "float $pz = $pos.z;\n" newExp += "float $disp[] = `colorAtPoint -u $px -v $pz %s`;\n"%oceanShader newExp += "if( $pos.y > $disp[0]-0.2 ){\n" newExp += "\n\t%s.lifespanPP = 0;\n"%objectNameParticle newExp += "}\n" cmds.dynExpression(objectNameParticle, string=newExp, runtimeBeforeDynamics=True) return newExp
def _dynamicField(field = "uniform", opts = {}): ## Only proceed if nParticle(s) in selection selection = _filter_type_on_selection(type = 'nParticle', toShape = True) if selection: cmds.select(clear = True) try: ## Field creation node = eval( 'cmds.%s(**%s)' %(field, opts) ) except: node = None if node: for each in selection: cmds.connectDynamic(each, fields = node[0]) ## Set expression to all nParticle (runtimeAfterDynamics) inputForce = cmds.listConnections('%s.outputForce' % node[0], type = 'nParticle', plugs = True) if inputForce: inputForce = list( set( inputForce ) ) for each in inputForce: ## Get expression's current string to add-on inputForce line nParticleShape = each.split(".")[0] currentStr = cmds.dynExpression(nParticleShape, query = True, rad = True, string = True) inputForceStr = 'if (mag(%s) >= 0.001){%s.lifespanPP = 0.0;}\n' %(each, nParticleShape) if not currentStr.endswith('\n'): currentStr = '%s\n' % currentStr currentStr += inputForceStr cmds.dynExpression(nParticleShape, edit = True, rad = True, string = currentStr) else: mel.eval('warning "Failed to create killField!";') else: mel.eval('warning "Please select proper nParticle(s)!";')
def addDriverByParForWrapedTFNode(tfGrp): '''{'del_path':'TfCtrl/Add/Group/addDriverByParForWrapedTFNode(cmds.ls(sl=True)[0])', 'usage':'$fun(cmds.ls(sl=True)[0])', } ''' #get tfNodeGrp cmds.lockNode(tfGrp, l=False) if cmds.attributeQuery('shellPoly', n=tfGrp, exists=True) == False: raise IOError('This is not tfGrp object') else: shellPoly = cmds.getAttr('%s.shellPoly' % (tfGrp)) if cmds.attributeQuery('nParShapeNode', n=tfGrp, exists=True) == False: cmds.addAttr(tfGrp, ln="nParShapeNode", dt="string") else: raise IOError('%s object has a nParShapeNode to control it') tfNodeGrp = tfGrp #print '%s, %s'%(shellPoly, tfNodeGrp) tfNodeGrpVarStr = tfNodeGrp.replace('|', '__') objects = cmds.listRelatives(tfNodeGrp, type='transform', f=True) cmds.lockNode([shellPoly, tfNodeGrp], l=False) ####################create and set nParticle etc.###################################### #create nParticle nPar = cmds.nParticle(n='%s_nPar' % (tfNodeGrp)) cmds.setAttr(nPar[0] + '.t', l=True) cmds.setAttr(nPar[0] + '.r', l=True) cmds.setAttr(nPar[0] + '.s', l=True) cmds.lockNode(nPar[0], l=True) nParShape = nPar[1] #setAttr to get_tfGrpNode cmds.setAttr(tfNodeGrp + '.nParShapeNode', nParShape, type='string', l=True) cmds.lockNode([shellPoly, tfNodeGrp], l=True) cmds.setAttr('%s.computeRotation' % (nParShape), 1) cmds.goal(nParShape, g=shellPoly, w=.99) #set attributes cmds.setAttr(nParShape + '.goalSmoothness', .01) cmds.setAttr(nParShape + '.radius', .01) #add attributes cmds.addAttr(nParShape, ln="cus_toObjPos", dt='doubleArray') cmds.addAttr(nParShape, ln="cus_toObjPos0", dt='doubleArray') #Add particles and set attributes(goalU, goalV, cus_bbsiRadius) initialize states posLi, radiusLi, atULi, atVLi = [], [], [], [] for tfNode in objects: objPos = cmds.objectCenter(tfNode) bbsize = cmds.getAttr(tfNode + '.bbsi')[0] radius = vectorLen(bbsize) / 2 atU = cmds.getAttr(tfNode + '.atU') atV = cmds.getAttr(tfNode + '.atV') posLi.append(objPos) radiusLi.append(radius) atULi.append(atU) atVLi.append(atV) qsEmit(object = nParShape, position=posLi, attributes=( ('cus_radiusPP', 'floatValue', radiusLi), ('goalU', 'floatValue', atULi),\ ('goalV', 'floatValue', atVLi) )\ ) ##creation expression #parCExpStr = cmds.dynExpression(nParShape, q=True,s=True, c=True) parCExpStr = '\n\n\ /*string $tfNode = $%s[int(particleId)];\n\ goalU = `getAttr ($tfNode+".atU")`;\n\ goalV = `getAttr ($tfNode+".atV")`;\n\ cus_toObjPos = 0;*/' % (tfNodeGrpVarStr) cmds.dynExpression(nParShape, s=parCExpStr, c=True) ##runtime after dynamics expression #parRADExpStr = cmds.dynExpression(nParShape, q=True, s=True, rad=True) parRADExpStr = '\n\n\ /*string $tfNode = $%s[int(particleId)];\n\n\ \ if (cus_toObjPos == 1){\n\ float $pos[] = position;\n\ vector $rotate = rotationPP;\n\ setAttr ($tfNode + ".pBInT2") -type "double3" ($pos[0]) ($pos[1]) ($pos[2]);\n\ setAttr ($tfNode + ".pBInR2") -type "double3" ($rotate.x) ($rotate.y) ($rotate.z);\n\ }\n\n\ \ \ if (goalPP==0 && cus_toObjPos==0){\n\ cus_toObjPos = 1;\n\ float $pos[] = `getAttr ($tfNode+".translate")`;\n\ position = <<$pos[0], $pos[1], $pos[2]>>;\n\ vector $rotate = rotationPP;\n\ setAttr ($tfNode + ".pBInT2") -type "double3" ($pos[0]) ($pos[1]) ($pos[2]);\n\ setAttr ($tfNode + ".pBInR2") -type "double3" ($rotate.x) ($rotate.y) ($rotate.z);\n\ setAttr ($tfNode+".pBWeight") 1;\n\ setAttr ($tfNode+".follicleNodeState") 2;\n\ }*/' % (tfNodeGrpVarStr) cmds.dynExpression(nParShape, s=parRADExpStr, rad=True) ######################################create script nodes######################################## ####openCloseMel script node Execute On:Open/close openCloseMelStr = '\n\n\ ///////////for TFNode by Particles/////////////////////\n\ global string $%s[];\n\ $%s = `listRelatives -f "%s"`;\n' % (tfNodeGrpVarStr, tfNodeGrpVarStr, tfNodeGrp) mel.eval(openCloseMelStr) if cmds.objExists("QS_VFX_M_OC"): existsStr = cmds.scriptNode('QS_VFX_M_OC', q=True, bs=True) openCloseMelStr += existsStr cmds.scriptNode('QS_VFX_M_OC', e=True, bs=openCloseMelStr) else: cmds.scriptNode(n='QS_VFX_M_OC', scriptType=1, bs=openCloseMelStr, sourceType='mel') cmds.setAttr('QS_VFX_M_OC.scriptType', l=True) ####timeChangedMel script Node Execute on: Time changed timeChangedMelStr = '\n\n\ ///////////for TFNode by Particles/////////////////////\n\ int $current = `currentTime -q`;\n\ int $start = `playbackOptions -q -min`;\n\ if ($current == $start){\n\ //%s is a global variable, Declare in QS_VFX_M_QC script node.\n\ $%s = `listRelatives -type "transform" "%s"`; \n\ for ($tfNode in $%s){\n\ setAttr($tfNode+".follicleNodeState") 0;\n\ setAttr($tfNode+".pBWeight") 0;\n\ }\n\ }' % (tfNodeGrpVarStr, tfNodeGrpVarStr, tfNodeGrp, tfNodeGrpVarStr) mel.eval(timeChangedMelStr) if cmds.objExists("QS_VFX_M_TC"): existsStr = cmds.scriptNode('QS_VFX_M_TC', q=True, bs=True) timeChangedMelStr += existsStr cmds.scriptNode('QS_VFX_M_TC', e=True, bs=timeChangedMelStr) else: cmds.scriptNode(n='QS_VFX_M_TC', scriptType=7, bs=timeChangedMelStr, sourceType='mel') cmds.setAttr('QS_VFX_M_TC.scriptType', l=True)
def __init__(self, prefix, mesh): ## Create ctrl for bubbles self.bubbleCtrlShape = cmds.createNode( 'implicitSphere', name = '%s_%sShape' % (prefix, self.BUBBLE_CTRL_NAME) ) self.bubbleCtrl = cmds.listRelatives(self.bubbleCtrlShape, parent = True, fullPath = True) self.bubbleCtrl = cmds.rename( self.bubbleCtrl, '%s_%s' % (prefix, self.BUBBLE_CTRL_NAME) ) self.bubbleCtrlGroup = cmds.group( self.bubbleCtrl, name = '%s_%s' % (prefix, self.BUBBLE_CTRL_OFFSET_GRP) ) ## Space locator with speed attribute self.speedLocator = cmds.spaceLocator( name = '%s_%s' % (prefix, self.LOCATOR_NAME) )[0] cmds.addAttr(self.speedLocator, longName = 'speed', attributeType = 'double') cmds.setAttr('%s.speed' % self.speedLocator, keyable = True) ################################################################################################### ## Creation self.bubble, self.bubbleShape = cmds.particle(name = '%s_%s' % (prefix, self.BUBBLE_NAME) ) ## Set presets for attr, val in self.BUBBLE_PRESET_ATTRS.iteritems(): cmds.setAttr('%s.%s' % (self.bubbleShape, attr), val) ## Create necessary PP attr and hook-up necsesary ramp info arrayMap, ramp = self.addAttrPP(particleShapeName = self.bubbleShape, attrPP = self.BUBBLE_ATTR_PP) ## Emitter cmds.select(mesh, replace = True) self.bubbleEmitter = cmds.emitter(type = 'surface', rate = 100, sro = 0, nuv = 0, cye = 'none', cyi = 1, spd = 1, srn = 0, nsp = 1, tsp = 0, mxd = 0, mnd = 0, dx = 1, dy = 0, dz = 0, sp = 0)[1] # elif _TYPE == 'volume': # cmds.select(clear = True) # self.bubbleEmitter = cmds.emitter(pos = [0, 0, 0], type = 'volume', r = 100, sro = 0, nuv = 0, cye = 'none', cyi = 1, spd = 1, srn = 0, nsp = 1, tsp = 0, mxd = 0, mnd = 0, dx = 0, dy = 0, dz = 0, sp = 0, vsh = 'sphere', vof = [0, 0, 0], vsw = 360, tsr = 0.5, afc = 1, afx = 1, arx = 0, alx = 0, rnd = 0, drs = 0, ssz = 0)[0] # cmds.setAttr('%s.scaleX' % self.bubbleEmitter, 0.2) # cmds.setAttr('%s.scaleY' % self.bubbleEmitter, 0.2) # cmds.setAttr('%s.scaleZ' % self.bubbleEmitter, 0.2) self.bubbleEmitter = cmds.rename(self.bubbleEmitter, '%s_%s' % (prefix, self.BUBBLE_EMITTER_NAME) ) cmds.connectDynamic(self.bubbleShape, emitters = self.bubbleEmitter) ################################################################################################### ## Creation self.bubbleBurst, self.bubbleBurstShape = cmds.particle(name = '%s_%s' % (prefix, self.BUBBLEBURST_NAME) ) ## Set presets for attr, val in self.BUBBLEBURST_PRESET_ATTRS.iteritems(): cmds.setAttr('%s.%s' % (self.bubbleBurstShape, attr), val) ## Create necessary PP attr and hook-up necsesary ramp info self.addAttrPP(particleShapeName = self.bubbleBurstShape, attrPP = self.BUBBLEBURST_ATTR_PP) cmds.select(self.bubbleShape, replace = True) self.bubbleBurstEmitter = cmds.emitter(type = 'omni', rate = 100, sro = 0, nuv = 0, cye = 'none', cyi = 1, spd = 1, srn = 0, nsp = 1, tsp = 0, mxd = 0, mnd = 0, dx = 1, dy = 0, dz = 0, sp = 0)[1] self.bubbleBurstEmitter = cmds.rename(self.bubbleBurstEmitter, '%s_%s' % (prefix, self.BUBBLEBURST_EMITTER_NAME) ) cmds.setAttr('%s.speed' % self.bubbleBurstEmitter, 0.4) cmds.addPP(self.bubbleBurstEmitter, attribute = 'rate') cmds.connectDynamic(self.bubbleBurstShape, emitters = self.bubbleBurstEmitter) ################################################################################################### ## Create necessary fields ## Uniform Field self.uniformField = cmds.uniform(name = '%s_%s' % (prefix, self.UNIFORM_FIELD_NAME), pos = [0, 0, 0], m = 2.5, att = 0, dx = 0, dy = 2, dz = 0, mxd = -1, vsh = 'none', vex = 0, vof = [0, 0, 0], vsw = 360, tsr = 0.5)[0] ## Turbulence Field self.turbulenceField = cmds.turbulence(name = '%s_%s' % (prefix, self.TURBULENCE_FIELD_NAME), pos = [0, 0, 0], m = 3, att = 0, f = 10, phaseX = 0, phaseY = 0, phaseZ = 0, noiseLevel = 0, noiseRatio = 0.707, mxd = -1, vsh = 'none', vex = 0, vof = [0, 0, 0], vsw = 360, tsr = 0.5)[0] ## Radial Field self.radialField = cmds.radial(name = '%s_%s' % (prefix, self.RADIAL_FIELD_NAME), pos = [0, 0, 0], m = 2, att = 1, typ = 0, mxd = 20, vsh = 'sphere', vex = 0, vof = [0, 0, 0], vsw = 360, tsr = 0.5)[0] ## Make necessary connections cmds.connectDynamic(self.bubbleShape, fields = self.uniformField) cmds.connectDynamic(self.bubbleBurstShape, fields = self.uniformField) cmds.connectDynamic(self.bubbleShape, fields = self.turbulenceField) cmds.connectDynamic(self.bubbleBurstShape, fields = self.turbulenceField) cmds.connectDynamic(self.bubbleShape, fields = self.radialField) cmds.connectDynamic(self.bubbleBurstShape, fields = self.radialField) ################################################################################################### self.bubbleGroup = cmds.group(self.bubbleCtrlGroup, self.bubble, self.bubbleBurst, self.uniformField, self.turbulenceField, self.radialField, self.bubbleEmitter, self.bubbleBurstEmitter, self.speedLocator, name = '%s_%s' % (prefix, self.BUBBLE_GROUP_NAME) ) cmds.parent(self.bubbleEmitter, self.speedLocator) cmds.pointConstraint(self.bubbleCtrl, self.speedLocator, maintainOffset = False) cmds.pointConstraint(cmds.listRelatives(mesh, parent = True, fullPath = True)[0], self.bubbleCtrlGroup, maintainOffset = False) cmds.setAttr('%s.scaleX' % self.radialField, 3.165) cmds.setAttr('%s.scaleY' % self.radialField, 3.165) cmds.setAttr('%s.scaleZ' % self.radialField, 3.165) attr = {'longName':'speed', 'niceName':' ', 'attributeType':'enum', 'enumName':'Speed:', 'keyable':False} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'minSpeed', 'attributeType':'double', 'defaultValue':0.01, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'maxSpeed', 'attributeType':'double', 'defaultValue':20} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'useSpeed', 'niceName':'Use Speed', 'attributeType':'bool', 'defaultValue':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'emitters', 'niceName':' ', 'attributeType':'enum', 'enumName':'Emitters:', 'keyable':False} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'rate', 'niceName':'Rate', 'attributeType':'double', 'defaultValue':20, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'splashMaxSpeed', 'niceName':'Splash Max Speed', 'attributeType':'double', 'defaultValue':0.1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'directionalSpeed', 'niceName':'Directional Speed', 'attributeType':'double', 'defaultValue':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'randomDirection', 'niceName':'Random Direction', 'attributeType':'double', 'defaultValue':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'burstAttr', 'niceName':' ', 'attributeType':'enum', 'enumName':'Burst Attrs:', 'keyable':False} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'popVelocity', 'niceName':'Pop Velocity', 'attributeType':'double', 'defaultValue':1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'burstSizeMin', 'niceName':'Size Min', 'attributeType':'double', 'defaultValue':0.01, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'burstSizeMax', 'niceName':'Size Max', 'attributeType':'double', 'defaultValue':0.1, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'burstLifespanMin', 'niceName':'Lifespan Min', 'attributeType':'double', 'defaultValue':1, 'min':-1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'burstLifespanMax', 'niceName':'Lifespan Max', 'attributeType':'double', 'defaultValue':2, 'min':-1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'bubbleAttr', 'niceName':' ', 'attributeType':'enum', 'enumName':'Bubble Attrs', 'keyable':False} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'bubbleSizeMin', 'niceName':'Size Min', 'attributeType':'double', 'defaultValue':0.2, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'bubbleSizeMax', 'niceName':'Size Max', 'attributeType':'double', 'defaultValue':0.4, 'min':0} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'lifespanMin', 'niceName':'Lifespan Min', 'attributeType':'double', 'defaultValue':2, 'min':-1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'lifespanMax', 'niceName':'Lifespan Max', 'attributeType':'double', 'defaultValue':4, 'min':-1} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'killField', 'niceName':' ', 'attributeType':'enum', 'enumName':'Kill Field:', 'keyable':False} self.add_custom_attrs(self.bubbleCtrl, **attr) attr = {'longName':'killHeight', 'niceName':'Kill Height', 'attributeType':'double', 'defaultValue':-0.1} self.add_custom_attrs(self.bubbleCtrl, **attr) ################################################################################################### ## Locator speed expression expStringList = [ 'float $time;', 'float $trx;', 'float $try;', 'float $trz;', 'float $dx = %s.translateX - $trx;' % self.speedLocator, 'float $dy = %s.translateY - $try;' % self.speedLocator, 'float $dz = %s.translateZ - $trz;' % self.speedLocator, 'float $d = sqrt( ($dx * $dx) + ($dy * $dy) + ($dz * $dz) );', '%s.speed = abs( $d / ( time - ($time + 0.001) ) );' % self.speedLocator, '$trx = %s.translateX;' % self.speedLocator, '$try = %s.translateY;' % self.speedLocator, '$trz = %s.translateZ;' % self.speedLocator, '$time = time;' ] expString = self.processExpressionString(expStringList) cmds.expression(self.speedLocator, string = expString) ## Bubbles Creation Expression expStringList = [ '%s.lifespanPP = rand(%s.lifespanMin, %s.lifespanMax);' %(self.bubbleShape, self.bubbleCtrl, self.bubbleCtrl) ] expString = self.processExpressionString(expStringList) cmds.dynExpression(self.bubbleShape, string = expString, creation = True) ## Bubbles Runtime After Dynamics expStringList = [ 'vector $vel = %s.velocity;' % self.bubbleShape, 'vector $kill = %s.position;' % self.bubbleShape, 'float $popVel = %s.popVelocity;' % self.bubbleCtrl, 'float $age = %s.age;' % self.bubbleShape, '', 'if ( $kill.y > %s.killHeight )' % self.bubbleCtrl, '{', ' %s.lifespanPP = 0;' % self.bubbleShape, '}', '', 'if ($vel.y >= $popVel)', '{', ' %s.lifespanPP = 0;' % self.bubbleShape, ' %s.%s_emitterRatePP = 100;' % (self.bubbleShape, '_'.join(self.bubbleBurst.split('_')[0:-1])), '}', ] expString = self.processExpressionString(expStringList) cmds.dynExpression(self.bubbleShape, string = expString, runtimeAfterDynamics = True) ## Bubble Bursts Creation Expression expStringList = [ '%s.lifespanPP = rand(%s.burstLifespanMin, %s.burstLifespanMax);' %(self.bubbleBurstShape, self.bubbleCtrl, self.bubbleCtrl), '%s.radiusPP = rand(%s.burstSizeMin, %s.burstSizeMax)' % (self.bubbleBurstShape, self.bubbleCtrl, self.bubbleCtrl), ] expString = self.processExpressionString(expStringList) cmds.dynExpression(self.bubbleBurstShape, string = expString, creation = True) ## Bubble Bursts Runtime After Dynamics Expression expStringList = [ 'vector $kill = %s.position;' % self.bubbleBurstShape, '', 'if ($kill.y > %s.killHeight)' % self.bubbleCtrl, '{', ' %s.lifespanPP = 0;' % self.bubbleBurstShape, '}', ] expString = self.processExpressionString(expStringList) cmds.dynExpression(self.bubbleBurstShape, string = expString, runtimeAfterDynamics = True) ## Expression for Turbulence Field expStringList = [ '%s.phaseX = time;' % self.turbulenceField, '%s.phaseY = time;' % self.turbulenceField, '%s.phaseZ = time;' % self.turbulenceField, ] expString = self.processExpressionString(expStringList) cmds.expression(self.turbulenceField, string = expString) ## Expression for Bubble Emitter expStringList = [ 'float $minSpeed = %s.minSpeed;' % self.bubbleCtrl, 'float $maxSpeed = %s.maxSpeed;' % self.bubbleCtrl, 'float $speed = %s.speed;' % self.speedLocator, 'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);', 'float $rateMuliplier = %s.rate;' % self.bubbleCtrl, 'float $splashMaxSpeed = %s.splashMaxSpeed;' % self.bubbleCtrl, '', 'if (%s.useSpeed == 1)' % self.bubbleCtrl, '{', ' %s.rate = $rateMuliplier * $curve;' % self.bubbleEmitter, '', ' float $emitterSpeed = $splashMaxSpeed * $curve;', ' if ($emitterSpeed == 0)', ' {', ' $emitterSpeed = 0.1;', ' }', ' %s.awayFromCenter = $emitterSpeed;' % self.bubbleEmitter, '}', 'else', '{', ' %s.rate = $rateMuliplier;' % self.bubbleEmitter, ' %s.awayFromCenter = $splashMaxSpeed;' % self.bubbleEmitter, '}', '%s.alongAxis = %s.directionalSpeed;' % (self.bubbleEmitter, self.bubbleCtrl), '%s.randomDirection = %s.randomDirection;' % (self.bubbleEmitter, self.bubbleCtrl), ] expString = self.processExpressionString(expStringList) cmds.expression(self.bubbleEmitter, string = expString) ################################################################################################### ## Finalizing stuffs cmds.connectAttr('%s.bubbleSizeMin' % self.bubbleCtrl, '%s.minValue' % arrayMap) cmds.connectAttr('%s.bubbleSizeMax' % self.bubbleCtrl, '%s.maxValue' % arrayMap) ################################################################################################### ## Assigning shader self.bubbleShader(particleShapeName = [self.bubbleShape, self.bubbleBurstShape])
def particleLocators(particle, bakeSimulation=False, rotate=False, scale=False, start=0, end=-1, prefix=''): """ """ # Check Particle if not cmds.objExists(particle): raise Exception('Object "' + nParticle + '" is not a valid particle or nParticle object!') # Check Prefix if not prefix: prefix = particle # Get particle count count = cmds.getAttr(particle + '.count') if not count: raise Exception('Invalid particle count! (' + count + ')') # Create locators partiLocs = [cmds.spaceLocator(n=prefix + '_loc' + str(i))[0] for i in range(count)] partiLocsGrp = prefix + '_locGrp' if not cmds.objExists(partiLocsGrp): partiLocsGrp = cmds.group(em=True, n=partiLocsGrp) cmds.parent(partiLocs, partiLocsGrp) # For each particle, set locator position for i in range(count): pt = cmds.pointPosition(particle + '.pt[' + str(i) + ']') cmds.setAttr(partiLocs[i] + '.t', *pt) if rotate: rt = cmds.particle(particle, q=True, at='rotatePP', id=i) cmds.setAttr(partiLocs[i] + '.r', *rt) if scale: sc = cmds.particle(particle, q=True, at='scalePP', id=i) cmds.setAttr(partiLocs[i] + '.s', *sc) # Bake Simulation if (bakeSimulation): # Append particle expression expStr = '\n\n//--\n' expStr += 'int $id = id;\n' expStr += 'vector $pos = pos;\n' expStr += 'string $loc = ("' + prefix + '_loc"+$id);\n' expStr += 'if(`objExists $loc`){' expStr += '\t move -a ($pos.x) ($pos.y) ($pos.z) $loc;\n' if rotate: expStr += '\tvector $rot = rotatePP;\n' expStr += '\t rotate -a ($rot.x) ($rot.y) ($rot.z) $loc;\n' if scale: expStr += '\tvector $scl = scalePP;\n' expStr += '\t scale -a ($scl.x) ($scl.y) ($scl.z) $loc;\n' expStr += '}' # Old expression string oldRadStr = cmds.dynExpression(particle, q=True, s=True, rad=True) # Apply particle expression cmds.dynExpression(particle, s=oldRadStr + expStr, rad=True) # Bake to keyframes if end < start: start = cmds.playbackOptions(q=True, min=True) end = cmds.playbackOptions(q=True, max=True) bakeAttrs = ['tx', 'ty', 'tz'] if rotate: bakeAttrs.extend(['rx', 'ry', 'rz']) if scale: bakeAttrs.extend(['sx', 'sy', 'sz']) cmds.bakeSimulation(partiLocs, at=bakeAttrs, t=(start, end)) # Restore particle expression cmds.dynExpression(particle, s=oldRadStr, rad=True)
partsShape.radiusPP = .2; float $rx = rand(.1)-.05; float $rz = rand(.1)-.05; //emit -pos ($p.x+$rx) ($p.y) ($p.z+$rz) -o partsShape; // set the color to be based on the parent's color - Brian if (partsShape.rgbPP == <<0,0,1>>) emit -pos ($p.x+$rx) ($p.y) ($p.z+$rz) -o partsShape -attribute rgbPP -vectorValue 0 0 1; else emit -pos ($p.x+$rx) ($p.y) ($p.z+$rz) -o partsShape; } """ % locals() mc.dynExpression('partsShape', s='%s' % expression, rbd=True) ## Capsule constructed along the z axis. #capsuleArray = pm.polyCylinder(axis=(0, 0, 1), r=1, h=2, sx=20, sy=10, sz=5, sa=20, rcp=True) ## Move the capsule 10 units along the z axis ## BUG - The function doesn't except "micrometers" as a unit #capsuleArray[0].translateBy(pm.datatypes.Vector(0, 0, 10, unit='millimeters')) ## A sphere is added at the center of the capsule. #sphereArray = pm.polySphere(r=1) ## Move the sphere 10 units along the z axis ## BUG - The function doesn't except "micrometers" as a unit #sphereArray[0].translateBy(pm.datatypes.Vector(0, 0, 10, unit='millimeters')) ## The capsule and sphere are grouped #group = pm.group(capsuleArray[0].nodeName(), sphereArray[0].nodeName())
def _setupSide_ParticleExpressions(particleShapeName='', type='splash', boatWorldCtrl='', boatName='', cPoS='', sideAnimatable=''): """ Setup the expressions for the sideEmitter's nParticleShape node @param particleShapeName: The name of the nParticleShape node @param boatWorldCtrl: The name of the boatWorldCtrl curve @param boatName: The name of the boat should be stripped : @type particleShapeName: String @type boatWorldCtrl: String @type boatName: String """ if type == 'splash': ############################ ## Creation expStringList = [ '%s.lifespanPP = rand(%s.lifespanMin, %s.lifespanMax);\n' % (particleShapeName, sideAnimatable, sideAnimatable), '%s.twistSpeedPP = rand(%s.twistSpeedMin, %s.twistSpeedMax);\n' % (particleShapeName, sideAnimatable, sideAnimatable), '%s.spriteStartSizePP = rand(%s.spriteStartSizeMin, %s.spriteStartSizeMax);\n' % (particleShapeName, sideAnimatable, sideAnimatable), '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP;\n' % (particleShapeName, particleShapeName, particleShapeName), '%s.spriteTwistPP = rand(%s.twistAngleMin, %s.twistAngleMax);\n' % (particleShapeName, sideAnimatable, sideAnimatable), ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sprite_settings' % particleShapeName) ## Build new expression cmds.dynExpression(particleShapeName, n="%s_sprite_settings" % particleShapeName, creation=True, string=utils.processExpressionString(expStringList)) ############################ ## Runtime Before Dynamics expStringList = [ '%s.spriteScaleYPP = %s.spriteScaleXPP = %s.spriteStartSizePP * %s.scaleOverLifeRamp;\n' % (particleShapeName, particleShapeName, particleShapeName, particleShapeName), '%s.spriteScaleXPP = %s.spriteScaleYPP;\n' % (particleShapeName, particleShapeName), '%s.spriteTwistPP += (%s.twistSpeedPP * %s.twistRateOverLife);\n' % (particleShapeName, particleShapeName, particleShapeName), '\n', ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sprite_settings' % particleShapeName) ## Build new expression cmds.dynExpression(particleShapeName, n="%s_sprite_settings" % particleShapeName, rbd=True, string=utils.processExpressionString(expStringList)) ## Connect some attrs to animatable group attrs = ['inheritFactor', 'conserve', 'drag', 'damp'] for att in attrs: if not cmds.isConnected('%s.%sSprite' % (sideAnimatable, att), '%s.%s' % (particleShapeName, att)): cmds.connectAttr('%s.%sSprite' % (sideAnimatable, att), '%s.%s' % (particleShapeName, att), force=True) elif type == 'mist': ## Creation expStringList = [ '%s.lifespanPP = rand(%s.lifespanMin, %s.lifespanMax);\n' % (particleShapeName, sideAnimatable, sideAnimatable), ] ## Check if the expression already exists in the scene, if so delete it utils.checkExpressionExists('%s_sprite_settings' % particleShapeName) ## Build new expression cmds.dynExpression(particleShapeName, n="%s_sprite_settings" % particleShapeName, creation=True, string=utils.processExpressionString(expStringList)) ## Connect some attrs to animatable group attrs = ['inheritFactor', 'conserve', 'drag', 'damp'] for att in attrs: if not cmds.isConnected('%s.%sMist' % (sideAnimatable, att), '%s.%s' % (particleShapeName, att)): cmds.connectAttr('%s.%sMist' % (sideAnimatable, att), '%s.%s' % (particleShapeName, att), force=True)
def particleLocators(particle, bakeSimulation=False, rotate=False, scale=False, start=0, end=-1, prefix=''): ''' ''' # Check Particle if not mc.objExists(particle): raise Exception('Object "' + nParticle + '" is not a valid particle or nParticle object!') # Check Prefix if not prefix: prefix = particle # Get particle count count = mc.getAttr(particle + '.count') if not count: raise Exception('Invalid particle count! (' + count + ')') # Create locators partiLocs = [ mc.spaceLocator(n=prefix + '_loc' + str(i))[0] for i in range(count) ] partiLocsGrp = prefix + '_locGrp' if not mc.objExists(partiLocsGrp): partiLocsGrp = mc.group(em=True, n=partiLocsGrp) mc.parent(partiLocs, partiLocsGrp) # For each particle, set locator position for i in range(count): pt = mc.pointPosition(particle + '.pt[' + str(i) + ']') mc.setAttr(partiLocs[i] + '.t', *pt) if rotate: rt = mc.particle(particle, q=True, at='rotatePP', id=i) mc.setAttr(partiLocs[i] + '.r', *rt) if scale: sc = mc.particle(particle, q=True, at='scalePP', id=i) mc.setAttr(partiLocs[i] + '.s', *sc) # Bake Simulation if (bakeSimulation): # Append particle expression expStr = '\n\n//--\n' expStr += 'int $id = id;\n' expStr += 'vector $pos = pos;\n' expStr += 'string $loc = ("' + prefix + '_loc"+$id);\n' expStr += 'if(`objExists $loc`){' expStr += '\t move -a ($pos.x) ($pos.y) ($pos.z) $loc;\n' if rotate: expStr += '\tvector $rot = rotatePP;\n' expStr += '\t rotate -a ($rot.x) ($rot.y) ($rot.z) $loc;\n' if scale: expStr += '\tvector $scl = scalePP;\n' expStr += '\t scale -a ($scl.x) ($scl.y) ($scl.z) $loc;\n' expStr += '}' # Old expression string oldRadStr = mc.dynExpression(particle, q=True, s=True, rad=True) # Apply particle expression mc.dynExpression(particle, s=oldRadStr + expStr, rad=True) # Bake to keyframes if end < start: start = mc.playbackOptions(q=True, min=True) end = mc.playbackOptions(q=True, max=True) bakeAttrs = ['tx', 'ty', 'tz'] if rotate: bakeAttrs.extend(['rx', 'ry', 'rz']) if scale: bakeAttrs.extend(['sx', 'sy', 'sz']) mc.bakeSimulation(partiLocs, at=bakeAttrs, t=(start, end)) # Restore particle expression mc.dynExpression(particle, s=oldRadStr, rad=True)
def setColor(*argv): rgb = cmds.colorSliderGrp("GalaxyColor", q = True, rgbValue = True) rgb = ', '.join(str(i) for i in rgb) rgb = 'rgbPP = rand(<<0, 0, 0.6>>,<<' + str(rgb) + '>>)' cmds.dynExpression("Galaxy_StarShape", s = rgb, creation = True, runtimeAfterDynamics = True) cmds.dynExpression("Galaxy_CloudShape", s = rgb, creation = True, runtimeAfterDynamics = True)
def doIt(self, args): # Procesar argumentos try: self.parseArgs(args) except Exception as e: print('[' + commandName + '] Sintaxis de flag invalida') return # Guardar seleccion de la superficie surface = cmds.ls(sl=True) ################################# Control maestro ############################### cmds.spaceLocator(name=self.controllerName) cmds.addAttr(ln='floor', at='double', defaultValue=self.floor) cmds.addAttr(ln='beginTolerance', at='double', defaultValue=0.3, minValue=0, maxValue=1) cmds.addAttr(ln='gravity', at='double', defaultValue=self.gravity) cmds.addAttr(ln='magnitudeTLow', at='double', defaultValue=self.turbulenceLow) cmds.addAttr(ln='magnitudeTHigh', at='double', defaultValue=self.turbulenceHigh) cmds.addAttr(ln='dewRate', at='double', defaultValue=self.dewRate, minValue=0) cmds.addAttr(ln='spumeRate', at='double', defaultValue=self.spumeRate, minValue=0) cmds.addAttr(ln='waterRate', at='double', defaultValue=self.waterRate, minValue=0) cmds.setAttr(self.controllerName + '.translateX', keyable=False) cmds.setAttr(self.controllerName + '.translateY', keyable=False) cmds.setAttr(self.controllerName + '.translateZ', keyable=False) cmds.setAttr(self.controllerName + '.rotateX', keyable=False) cmds.setAttr(self.controllerName + '.rotateY', keyable=False) cmds.setAttr(self.controllerName + '.rotateZ', keyable=False) cmds.setAttr(self.controllerName + '.scaleX', keyable=False) cmds.setAttr(self.controllerName + '.scaleY', keyable=False) cmds.setAttr(self.controllerName + '.scaleZ', keyable=False) cmds.setAttr(self.controllerName + '.floor', keyable=True) cmds.setAttr(self.controllerName + '.beginTolerance', keyable=True) cmds.setAttr(self.controllerName + '.gravity', keyable=True) cmds.setAttr(self.controllerName + '.magnitudeTLow', keyable=True) cmds.setAttr(self.controllerName + '.magnitudeTHigh', keyable=True) cmds.setAttr(self.controllerName + '.dewRate', keyable=True) cmds.setAttr(self.controllerName + '.spumeRate', keyable=True) cmds.setAttr(self.controllerName + '.waterRate', keyable=True) ################################ Campos de fuerza ############################### cmds.select(clear=True) cmds.gravity(name=self.gravityName, att=0, dx=0, dy=-1, dz=0) cmds.connectAttr(self.controllerName + '.gravity', self.gravityName + '.magnitude') cmds.select(clear=True) cmds.turbulence(name=self.turbulenceLowName, att=0, f=0.8, nsr=0.6) cmds.expression( s= "phaseX = rand(1,100)*10;\nphaseY = rand(1,100)*20;\nphaseZ = rand(1,100)*30;", o=self.turbulenceLowName, alwaysEvaluate=1) cmds.connectAttr(self.controllerName + '.magnitudeTLow', self.turbulenceLowName + '.magnitude') cmds.select(clear=True) cmds.turbulence(name=self.turbulenceHighName, att=0, f=0.8, nsr=0.7) cmds.expression( s= "phaseX = time*135.165;\nphaseY = time+10*135.165;\nphaseZ = time+767*135.165;", o=self.turbulenceHighName, alwaysEvaluate=1) cmds.connectAttr(self.controllerName + '.magnitudeTHigh', self.turbulenceHighName + '.magnitude') ##################################### Gotas ##################################### # Crear sistema y emisor cmds.select(surface) cmds.emitter(n=self.dewEmitterName, type='surface', rate=self.dewRate) cmds.particle(n=self.dewSystemName) cmds.connectDynamic(self.dewSystemShapeName, em=self.dewEmitterName) cmds.connectAttr(self.controllerName + '.dewRate', self.dewEmitterName + '.rate') # Agregar goal entre superficie y sistema cmds.select(self.dewSystemName, r=True) cmds.select(surface, add=True) cmds.goal(self.dewSystemName, g=surface, w=1, utr=0) cmds.connectDynamic(self.dewSystemName, f=self.gravityName) cmds.connectDynamic(self.dewSystemName, f=self.turbulenceLowName) cmds.connectDynamic(self.dewSystemName, f=self.turbulenceHighName) # Setear valores cmds.setAttr(self.dewSystemShapeName + ".conserve", 0.98) cmds.setAttr(self.dewSystemShapeName + ".lifespanMode", 3) # only LifespanPP cmds.setAttr(self.dewSystemShapeName + ".particleRenderType", 3) # points cmds.select(self.dewSystemShapeName) cmds.addAttr(ln='goalU', dt='doubleArray') cmds.addAttr(ln='goalU0', dt='doubleArray') cmds.addAttr(ln='goalV', dt='doubleArray') cmds.addAttr(ln='goalV0', dt='doubleArray') cmds.addAttr(ln='opacityPP', dt='doubleArray') cmds.addAttr(ln='opacityPP0', dt='doubleArray') cmds.dynExpression(self.dewSystemShapeName, s="goalV = 0;\ngoalU = rand(1);\nopacityPP = 0;", c=1) cmds.dynExpression( self.dewSystemShapeName, s="goalV += rand(0.1);\nif (goalV > " + self.controllerName + ".beginTolerance){\n\topacityPP = 1;\n}\nif (goalV > 0.99){\n\tgoalPP = 0;\n\tvector $pos = position;\n\tif ($pos.y < " + self.controllerName + ".floor){\n\t\tlifespanPP = 0;\n\t}\n}", rbd=1) ##################################### Espuma #################################### # Crear sistema y emisor cmds.select(surface) cmds.emitter(n=self.spumeEmitterName, type='surface', rate=self.spumeRate) cmds.particle(n=self.spumeSystemName) cmds.connectDynamic(self.spumeSystemShapeName, em=self.spumeEmitterName) cmds.connectAttr(self.controllerName + '.spumeRate', self.spumeEmitterName + '.rate') # Agregar goal entre superficie y sistema cmds.select(self.spumeSystemName, r=True) cmds.select(surface, add=True) cmds.goal(self.spumeSystemName, g=surface, w=1, utr=0) cmds.connectDynamic(self.spumeSystemName, f=self.gravityName) cmds.connectDynamic(self.spumeSystemName, f=self.turbulenceLowName) cmds.connectDynamic(self.spumeSystemName, f=self.turbulenceHighName) # Setear valores cmds.setAttr(self.spumeSystemShapeName + ".conserve", 0.98) cmds.setAttr(self.spumeSystemShapeName + ".lifespanMode", 3) # only LifespanPP cmds.setAttr(self.spumeSystemShapeName + ".particleRenderType", 6) # streaks cmds.select(self.spumeSystemShapeName) cmds.addAttr(ln='goalU', dt='doubleArray') cmds.addAttr(ln='goalU0', dt='doubleArray') cmds.addAttr(ln='goalV', dt='doubleArray') cmds.addAttr(ln='goalV0', dt='doubleArray') cmds.addAttr(ln='opacityPP', dt='doubleArray') cmds.addAttr(ln='opacityPP0', dt='doubleArray') cmds.dynExpression(self.spumeSystemShapeName, s="goalV = 0;\ngoalU = rand(1);\nopacityPP = 0;", c=1) cmds.dynExpression( self.spumeSystemShapeName, s="goalV += rand(0.1);\nif (goalV > " + self.controllerName + ".beginTolerance){\n\topacityPP = 1;\n}\nif (goalV > 0.99){\n\tgoalPP = 0;\n\tvector $pos = position;\n\tif ($pos.y < " + self.controllerName + ".floor){\n\t\tlifespanPP = 0;\n\t}\n}", rbd=1) ###################################### Agua ##################################### # Crear sistema y emisor cmds.select(surface) cmds.emitter(n=self.waterEmitterName, type='surface', rate=self.waterRate) cmds.particle(n=self.waterSystemName) cmds.connectDynamic(self.waterSystemShapeName, em=self.waterEmitterName) cmds.connectAttr(self.controllerName + '.waterRate', self.waterEmitterName + '.rate') # Agregar goal entre superficie y sistema cmds.select(self.waterSystemName, r=True) cmds.select(surface, add=True) cmds.goal(self.waterSystemName, g=surface, w=1, utr=0) cmds.connectDynamic(self.waterSystemName, f=self.gravityName) cmds.connectDynamic(self.waterSystemName, f=self.turbulenceLowName) cmds.connectDynamic(self.waterSystemName, f=self.turbulenceHighName) # Setear valores cmds.setAttr(self.waterSystemShapeName + ".conserve", 0.98) cmds.setAttr(self.waterSystemShapeName + ".lifespanMode", 3) # only LifespanPP cmds.setAttr(self.waterSystemShapeName + ".particleRenderType", 7) # Bubble cmds.select(self.waterSystemShapeName) cmds.addAttr(ln='threshold', at='float', defaultValue=0.75, minValue=0, maxValue=10) #cmds.addAttr(ln='radius',at='float',defaultValue=0.75,minValue=0,maxValue=20) cmds.addAttr(ln='radiusPP', dt='doubleArray') cmds.addAttr(ln='radiusPP0', dt='doubleArray') cmds.setAttr(self.waterSystemShapeName + ".threshold", 0.75) cmds.select(self.waterSystemShapeName) cmds.addAttr(ln='goalU', dt='doubleArray') cmds.addAttr(ln='goalU0', dt='doubleArray') cmds.addAttr(ln='goalV', dt='doubleArray') cmds.addAttr(ln='goalV0', dt='doubleArray') cmds.dynExpression( self.waterSystemShapeName, s= "goalV = 0;\ngoalU = rand(1);\nif (rand(1) < 0.25){\n\tradiusPP = rand(0.7);\n} else {\n\tradiusPP = rand(1,2);\n}", c=1) cmds.dynExpression( self.waterSystemShapeName, s="goalV += rand(0.1);\nif (goalV > 0.99){\n\tgoalPP = 0;\n\tvector $pos = position;\n\tif ($pos.y < " + self.controllerName + ".floor){\n\t\tlifespanPP = 0;\n\t}\n}", rbd=1) cmds.select(self.controllerName) # cmds.getAttr() self.dagModifier.doIt()
def __publish_maya_nParticle_export(self, item, output, work_template, primary_publish_path, sg_task, comment, thumbnail_path, progress_cb): """ Publish a Maya export selected for the selected nParticle systems and publish it to Shotgun. :param item: The item to publish :param output: The output definition to publish with :param work_template: The work template for the current scene :param primary_publish_path: The path to the primary published file :param sg_task: The Shotgun task we are publishing for :param comment: The publish comment/description :param thumbnail_path: The path to the publish thumbnail :param progress_cb: A callback that can be used to report progress """ # determine the publish info to use # print("Running maya export selected command...") progress_cb(10, "Determining publish details") # get the current scene path and extract fields from it # using the work template: scene_path = os.path.abspath(cmds.file(query=True, sn=True)) fields = work_template.get_fields(scene_path) publish_version = fields["version"] tank_type = output["tank_type"] fields["grp_name"] = str(item['name']).split("|")[1] print("Got fields...") print("Applying fields...") # create the publish path by applying the fields # with the publish template: publish_template = output["publish_template"] publish_path = publish_template.apply_fields(fields) # publish name, NO VERSION NUMBERS HERE # This should be a name that's the same accross all publishes so the Loader app can group them to create a version history # @TODO: Set up a template or something to handle this nicely, ideally this would be: basename.(publish_path) - {version} and {extension} publish_name = "nParticle_" + fields["grp_name"] + "_" + fields["name"] #publish_name = os.path.basename(publish_path) # Also get the cache template to copy over the particle cache as well # @TODO: Read this from *_step.yml, for now I'm just applying a naming convention cache_template = sgtk.platform.current_engine().get_template_by_name(output["publish_template"].name.replace("nparticle","nparticle_cache")) print("Applied fields to templates...") print(publish_path) # Find additional info from the scene: # progress_cb(10, "Analysing scene") # The main body of this export: # Select each node in the hierarchy above a particle system and a bunch of related nodes, such as instancers, cache nodes and the nucleus node selection = [] for nParticle_object in cmds.ls(item["name"], dag=True, type="nParticle", long=True): # get the name of the particle system split_path = str(nParticle_object).split("|")[1:] print(split_path) # get all instancers connected to the particle system and append it to the selection list con = cmds.listConnections(split_path[len(split_path)-1:], type="instancer") if con: for i in set(con): selection.extend(cmds.ls(i, long=True)) print(con) # get all instances connected to the instancer and append it to the selection list if con: inst = cmds.particleInstancer(split_path[len(split_path)-1:], q=True, object=True) if inst: for i in set(inst): selection.extend(cmds.ls(i, long=True)) print(inst) # get the cache node, append it to the selection list and copy the cache to the publishing directory cache = cmds.listConnections(split_path[len(split_path)-1:], type="cacheFile") print(cache) if cache: for i in set(cache): print("copy cache loop!") # append cache node to selection selection.extend(cmds.ls(i, long=True)) # modify a copy of "fields" to add the node name, the "grp_name" field is used for this # This is done to make sure all caches stay unique and with the correct node temp_fields = fields #temp_fields["grp_name"] = "{0}".format(cmds.getAttr('{0}.cacheName'.format(i))) cache_path = cache_template.apply_fields(temp_fields).replace("\\", "/") print("start copy!") progress_cb(30, "Copying Cache") # Copy the cache files to the publishing folder, this takes a while # @TODO: More interactive feedback for the user # @TODO2: Optimize, run this in background so the user can continue working and # make sure the files aren't copied locally first if they're moving from 1 location on the server # to another location on the server dirutil.copy_tree(cmds.getAttr('{0}.cachePath'.format(i)), cache_path) print("copy done!") progress_cb(50, "Analyzing scene") # Set the path of the cache node to the new location, # for some reason the setAttr MEL command for this is more reliable than the python setAttr command... mel.eval('setAttr -type "string" {0}.cachePath "{1}"'.format(i, cache_path)) print("cache path set!") # Get all nucleus nodes and append them to the selection list nucleus = cmds.listConnections(split_path[len(split_path)-1:], type="nucleus") if nucleus: for i in set(nucleus): selection.extend(cmds.ls(i, long=True)) print(nucleus) # Get all display layers and appends them to the selection list #for i in cmds.ls(type="displayLayer"): # selection.extend(cmds.ls(i, long=True)) selection.append(nParticle_object) # Remove all expressions from the particle systems in the selection as these can cause issues cmds.dynExpression(nParticle_object, c=True, s="") cmds.dynExpression(nParticle_object, rbd=True, s="") cmds.dynExpression(nParticle_object, rad=True, s="") # Get display layers the object is in and appends them to the selection list print(selection) for i in range(len(selection)): split_sel = selection[i].split("|") print split_sel if len(split_sel) > 1: dispLayer = cmds.listConnections(list(split_sel[1:]), type="displayLayer") else: dispLayer = cmds.listConnections(str(split_sel[0]), type="displayLayer") print(dispLayer) if dispLayer: for i in set(dispLayer): selection.extend(cmds.ls(i, long=True)) # Make a set of the selection list to get rid of duplicate entries selection = set(selection) print("test") print(selection) # Because we want to delete everything except what is in the selection list # we select everything and then deselect the things in the selection list cmds.select(all=True, hi=True) for i in selection: split_sel = i.split("|") if len(split_sel) > 1: cmds.select(split_sel[1:], deselect=True) else: cmds.select(split_sel[0], deselect=True) print("test2") self.parent.log_debug("Executing delete, export selection and reopen") # delete everything that is selected now cmds.delete() print("test3") # clear the selection, just in case things didn't get deleted for some reason (ie, maya system nodes, reference nodes, etc.) # then select everything to be exported again cmds.select(clear=True) for i in selection: split_sel = i.split("|") if len(split_sel) > 1: cmds.select(split_sel[1:], add=True) else: cmds.select(split_sel[0], add=True) progress_cb(60, "Export scene and reopening file") # get the current file, so we can reopen it after saving old_file = cmds.file(q=True,sceneName=True) # rename the file and "export selected" cmds.file(rename=publish_path) cmds.file(exportSelected=True,type='mayaAscii',force=True) # create a new empty file in case it's easier to open from cmds.file(new=True, force=True) # open the old file from before for the publish registration, otherwise the template won't fit # could this cause issues? cmds.file(old_file, open=True) print("Registering Export Publish") # all data to register the publish # NOTE!!: publish_path has to have backslashes, forward slashes cause the publish to fail! progress_cb(75, "Registering the publish") args = { "tk": self.parent.tank, "context": self.parent.context, "comment": comment, "path": publish_path, "name": publish_name, "version_number": publish_version, "thumbnail_path": thumbnail_path, "task": sg_task, "dependency_paths": [primary_publish_path], "published_file_type":tank_type } # register the publish tank.util.register_publish(**args) print("Finished Registering Export Publish")
def set_goals(): sel = cmds.ls(sl=True, l=True) # make sure we have at least two items if len(sel) < 2: print 'Please select a nParticle system followed by the objects to set as goals' return elif len(sel) > 2: print 'For inital goal we want one particle system and one object to goal!' print 'Try again :)' return print sel # from the list make sure the first object is a nparticle system, get a handle on this # then remove from the list if not cmds.objectType(sel[0]) == 'nParticle': shape = cmds.listRelatives(sel[0])[0] if not cmds.objectType(shape) == 'nParticle': print 'Please select a nParticle system followed by objects to goal to!' return else: npSystem = sel.pop(0) npShape = shape else: npShape = sel.pop(0) npSystem = cmds.listRelatives(npShape, parent=True, f=True) obj = sel[0] selList = om.MSelectionList() selList.add(npShape) npDag = om.MDagPath() npMObj = om.MObject() selList.getDependNode(0, npMObj) selList.getDagPath(0, npDag) npNode = om.MFnDependencyNode(npMObj) npFnPart = omfx.MFnParticleSystem(npDag) if _get_goal(npDag): print 'Particle system already has goal. For now we are only supporting one goal!' return cmds.goal(npSystem, g=obj, w=1) set_initial_state(npNode, npFnPart) print '#------------------------------#' creation_dynExpression = ('.goalV = 0;\n' '.goalU = 0;\n' '.goalWeight0PP = .2;\n' '.verticalSpeedPP = rand(0.01, 0.1);\n' '.rotationRatePP = rand(0.03, 0.05);\n' '.jitterIntervalPP = 0;\n' '.jitterStepPP = 0;\n' '.jitterRangePP = 0;\n' '.lifespanPP = 5;') runtime_dynExpression = ('.goalV += .verticalSpeedPP;\n' '.goalU += .rotationRatePP;\n\n' 'if (.jitterIntervalPP > .jitterStepPP)\n' '{\n' '\t.jitterStepPP ++;\n' '}\n' 'else\n' '{\n' '\t.goalU += .jitterValuePP;\n' '\t$hiRange = rand(0, .jitterRangePP);\n' '\t$loRange = $hiRange * -1;\n' '\t.jitterValuePP = rand($loRange, $hiRange);\n' '\t.jitterStepPP = 0;\n' '}\n\n' 'if (.goalU > 1)\n' '{\n' '\t.goalU -= 1;\n' '}\n' 'else if(.goalU < 0)\n' '{\n' '\t.goalU += 1;\n' '}') cmds.dynExpression(npShape, creation=True, string=creation_dynExpression) cmds.dynExpression(npShape, rbd=True, string=runtime_dynExpression) # now we want to make our goal object a passive rigid body so that # the particles don't go through it cmds.select(obj) print 'Selection is: %s' % cmds.ls(sl=True) # make our goal object a passive rigid body so the particles # can collide with it cmd = 'makeCollideNCloth' rigidShape = mel.eval(cmd) # rigid shape is not created if it already exists! if rigidShape: # parent the rigid body to keep things tidy nRigid = cmds.listRelatives(rigidShape[0], parent=True, f=True) #cmds.parent(nRigid, dynamics_grp) # select our particle system to tidy things up cmds.select(npSystem)
def miSequence(start=None, end=None): '''{'path':'Rendering/Render/miSequence()ONLYSE', 'icon' : ':/menuIconRender.png', 'tip' : '将物体转为mentalray代理的粒子替代', 'usage':'$fun( start=0, end=100)', } ''' projDir = cmds.workspace(q=1, rootDirectory=1) proxyFolder = os.path.join(projDir, 'data/mrProxyFiles') if os.path.exists(proxyFolder) == False: os.makedirs(proxyFolder) exportObjs = cmds.ls(sl=True) if start == None: start = cmds.playbackOptions(q=True, min=True) if end == None: end = cmds.playbackOptions(q=True, max=True) end = end + 1 pad = 5 padStr = '%0' + '%sd' % (pad) #print padStr subFolder = exportObjs[0] finalFolder = proxyFolder + '/' + subFolder if os.path.exists(finalFolder) == False: os.makedirs(finalFolder) import mentalray.renderProxyUtils proxyObjs = [] for i in range(start, end): cmds.currentTime(i) exec('frameStr = padStr%(i)') miName = '%s_s.%s.mi' % (exportObjs[0], frameStr) miFilePath = finalFolder + '/' + miName print miFilePath #miFilePath = 'F:/t.mi' cmds.select(exportObjs, r=True) mel.eval( 'Mayatomr -mi -exportFilter 721600 -active -binary -fe -fem -fma -fis -fcd -pcm -as -asn "%s" -xp "3313333333" -file "%s";' % (exportObjs[0] + "_s", miFilePath)) proxyName = miName.replace('.', '-') proxyObj = cmds.polyCube(ch=False, name=proxyName)[0] proxyObjs.append(proxyObj) boxShape = cmds.listRelatives(proxyObj, shapes=True)[0] cmds.setAttr(proxyObj + '.miProxyFile', miFilePath, type='string') mentalray.renderProxyUtils.resizeToBoundingBox(boxShape) cmds.setAttr(proxyObj + ".t", lock=True) cmds.setAttr(proxyObj + ".r", lock=True) cmds.setAttr(proxyObj + ".s", lock=True) cmds.currentTime(start) nPar, parShape = cmds.nParticle() cmds.setAttr(parShape + '.collide', 0) cmds.setAttr(parShape + ".conserve", 0) cmds.setAttr(parShape + ".dynamicsWeight", 0) cmds.setAttr(parShape + ".particleRenderType", 2) #cmds.setAttr( parShape+".selectedOnly", 1) cmds.addAttr(parShape, ln="cus_index0", dt="doubleArray") cmds.addAttr(parShape, ln="cus_index", dt="doubleArray") mel.eval('emit -object nParticle1 -pos 0 0 0') expString = "cus_index = clamp(0, %i, frame-%i);" % (end - start - 1, start) cmds.dynExpression(parShape, s=expString, c=True) cmds.dynExpression(parShape, s=expString, rbd=True) instancerObj = cmds.particleInstancer(parShape, addObject=True, object=proxyObjs, cycle='None', cycleStep=1, cycleStepUnits='Frames', levelOfDetail='Geometry', rotationUnits='Degrees', rotationOrder='XYZ', position='worldPosition', age='age') cmds.particleInstancer(parShape, e=True, name=instancerObj, objectIndex='cus_index') cmds.saveInitialState(parShape) miGrp = cmds.group(proxyObjs, n=exportObjs[0] + '_s_mi') cmds.setAttr(miGrp + '.v', False) cmds.setAttr(miGrp + '.v', lock=True) papaGrp = cmds.group([nPar, miGrp, instancerObj], n=exportObjs[0] + '_mi_group') for obj in (nPar, miGrp, instancerObj, papaGrp): cmds.setAttr(obj + ".t", lock=True) cmds.setAttr(obj + ".r", lock=True) cmds.setAttr(obj + ".s", lock=True)
def addParByTFSet(tfSet=cmds.ls(sl=True, exactType='objectSet')): '''{'del_path':'TfCtrl/Add/Set/addParByTFSet( tfSet = cmds.ls(sl=True, exactType="objectSet") )', 'usage':'$fun( tfSet = cmds.ls(sl=True, exactType="objectSet") )', } ''' #tfSet = cmds.ls(sl=True, type='objectSet')[0] if isinstance(tfSet, list): tfSet = tfSet[0] cmds.lockNode(tfSet, l=False) objects = cmds.listConnections(tfSet + '.dagSetMembers', d=False) createNewPar = True if cmds.attributeQuery( 'setType', n=tfSet, exists=True) and cmds.getAttr(tfSet + '.setType') == 1: raise IOError('This set type is three particle controls!') if cmds.attributeQuery( 'setType', n=tfSet, exists=True) and cmds.attributeQuery( 'posPar', n=tfSet, exists=True) and cmds.objExists( cmds.getAttr(tfSet + '.posPar')): createNewPar = False if createNewPar: for attr in ['posPar', 'aimPar', 'upPar']: if cmds.attributeQuery(attr, n=tfSet, exists=True) and cmds.objExists( cmds.getAttr('%s.%s' % (attr))): cmds.delete(cmds.getAttr('%s.%s' % (attr))) delAttr(tfSet, ['setType', 'posPar', 'aimPar', 'upPar']) cmds.addAttr(tfSet, ln="setType", at="enum", en="singlePar:threePar:", k=False, r=False) cmds.setAttr(tfSet + '.setType', 0, l=True) cmds.addAttr(tfSet, ln="posPar", dt="string") nPar = cmds.nParticle(n='%s_nPar' % (tfSet)) cmds.setAttr(nPar[0] + '.t', l=True) cmds.setAttr(nPar[0] + '.r', l=True) cmds.setAttr(nPar[0] + '.s', l=True) nParShape = nPar[1] cmds.setAttr(tfSet + '.posPar', nParShape, type='string', l=True) cmds.setAttr("%s.computeRotation" % (nParShape), 1) cmds.addAttr(nParShape, ln="cus_toObjPos", dt='doubleArray') cmds.addAttr(nParShape, ln="cus_toObjPos0", dt='doubleArray') else: nParShape = cmds.getAttr(tfSet + '.posPar') cmds.lockNode(nParShape, l=False) #Add particles and set attributes(goalU, goalV, cus_bbsiRadius) initialize states posLi, radiusLi, atULi, atVLi = [], [], [], [] for tfNode in objects: objPos = cmds.objectCenter(tfNode) bbsize = cmds.getAttr(tfNode + '.bbsi')[0] radius = newom.MVector(bbsize).length() / 2 atU = cmds.getAttr(tfNode + '.atU') atV = cmds.getAttr(tfNode + '.atV') posLi.append(objPos) radiusLi.append(radius) atULi.append(atU) atVLi.append(atV) qsEmit(object = nParShape, position=posLi, attributes=( ('cus_radiusPP', 'floatValue', radiusLi), ('goalU', 'floatValue', atULi),\ ('goalV', 'floatValue', atVLi) )\ ) cmds.lockNode(tfSet, l=True) if createNewPar: ##creation expression #parCExpStr = cmds.dynExpression(nParShape, q=True,s=True, c=True) parCExpStr = '\n\n\ /*string $tfNode = $%s[int(particleId)];\n\ goalU = `getAttr ($tfNode+".atU")`;\n\ goalV = `getAttr ($tfNode+".atV")`;\n\ cus_toObjPos = 0;*/' % (tfSet) cmds.dynExpression(nParShape, s=parCExpStr, c=True) ##runtime after dynamics expression #parRADExpStr = cmds.dynExpression(nParShape, q=True, s=True, rad=True) parRADExpStr = '\n\n\ /*string $tfNode = $%s[int(particleId)];\n\n\ \ if (cus_toObjPos == 1){\n\ float $pos[] = position;\n\ vector $rotate = rotationPP;\n\ setAttr ($tfNode + ".pBInT2") -type "double3" ($pos[0]) ($pos[1]) ($pos[2]);\n\ setAttr ($tfNode + ".pBInR2") -type "double3" ($rotate.x) ($rotate.y) ($rotate.z);\n\ }\n\n\ \ \ if (goalPP==0 && cus_toObjPos==0){\n\ cus_toObjPos = 1;\n\ float $pos[] = `getAttr ($tfNode+".translate")`;\n\ position = <<$pos[0], $pos[1], $pos[2]>>;\n\ vector $rotate = rotationPP;\n\ setAttr ($tfNode + ".pBInT2") -type "double3" ($pos[0]) ($pos[1]) ($pos[2]);\n\ setAttr ($tfNode + ".pBInR2") -type "double3" ($rotate.x) ($rotate.y) ($rotate.z);\n\ setAttr ($tfNode+".pBWeight") 1;\n\ setAttr ($tfNode+".follicleNodeState") 2;\n\ }*/' % (tfSet) cmds.dynExpression(nParShape, s=parRADExpStr, rad=True) ######################################create script nodes######################################## ####openCloseMel script node Execute On:Open/close openCloseMelStr = '\n\n\ ///////////for TFNode by Particles/////////////////////\n\ global string $%s[];\n\ $%s = `listConnections -d off "%s.dagSetMembers"`;\n' % (tfSet, tfSet, tfSet) mel.eval(openCloseMelStr) if cmds.objExists("QS_VFX_M_OC"): existsStr = cmds.scriptNode('QS_VFX_M_OC', q=True, bs=True) openCloseMelStr += existsStr cmds.scriptNode('QS_VFX_M_OC', e=True, bs=openCloseMelStr) else: cmds.scriptNode(n='QS_VFX_M_OC', scriptType=1, bs=openCloseMelStr, sourceType='mel') cmds.setAttr('QS_VFX_M_OC.scriptType', l=True) ####timeChangedMel script Node Execute on: Time changed timeChangedMelStr = '\n\n\ ///////////for TFNode by Particles/////////////////////\n\ int $current = `currentTime -q`;\n\ int $start = `playbackOptions -q -min`;\n\ if ($current == $start){\n\ //%s is a global variable, Declare in QS_VFX_M_QC script node.\n\ $%s = `listConnections -d off "%s.dagSetMembers"`; \n\ for ($tfNode in $%s){\n\ setAttr($tfNode+".follicleNodeState") 0;\n\ setAttr($tfNode+".pBWeight") 0;\n\ }\n\ }' % (tfSet, tfSet, tfSet, tfSet) mel.eval(timeChangedMelStr) if cmds.objExists("QS_VFX_M_TC"): existsStr = cmds.scriptNode('QS_VFX_M_TC', q=True, bs=True) timeChangedMelStr += existsStr cmds.scriptNode('QS_VFX_M_TC', e=True, bs=timeChangedMelStr) else: cmds.scriptNode(n='QS_VFX_M_TC', scriptType=7, bs=timeChangedMelStr, sourceType='mel') cmds.setAttr('QS_VFX_M_TC.scriptType', l=True)