def creatSphere(*args):
    circleSel = mc.ls(sl=1)[0]
    radiusCircle = mc.circle(circleSel, q=1, r=1)
    radiusSpere = radiusCircle*.75
    particleSphere = mc.polySphere(n='%s_Sphere'%circleSel, r=radiusSpere, sx=float(radiusSpere), sy=float(radiusSpere), ax=[0, 1, 0])[0]
    mc.parentConstraint(circleSel, particleSphere, mo=0, w=1)
    #mc.parent(particleSphere, circleSel)
    mc.setAttr('%s.tx'%particleSphere, 0)
    mc.setAttr('%s.ty'%particleSphere, 0)
    mc.setAttr('%s.tz'%particleSphere, 0)
    mc.setAttr('%s.rx'%particleSphere, 0)
    mc.setAttr('%s.ry'%particleSphere, 0)
    mc.setAttr('%s.rz'%particleSphere, 0)
    mc.setAttr('%s.v'%particleSphere, 0)
    mc.select(particleSphere, r=1) 
    mc.emitter(type='surface', r=4, dx=1, dy=0, dz=0, n='%s_emitter'%circleSel )
    mc.particle( n='%s_Particles'%circleSel )
    mc.connectDynamic( '%s_Particles'%circleSel, em='%s_emitter'%circleSel )
    particlesShape = mc.listRelatives('%s_Particles'%circleSel, s=1)[0]
    mc.setAttr('%s.lifespanMode'%particlesShape, 1)
    mc.setAttr('%s.lifespan'%particlesShape, 0.4)
    mc.setAttr('%s.startFrame'%particlesShape, 1001)
    mc.connectControl( 'numText', '%s.rate'%('%s_emitter'%circleSel) )
    mc.shadingNode('blinn', n='%s_blinn'%circleSel, asShader=1)
    mc.sets( n='%s_blinnSG'%circleSel, renderable=True, noSurfaceShader=True, empty=1)
    mc.connectAttr('%s.outColor'%('%s_blinn'%circleSel), '%s.surfaceShader'%('%s_blinnSG'%circleSel))
    mc.connectControl( 'myColorIndex', '%s.color'%('%s_blinn'%circleSel) )
    mc.connectControl( 'lifeText', '%s.lifespan'%particlesShape )
    mc.sets('%s_Particles'%circleSel, e=1, forceElement='%s'%('%s_blinnSG'%circleSel))
Exemple #2
0
def pub_spawnPoints():
	_sel = mc.ls(sl=True)
	if len(_sel) > 0:
		# template the object
		mc.setAttr ( _sel[0] + ".template", 1)
		# get object BB and position in worldspace
		_objBB = mc.xform( _sel[0], q=True, bb=True)
		_objPos = mc.xform( _sel[0], ws=True, q=True, rp=True)
		# set the position of the plane under the object
		_poz = [0, 0, 0]
		_poz[0] = _objPos[0]
		_poz[1] = _objPos[1] - (( _objBB[4] - _objBB[1]) / 1.75)
		_poz[2] = _objPos[2]
		# scale the plane larger than the bounding box
		_scale = [0, 0, 0]
		_scale[0] = ( _objBB[0] - _objBB[3]) * 1.2
		_scale[2] = ( _objBB[2] - _objBB[5]) * 1.2
		# create, place, scale and rename the plane
		mc.nurbsPlane( p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=1, v=1, ch=0)
		mc.move( _poz[0], _poz[1], _poz[2])
		mc.scale( _scale[0], 0, _scale[2])
		_nPlane = mc.rename( "emissionPlane_" + _sel[0] )
		# create the emitter
		mc.emitter( _nPlane, type='surface', r=20, sro=0, nuv=1, cye='none', cyi=1, spd=2, srn=1, nsp=1, tsp=0, mxd=0, mnd=0, sp=0)
		_emitter = mc.rename( "emitter_" + _sel[0] )
		# create the particle object
		mc.particle( n="xxx")
		_pParticle = mc.rename( "particle_" + _sel[0] )
		# connect the emitter to the particle object
		mc.connectDynamic( _pParticle, em=_emitter )
		# template the plane and the particle object
		mc.setAttr ( _nPlane + ".template", 1)
		mc.setAttr ( _pParticle + ".template", 1)
	else:
		assert "No object selected!"
	def makeMe(self, e, p):
		#create emitters for firework effect and set certain attributes that don't need to be keyed
		cmds.emitter(n=e)
		cmds.particle(n=p)
		cmds.connectDynamic(p, em=e)
		cmds.setAttr(p+'Shape.lifespanMode', 2)
		cmds.setAttr(p+'Shape.lifespan', self.life)
		cmds.setAttr(p+'Shape.lifespanRandom', self.lifeRand)
		cmds.setAttr(p+'Shape.particleRenderType', 4)
		cmds.setAttr(e+'.minDistance', self.minDist)
		cmds.setAttr(e+'.speedRandom', self.speedRand)
Exemple #4
0
def dynamic():
    # Create an emitter
    cmds.emitter( pos=(0, 0, 0), type='omni', r=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 )
    # Result: emitter1 #

    # Get the emitter to emit particles
    cmds.particle()
    # Result: particle2
    cmds.connectDynamic( 'particle1', em='emitter1' )

    # Create a particle to use as the source of the emitter
    cmds.particle( p=((6.0, 0, 7.0), (6.0, 0, 2.0)), c=1 )
    # Result: particle2

    # Use particle2 as a source of the emitter
    cmds.addDynamic( 'emitter1', 'particle2' )
Exemple #5
0
def createParticles(position, ampList, audioLength, particleStr, threshold):
	'''create a basic particle system with an emitter and particles, where the colour, emission rate
	and emission speed depends on the amplitude list and particle strength.
	
	position    : the position to place the particles
	ampList     : list of amplitudes to control particle speed and emission
	audioLength : the length of the audio, in frames
	particleStr : value to weight the emission rate of particles
	threshold   : minimum value required for particle emission
	'''
	cmds.select(d=True)
	#create emitter
	particleEmitter = cmds.emitter(type="direction", r=100, sro=0, dx=-1, dy=0, dz=0, sp=1, cye="Frame", cyi=25)
	#move emitter to position
	cmds.xform(particleEmitter, translation=position)
	#create particles
	particles = cmds.particle(p=position, conserve=0.99)
	#connect particles and emitter
	cmds.connectDynamic(particles, em=particleEmitter)
	
	#set particles' lifespan to random
	cmds.setAttr(particles[1]+".lifespanMode", 2)
	#change weight of random lifespans
	cmds.setAttr(particles[1]+".lifespanRandom", 2)
	#render particles as multistreaks
	cmds.setAttr(particles[1]+".particleRenderType", 1)
	
	#set particle emission rate and speed
	setParticleEmission(particleEmitter, ampList, audioLength, particleStr, threshold)
	
	#give particles a material
	particleShader = colorObject(particles)
	return particleEmitter[0], particles[1], particleShader
Exemple #6
0
def createParticles(position, ampList, audioLength, particleStr, threshold):
    """create a basic particle system with an emitter and particles, where the colour, emission rate
	and emission speed depends on the amplitude list and particle strength.
	
	position    : the position to place the particles
	ampList     : list of amplitudes to control particle speed and emission
	audioLength : the length of the audio, in frames
	particleStr : value to weight the emission rate of particles
	threshold   : minimum value required for particle emission
	"""
    cmds.select(d=True)
    # create emitter
    particleEmitter = cmds.emitter(type="direction", r=100, sro=0, dx=-1, dy=0, dz=0, sp=1, cye="Frame", cyi=25)
    # move emitter to position
    cmds.xform(particleEmitter, translation=position)
    # create particles
    particles = cmds.particle(p=position, conserve=0.99)
    # connect particles and emitter
    cmds.connectDynamic(particles, em=particleEmitter)

    # set particles' lifespan to random
    cmds.setAttr(particles[1] + ".lifespanMode", 2)
    # change weight of random lifespans
    cmds.setAttr(particles[1] + ".lifespanRandom", 2)
    # render particles as multistreaks
    cmds.setAttr(particles[1] + ".particleRenderType", 1)

    # set particle emission rate and speed
    setParticleEmission(particleEmitter, ampList, audioLength, particleStr, threshold)

    # give particles a material
    particleShader = colorObject(particles)
    return particleEmitter[0], particles[1], particleShader
Exemple #7
0
def createEmitter(vertex, meshName):
    """
    create a point emitter
    :param vertex: str, vertex name
    :return: dict(str), point Emitter, meshTransform Node.
    """
    cmds.select(cl=1)

    cmds.select(vertex)
    # create emitter on selected vertex
    emitterList = cmds.emitter(n=vertex + '_EM', type='omni', r=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)
    particle = cmds.particle(n=vertex + '_PTC')
    cmds.connectDynamic(particle[0], em=emitterList[-1])
    cmds.select(cl=1)

    emitter = emitterList[-1]

    cmds.select(cl=1)

    if not cmds.attributeQuery('bindMesh', node=emitter, exists=1):
        cmds.addAttr(emitter, ln='bindMesh', at='message')

    if not cmds.attributeQuery('bindEmitter', node=meshName, exists=1):
        cmds.addAttr(meshName, ln='bindEmitter', at='message')

    if not cmds.attributeQuery('targetJoint', node=emitter, exists=1):
        cmds.addAttr(emitter, ln='targetJoint', exists=1)

    cmds.connectAttr(meshName + '.bindEmitter', emitter + '.bindMesh', f=1)

    return {'emitter': emitter,
            'particle': particle[0],
            'particleShape': particle[-1]}
def create_emit(myEmitter_name, current_rate=100):
    emit_obj = cmds.emitter(name=myEmitter_name, pos=[0, 0, 0], type='omni', r=current_rate, sro=0, nuv=0, cye='none', spd=1, srn=0,
             nsp=1, tsp=0, mnd=0, dx=1, dy=0, dz=0, sp=0)

    part_obj = cmds.particle(name=emit_obj[0] + '_part')
    
    cmds.connectDynamic(part_obj[0], em=emit_obj[0])
    return [emit_obj[0], part_obj[0], part_obj[1]]
Exemple #9
0
def emitter(*args, **kwargs):
    res = cmds.emitter(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    # unpack create/edit list result
    if isinstance(res, list) and len(res) == 1 and not kwargs.get('query', kwargs.get('q', False)):
        res = res[0]
    return res
Exemple #10
0
	def slider_drag_callback(*args):
		if c.objExists('turb'):
			valueTurb = c.floatSliderGrp('snowTurbSlider', query=True, value=True);
			c.turbulence('turb', e=True, m=valueTurb);
		
		if c.objExists('snowEmitter'):
			valueSnowInt = c.floatSliderGrp('snowIntens', query=True, value=True);
			c.emitter('snowEmitter', e=True, r=valueSnowInt);
		
		if c.objExists('rainEmitter'):
			valueRainInt = c.floatSliderGrp('rainIntens', query=True, value=True);
			c.emitter('rainEmitter', e=True, r=valueRainInt);
			
		if c.objExists('air'):
			value2 = c.floatSliderGrp('airMSlider', query=True, value=True);
			value3 = c.floatSliderGrp('airMxdSlider', query=True, value=True);
			c.air('air', e=True, m=value2, mxd=value3);
    def testAnimPointPrimitiveReadWrite(self):

        # Creates a point emitter.
        MayaCmds.emitter(dx=1, dy=0, dz=0, sp=0.33, pos=(1, 1, 1),
            n='myEmitter')

        MayaCmds.particle(n='emittedParticles')
        MayaCmds.setAttr('emittedParticles.lfm', 2)
        MayaCmds.setAttr('emittedParticles.lifespan', 50)
        MayaCmds.setAttr('emittedParticles.lifespanRandom', 2)
        MayaCmds.connectDynamic('emittedParticles', em='myEmitter')

        self.__files.append(util.expandFileName('testAnimParticleReadWrite.abc'))
        MayaCmds.AbcExport(j='-fr 1 24 -root emittedParticles -file ' + self.__files[-1])

        # reading test
        MayaCmds.AbcImport(self.__files[-1], mode='open')
	def makeMe(self, e, p):
		#create emitters for firework effect and set certain attributes that don't need to be keyed
		ea = e + "_A"
		eb = e + "_B"
		pa = p + "_A"
		pb = p + "_B"
		cmds.emitter(n=ea)
		cmds.particle(n=pa)
		cmds.connectDynamic(pa, em=ea)
		cmds.setAttr(pa+'Shape.lifespanMode', 2)
		cmds.setAttr(pa+'Shape.lifespan', self.lifeA)
		cmds.setAttr(pa+'Shape.lifespanRandom', self.lifeRand)
		cmds.setAttr(pa+'Shape.particleRenderType', 4)
		cmds.setAttr(ea+'.minDistance', self.minDist)
		cmds.setAttr(ea+'.speedRandom', self.speedRand)
		
		cmds.select(cl=True)
		
		cmds.emitter(n=eb)
		cmds.particle(n=pb)
		cmds.connectDynamic(pb, em=eb)
		cmds.setAttr(pb+'Shape.lifespanMode', 2)
		cmds.setAttr(pb+'Shape.lifespan', self.lifeB)
		cmds.setAttr(pb+'Shape.lifespanRandom', self.lifeRand)
		cmds.setAttr(pb+'Shape.particleRenderType', 6)
		cmds.setAttr(eb+'.minDistance', self.minDist)
		cmds.setAttr(eb+'.speedRandom', self.speedRand)
		cmds.setAttr(eb+'.speed', self.exSpeedB)
		mel.eval("AEparticleAddDynamicRenderAttr " + pb + "Shape")
		cmds.setAttr(pb+'.tailFade', -0.166)
		cmds.setAttr(pb+'.tailSize', 30.0)
		
		"""
		cmds.addAttr(pb+"Shape", internalSet=True, ln="colorAccum", at="boolean", dv=False)
		cmds.addAttr(pb+"Shape", internalSet=True, ln="useLighting", at="boolean", dv=False)
		cmds.addAttr(pb+"Shape", internalSet=True, ln="linewidth", at="long", min=1, max=20, dv=3)
		cmds.addAttr(pb+"Shape", internalSet=True, ln="tailFade", at="long", min=-1, max=1, dv=-0.166)
		cmds.addAttr(pb+"Shape", internalSet=True, ln="tailSize", at="long", min=-100, max=100, dv=30.0)
		cmds.addAttr(pb+"Shape", internalSet=True, ln="normalDir", at="long", min=1, max=3, dv=2)
		"""
		
		#TODO:
		#If firework2 gravity field exists, connect particles to it!
		cmds.group(ea,eb, n=e)
		cmds.group(pa,pb, n=p)
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
Exemple #14
0
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
Exemple #15
0
    def testAnimPointPrimitiveReadWrite(self):

        # Creates a point emitter.
        MayaCmds.emitter(dx=1,
                         dy=0,
                         dz=0,
                         sp=0.33,
                         pos=(1, 1, 1),
                         n='myEmitter')

        MayaCmds.particle(n='emittedParticles')
        MayaCmds.setAttr('emittedParticles.lfm', 2)
        MayaCmds.setAttr('emittedParticles.lifespan', 50)
        MayaCmds.setAttr('emittedParticles.lifespanRandom', 2)
        MayaCmds.connectDynamic('emittedParticles', em='myEmitter')

        self.__files.append(
            util.expandFileName('testAnimParticleReadWrite.abc'))
        MayaCmds.AbcExport(j='-fr 1 24 -root emittedParticles -file ' +
                           self.__files[-1])

        # reading test
        MayaCmds.AbcImport(self.__files[-1], mode='open')
Exemple #16
0
	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);
Exemple #17
0
	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 createParticleSystem_1():
    # Creates a very basic particle system with custom attribute

    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 optoinVar value, make sure we use the default one
    cmds.optionVar( sv=("NParticleStyle","Points") )

    particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_1")
    cmds.setAttr('%s.lfm' % particleSystemShape, 0) # live forever
    cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius
    cmds.connectDynamic( particleSystemShape, em=emitter)

    # Keyframe the radius parametter to have a single sample but varying in time ( abc kUniformScope )
    cmds.setKeyframe( "%s.radius" % particleSystem, v=.2, t=1)
    cmds.setKeyframe( "%s.radius" % particleSystem, v=1.0, t=24)
    cmds.setKeyframe( "%s.radius" % particleSystem, v=2.0, t=50)
    cmds.setKeyframe( "%s.radius" % particleSystem, v=.5, t=100)

    # Create a custom attribute that will be handled by AbcExport as uniform double
    cmds.addAttr( particleSystemShape, ln="abcTestUniformDoublePP", at="double")
    exp = "%s.abcTestUniformDoublePP = frame;\n" % particleSystemShape

    # Create a custom attribute that will be handled by AbcExport as constant double
    cmds.addAttr( particleSystemShape, ln="abcTestConstantDoublePP", at="double")
    cmds.setAttr( "%s.abcTestConstantDoublePP" % particleSystemShape, 0x2697 )

    # Create a custom attribute that will be handled by AbcExport as a uniform vector
    cmds.addAttr( particleSystemShape, ln="abcTestUniformVectorPP", at="double3")
    cmds.addAttr( particleSystemShape, ln="abcTestUniformVectorPPX", p="abcTestUniformVectorPP")
    cmds.addAttr( particleSystemShape, ln="abcTestUniformVectorPPY", p="abcTestUniformVectorPP")
    cmds.addAttr( particleSystemShape, ln="abcTestUniformVectorPPZ", p="abcTestUniformVectorPP")
    exp += "%s.abcTestUniformVectorPPX = frame;\n" % particleSystemShape
    exp += "%s.abcTestUniformVectorPPY = time;\n" % particleSystemShape
    exp += "%s.abcTestUniformVectorPPZ = 9.81;\n" % particleSystemShape

    # Create a custom attribute that will be handled by AbcExport as a constant vector
    cmds.addAttr( particleSystemShape, ln="abcTestConstantVectorPP", at="double3")
    cmds.addAttr( particleSystemShape, ln="abcTestConstantVectorPPX", p="abcTestConstantVectorPP")
    cmds.addAttr( particleSystemShape, ln="abcTestConstantVectorPPY", p="abcTestConstantVectorPP")
    cmds.addAttr( particleSystemShape, ln="abcTestConstantVectorPPZ", p="abcTestConstantVectorPP")
    cmds.setAttr( "%s.abcTestConstantVectorPP" % particleSystemShape, 0x2697, 3.141592654, 6.02e23 )

    cmds.expression( particleSystemShape, s=exp, o="", ae=1, uc="all" )

    return particleSystem, particleSystemShape
Exemple #19
0
def createParticleSystem_1():
    # Creates a very basic particle system with custom attribute

    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 optoinVar value, make sure we use the default one
    cmds.optionVar(sv=("NParticleStyle", "Points"))

    particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_1")
    cmds.setAttr('%s.lfm' % particleSystemShape, 0)  # live forever
    cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7)  # Blobby, to see radius
    cmds.connectDynamic(particleSystemShape, em=emitter)

    # Keyframe the radius parametter to have a single sample but varying in time ( abc kUniformScope )
    cmds.setKeyframe("%s.radius" % particleSystem, v=.2, t=1)
    cmds.setKeyframe("%s.radius" % particleSystem, v=1.0, t=24)
    cmds.setKeyframe("%s.radius" % particleSystem, v=2.0, t=50)
    cmds.setKeyframe("%s.radius" % particleSystem, v=.5, t=100)

    # Create a custom attribute that will be handled by AbcExport as uniform double
    cmds.addAttr(particleSystemShape, ln="abcTestUniformDoublePP", at="double")
    exp = "%s.abcTestUniformDoublePP = frame;\n" % particleSystemShape

    # Create a custom attribute that will be handled by AbcExport as constant double
    cmds.addAttr(particleSystemShape, ln="abcTestConstantDoublePP", at="double")
    cmds.setAttr("%s.abcTestConstantDoublePP" % particleSystemShape, 0x2697)

    # Create a custom attribute that will be handled by AbcExport as a uniform vector
    cmds.addAttr(particleSystemShape, ln="abcTestUniformVectorPP", at="double3")
    cmds.addAttr(particleSystemShape, ln="abcTestUniformVectorPPX", p="abcTestUniformVectorPP")
    cmds.addAttr(particleSystemShape, ln="abcTestUniformVectorPPY", p="abcTestUniformVectorPP")
    cmds.addAttr(particleSystemShape, ln="abcTestUniformVectorPPZ", p="abcTestUniformVectorPP")
    exp += "%s.abcTestUniformVectorPPX = frame;\n" % particleSystemShape
    exp += "%s.abcTestUniformVectorPPY = time;\n" % particleSystemShape
    exp += "%s.abcTestUniformVectorPPZ = 9.81;\n" % particleSystemShape

    # Create a custom attribute that will be handled by AbcExport as a constant vector
    cmds.addAttr(particleSystemShape, ln="abcTestConstantVectorPP", at="double3")
    cmds.addAttr(particleSystemShape, ln="abcTestConstantVectorPPX", p="abcTestConstantVectorPP")
    cmds.addAttr(particleSystemShape, ln="abcTestConstantVectorPPY", p="abcTestConstantVectorPP")
    cmds.addAttr(particleSystemShape, ln="abcTestConstantVectorPPZ", p="abcTestConstantVectorPP")
    cmds.setAttr("%s.abcTestConstantVectorPP" % particleSystemShape, 0x2697, 3.141592654, 6.02e23)

    cmds.expression(particleSystemShape, s=exp, o="", ae=1, uc="all")

    return particleSystem, particleSystemShape
def createParticleSystem_goal():
    # Create a constant sized particle object following a deformed torus shape (using goal)

    cmds.file(new=True, force=True)

    # Create a torus, we will use it as goal
    xrez = 14
    yrez = 8
    goalTorus = cmds.polyTorus( r=1, sr=0.5, tw=0, sx=xrez, sy=yrez, ax=(0, 1, 0), cuv=1, ch=0)[0]

    # nParticle creation depends on an optoinVar value, make sure we use the default one
    cmds.optionVar( sv=("NParticleStyle","Points") )

    # Emit a lot of particle, the actual number will be limited to the max particle attribute in the particleShape
    emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0),rate=2500)[0]
    particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_goal")
    cmds.setAttr('%s.lfm' % particleSystemShape, 0) # live forever
    cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius
    cmds.setAttr('%s.maxCount' % particleSystemShape, xrez*yrez) # max count is the number of vertices on the torus

    cmds.connectDynamic( particleSystemShape, em=emitter)

    # Create Goal
    cmds.goal(particleSystem, w=1, utr=0, g=goalTorus);


    # Create Initial state to we start with the correct amount of particle
    # NOTE: When using this script in command line, the first frame is not correctly evaluated and the particleShape is empty
    # This doesn't happens in interactive maya
    for i in range(1, 10):
        cmds.currentTime(i)
    cmds.saveInitialState(particleSystemShape)
    cmds.currentTime(1)

    bend, bendHandle = cmds.nonLinear( goalTorus, type="bend", lowBound=-1, highBound=1, curvature=0)

    cmds.setAttr( "%s.rotateZ" % bendHandle, 90)
    cmds.setKeyframe( "%s.curvature" % bend, v=0, t=1, inTangentType="flat", outTangentType="flat")
    cmds.setKeyframe( "%s.curvature" % bend, v=-130, t=12, inTangentType="flat", outTangentType="flat")
    cmds.setKeyframe( "%s.curvature" % bend, v=130, t=24, inTangentType="flat", outTangentType="flat")

    # Make the bend animation loop
    cmds.setInfinity( bend, poi="oscillate", attribute="curvature")

    return particleSystem, particleSystemShape
Exemple #21
0
def createParticleSystem_goal():
    # Create a constant sized particle object following a deformed torus shape (using goal)

    cmds.file(new=True, force=True)

    # Create a torus, we will use it as goal
    xrez = 14
    yrez = 8
    goalTorus = cmds.polyTorus(r=1, sr=0.5, tw=0, sx=xrez, sy=yrez, ax=(0, 1, 0), cuv=1, ch=0)[0]

    # nParticle creation depends on an optoinVar value, make sure we use the default one
    cmds.optionVar(sv=("NParticleStyle", "Points"))

    # Emit a lot of particle, the actual number will be limited to the max particle attribute in the particleShape
    emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0), rate=2500)[0]
    particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_goal")
    cmds.setAttr('%s.lfm' % particleSystemShape, 0)  # live forever
    cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7)  # Blobby, to see radius
    cmds.setAttr('%s.maxCount' % particleSystemShape, xrez * yrez)  # max count is the number of vertices on the torus

    cmds.connectDynamic(particleSystemShape, em=emitter)

    # Create Goal
    cmds.goal(particleSystem, w=1, utr=0, g=goalTorus);

    # Create Initial state to we start with the correct amount of particle
    # NOTE: When using this script in command line, the first frame is not correctly evaluated and the particleShape is empty
    # This doesn't happens in interactive maya
    for i in range(1, 10):
        cmds.currentTime(i)
    cmds.saveInitialState(particleSystemShape)
    cmds.currentTime(1)

    bend, bendHandle = cmds.nonLinear(goalTorus, type="bend", lowBound=-1, highBound=1, curvature=0)

    cmds.setAttr("%s.rotateZ" % bendHandle, 90)
    cmds.setKeyframe("%s.curvature" % bend, v=0, t=1, inTangentType="flat", outTangentType="flat")
    cmds.setKeyframe("%s.curvature" % bend, v=-130, t=12, inTangentType="flat", outTangentType="flat")
    cmds.setKeyframe("%s.curvature" % bend, v=130, t=24, inTangentType="flat", outTangentType="flat")

    # Make the bend animation loop
    cmds.setInfinity(bend, poi="oscillate", attribute="curvature")

    return particleSystem, particleSystemShape
Exemple #22
0
def snowyObj():
    snowyFaces = mc.ls(sl=1)
    objName = snowyFaces[0].split(".")[0]
    faceNum = mc.polyEvaluate(objName, f=True)
    
    mc.duplicate(objName)
    
    mc.polyChipOff(snowyFaces[:], dup=True, kft=True, ch=True)
    mc.delete(objName + ".f[:" + str(faceNum-1) + "]")
    
   # create emmiter from surface
    emitter = mc.emitter( objName, n=objName + "_emitter" , typ = "surface",  r=5000, sro=0, nuv=0, cye='none', cyi=1, spd=0, srn=0, nsp=1, tsp=0, mxd=0, mnd=0, dx=1, dy=0, dz=0, sp=0)
    particle = mc.nParticle( n = objName + "_nParticles" )
    mc.connectDynamic( particle, em = emitter)
    
    NucleusList = mc.ls(type='nucleus')
    mc.setAttr(NucleusList[0] + ".gravity", 0)
    
    #parameter setting
    global snowParticleShape
    snowParticleShape = objName + "_nParticlesShape"
    
    mc.setAttr(objName + "_nParticlesShape" + '.dynamicsWeight', 0)
    mc.setAttr(objName + "_nParticlesShape" + '.conserve', 0)
    mc.setAttr(objName + "_nParticlesShape" + '.radius', 0.1)
    mc.setAttr(objName + "_nParticlesShape" + '.radiusScaleRandomize', 0.5)
    mc.setAttr(objName + "_nParticlesShape" + '.particleRenderType', 3)
    
    mc.setAttr(objName + "_nParticlesShape" + '.blobbyRadiusScale', 1.8)
    mc.setAttr(objName + "_nParticlesShape" + '.meshTriangleSize', 0.2)
    # set to quad shape
    mc.setAttr(objName + "_nParticlesShape" + '.meshMethod', 3)
    #smoothing snow polygon
    mc.setAttr(objName + "_nParticlesShape" + '.meshSmoothingIterations', 8)
    

    mc.select(objName + "_nParticles", r=True)
    snowPolygon = mm.eval("particleToPoly")
 def particleCreate_action(self):
     selected = cmds.ls(sl=1)
     if not len(selected) > 0:
         QtGui.QMessageBox.information(
             self, "Note",
             "Please select the surface for the particle to scatter at.")
     else:
         self.memoData["surface"] = selected[0]
         print "Surface Defined \n"
         emitterSys = cmds.emitter(n="ScatterUI_emitter",
                                   type="surface",
                                   r=100,
                                   sro=0,
                                   spd=0,
                                   srn=0)[1]
         particleSys = cmds.particle(n="ScatterUI_particle")[0]
         cmds.connectDynamic(particleSys, em=emitterSys)
         self.memoData["particle"] = particleSys
         # move a few frame to generate particle
         for i in range(10):
             cmds.NextFrame()
         print "Particle Defined \n"
         self.storePositionBy_particle()
    def createParticles(self, geo):

        emitterVar = cmds.emitter(geo, type='surface', r=1)[0]
        nParticleVar = cmds.nParticle()[0]
        cmds.connectDynamic(nParticleVar, em=emitterVar)

        nParticleShape = cmds.listRelatives(nParticleVar, s=True)[0]

        self.tryAddingDefaultArgs(nParticleShape)

        cmds.setAttr(nParticleShape + '.enableSPH', 1)
        cmds.setAttr(nParticleShape + '.incompressibility', 1)
        cmds.setAttr(nParticleShape + '.restDensity', 2)
        cmds.setAttr(nParticleShape + '.radiusScaleSPH', 0)
        cmds.setAttr(nParticleShape + '.viscosity', 0.1)
        cmds.setAttr(nParticleShape + '.threshold', 0.001)
        cmds.setAttr(nParticleShape + '.blobbyRadiusScale', 0.01)
        cmds.setAttr(nParticleShape + '.motionStreak', 8)
        cmds.setAttr(nParticleShape + '.meshTriangleSize', 0.001)
        cmds.setAttr(nParticleShape + '.maxTriangleResolution', 300)
        cmds.setAttr(nParticleShape + '.particleRenderType', 6)
        cmds.setAttr(nParticleShape + '.tailSize', 9.5)

        return emitterVar, nParticleVar
def _buildRearEmitter(name = '', boatName = '', splashParticleName = '', rearAnimatable = '', presetName = None):
    """
    New builder for rear nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: The name of the nParticleShape node for the splash
    @type name:  String
    @type splashParticleName: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n = 'nPARTICLE_EMITTERS_hrc', em = True)

    debug(None, method = '_buildRearEmitter', message = 'name: %s' % name, verbose = False)
    cmds.select(clear = True) ## Because if you have anything selected maya may freak out it's the wrong damn thing.. f**k you maya seriously!

    ## Build the emitter
    emitter = cmds.emitter(name = name)
    emitter[0] = cmds.ls(emitter[0], long = True)[0]

    if presetName:
        pathToPreset = '%s/%s' %(CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None, method = '_buildRearEmitter', message = 'emitter: %s' % emitter, verbose = False)
        debug(None, method = '_buildRearEmitter', message = 'pathToPreset: %s' % pathToPreset, verbose = False)

        ## Apply the preset to the emitter
        try:
            mel.eval( 'applyPresetToNode "%s" "" "" "%s" 1;' %(emitter[0], pathToPreset) )
            debug(None, method = '_buildRearEmitter', message = 'Mel preset applied to %s: %s' % (emitter[0], pathToPreset), verbose = False)
        except RuntimeError:
            pass

    ## Now parent it
    try:
        emitter[0] = cmds.parent(emitter[0], 'nPARTICLE_EMITTERS_hrc')[0]
    except:
        pass

    ## Connect the emitter to the particles
    _connect_NParticleShape_to_NParticleEmitter(particleShapeNode = splashParticleName, emitter = emitter[0])

    ## Now do the expression for the rear emitter
    expStringList = [
                    'float $minSpeed = %s.minSpeed;\n' % rearAnimatable,
                    'float $maxSpeed = %s.maxSpeed;\n' % rearAnimatable,
                    'float $speed = %s:world_ctrl.speed;\n' % boatName,
                    'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
                    'float $rateMuliplier = %s.rateMultiplier;\n' % rearAnimatable,
                    'float $splashMaxSpeed = %s.splashMaxSpeed;\n' % rearAnimatable,
                    '\n',
                    'if (%s.useSpeed == 1)\n' % rearAnimatable,
                    '{\n\t',
                        '%s.rate = $rateMuliplier * $curve;\n\t\t' % emitter[0],
                        '\n\t\t',
                        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
                        'if ($emitterSpeed == 0)\n\t\t',
                        '{\n\t\t\t',
                            '$emitterSpeed = 0.1;\n\t\t',
                        '}\n\t\t',
                        '%s.alongAxis = $emitterSpeed;\n' % emitter[0],
                    '}\n',
                    'else\n',
                    '{\n\t',
                        '%s.rate = $rateMuliplier;\n\t' % emitter[0],
                        '%s.alongAxis = $splashMaxSpeed;\n' % emitter[0],
                    '}\n',
                    ]
    ## Check if the expression already exists in the scene, if so delete it
    # utils.checkExpressionExists('%s_rearEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[0], n = '%s_rearEmitter' % boatName, string = utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.randomSpeed' % rearAnimatable, '%s.speedRandom' % emitter[0]):
        cmds.connectAttr('%s.randomSpeed' % rearAnimatable, '%s.speedRandom' % emitter[0])
    if not cmds.isConnected('%s.randomDirection' % rearAnimatable, '%s.randomDirection' % emitter[0]):
        cmds.connectAttr('%s.randomDirection' % rearAnimatable, '%s.randomDirection' % emitter[0])

    return emitter[0]
def _buildSideSplashEmitter(name = '', boatName = '', splashParticleName = [], boatIntersectCurveShape = '', sideAnimatable = '', presetName = None):
    """
    New builder for sideSplash nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter
    @param boatIntersectCurveShape: The name of the intersection curve to emit from.
    @type name:  String
    @type splashParticleName: List
    @type boatIntersectCurveShape: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n = 'nPARTICLE_EMITTERS_hrc', em = True)

    debug(None, method = '_buildSideSplashEmitter', message = 'name: %s' % name, verbose = False)

    # Get base flat surface
    lineCurve       = cmds.curve( name = '%s_extrudeCurve' % name, degree = 1, point = [(-0.01, 0, 0), (0.01, 0, 0)] )
    flatSurface  = cmds.extrude(lineCurve, boatIntersectCurveShape, name = '%s_flatSurface' % name, constructionHistory = True, range = False, polygon = 0, useComponentPivot = 1, fixedPath = True, useProfileNormal = True, extrudeType = 2, reverseSurfaceIfPathReversed = True)[0]
    cmds.rebuildSurface(flatSurface, constructionHistory = True, replaceOriginal = True, rebuildType = 0, endKnots = 1, keepCorners = False, spansU = 1, degreeU = 1, spansV = 100, degreeV = 3)

    # Offset upwards curve from surface
    offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface, name = '%s_offsetUp' % name, distance = 0, constructionHistory = True, range = 0, subdivisionDensity = 1)[0]
    cmds.rebuildCurve(offsetUp, constructionHistory = False, replaceOriginal = True, end = 1, keepRange = 0, keepControlPoints = True, degree = 1)
    cmds.setAttr('%s.translateY' % offsetUp, 0.01)

    # Offset from upwards curve with distance and translate down to get the 45 degree angle
    offset_distance = -0.01
    offsetOut = cmds.offsetCurve(offsetUp, name = '%s_offsetOut' % name, distance = offset_distance, constructionHistory = True, range = 0, subdivisionDensity = 1)[0]
    cmds.setAttr('%s.translateY' % offsetOut, offset_distance)

    # Finally, loft a non-flipping surface solution (45 degree angle of the boat)
    noFlipSurface = cmds.loft(offsetUp, offsetOut, degree = 1, constructionHistory = True, range = 0, polygon = 0, sectionSpans = 1)[0]
    noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name)

    ## Build the emitter
    emitter = cmds.emitter(noFlipSurface, name = '%s_emitter' % name, type = 'surface')

    # Create closestPointOnSurface for acceleration expression where front more acceleration
    cPoS = cmds.createNode('closestPointOnSurface', name = '%s_cPoS' % name)
    cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS)

    ## Build the emitter group if it doesn't already exist
    emitterGroup = '%s_hrc' % name
    if not cmds.objExists(emitterGroup):
        cmds.group(lineCurve, flatSurface, offsetUp, offsetOut, noFlipSurface, emitter[0], n = emitterGroup)
    debug(None, method = '_buildSideSplashEmitter', message = 'emitterName: %s' % emitter[1], verbose = False)

    ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset...
    if presetName:
        pathToPreset = '%s/%s' %(CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None, method = '_buildSideSplashEmitter', message = 'pathToPreset: %s' % pathToPreset, verbose = False)
        mel.eval( 'applyPresetToNode "%s" "" "" "%s" 1;' %(emitter[1], pathToPreset) )

    ## Now parent it
    try:    cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc')
    except: pass

    ## Connect the emitter to the particles
    debug(None, method = '_buildSideSplashEmitter', message = 'Connected %s: %s' % (splashParticleName, emitter[1]), verbose = False)
    for each in splashParticleName:
        _connect_NParticleShape_to_NParticleEmitter(particleShapeNode = each, emitter = emitter[1])

    ## Now do the expression for the side emitter
    if 'IntersectCurveRight' in emitter[1]:
        direction = 'R'
    else:
        direction = 'L'

    expStringList = [
                    'float $minSpeed = %s.minSpeed;\n' % sideAnimatable,
                    'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable,
                    'float $speed = %s:world_ctrl.speed;\n' % boatName,
                    'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
                    'float $rateMuliplier = %s.rateMultiplier%s;\n' %(sideAnimatable, direction),
                    'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' %(sideAnimatable, direction),
                    '\n',
                    'if (%s.useSpeed == 1)\n' % sideAnimatable,
                    '{\n\t',
                        '%s.rate = $rateMuliplier * $curve;\n' % emitter[1],
                        '\n\t\t',
                        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
                        'if ($emitterSpeed == 0)\n\t\t',
                        '{\n\t\t\t',
                            '$emitterSpeed = 0.1;\n\t\t',
                        '}\n\t\t',
                        '%s.speed = $emitterSpeed;\n' % emitter[1],
                    '}\n',
                    'else\n',
                    '{\n\t',
                        '%s.rate = $rateMuliplier;\n\t' % emitter[1],
                        '%s.speed = $splashMaxSpeed;\n' % emitter[1],
                    '}\n',
                    ]
    ## Check if the expression already exists in the scene, if so delete it
    utils.checkExpressionExists('%s_sideSplashEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[1], n = '%s_sideSplashEmitter' % emitter[1], string = utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.normalSpeed%s' %(sideAnimatable, direction), '%s.normalSpeed' % emitter[1]):
        cmds.connectAttr('%s.normalSpeed%s' %(sideAnimatable, direction), '%s.normalSpeed' % emitter[1])
    if not cmds.isConnected('%s.randomSpeed%s' %(sideAnimatable, direction), '%s.speedRandom' % emitter[1]):
        cmds.connectAttr('%s.randomSpeed%s' %(sideAnimatable, direction), '%s.speedRandom' % emitter[1])

    return cPoS
Exemple #27
0
import maya.cmds as cmds

mygrid = cmds.polyPlane(name='emi')
cmds.setAttr("emi.rotateX", -45)
cmds.setAttr("emi.translateZ", 10)
cmds.setAttr("emi.translateY", 10)
cmds.setAttr("emi.scaleX", 30)
cmds.setAttr("emi.scaleY", 20)
cmds.setAttr("emi.scaleZ", 20)

cmds.select('emi')
myem = cmds.emitter(name='myEmitter', speed=30, speedRandom=10, rate=0.005)
mypa = cmds.particle(name='myParticle')
cmds.connectDynamic(mypa[0], em=myem)

cmds.setAttr("myEmitter.emitterType", 2)

mygr = cmds.gravity(name='myGravity')
cmds.connectDynamic(mypa, f=mygr)
cmds.setAttr("myGravity.magnitude", 4)

cmds.select('pCone1', 'myParticle')
cmds.particleInstancer("myParticle", object='pCone1', aimDirection='velocity')

cmds.select('myParticle')
myem2 = cmds.emitter(name='trailEmitter',
                     rate=1000,
                     spread=1,
                     speed=4,
                     speedRandom=3)
mypa2 = cmds.particle(name='trailParticle')
    -dx 1

    #directionY
    -dy 0

    #directionZ
    -dz 0

    #spread
    -sp 0 ;
'''
#Turn the Particle Emitter Creation Mel into Python
#Make the objects name into hose so the emitter can properly parent
import maya.cmds as cmds

emit = cmds.emitter(n='spray',)
part = cmds.particle(n='droplets')
cmds.select('droplets')
cmds.connectDynamic(part[0], em=emit[0])
cmds.select('hose')
selected = cmds.ls(sl=True)[0]
cmds.parent( 'spray', selected )


#To turn Depth Sort on the particles
cmds.setAttr(part[1] + '.depthSort', True)
attrName = 'depthSort'
cmds.setAttr('%s.depthSort' %(part[1]), True)
#For some reason the script editor will not work with these below
#along with all of the script at once, but they will individualy.
#Turn particle shape into Multipoints... selected list is 0
import maya.cmds as cmds

# Creating emitter and particle object
emit = cmds.emitter(n='spray', dx=0, dy=1, dz=0, r=100, sp=0.17,
                    spd=5)  # Returns lists

# Return List [particle, particleShape]
part = cmds.particle(n='droplets')

# Connecting particle to emitter
cmds.connectDynamic(part[0], em=emit[0])

# Selecting object in scene
hose_objects = cmds.ls(sl=True)

# Parenting emitter to hose. First selected object.
cmds.parent(emit[0], hose_objects[0])

part_attrs = {'depthSort': True, 'particleRenderType': 0}

for attr, value in part_attrs.items():
    cmds.setAttr('%s.%s' % (part[1], attr), value)

#The code for Current Render Type button inside the particleShape
#ln=longName, at=attributeType, dv=defaultValue, min=minValue, max=maxValue
#When activating the Current Render Type button, make sure the code is part[1],
#this is the particleShape node that will need to be selected when editing attrs and not [0]
#[0] is the particle.
cmds.addAttr(part[1], internalSet=True, ln="colorAccum", at="bool", dv=False)
cmds.addAttr(part[1], internalSet=True, ln="useLighting", at="bool", dv=False)
cmds.addAttr(part[1],
    def generateCity(self, *args):
        map_file = cmds.textField(self.widgets["osmFileTextField"], q = True, fi = True)
        winds_file = cmds.textField(self.widgets["wrfFileTextField"], q = True, fi = True)
        heights_file = cmds.textField(self.widgets["demFileTextField"], q = True, fi = True)
        jams_file = cmds.textField(self.widgets["jamsFileTextField"], q = True, fi = True)

        raw_wrf = cmds.checkBox(self.widgets["wrfCheckBox"], q=True, v=True)
        raw_dem = cmds.checkBox(self.widgets["demCheckBox"], q=True, v=True)

        if raw_wrf:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            winds_file = subprocess.check_output([python_path, script_dir + "\NetCDF_converter.py", map_file, winds_file], shell=False).rstrip()

        if raw_dem:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            heights_file = subprocess.check_output([python_path, script_dir + "\DEM_converter.py", map_file, heights_file], shell=False).rstrip()


        if cmds.objExists('city'):
            cmds.delete('city')

        def calc_emmiter_level(waypoints):
            if (jams_file == ""):
                return 0

            jams_data = open(jams_file, 'r')
            sum_jams_level = 0
            jams_points = 0

            shift_lat = -0.00766
            shift_lon = 0.006868

            for waypoint in waypoints:
                for line in jams_data:
                    tmp = line.split(' ')
                    lon = float(tmp[0]) - shift_lon
                    lat = float(tmp[1]) - shift_lat
                    if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                        continue
                    data = float(tmp[2])
                    jams_point = convert_coordinates(lon, lat)
                    dist = math.sqrt(math.pow(waypoint[0]-jams_point[0], 2)+math.pow(waypoint[2]-jams_point[2], 2))
                    if dist < (25.0/size_multiplier):
                        sum_jams_level += data
                        jams_points += 1

            if jams_points >= (len(waypoints) * 0.5):
                return 1.0*sum_jams_level/jams_points
            else:
                return 0

            jams_data.close()


        def convert_coordinates(lon, lat):
            centered_lat = (lat-minlat) - (maxlat-minlat)/2
            centered_lon = (lon-minlon) - (maxlon-minlon)/2
            normalized_lat = centered_lat * norm_lat
            normalized_lon = centered_lon * norm_lon
            return [normalized_lon, 0, -normalized_lat]

        #meters
        size_multiplier = float(cmds.textField(self.widgets["sizeMultTextField"], q = True, tx = True))
        emit_multiplier = float(cmds.textField(self.widgets["emitMultTextField"], q = True, tx = True))
        hasl = float(cmds.textField(self.widgets["haslTextField"], q = True, tx = True))

        xmlData = xml.dom.minidom.parse(map_file)

        points_ids = []
        points = []
        heights = []

        bounds = xmlData.getElementsByTagName("bounds")[0]
        minlat = float(bounds.getAttribute('minlat'))
        maxlat = float(bounds.getAttribute('maxlat'))
        minlon = float(bounds.getAttribute('minlon'))
        maxlon = float(bounds.getAttribute('maxlon'))

        dist_lon = self.coordinates_dist(minlon, minlat, maxlon, minlat)
        dist_lat = self.coordinates_dist(minlon, minlat, minlon, maxlat)

        norm_lat = (dist_lat/size_multiplier)/(maxlat-minlat)
        norm_lon = (dist_lon/size_multiplier)/(maxlon-minlon)

        #============================Get heights===================================
        heights_data = open(heights_file, 'r')

        rows = 0
        cols = 0
        start_lon = 0
        start_lat = 0
        delta_lon = 0
        delta_lat = 0

        heights_matrix = []

        for line in heights_data:
            tmp = line.strip().split(' ')

            if rows == 0:
                rows = float(tmp[0])
                cols = float(tmp[1])
            elif start_lon == 0:
                start_lon = float(tmp[0])
                start_lat = float(tmp[1])
            elif delta_lon == 0:
                delta_lon = float(tmp[0])
                delta_lat = float(tmp[1])
            else:
                row = []
                for cell in tmp:
                    row.append(int(cell)-hasl)
                heights_matrix.append(row)

        #==========================================================================

        maxprogress = 0
        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            tags = way.getElementsByTagName('tag')
            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if (tag_type == 'highway'):
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        maxprogress += 1
                if (tag_type == 'building'):
                    maxprogress += 1

        progress = 0
        cmds.progressWindow(title='Generating city', min = 0, max = maxprogress,  progress = progress, status = 'Processing nodes', isInterruptable = False)

        #============================Handle nodes==================================
        nodes = xmlData.getElementsByTagName('node')
        for node in nodes:
            lat = float(node.getAttribute('lat'))
            lon = float(node.getAttribute('lon'))

            if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                continue

            point = convert_coordinates(lon, lat)

            points_ids.append(int(node.getAttribute('id')))
            points.append(point)
            heights.append(heights_matrix[int(math.floor((lon-start_lon)/delta_lon))][int(math.floor((lat-start_lat)/delta_lat))])
        #==========================================================================

        #=============================Handle ways==================================
        roads = 0
        buildings = 0
        emitter = 0

        cmds.particle(n='nParticle')
        cmds.particle('nParticle', e=True, at='mass', order=0, fv=1e-5)
        cmds.setAttr('nParticleShape.lifespanMode', 2)
        cmds.setAttr('nParticleShape.lifespan', 6)
        cmds.setAttr('nParticleShape.lifespanRandom', 2)

        cmds.select('nParticleShape', r=True)
        cmds.addAttr(longName='betterIllumination', at='bool', defaultValue=False )
        cmds.addAttr(longName='surfaceShading', at='float', defaultValue=0, minValue=0, maxValue=1)
        cmds.addAttr(longName='threshold', at='float', defaultValue=0, minValue=0, maxValue=10)
        cmds.addAttr(longName='radius', at='float', defaultValue=1, minValue=0, maxValue=20)
        cmds.addAttr(longName='flatShaded', at='bool', defaultValue=False)

        cmds.setAttr('nParticleShape.particleRenderType', 8)
        cmds.setAttr('nParticleShape.radius', 0.06)

        cmds.setAttr('particleCloud1.transparency', 0.53, 0.53, 0.53, type='double3')
        cmds.setAttr('particleCloud1.color', 1.0, 0.0, 0.483, type='double3')
        cmds.setAttr('particleCloud1.incandescence', 1.0, 0.0, 0.850, type='double3')
        cmds.setAttr('particleCloud1.glowIntensity', 0.111)


        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            waypoints = []
            heights_sum = 0
            nodes = way.getElementsByTagName('nd')
            tags = way.getElementsByTagName('tag')

            for node in nodes:
                ref = int(node.getAttribute('ref'))
                try:
                    index = points_ids.index(ref)
                except ValueError:
                    index = -1

                if index != -1:
                    waypoints.append(points[index])
                    heights_sum += heights[index]

            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if tag_type == 'highway':
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        roads += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating road: ' + str(roads))

                        lanes = 2
                        for tag in tags:
                            tag_type = str(tag.getAttribute('k'))
                            if tag_type == 'lanes':
                                lanes = float(str(tag.getAttribute('v')))

                        if len(waypoints) >= 2:
                            cmds.curve(n='pathcurve_' + str(roads), p=waypoints, d=1)
                            sx = waypoints[0][0]
                            sz = waypoints[0][2]
                            dx = waypoints[0][2]-waypoints[1][2]
                            dz = waypoints[1][0]-waypoints[0][0]
                            ln = math.sqrt(math.pow(2*dx, 2) + math.pow(2*dz, 2))
                            dx /= (ln*size_multiplier)/(3*lanes)
                            dz /= (ln*size_multiplier)/(3*lanes)
                            ln = 0

                            for i in range(0, len(waypoints)-2):
                                ln += math.trunc(math.sqrt(math.pow(waypoints[i+1][0]-waypoints[i][0], 2) + math.pow(waypoints[i+1][2]-waypoints[i][2], 2))) + 1
                            cmds.curve(n='extrudecurve_' + str(roads), p=[(sx-dx, 0, sz-dz), (sx+dx, 0, sz+dz)], d=1)
                            cmds.rebuildCurve('pathcurve_' + str(roads), rt=0, s=200)
                            cmds.nurbsToPolygonsPref(f=2, pt=1, ut=1, un=2, vt=1, vn=ln * 5 + 30)
                            cmds.extrude('extrudecurve_' + str(roads), 'pathcurve_' + str(roads), n='road_' + str(roads), et=2, po=1)
                            cmds.delete('extrudecurve_' + str(roads),)


                            emitter_level = calc_emmiter_level(waypoints)
                            if emitter_level > 0:
                                emitter += 1
                                cmds.select('pathcurve_' + str(roads), r=True)
                                cmds.move(0, 0.03, 0)
                                cmds.emitter(n='emitter_' + str(emitter), type='omni', r=emit_multiplier*emitter_level, spd=0.1, srn=0, sp=0)
                                cmds.connectDynamic('nParticle', em='emitter_' + str(emitter))


                            cmds.select('road_' + str(roads), r=True)
                            cmds.move(0, 0.004, 0)


                elif tag_type == 'building':
                    temp = str(tag.getAttribute('v'))
                    if temp == 'yes':
                        buildings += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating building: ' + str(buildings))

                        if len(waypoints) >= 3:
                            cmds.polyCreateFacet(n='building_' + str(buildings), p=waypoints)
                            cmds.select('building_' + str(buildings), r=True)
                            normal = cmds.polyInfo(fn=True)[0].partition('0: ')[2].split(' ')[1]
                            if float(normal) < 0:
                                cmds.polyMirrorFace(direction=2, p=(0, 0, 0), mergeMode=0, worldSpace=1)
                                cmds.polyDelFacet('building_' + str(buildings) + '.f[0]')

                            avg_height = heights_sum / len(waypoints)

                            cmds.polyExtrudeFacet('building_' + str(buildings) + '.f[0]',  ltz=(1.0 * avg_height/size_multiplier))

                            cmds.select('building_' + str(buildings), r=True)

                            cmds.collision('building_' + str(buildings), 'nParticle')

        #==========================================================================

        #============================Handle winds==================================
        winds_data = open(winds_file, 'r')
        winds = 0
        cmds.progressWindow(edit=True, progress = progress, status='Setting winds')
        for line in winds_data:
            winds += 1

            tmp = line.split(' ')
            lon = float(tmp[0])
            lat = float(tmp[1])
            x = float(tmp[2])
            y = float(tmp[3])
            z = float(tmp[4])

            magn = math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(z, 2))
            max_dist = self.coordinates_dist(0, 0, 0.006364, 0.006364)/size_multiplier
            volume_size = self.coordinates_dist(0, 0, 0.0045, 0.0045)/size_multiplier
            position = convert_coordinates(lon, lat)

            cmds.air(n='wind_' + str(winds), pos=position, wns=True, dx=x, dy=y, dz=z, m=magn, s=1, mxd=max_dist)
            cmds.setAttr('wind_' + str(winds) + '.volumeShape', 1)
            cmds.setAttr('wind_' + str(winds) + '.volumeOffsetY', 1)
            cmds.scale(volume_size, volume_size/2, volume_size, 'wind_' + str(winds))
            cmds.connectDynamic('nParticle', f='wind_' + str(winds))
            cmds.select(cl=True)
        #==========================================================================

        cmds.gravity(n='gravity', m=9.8*1e-5)
        cmds.connectDynamic('nParticle', f='gravity')
        cmds.polyPlane(n='ground', sx=(maxlon-minlon), sy=(maxlat-minlat), w=(maxlon-minlon)*norm_lon, h=(maxlat-minlat)*norm_lat)
        cmds.collision('ground', 'nParticle')

        cmds.select('building_*', r=True)
        cmds.select('road_*', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.editRenderLayerGlobals(currentRenderLayer='AOLayer')
        cmds.editRenderLayerMembers('AOLayer')

        cmds.select('road_*', r=True)
        cmds.group(n='roads')

        cmds.select('building_*', r=True)
        cmds.group(n='buildings')

        cmds.select('pathcurve_*', r=True)
        cmds.group(n='emitters')

        cmds.select('roads', r=True)
        cmds.select('buildings', tgl=True)
        cmds.select('emitters', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.select('gravity', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('wind_1', tgl=True)
        cmds.group(n='city')

        xmlData.unlink()
        winds_data.close()
        heights_data.close()

        if raw_wrf:
            os.remove(winds_file)

        if raw_dem:
            os.remove(heights_file)

        cmds.progressWindow(endProgress = True)
def _buildSideSplashEmitter(name='',
                            boatName='',
                            splashParticleName=[],
                            boatIntersectCurveShape='',
                            sideAnimatable='',
                            presetName=None):
    """
    New builder for sideSplash nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: List of the names of nParticleShape nodes to connect to the emitter
    @param boatIntersectCurveShape: The name of the intersection curve to emit from.
    @type name:  String
    @type splashParticleName: List
    @type boatIntersectCurveShape: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True)

    debug(None,
          method='_buildSideSplashEmitter',
          message='name: %s' % name,
          verbose=False)

    # Get base flat surface
    lineCurve = cmds.curve(name='%s_extrudeCurve' % name,
                           degree=1,
                           point=[(-0.01, 0, 0), (0.01, 0, 0)])
    flatSurface = cmds.extrude(lineCurve,
                               boatIntersectCurveShape,
                               name='%s_flatSurface' % name,
                               constructionHistory=True,
                               range=False,
                               polygon=0,
                               useComponentPivot=1,
                               fixedPath=True,
                               useProfileNormal=True,
                               extrudeType=2,
                               reverseSurfaceIfPathReversed=True)[0]
    cmds.rebuildSurface(flatSurface,
                        constructionHistory=True,
                        replaceOriginal=True,
                        rebuildType=0,
                        endKnots=1,
                        keepCorners=False,
                        spansU=1,
                        degreeU=1,
                        spansV=100,
                        degreeV=3)

    # Offset upwards curve from surface
    offsetUp = cmds.offsetCurve('%s.u[0.5]' % flatSurface,
                                name='%s_offsetUp' % name,
                                distance=0,
                                constructionHistory=True,
                                range=0,
                                subdivisionDensity=1)[0]
    cmds.rebuildCurve(offsetUp,
                      constructionHistory=False,
                      replaceOriginal=True,
                      end=1,
                      keepRange=0,
                      keepControlPoints=True,
                      degree=1)
    cmds.setAttr('%s.translateY' % offsetUp, 0.01)

    # Offset from upwards curve with distance and translate down to get the 45 degree angle
    offset_distance = -0.01
    offsetOut = cmds.offsetCurve(offsetUp,
                                 name='%s_offsetOut' % name,
                                 distance=offset_distance,
                                 constructionHistory=True,
                                 range=0,
                                 subdivisionDensity=1)[0]
    cmds.setAttr('%s.translateY' % offsetOut, offset_distance)

    # Finally, loft a non-flipping surface solution (45 degree angle of the boat)
    noFlipSurface = cmds.loft(offsetUp,
                              offsetOut,
                              degree=1,
                              constructionHistory=True,
                              range=0,
                              polygon=0,
                              sectionSpans=1)[0]
    noFlipSurface = cmds.rename(noFlipSurface, '%s_noFlipSurface' % name)

    ## Build the emitter
    emitter = cmds.emitter(noFlipSurface,
                           name='%s_emitter' % name,
                           type='surface')

    # Create closestPointOnSurface for acceleration expression where front more acceleration
    cPoS = cmds.createNode('closestPointOnSurface', name='%s_cPoS' % name)
    cmds.connectAttr('%s.worldSpace' % noFlipSurface, '%s.inputSurface' % cPoS)

    ## Build the emitter group if it doesn't already exist
    emitterGroup = '%s_hrc' % name
    if not cmds.objExists(emitterGroup):
        cmds.group(lineCurve,
                   flatSurface,
                   offsetUp,
                   offsetOut,
                   noFlipSurface,
                   emitter[0],
                   n=emitterGroup)
    debug(None,
          method='_buildSideSplashEmitter',
          message='emitterName: %s' % emitter[1],
          verbose=False)

    ## Check if a custom preset has been assigned via the func flags for the emitter, if not use the default preset...
    if presetName:
        pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None,
              method='_buildSideSplashEmitter',
              message='pathToPreset: %s' % pathToPreset,
              verbose=False)
        mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' %
                 (emitter[1], pathToPreset))

    ## Now parent it
    try:
        cmds.parent(emitterGroup, 'nPARTICLE_EMITTERS_hrc')
    except:
        pass

    ## Connect the emitter to the particles
    debug(None,
          method='_buildSideSplashEmitter',
          message='Connected %s: %s' % (splashParticleName, emitter[1]),
          verbose=False)
    for each in splashParticleName:
        _connect_NParticleShape_to_NParticleEmitter(particleShapeNode=each,
                                                    emitter=emitter[1])

    ## Now do the expression for the side emitter
    if 'IntersectCurveRight' in emitter[1]:
        direction = 'R'
    else:
        direction = 'L'

    expStringList = [
        'float $minSpeed = %s.minSpeed;\n' % sideAnimatable,
        'float $maxSpeed = %s.maxSpeed;\n' % sideAnimatable,
        'float $speed = %s:world_ctrl.speed;\n' % boatName,
        'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
        'float $rateMuliplier = %s.rateMultiplier%s;\n' %
        (sideAnimatable, direction),
        'float $splashMaxSpeed = %s.splashMaxSpeed%s;\n' %
        (sideAnimatable, direction),
        '\n',
        'if (%s.useSpeed == 1)\n' % sideAnimatable,
        '{\n\t',
        '%s.rate = $rateMuliplier * $curve;\n' % emitter[1],
        '\n\t\t',
        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
        'if ($emitterSpeed == 0)\n\t\t',
        '{\n\t\t\t',
        '$emitterSpeed = 0.1;\n\t\t',
        '}\n\t\t',
        '%s.speed = $emitterSpeed;\n' % emitter[1],
        '}\n',
        'else\n',
        '{\n\t',
        '%s.rate = $rateMuliplier;\n\t' % emitter[1],
        '%s.speed = $splashMaxSpeed;\n' % emitter[1],
        '}\n',
    ]
    ## Check if the expression already exists in the scene, if so delete it
    utils.checkExpressionExists('%s_sideSplashEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[1],
                    n='%s_sideSplashEmitter' % emitter[1],
                    string=utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.normalSpeed%s' % (sideAnimatable, direction),
                            '%s.normalSpeed' % emitter[1]):
        cmds.connectAttr('%s.normalSpeed%s' % (sideAnimatable, direction),
                         '%s.normalSpeed' % emitter[1])
    if not cmds.isConnected('%s.randomSpeed%s' % (sideAnimatable, direction),
                            '%s.speedRandom' % emitter[1]):
        cmds.connectAttr('%s.randomSpeed%s' % (sideAnimatable, direction),
                         '%s.speedRandom' % emitter[1])

    return cPoS
Exemple #32
0
	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])
    #directionY
    -dy 0

    #directionZ
    -dz 0

    #spread
    -sp 0 ;
'''
#Turn the Particle Emitter Creation Mel into Python
#Make the objects name into hose so the emitter can properly parent
#Just activate script and emitter will be created with fields
import maya.cmds as cmds

# Creating emitter and particle object
emit = cmds.emitter(n='spray',) # Returns lists
part = cmds.particle(n='droplets') # Return List [particle, particleShape]
# Connecting particle to emitter
cmds.connectDynamic(part[0], em=emit[0])
# Selecting object in scene
hose_objects = cmds.ls(sl=True)
# Parenting emitter to hose. First selected object.
cmds.parent( emit[0], hose_objects[0] )


#To turn Depth Sort on the particles
cmds.setAttr(part[1] + '.depthSort', True)
attrName = 'depthSort'

'''
# Parellel Lists (Array)
 def createParticleBucket(self,emitSurface,dressType,ptcCount):
     '''creates a particle system named after the surface that the particles emit from
     returns the emitter, particles, instancer created.  This proc also builds
     the initial expressions that a modified by the UI'''
     firstFrame = cmds.playbackOptions( query = True, minTime = True )
     print ("creating a new particle for ")
     #TODO build a data class that is easily edited outside the script to set
     #these default settings
     if dressType == 'all':
         emitSurfaceName = emitSurface + "_Dress"
         scaleMin = str(self.ptcMin)
         scaleMax = str(self.ptcMax)
     emitterName = emitSurfaceName +"_Emitter"
     ptcBktName = emitSurfaceName + "_Particles"
     insterName = emitSurfaceName + "_Instancer"
     cmds.select(emitSurface)
     #create the emitter 
     emitter = cmds.emitter(type = 'surface', r=1000, nuv=True,spd = 0.01, sro = False, cye = 'none', cyi = 0, sp = 0, n = emitterName )
     #create the particles
     emitSurfPtcs = cmds.particle( c = 1.0, name = ptcBktName )
     cmds.goal(emitSurfPtcs, w=1,utr=0,g = emitSurface)
     emitSurfPtcsShape = emitSurfPtcs[-1]
     #add the per particle attributes
     cmds.select(emitSurfPtcsShape)
     #instance selection 
     cmds.addAttr( ln ='indexPP',dt = 'doubleArray')
     #random scaling
     cmds.addAttr( ln ='scalePP',dt = 'vectorArray') 
     #rotation vector around X axis based on surface normal
     cmds.addAttr( ln ='surfRotOffPP',dt = 'vectorArray')
     cmds.addAttr( ln ='surfRotPP',dt = 'vectorArray')
     #user specificied aim & user specified aim rotation around aim
     #not used in the example but can be leveraged for different behavior
     cmds.addAttr( ln ="aimVectorPP",dt = 'vectorArray')
     cmds.addAttr( ln ="aimRotOffPP",dt = 'vectorArray')
     cmds.addAttr( ln ="aimRotPP",dt = 'vectorArray')
     #Goal UV based attrs
     cmds.addAttr( ln ='goalWorldNormal0PP',dt = 'vectorArray')
     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 ='parentU',dt = 'doubleArray')
     cmds.addAttr( ln ='parentU0',dt = 'doubleArray')
     cmds.addAttr( ln ='parentV',dt = 'doubleArray')
     cmds.addAttr( ln ='parentV0',dt = 'doubleArray')
     #custom attrs from the UI that change how the system behaves
     cmds.addAttr( ln = 'scaleMin', at ='double')
     cmds.addAttr( ln = 'scaleMax', at ='double')
     cmds.addAttr( ln = 'dressType', dt = 'string')
     cmds.addAttr( ln = 'randSeed', at = 'long')
     #update the attrs 
     cmds.setAttr(emitSurfPtcsShape+'.scaleMin', float(scaleMin))
     cmds.setAttr(emitSurfPtcsShape+'.scaleMax', float(scaleMax))
     cmds.setAttr(emitSurfPtcsShape+'.dressType', str(dressType), typ = 'string')
     cmds.setAttr(emitSurfPtcsShape+'.seed[0]', random.randrange(100, 360,1))
     cmds.setAttr(emitSurfPtcsShape+'.randSeed', random.randrange(100, 360,1))
     cmds.setAttr(emitSurfPtcsShape+".maxCount",int(ptcCount))
     cmds.setAttr(emitSurfPtcsShape+".startFrame", firstFrame)
     #return what was created
     return (emitSurface,emitter,emitSurfPtcs,emitSurfPtcsShape,insterName)
    -dx 1

    #directionY
    -dy 0

    #directionZ
    -dz 0

    #spread
    -sp 0 ;
'''
#Turn the Particle Emitter Creation Mel into Python
#Make the objects name into hose so the emitter can properly parent
import maya.cmds as cmds

emit = cmds.emitter(n='spray',)
part = cmds.particle(n='droplets')
cmds.connectDynamic(part[0], em=emit[0])
selected = cmds.ls(sl=True)[0]
cmds.parent( 'spray', selected )


#To turn Depth Sort on the particles
cmds.setAttr(part[1] + '.depthSort', True)
attrName = 'depthSort'
cmds.setAttr('%s.depthSort' %(part[1]), True)
#For some reason the script editor will not work with these below
#along with all of the script at once, but they will individualy.
#Turn particle shape into Multipoints... selected list is 0
cmds.setAttr('dropletsShape.particleRenderType', 0)
    def buildSplash(self):            
        objectName = str(self.getObject.text())
        if self.checkWake.isChecked()==True:
            wakeEmitter = str(self.getWake.text())
        else:
            wakeEmitter = "OceanWakeEmitter1"
        if self.checkOcean.isChecked()==True:
            oceanShader = str(self.getOcean.text())
        else:
            oceanShader = "oceanShader1"
        
        ###Bcreating Splash Disc
        objectNameAxis = generator.getMaxAndMinAxis(objectName)
        #generator_Return: 0-maxX, 1-minX, 2-maxY, 3-minY, 4-maxZ, 5-minZ
        avrgX = objectNameAxis[0] - objectNameAxis[1]
        avrgZ = objectNameAxis[4] - objectNameAxis[5]
        avrgY = objectNameAxis[2] - objectNameAxis[3]
        if avrgX > avrgZ:
            SplashCurve = avrgX
        else:
            SplashCurve = avrgZ
        baseCurve = cmds.circle(name="base",normal=[0,1,0],radius=SplashCurve/1.5)
        headCurve = cmds.circle(name="head",normal=[0,1,0],radius=SplashCurve/2)
        cmds.move(0,(avrgY/4),0,headCurve)
        cmds.rebuildCurve ("base", ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=0, kt=0, s=100, d=7, tol=0.01)
        cmds.rebuildCurve ("head", ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=0, kt=0, s=100, d=7, tol=0.01)
        splashDisc = cmds.loft ("base", "head",name="%s_SplashDisc"%objectName, ch=1, u=1, c=0, ar=1, d=3, ss=int(avrgY+1), rn=0, po=0, rsn=True)
        #Return: 0-SplashDisc, 1-loft1
        cmds.delete(baseCurve,headCurve)    
        cmds.setAttr("%s.visibility"%splashDisc[0], False )
        objectPosition = cmds.xform(objectName, query=True, translation=True, worldSpace=True )
        cmds.move(objectPosition[0], 0, objectPosition[2], splashDisc[0])
        
        ###adding emitter and particle to Object
        objectNameEmitter = cmds.emitter(objectName,type='surface',rate=0,scaleRateByObjectSize=False,needParentUV=False,cycleEmission="none",
                           cycleInterval=1,speed=1,speedRandom=0,normalSpeed=1,tangentSpeed=0,maxDistance=0,minDistance=0,
                           directionX=1,directionY=0,directionZ=0,spread=0,name="%s_emitter"%objectName)
        #Return: 0-objectName, 1-objectName_emitter
        objectNameParticle = cmds.particle(name="%s_particle"%objectName)
        cmds.connectDynamic(objectNameParticle[0],emitters=objectNameEmitter[0])
        ###adding emitter and particle to Splash Disc
        splashDiscEmitter = cmds.emitter(splashDisc[0],type='surface',rate=0,scaleRateByObjectSize=False,needParentUV=False,cycleEmission="none",
                           cycleInterval=1,speed=1,speedRandom=1.5,normalSpeed=1,tangentSpeed=0,maxDistance=0,minDistance=0,
                           directionX=1,directionY=0,directionZ=0,spread=0,name="%s_emitter"%splashDisc[0])
        #Return: 0-SplashDisc, 1-SplashDisc_emitter
        splashDiscParticle = cmds.particle(name="%s_particle"%splashDisc[0])
        cmds.connectDynamic(splashDiscParticle[0],emitters=splashDiscEmitter[0])
        
        #connecting the X and Z object position to Splash Disc to follow 
        cmds.connectAttr("%s.translate.translateZ"%objectName, "%s.translate.translateZ"%splashDisc[0])
        cmds.connectAttr("%s.translate.translateX"%objectName, "%s.translate.translateX"%splashDisc[0])
        
        #setting up the splash Disc particle Setting 
        cmds.setAttr("%s.lifespanMode"%splashDiscParticle[1],3)
        cmds.setAttr("%s.lifespanRandom"%splashDiscParticle[1],0.5)
        cmds.setAttr("%s.conserve"%splashDiscParticle[1],0.983)
        cmds.setAttr("%s.inheritFactor"%splashDiscParticle[1],0.2)
        cmds.setAttr("%s.particleRenderType"%splashDiscParticle[1],5)
        cmds.addAttr(splashDiscParticle[1], keyable=True, ln="useLighting", at="bool", dv=False)
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleYPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleYPP0", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleXPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleXPP0", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteTwistPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteTwistPP0", dt="doubleArray")
        #creating Ramp for Splash Disc particle
        splashDiscParticle_spriteScaleXPP = cmds.arrayMapper(target=splashDiscParticle[1], destAttr="spriteScaleXPP", inputV="ageNormalized", type="ramp")
        ramp_spriteScaleXPP = cmds.listConnections(splashDiscParticle_spriteScaleXPP, type="ramp")
        ramp_spriteScaleXPP = cmds.rename(ramp_spriteScaleXPP[1], "%s_spriteScaleXPP_Rampe"%splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_spriteScaleXPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_spriteScaleXPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_spriteScaleXPP, 0.5,0.5,0.5)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_spriteScaleXPP, 0.165)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_spriteScaleXPP, 1,1,1)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_spriteScaleXPP, 0)
        
        splashDiscParticle_spriteScaleYPP = cmds.arrayMapper(target=splashDiscParticle[1], destAttr="spriteScaleYPP", inputV="ageNormalized", type="ramp")
        ramp_spriteScaleYPP = cmds.listConnections(splashDiscParticle_spriteScaleYPP, type="ramp")
        ramp_spriteScaleYPP = cmds.rename(ramp_spriteScaleYPP[1], "%s_SpriteScaleYPP_Rampe"%splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_spriteScaleYPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_spriteScaleYPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_spriteScaleYPP, 0.5,0.5,0.5)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_spriteScaleYPP, 0.165)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_spriteScaleYPP, 1,1,1)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_spriteScaleYPP, 0)
         
        #setting up the object particle Setting 
        cmds.setAttr("%s.lifespanMode"%objectNameParticle[1],3)
        cmds.setAttr("%s.particleRenderType"%objectNameParticle[1],7)
        cmds.addAttr(objectNameParticle[1], keyable=True, ln="threshold", at="float", min=0, max=10, dv=0.7)
        cmds.addAttr(objectNameParticle[1], keyable=True, ln="radius", at="float", min=0, max=10, dv=0.5)
        cmds.addAttr (objectNameParticle[1], ln="radiusPP", dt="doubleArray")
        #creating Ramp for object particle
        objectNameParticle_radiusPP = cmds.arrayMapper(target=objectNameParticle[1], destAttr="radiusPP", inputV="ageNormalized", type="ramp")
        ramp_radiusPP = cmds.listConnections(objectNameParticle_radiusPP, type="ramp")
        ramp_radiusPP = cmds.rename(ramp_radiusPP[1], "%s_RadiusPP_Rampe"%objectNameParticle[1])
        cmds.setAttr("%s.colorEntryList[3].color"%ramp_radiusPP, 0.056,0.056,0.056)
        cmds.setAttr("%s.colorEntryList[3].position"%ramp_radiusPP, 1)
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_radiusPP, 0.223,0.223,0.223)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_radiusPP, 0.690)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_radiusPP, 0.178,0.178,0.178)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_radiusPP, 0.455)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_radiusPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_radiusPP, 0)
         
        #adding gravity to SplashDisc
        splashDiscGravity = cmds.gravity(name="%s_GravityField"%splashDiscParticle[0], pos=[0,0,0], m=9.8, att=0, dx=0, dy=-1, dz=0, mxd=-1, vsh="none", vex=0, vof=[0,0,0], vsw=360, tsr=0.5)
        cmds.connectDynamic(splashDiscParticle[0], fields=splashDiscGravity)
         
        #adding gravity to Object
        objectNameGravity = cmds.uniform(name="%s_UniformField"%objectNameParticle[0], pos=[0,0,0], m=5, att=1, dx=1, dy=-1, dz=0, mxd=-1, vsh="none", vex=0, vof=[0,0,0], vsw=360, tsr=0.5)
        cmds.connectDynamic(objectNameParticle[0], fields=objectNameGravity)
        print objectNameGravity
        cmds.setAttr("%s.directionX"%objectNameGravity[0],0)
        cmds.setAttr("%s.directionY"%objectNameGravity[0],1)
        cmds.setAttr("%s.directionZ"%objectNameGravity[0],0)
        cmds.setAttr("%s.magnitude"%objectNameGravity[0],28)
         
        #adding Expression for Object and SplashDisc
        generator.objectNameParticleExpressionBeforeDynamics(objectNameParticle[1], oceanShader)
        generator.splashDiscParticleExpressionBeforeDynamics(splashDiscParticle[1], oceanShader)
        generator.splashDiscParticleExpressionAfterDynamics(splashDiscParticle[1])
        generator.splashDiscParticleExpressionCreation(splashDiscParticle[1])
        if "ocean_MainExpression" not in cmds.ls() :
            generator.createMainExpression(objectNameEmitter[1])
        if "ocean_MainExpression" in cmds.ls() :
            generator.editMainExpression(objectName, splashDiscEmitter[0], oceanShader, objectNameEmitter[1], wakeEmitter, splashDiscEmitter[1])
#         num=0 
        if "mainSplashDisc_Shader" not in cmds.ls():
            generator.shaderSetup()
#             cmds.select(splashDiscEmitter[0], replace=True)
#             cmds.sets(edit=True,forceElement="mainSplashDisc_ShaderSG")
            cmds.sets(splashDiscParticle, edit = True, forceElement = 'mainSplashDisc_ShaderSG')
        else:
            cmds.sets(splashDiscParticle, edit = True, forceElement = 'mainSplashDisc_ShaderSG')
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         else:     
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         pSphere1_SplashDisc.translateX = pSphere1.translateX;
#         pSphere1_SplashDisc.translateZ = pSphere1.translateZ;
        return  
    def create_rain(self, *args):
        # Create the initial rain surface
        rainSurface = cmds.polyPlane(n="rainSurface", sx=10, sy=10, width=10, height=10)
        cmds.move(10, "rainSurface", y=True)

        # Create the emitter and particles
        rate = self.get_float_value(self.rain_rate)
        _emitter = cmds.emitter(type='omni', r=rate, sro=False)
        emitterName = _emitter[1]
        particleName, particleShape = cmds.particle()

        cmds.select(emitterName)
        emitterConnect = cmds.connectDynamic(particleName, em=emitterName)
        cmds.setAttr(emitterName+".emitterType", 2)

        # Set particle attributes
        cmds.setAttr(particleShape+".lifespanMode", 2)
        cmds.setAttr(particleShape+".lifespanRandom", 5)

        # Select particle for gravity field creation
        cmds.select(particleName)

        _gravity = cmds.gravity(pos=(0,0,0), m=9.8)
        #print _gravity
        gravityName = _gravity[0]

        gravityConnect = cmds.connectDynamic(particleName, f=gravityName)

        # Change particle render type
        cmds.setAttr(particleShape + ".particleRenderType", 6)

        # Create turbulence field
        cmds.select(particleName)
        _turbulence = cmds.turbulence()
        turbulenceName = _turbulence[1]
        cmds.connectDynamic(particleShape, f=turbulenceName)
        turb_magnitude = self.get_float_value(self.turbulence_magnitude)
        cmds.setAttr(turbulenceName+".magnitude", turb_magnitude)
        cmds.setAttr(turbulenceName+".attenuation", 0) # Attenuation at 0 for
        cmds.setAttr(turbulenceName+".frequency", 50)

        # Create vortex field
        cmds.select(particleName)
        vortex = cmds.vortex()
        vortexName = vortex[1]
        vortexConnect = cmds.connectDynamic(particleShape,f=vortexName)

        vort_magnitude = self.get_float_value(self.vortex_magnitude)
        print vort_magnitude

        # Update Vortex Attributes
        cmds.setAttr(vortexName+".magnitude",  vort_magnitude)

        # Make raindrops past the bounds of the surface plane
        cmds.setAttr(emitterName+".minDistance", 1)
        cmds.setAttr(emitterName+".maxDistance", 1)

        # Set raindrops speed
        cmds.setAttr(emitterName+".speedRandom", 0.9)
        cmds.setAttr(emitterName+".tangentSpeed", 1.5)

        wind_speed = self.get_float_value(self.rain_speed)
        cmds.setAttr(emitterName+".speed", wind_speed)

        print "Raindrops speed added."
        # Create surface for collisions (should be selected in the beginning, if not, a new surface will be created)
        #if self.selected_surface is None:
        groundName, groundShape = cmds.polyPlane(n="groundSurface", sx=10, sy=10, width=25, height=25)

        # Set resilience
        resilience = self.get_float_value(self.surface_resilience)
        cmds.select(particleName, r=True)
        cmds.select(groundName, add=True)
        cmds.collision(groundName, particleName, r=resilience)
        cmds.connectDynamic(particleName, c=groundName)
        print "Collisions added."

        # Split the raindrops on collision
        splitName, splitShape = cmds.particle(inherit=0.5, name="splitParticle")
        #print splitName, splitShape

        cmds.event(particleName, split=3, t=splitShape, spread=0.5, random=False)
        cmds.setAttr(splitShape+".inheritFactor", 0.5)
        print "Raindrop splits added."

        # Add the gravity field to newly split particles
        cmds.select(gravityName, r=True)
        cmds.select(splitShape, add=True)
        cmds.connectDynamic(splitShape, f=gravityName)
        print "Gravity field added."
    def create_rain(self, *args):
        # Create the initial rain surface
        rainSurface = cmds.polyPlane(n="rainSurface",
                                     sx=10,
                                     sy=10,
                                     width=10,
                                     height=10)
        cmds.move(10, "rainSurface", y=True)

        # Create the emitter and particles
        rate = self.get_float_value(self.rain_rate)
        _emitter = cmds.emitter(type='omni', r=rate, sro=False)
        emitterName = _emitter[1]
        particleName, particleShape = cmds.particle()

        cmds.select(emitterName)
        emitterConnect = cmds.connectDynamic(particleName, em=emitterName)
        cmds.setAttr(emitterName + ".emitterType", 2)

        # Set particle attributes
        cmds.setAttr(particleShape + ".lifespanMode", 2)
        cmds.setAttr(particleShape + ".lifespanRandom", 5)

        # Select particle for gravity field creation
        cmds.select(particleName)

        _gravity = cmds.gravity(pos=(0, 0, 0), m=9.8)
        #print _gravity
        gravityName = _gravity[0]

        gravityConnect = cmds.connectDynamic(particleName, f=gravityName)

        # Change particle render type
        cmds.setAttr(particleShape + ".particleRenderType", 6)

        # Create turbulence field
        cmds.select(particleName)
        _turbulence = cmds.turbulence()
        turbulenceName = _turbulence[1]
        cmds.connectDynamic(particleShape, f=turbulenceName)
        turb_magnitude = self.get_float_value(self.turbulence_magnitude)
        cmds.setAttr(turbulenceName + ".magnitude", turb_magnitude)
        cmds.setAttr(turbulenceName + ".attenuation",
                     0)  # Attenuation at 0 for
        cmds.setAttr(turbulenceName + ".frequency", 50)

        # Create vortex field
        cmds.select(particleName)
        vortex = cmds.vortex()
        vortexName = vortex[1]
        vortexConnect = cmds.connectDynamic(particleShape, f=vortexName)

        vort_magnitude = self.get_float_value(self.vortex_magnitude)
        print vort_magnitude

        # Update Vortex Attributes
        cmds.setAttr(vortexName + ".magnitude", vort_magnitude)

        # Make raindrops past the bounds of the surface plane
        cmds.setAttr(emitterName + ".minDistance", 1)
        cmds.setAttr(emitterName + ".maxDistance", 1)

        # Set raindrops speed
        cmds.setAttr(emitterName + ".speedRandom", 0.9)
        cmds.setAttr(emitterName + ".tangentSpeed", 1.5)

        wind_speed = self.get_float_value(self.rain_speed)
        cmds.setAttr(emitterName + ".speed", wind_speed)

        print "Raindrops speed added."
        # Create surface for collisions (should be selected in the beginning, if not, a new surface will be created)
        #if self.selected_surface is None:
        groundName, groundShape = cmds.polyPlane(n="groundSurface",
                                                 sx=10,
                                                 sy=10,
                                                 width=25,
                                                 height=25)

        # Set resilience
        resilience = self.get_float_value(self.surface_resilience)
        cmds.select(particleName, r=True)
        cmds.select(groundName, add=True)
        cmds.collision(groundName, particleName, r=resilience)
        cmds.connectDynamic(particleName, c=groundName)
        print "Collisions added."

        # Split the raindrops on collision
        splitName, splitShape = cmds.particle(inherit=0.5,
                                              name="splitParticle")
        #print splitName, splitShape

        cmds.event(particleName,
                   split=3,
                   t=splitShape,
                   spread=0.5,
                   random=False)
        cmds.setAttr(splitShape + ".inheritFactor", 0.5)
        print "Raindrop splits added."

        # Add the gravity field to newly split particles
        cmds.select(gravityName, r=True)
        cmds.select(splitShape, add=True)
        cmds.connectDynamic(splitShape, f=gravityName)
        print "Gravity field added."
Exemple #39
0
def createPoEmByShaderAndObjList(includeObjects, shaderList, **kwargs):
    '''{'del_path':'Dynamics/Particles/Emitter/createPoEmByShaderAndObjList()ONLYSE',
'icon':':/emitter.png',
'tip':'指定某些材质的面创建pointEmitter',
'usage':'\
    ########## No creation new uvsets##########\\n\
    objectList = cmds.ls(sl=True)\\n\
    for obj in objectList:\\n\
        fCount = cmds.polyEvaluate(obj,f=True)\\n\
        cmds.polyProjection("%s.f[0:%s]"%(obj,fCount), ch=False, type="Planar", ibd=False, cm=False, md="x")\\n\
    ##########################################\\n\
includeObjects = cmds.ls(sl=True,exactType="transform")\\n\
shaderList = cmds.ls(sl=True,mat=True)\\n\
$fun(includeObjects, shaderList, uvSetName="forEm", plannarMapping=False,mapDirectionValue="x")\\n\\n\
shaderList = cmds.ls(sl=True,mat=True)\\n\
includeObjects = cmds.listRelatives(cmds.ls(sl=True)[0],type="transform")\\n\
$fun(includeObjects, shaderList, uvSetName="forEm", plannarMapping=False,mapDirectionValue="x")'
}
'''
    if isinstance(includeObjects, str) or isinstance(includeObjects, unicode):
        includeObjects = [includeObjects]
    if isinstance(shaderList, str) or isinstance(shaderList, unicode):
        shaderList = [shaderList]


    defalutKwargs = dict(\
                         uvSetName='forEm', \
                         plannarMapping=False,\
                         mapDirectionValue='x'\
                         )

    execStr = __check_kwargs(defalutKwargs, kwargs)
    exec execStr
    print plannarMapping, uvSetName

    cmds.constructionHistory(toggle=False)

    includeObjects += cmds.listRelatives(includeObjects, type='mesh')
    #create ramp for emitter of textureRate
    if not cmds.objExists(
            "uvEmMap"):  #and not cmds.objectType('uvEmMap')=="ramp":
        emitMat = cmds.shadingNode('ramp', asTexture=True, n="uvEmMap")
        cmds.removeMultiInstance(emitMat + '.colorEntryList[2]', b=True)
        cmds.setAttr(emitMat + '.interpolation', 0)
        cmds.setAttr(emitMat + '.colorEntryList[0].color',
                     0,
                     0,
                     0,
                     type='double3')
        cmds.setAttr(emitMat + '.colorEntryList[1].position', 0.05)
        cmds.setAttr(emitMat + '.colorEntryList[1].color',
                     1,
                     1,
                     1,
                     type='double3')
    else:
        emitMat = "uvEmMap"

    for inSideShader in shaderList:
        cmds.hyperShade(objects=inSideShader)
        faceList = cmds.ls(sl=True)

        cmds.select(cl=True)
        emitObjList, faceSet = [], []

        for faceGrp in faceList:
            emitObj = re.split(r'\.f', faceGrp)[0]
            #worldarea = cmds.polyEvaluate( emitObj, wa=True )
            #if emitObj not in emitObjList and worldarea>maxArea:
            if emitObj not in emitObjList and emitObj in includeObjects:
                emitObjList.append(emitObj)
                #print emitObj
                #append list to faceSet List
                faceSet.append([])

            if emitObj in emitObjList:
                faceSetIndex = emitObjList.index(emitObj)
                #add faceGrp to faceSet[]
                faceSet[faceSetIndex].append(faceGrp)

        #create uvSet for pointEmitter and create pointEmitter for emitObj
        for objFaceGrp in faceSet:
            emitObjIndex = faceSet.index(objFaceGrp)

            parEmit = cmds.emitter(emitObjList[emitObjIndex],
                                   type='surf',
                                   nsp=.1,
                                   tsp=1,
                                   srn=1,
                                   n='shtterEmit##')[1]

            if objFaceGrp[0] != emitObjList[emitObjIndex]:
                #Delete uvSetName uvset if it exists
                temp = cmds.polyUVSet(emitObjList[emitObjIndex],
                                      q=True,
                                      allUVSets=True)
                if temp != None and uvSetName in temp:
                    cmds.polyUVSet(emitObjList[emitObjIndex],
                                   delete=True,
                                   uvSet=uvSetName)

                #create new uvsets
                if plannarMapping:
                    cmds.polyProjection(objFaceGrp,
                                        ch=False,
                                        type='Planar',
                                        ibd=False,
                                        cm=True,
                                        uvSetName=uvSetName,
                                        md=mapDirectionValue)
                #copy uv to uvSetName from map1
                else:
                    emitterUVSet = cmds.polyUVSet(emitObjList[emitObjIndex],
                                                  create=True,
                                                  uvSet=uvSetName)[0]
                    cmds.polyCopyUV(objFaceGrp,
                                    uvi='map1',
                                    uvs=emitterUVSet,
                                    ch=False)

                    firstUVSet = cmds.polyUVSet(emitObjList[emitObjIndex],
                                                q=True,
                                                allUVSets=True)[0]
                    cmds.polyUVSet(emitObjList[emitObjIndex],
                                   currentUVSet=True,
                                   uvSet=firstUVSet)

                cmds.setAttr(parEmit + '.enableTextureRate', 1)
                cmds.connectAttr(emitMat + '.outColor',
                                 parEmit + '.textureRate')
                geoConnectNodeList = cmds.ls(cmds.listHistory(
                    emitObjList[emitObjIndex], f=True, levels=1),
                                             exactType='geoConnector')
                if geoConnectNodeList != []:
                    for geoConnectNode in geoConnectNodeList:
                        cmds.setAttr(geoConnectNode + '.guv',
                                     uvSetName,
                                     type='string',
                                     l=True)

    cmds.constructionHistory(toggle=True)
Exemple #40
0
    def buildSplash(self):
        objectName = str(self.getObject.text())
        if self.checkWake.isChecked() == True:
            wakeEmitter = str(self.getWake.text())
        else:
            wakeEmitter = "OceanWakeEmitter1"
        if self.checkOcean.isChecked() == True:
            oceanShader = str(self.getOcean.text())
        else:
            oceanShader = "oceanShader1"

        ###Bcreating Splash Disc
        objectNameAxis = generator.getMaxAndMinAxis(objectName)
        #generator_Return: 0-maxX, 1-minX, 2-maxY, 3-minY, 4-maxZ, 5-minZ
        avrgX = objectNameAxis[0] - objectNameAxis[1]
        avrgZ = objectNameAxis[4] - objectNameAxis[5]
        avrgY = objectNameAxis[2] - objectNameAxis[3]
        if avrgX > avrgZ:
            SplashCurve = avrgX
        else:
            SplashCurve = avrgZ
        baseCurve = cmds.circle(name="base",
                                normal=[0, 1, 0],
                                radius=SplashCurve / 1.5)
        headCurve = cmds.circle(name="head",
                                normal=[0, 1, 0],
                                radius=SplashCurve / 2)
        cmds.move(0, (avrgY / 4), 0, headCurve)
        cmds.rebuildCurve("base",
                          ch=1,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=0,
                          kt=0,
                          s=100,
                          d=7,
                          tol=0.01)
        cmds.rebuildCurve("head",
                          ch=1,
                          rpo=1,
                          rt=0,
                          end=1,
                          kr=0,
                          kcp=0,
                          kep=0,
                          kt=0,
                          s=100,
                          d=7,
                          tol=0.01)
        splashDisc = cmds.loft("base",
                               "head",
                               name="%s_SplashDisc" % objectName,
                               ch=1,
                               u=1,
                               c=0,
                               ar=1,
                               d=3,
                               ss=int(avrgY + 1),
                               rn=0,
                               po=0,
                               rsn=True)
        #Return: 0-SplashDisc, 1-loft1
        cmds.delete(baseCurve, headCurve)
        cmds.setAttr("%s.visibility" % splashDisc[0], False)
        objectPosition = cmds.xform(objectName,
                                    query=True,
                                    translation=True,
                                    worldSpace=True)
        cmds.move(objectPosition[0], 0, objectPosition[2], splashDisc[0])

        ###adding emitter and particle to Object
        objectNameEmitter = cmds.emitter(objectName,
                                         type='surface',
                                         rate=0,
                                         scaleRateByObjectSize=False,
                                         needParentUV=False,
                                         cycleEmission="none",
                                         cycleInterval=1,
                                         speed=1,
                                         speedRandom=0,
                                         normalSpeed=1,
                                         tangentSpeed=0,
                                         maxDistance=0,
                                         minDistance=0,
                                         directionX=1,
                                         directionY=0,
                                         directionZ=0,
                                         spread=0,
                                         name="%s_emitter" % objectName)
        #Return: 0-objectName, 1-objectName_emitter
        objectNameParticle = cmds.particle(name="%s_particle" % objectName)
        cmds.connectDynamic(objectNameParticle[0],
                            emitters=objectNameEmitter[0])
        ###adding emitter and particle to Splash Disc
        splashDiscEmitter = cmds.emitter(splashDisc[0],
                                         type='surface',
                                         rate=0,
                                         scaleRateByObjectSize=False,
                                         needParentUV=False,
                                         cycleEmission="none",
                                         cycleInterval=1,
                                         speed=1,
                                         speedRandom=1.5,
                                         normalSpeed=1,
                                         tangentSpeed=0,
                                         maxDistance=0,
                                         minDistance=0,
                                         directionX=1,
                                         directionY=0,
                                         directionZ=0,
                                         spread=0,
                                         name="%s_emitter" % splashDisc[0])
        #Return: 0-SplashDisc, 1-SplashDisc_emitter
        splashDiscParticle = cmds.particle(name="%s_particle" % splashDisc[0])
        cmds.connectDynamic(splashDiscParticle[0],
                            emitters=splashDiscEmitter[0])

        #connecting the X and Z object position to Splash Disc to follow
        cmds.connectAttr("%s.translate.translateZ" % objectName,
                         "%s.translate.translateZ" % splashDisc[0])
        cmds.connectAttr("%s.translate.translateX" % objectName,
                         "%s.translate.translateX" % splashDisc[0])

        #setting up the splash Disc particle Setting
        cmds.setAttr("%s.lifespanMode" % splashDiscParticle[1], 3)
        cmds.setAttr("%s.lifespanRandom" % splashDiscParticle[1], 0.5)
        cmds.setAttr("%s.conserve" % splashDiscParticle[1], 0.983)
        cmds.setAttr("%s.inheritFactor" % splashDiscParticle[1], 0.2)
        cmds.setAttr("%s.particleRenderType" % splashDiscParticle[1], 5)
        cmds.addAttr(splashDiscParticle[1],
                     keyable=True,
                     ln="useLighting",
                     at="bool",
                     dv=False)
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteScaleYPP",
                     dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteScaleYPP0",
                     dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteScaleXPP",
                     dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteScaleXPP0",
                     dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteTwistPP",
                     dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1],
                     ln="spriteTwistPP0",
                     dt="doubleArray")
        #creating Ramp for Splash Disc particle
        splashDiscParticle_spriteScaleXPP = cmds.arrayMapper(
            target=splashDiscParticle[1],
            destAttr="spriteScaleXPP",
            inputV="ageNormalized",
            type="ramp")
        ramp_spriteScaleXPP = cmds.listConnections(
            splashDiscParticle_spriteScaleXPP, type="ramp")
        ramp_spriteScaleXPP = cmds.rename(
            ramp_spriteScaleXPP[1],
            "%s_spriteScaleXPP_Rampe" % splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color" % ramp_spriteScaleXPP, 0, 0,
                     0)
        cmds.setAttr("%s.colorEntryList[2].position" % ramp_spriteScaleXPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color" % ramp_spriteScaleXPP, 0.5,
                     0.5, 0.5)
        cmds.setAttr("%s.colorEntryList[1].position" % ramp_spriteScaleXPP,
                     0.165)
        cmds.setAttr("%s.colorEntryList[0].color" % ramp_spriteScaleXPP, 1, 1,
                     1)
        cmds.setAttr("%s.colorEntryList[0].position" % ramp_spriteScaleXPP, 0)

        splashDiscParticle_spriteScaleYPP = cmds.arrayMapper(
            target=splashDiscParticle[1],
            destAttr="spriteScaleYPP",
            inputV="ageNormalized",
            type="ramp")
        ramp_spriteScaleYPP = cmds.listConnections(
            splashDiscParticle_spriteScaleYPP, type="ramp")
        ramp_spriteScaleYPP = cmds.rename(
            ramp_spriteScaleYPP[1],
            "%s_SpriteScaleYPP_Rampe" % splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color" % ramp_spriteScaleYPP, 0, 0,
                     0)
        cmds.setAttr("%s.colorEntryList[2].position" % ramp_spriteScaleYPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color" % ramp_spriteScaleYPP, 0.5,
                     0.5, 0.5)
        cmds.setAttr("%s.colorEntryList[1].position" % ramp_spriteScaleYPP,
                     0.165)
        cmds.setAttr("%s.colorEntryList[0].color" % ramp_spriteScaleYPP, 1, 1,
                     1)
        cmds.setAttr("%s.colorEntryList[0].position" % ramp_spriteScaleYPP, 0)

        #setting up the object particle Setting
        cmds.setAttr("%s.lifespanMode" % objectNameParticle[1], 3)
        cmds.setAttr("%s.particleRenderType" % objectNameParticle[1], 7)
        cmds.addAttr(objectNameParticle[1],
                     keyable=True,
                     ln="threshold",
                     at="float",
                     min=0,
                     max=10,
                     dv=0.7)
        cmds.addAttr(objectNameParticle[1],
                     keyable=True,
                     ln="radius",
                     at="float",
                     min=0,
                     max=10,
                     dv=0.5)
        cmds.addAttr(objectNameParticle[1], ln="radiusPP", dt="doubleArray")
        #creating Ramp for object particle
        objectNameParticle_radiusPP = cmds.arrayMapper(
            target=objectNameParticle[1],
            destAttr="radiusPP",
            inputV="ageNormalized",
            type="ramp")
        ramp_radiusPP = cmds.listConnections(objectNameParticle_radiusPP,
                                             type="ramp")
        ramp_radiusPP = cmds.rename(
            ramp_radiusPP[1], "%s_RadiusPP_Rampe" % objectNameParticle[1])
        cmds.setAttr("%s.colorEntryList[3].color" % ramp_radiusPP, 0.056,
                     0.056, 0.056)
        cmds.setAttr("%s.colorEntryList[3].position" % ramp_radiusPP, 1)
        cmds.setAttr("%s.colorEntryList[2].color" % ramp_radiusPP, 0.223,
                     0.223, 0.223)
        cmds.setAttr("%s.colorEntryList[2].position" % ramp_radiusPP, 0.690)
        cmds.setAttr("%s.colorEntryList[1].color" % ramp_radiusPP, 0.178,
                     0.178, 0.178)
        cmds.setAttr("%s.colorEntryList[1].position" % ramp_radiusPP, 0.455)
        cmds.setAttr("%s.colorEntryList[0].color" % ramp_radiusPP, 0, 0, 0)
        cmds.setAttr("%s.colorEntryList[0].position" % ramp_radiusPP, 0)

        #adding gravity to SplashDisc
        splashDiscGravity = cmds.gravity(name="%s_GravityField" %
                                         splashDiscParticle[0],
                                         pos=[0, 0, 0],
                                         m=9.8,
                                         att=0,
                                         dx=0,
                                         dy=-1,
                                         dz=0,
                                         mxd=-1,
                                         vsh="none",
                                         vex=0,
                                         vof=[0, 0, 0],
                                         vsw=360,
                                         tsr=0.5)
        cmds.connectDynamic(splashDiscParticle[0], fields=splashDiscGravity)

        #adding gravity to Object
        objectNameGravity = cmds.uniform(name="%s_UniformField" %
                                         objectNameParticle[0],
                                         pos=[0, 0, 0],
                                         m=5,
                                         att=1,
                                         dx=1,
                                         dy=-1,
                                         dz=0,
                                         mxd=-1,
                                         vsh="none",
                                         vex=0,
                                         vof=[0, 0, 0],
                                         vsw=360,
                                         tsr=0.5)
        cmds.connectDynamic(objectNameParticle[0], fields=objectNameGravity)
        print objectNameGravity
        cmds.setAttr("%s.directionX" % objectNameGravity[0], 0)
        cmds.setAttr("%s.directionY" % objectNameGravity[0], 1)
        cmds.setAttr("%s.directionZ" % objectNameGravity[0], 0)
        cmds.setAttr("%s.magnitude" % objectNameGravity[0], 28)

        #adding Expression for Object and SplashDisc
        generator.objectNameParticleExpressionBeforeDynamics(
            objectNameParticle[1], oceanShader)
        generator.splashDiscParticleExpressionBeforeDynamics(
            splashDiscParticle[1], oceanShader)
        generator.splashDiscParticleExpressionAfterDynamics(
            splashDiscParticle[1])
        generator.splashDiscParticleExpressionCreation(splashDiscParticle[1])
        if "ocean_MainExpression" not in cmds.ls():
            generator.createMainExpression(objectNameEmitter[1])
        if "ocean_MainExpression" in cmds.ls():
            generator.editMainExpression(objectName, splashDiscEmitter[0],
                                         oceanShader, objectNameEmitter[1],
                                         wakeEmitter, splashDiscEmitter[1])
#         num=0
        if "mainSplashDisc_Shader" not in cmds.ls():
            generator.shaderSetup()
            #             cmds.select(splashDiscEmitter[0], replace=True)
            #             cmds.sets(edit=True,forceElement="mainSplashDisc_ShaderSG")
            cmds.sets(splashDiscParticle,
                      edit=True,
                      forceElement='mainSplashDisc_ShaderSG')
        else:
            cmds.sets(splashDiscParticle,
                      edit=True,
                      forceElement='mainSplashDisc_ShaderSG')
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         else:
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         pSphere1_SplashDisc.translateX = pSphere1.translateX;
#         pSphere1_SplashDisc.translateZ = pSphere1.translateZ;
        return
Exemple #41
0
    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()
Exemple #42
0
def snowFactory(self):
    #Duplicate Face
    faceSelection = mc.ls(sl=True)
    object = mc.ls(sl=True, o=True)
    mc.polyChipOff(faceSelection, ch=True, kft=True, dup=True, off=0)
    mc.polySeparate(object)
    mc.parent(w=True)
    mc.select(object, deselect=True)
    mm.eval("CenterPivot")
    objA = mc.ls(sl=True, head=1)
    objB = mc.ls(sl=True, tail=1)
    mc.select(objA, deselect=True)
    global objC
    objC = mc.ls(sl=True)
    totalDuplicatedMesh = len(objC)
    #Delete History
    for j in range(0, totalDuplicatedMesh, 1):
        TransformNode = mc.ls(objC[j], dependencyNodes=True)
        mc.select(TransformNode[0])
        mm.eval('DeleteHistory')
        mc.delete(TransformNode[0], ch=True)
    orgTrans = mc.ls(objA, dependencyNodes=True)
    mc.select(orgTrans[0])
    mm.eval('DeleteHistory')
    mc.delete(orgTrans[0], ch=True)

    #Nparticle Setup
    snowParticle = mc.nParticle()
    for i in range(0, totalDuplicatedMesh, 1):
        mc.select(objC[i])
        snowEmitter = mc.emitter(n=(objC[i] + 'snowEmitter'),
                                 type='surface',
                                 r=5000,
                                 sro=0,
                                 nuv=0,
                                 cye='none',
                                 cyi=1,
                                 spd=0,
                                 srn=0,
                                 nsp=1,
                                 tsp=0,
                                 mxd=0,
                                 mnd=0,
                                 dx=1,
                                 dy=0,
                                 dz=0,
                                 sp=0)
        mc.connectDynamic(snowParticle, em=snowEmitter[1])
    mc.setAttr(str(snowParticle[0]) + '.ignoreSolverGravity', 1)
    mc.setAttr(str(snowParticle[0]) + '.dynamicsWeight', 0)
    mc.setAttr(str(snowParticle[0]) + '.conserve', 0)
    mc.setAttr(str(snowParticle[0]) + '.radius', 0.1)
    mc.setAttr(str(snowParticle[0]) + '.radiusScaleRandomize', 0.5)
    mc.setAttr(str(snowParticle[0]) + '.particleRenderType', 3)
    #Play Forward

    #Generate Nparticle Mesh
    mc.select(snowParticle[0], r=True)
    outMesh = mm.eval('particleToPoly')
    global snowParticleShape
    snowParticleShape = mc.listRelatives(snowParticle[0], s=True)
    mc.setAttr(str(snowParticleShape[0]) + '.blobbyRadiusScale', 1.8)
    mc.setAttr(str(snowParticleShape[0]) + '.meshTriangleSize', 0.2)
    mc.setAttr(str(snowParticleShape[0]) + '.meshMethod', 3)
    mc.setAttr(str(snowParticleShape[0]) + '.meshSmoothingIterations', 10)
emitter -pos 0 0 0 -type omni  -name "emit1#" -r 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 ;
// Result: emit11 // 
particle;
// Result: particle1 particleShape1 // 
connectDynamic -em emit11 particle1;
// Result: particleShape1 // 


import maya.cmds as cmds
# cye=none???
myEmitter_name = 'myEmit'
myParticle_name = 'par1'
emit_obj = cmds.emitter(name=myEmitter_name, pos=[0, 0, 0], type='omni', r=100, sro=0, nuv=0, cye='none', spd=1, srn=0,
             nsp=1, tsp=0, mnd=0, dx=1, dy=0, dz=0, sp=0)

part_obj = cmds.particle(name=myParticle_name)

cmds.connectDynamic(part_obj[0], em=emit_obj[0])

# Create emitters
def create_emit(myEmitter_name, current_rate=100):
    emit_obj = cmds.emitter(name=myEmitter_name, pos=[0, 0, 0], type='omni', r=current_rate, sro=0, nuv=0, cye='none', spd=1, srn=0,
             nsp=1, tsp=0, mnd=0, dx=1, dy=0, dz=0, sp=0)

    part_obj = cmds.particle(name=emit_obj[0] + '_part')
    
    cmds.connectDynamic(part_obj[0], em=emit_obj[0])
    return [emit_obj[0], part_obj[0], part_obj[1]]

emit1 = create_emit('myEmit1', 1000)
import maya.cmds as cmds

# Creating emitter and particle object
emit = cmds.emitter(n='spray', dx=0, dy=1, dz=0, r=100, sp=0.17, spd=5) # Returns lists

# Return List [particle, particleShape]
part = cmds.particle(n='droplets')

# Connecting particle to emitter
cmds.connectDynamic(part[0], em=emit[0])

# Selecting object in scene
hose_objects = cmds.ls(sl=True)

# Parenting emitter to hose. First selected object.
cmds.parent( emit[0], hose_objects[0] )

part_attrs = {'depthSort':True, 'particleRenderType':0}

for attr, value in part_attrs.items():
    cmds.setAttr('%s.%s' %(part[1], attr), value)
   
#The code for Current Render Type button inside the particleShape
#ln=longName, at=attributeType, dv=defaultValue, min=minValue, max=maxValue
#When activating the Current Render Type button, make sure the code is part[1],
#this is the particleShape node that will need to be selected when editing attrs and not [0]
#[0] is the particle.
cmds.addAttr(part[1], internalSet=True, ln="colorAccum", at="bool", dv=False )
cmds.addAttr(part[1], internalSet=True, ln="useLighting", at="bool", dv=False )
cmds.addAttr(part[1], internalSet=True, ln="pointSize", at="long", min=1, max=60, dv=2 )
cmds.addAttr(part[1], internalSet=True, ln="multiCount", at="long", min=1, max=60, dv=10 )
Exemple #45
0
	def __init__(self):

		for i in itertools.count():
			self.ANIMATABLE_GRP = 'spriteSpray_GRP_%03d' % i
			self.SPEED_LOCATOR_NAME = 'spriteSpray_locator_%03d' % i
			self.PARTICLE_NAME = 'spriteSpray_nParticle_%03d' % i
			self.EMITTER_NAME = 'spriteSpray_emitter_%03d' % i

			if not cmds.objExists(self.ANIMATABLE_GRP) and not cmds.objExists(self.SPEED_LOCATOR_NAME) and not cmds.objExists(self.PARTICLE_NAME) and not cmds.objExists(self.EMITTER_NAME):
				self.ANIMATABLE_GRP = 'spriteSpray_GRP_%03d' % i
				self.SPEED_LOCATOR_NAME = 'spriteSpray_locator_%03d' % i
				self.PARTICLE_NAME = 'spriteSpray_nParticle_%03d' % i
				self.EMITTER_NAME = 'spriteSpray_emitter_%03d' % i

				break

		## Creation of whatever teh shits it needs man
		self.nParticle, self.nParticleShape = self.nParticle_(name = self.PARTICLE_NAME)
		self.locator = cmds.spaceLocator(name = self.SPEED_LOCATOR_NAME)[0]
		cmds.select(clear = True)
		self.emitter = cmds.emitter(name = self.EMITTER_NAME, type = 'volume', scaleRateByObjectSize = False, directionX = 0, volumeShape = 'sphere')[0]

		self.nucleus = self.NUCLEUS_NAME
		if not cmds.objExists(self.nucleus):
			self.nucleus = self.nucleus_(name = self.nucleus)

		## Connect nParticle to nucleus
		cmds.select(self.nParticleShape, replace = True)
		mel.eval('assignNSolver "%s";' % self.nucleus)

		## Build shader for the sprite
		self.spriteSG = self.spriteShader(name = 'fx_sprite')
		cmds.sets(self.nParticleShape, edit = True, forceElement = self.spriteSG)

		## Grouping stuffs
		self.topGroup = cmds.group(self.locator, self.nParticle, name = self.ANIMATABLE_GRP)
		cmds.parent(self.emitter, self.locator)

		## Locking/Hiding attrs for various objects...
		toLockAndHide = ['translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ', 'scaleX', 'scaleY', 'scaleZ']
		[cmds.setAttr('%s.%s' %(self.topGroup, each), lock = True, keyable = False, channelBox = False) for each in toLockAndHide]
		[cmds.setAttr('%s.%s' %(self.nParticle, each), lock = True, keyable = False, channelBox = False) for each in toLockAndHide]
		toScale = ['localScaleX', 'localScaleY', 'localScaleZ']
		[cmds.setAttr('%s.%s' %(self.locator, each), 10) for each in toScale]

		# ## Getting the final long name for each objects
		# self.nParticle = cmds.ls(self.nParticle, long = True)[0]
		# self.nParticleShape = cmds.ls(self.nParticleShape, long = True)[0]
		# self.locator = cmds.ls(self.locator, long = True)[0]
		# self.emitter = cmds.ls(self.emitter, long = True)[0]

		## SPEED
		attr = {'longName':'speedDisplay', 'niceName':' ', 'attributeType':'enum', 'enumName':'Speed:', 'keyable':False}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'speed', 'attributeType':'double', 'keyable':False}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'minSpeed', 'attributeType':'double', 'defaultValue':5, 'min':0}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'maxSpeed', 'attributeType':'double', 'defaultValue':20}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'useSpeed', 'niceName':'Use Speed', 'attributeType':'bool', 'defaultValue':1}
		self.add_custom_attrs(self.locator, **attr)
		## EMITTERS
		attr = {'longName':'sideEmitters', 'niceName':' ', 'attributeType':'enum', 'enumName':'Emitters:', 'keyable':False}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'rateMultiplier', 'niceName':'Rate * ', 'attributeType':'double', 'defaultValue':2250, 'min':0}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'splashMaxSpeed', 'niceName':'Speed * ', 'attributeType':'double', 'defaultValue':2.25, 'min':1}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'randomSpeed', 'niceName':'Random Speed', 'attributeType':'double', 'defaultValue':1, 'min':0}
		self.add_custom_attrs(self.locator, **attr)
		## PER PARTICLE CREATION
		attr = {'longName':'ppCreation', 'niceName':' ', 'attributeType':'enum', 'enumName':'PP Creation:', 'keyable':False}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'lifespanMin', 'attributeType':'double', 'defaultValue':1}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'lifespanMax', 'attributeType':'double', 'defaultValue':1.5}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'twistAngleMin', 'attributeType':'double', 'defaultValue':0, 'min':0, 'max':360}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'twistAngleMax', 'attributeType':'double', 'defaultValue':360, 'min':0, 'max':360}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'twistSpeedMin', 'attributeType':'double', 'defaultValue':-4}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'twistSpeedMax', 'attributeType':'double', 'defaultValue':30}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'spriteStartSizeMin', 'attributeType':'double', 'defaultValue':0.15, 'min':0}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'spriteStartSizeMax', 'attributeType':'double', 'defaultValue':0.46, 'min':0}
		self.add_custom_attrs(self.locator, **attr)
		## NPARTICLE
		attr = {'longName':'nParticleSprite', 'niceName':' ', 'attributeType':'enum', 'enumName':'nParticle:', 'keyable':False}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'inheritFactorSprite', 'attributeType':'double', 'defaultValue':0.6, 'min':0, 'max':1}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'conserveSprite', 'attributeType':'double', 'defaultValue':1, 'min':0, 'max':1}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'dragSprite', 'attributeType':'double', 'defaultValue':0.01, 'min':0, 'max':1}
		self.add_custom_attrs(self.locator, **attr)
		attr = {'longName':'dampSprite', 'attributeType':'double', 'defaultValue':0, 'min':0, 'max':1}
		self.add_custom_attrs(self.locator, **attr)

		## Base setups
		self._doBaseParticleShapeSetup(particleShapeName = self.nParticleShape, presetName = self.PRESET_PATH)
		## Connect the emitter to the particles
		cmds.connectDynamic(self.nParticleShape, em = self.emitter)
		## Make sure visibility is connected to isDynamic so hidden means won't simulate
		cmds.connectAttr('%s.visibility' % self.nParticle, '%s.isDynamic' % self.nParticleShape)

		## Expression
		self._build_nParticleExpressions(particleShapeName = self.nParticleShape, animatable = self.locator)
		self._buildSpeedExpression(speedObject = self.locator)
		self._buildEmitterExpression(speedObject = self.locator, emitter = self.emitter, animatable = self.locator)
import maya.cmds as cmds

# Creating emitter and particle object
emit = cmds.emitter(n='spray', )  # Returns lists
part = cmds.particle(n='droplets')  # Return List [particle, particleShape]
# Connecting particle to emitter
cmds.connectDynamic(part[0], em=emit[0])
# Selecting object in scene
hose_objects = cmds.ls(sl=True)
# Parenting emitter to hose. First selected object.
cmds.parent(emit[0], hose_objects[0])
Exemple #47
0
def run():
    selected = cmds.ls(sl=True)
    fattrs = {
        'squareVoxels': 0,
        'dimensionsW': 30,
        'dimensionsH': 6,
        'dimensionsD': 30,
        'densityMethod': 0,
        'velocitySwirl': 5,
        'highDetailSolve': 3,
        'boundaryDraw': 4
    }
    fc = mel.eval('create3DFluid 10 10 10 10 10 10')
    scale = 20

    print(fc)
    cmds.setAttr(fc + '.resolution', 100, 20, 100)
    for attr in fattrs:
        cmds.setAttr(fc + '.' + attr, fattrs[attr])
    cmds.select(selected[0])
    fm = cmds.fluidEmitter(type='surface',
                           densityEmissionRate=1,
                           heatEmissionRate=0,
                           fuelEmissionRate=0,
                           fluidDropoff=2,
                           rate=100,
                           cycleInterval=1,
                           maxDistance=1,
                           minDistance=0)[1]
    cmds.connectDynamic(fc, em=fm)
    cmds.setAttr(fm + '.emitterType', 2)
    pt = cmds.particle()
    cmds.setAttr(pt[1] + '.conserve', 0)
    cmds.select(selected[0])
    pm = cmds.emitter(type='surface',
                      rate=100000,
                      scaleRateByObjectSize=0,
                      needParentUV=0,
                      cycleInterval=1,
                      speed=0,
                      speedRandom=0,
                      normalSpeed=1,
                      tangentSpeed=0)
    cmds.connectDynamic(pt[1], em=pm)
    va = cmds.volumeAxis(pos=(0, 0, 0),
                         magnitude=5,
                         attenuation=0,
                         invertAttenuation=0,
                         awayFromCenter=0,
                         awayFromAxis=0,
                         aroundAxis=1,
                         alongAxis=0,
                         drs=0,
                         turbulence=0.1,
                         turbulenceSpeed=0.2,
                         detailTurbulence=1)[0]
    cmds.setAttr('.sx', scale)
    cmds.setAttr('.sy', scale)
    cmds.setAttr('.sz', scale)
    cmds.connectDynamic(fc, f=va)
    cmds.connectDynamic(pt, f=fc)
    cmds.connectAttr('time1.outTime', va + '.time')
    cmds.setAttr(selected[0] + '.overrideEnabled', 1)
    cmds.setAttr(selected[0] + '.overrideDisplayType', 1)
    # parent under a group
    grp = cmds.group(n='vortex', em=True)
    cmds.parent(va, grp)
    cmds.parent(fc, grp)
    cmds.parent(pt, grp)
    #cmds.parent(selected[0], grp)
    pass
def _buildRearEmitter(name='',
                      boatName='',
                      splashParticleName='',
                      rearAnimatable='',
                      presetName=None):
    """
    New builder for rear nParticle Emitter
    Checks if the NPARTICLE_EMITTLERS_hrc exists or not too

    @param name: The name of the new emitter
    @param splashParticleName: The name of the nParticleShape node for the splash
    @type name:  String
    @type splashParticleName: String
    """
    if not cmds.objExists('nPARTICLE_EMITTERS_hrc'):
        cmds.group(n='nPARTICLE_EMITTERS_hrc', em=True)

    debug(None,
          method='_buildRearEmitter',
          message='name: %s' % name,
          verbose=False)
    cmds.select(
        clear=True
    )  ## Because if you have anything selected maya may freak out it's the wrong damn thing.. f**k you maya seriously!

    ## Build the emitter
    emitter = cmds.emitter(name=name)
    emitter[0] = cmds.ls(emitter[0], long=True)[0]

    if presetName:
        pathToPreset = '%s/%s' % (CONST.EMITTERBASEPRESETPATH, presetName)
        debug(None,
              method='_buildRearEmitter',
              message='emitter: %s' % emitter,
              verbose=False)
        debug(None,
              method='_buildRearEmitter',
              message='pathToPreset: %s' % pathToPreset,
              verbose=False)

        ## Apply the preset to the emitter
        try:
            mel.eval('applyPresetToNode "%s" "" "" "%s" 1;' %
                     (emitter[0], pathToPreset))
            debug(None,
                  method='_buildRearEmitter',
                  message='Mel preset applied to %s: %s' %
                  (emitter[0], pathToPreset),
                  verbose=False)
        except RuntimeError:
            pass

    ## Now parent it
    try:
        emitter[0] = cmds.parent(emitter[0], 'nPARTICLE_EMITTERS_hrc')[0]
    except:
        pass

    ## Connect the emitter to the particles
    _connect_NParticleShape_to_NParticleEmitter(
        particleShapeNode=splashParticleName, emitter=emitter[0])

    ## Now do the expression for the rear emitter
    expStringList = [
        'float $minSpeed = %s.minSpeed;\n' % rearAnimatable,
        'float $maxSpeed = %s.maxSpeed;\n' % rearAnimatable,
        'float $speed = %s:world_ctrl.speed;\n' % boatName,
        'float $curve = smoothstep($minSpeed, $maxSpeed, $speed);\n',
        'float $rateMuliplier = %s.rateMultiplier;\n' % rearAnimatable,
        'float $splashMaxSpeed = %s.splashMaxSpeed;\n' % rearAnimatable,
        '\n',
        'if (%s.useSpeed == 1)\n' % rearAnimatable,
        '{\n\t',
        '%s.rate = $rateMuliplier * $curve;\n\t\t' % emitter[0],
        '\n\t\t',
        'float $emitterSpeed = $splashMaxSpeed * $curve;\n\t\t',
        'if ($emitterSpeed == 0)\n\t\t',
        '{\n\t\t\t',
        '$emitterSpeed = 0.1;\n\t\t',
        '}\n\t\t',
        '%s.alongAxis = $emitterSpeed;\n' % emitter[0],
        '}\n',
        'else\n',
        '{\n\t',
        '%s.rate = $rateMuliplier;\n\t' % emitter[0],
        '%s.alongAxis = $splashMaxSpeed;\n' % emitter[0],
        '}\n',
    ]
    ## Check if the expression already exists in the scene, if so delete it
    # utils.checkExpressionExists('%s_rearEmitter' % boatName)

    ## Build new expression
    cmds.expression(emitter[0],
                    n='%s_rearEmitter' % boatName,
                    string=utils.processExpressionString(expStringList))

    ## Connect some attributes
    if not cmds.isConnected('%s.randomSpeed' % rearAnimatable,
                            '%s.speedRandom' % emitter[0]):
        cmds.connectAttr('%s.randomSpeed' % rearAnimatable,
                         '%s.speedRandom' % emitter[0])
    if not cmds.isConnected('%s.randomDirection' % rearAnimatable,
                            '%s.randomDirection' % emitter[0]):
        cmds.connectAttr('%s.randomDirection' % rearAnimatable,
                         '%s.randomDirection' % emitter[0])

    return emitter[0]