Beispiel #1
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!"
Beispiel #2
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 add_rigid_body( self, objects, magnitude = 50 ):
		
		cmds.rigidBody( objects, active = False, m = magnitude, collisions = False )
		
		cmds.gravity( pos = [0, 0, 0], m = magnitude, att = 0, dx = 0, dy = -1, dz = 0, mxd = -1, vsh = 'none', vex = 0, vof = [0, 0, 0], vsw = 360, tsr = 0.5 )
		gravity_dag = oopmaya.DAG_Node()
		cmds.connectDynamic( objects, fields = gravity_dag.name() )
Beispiel #4
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
Beispiel #5
0
	def addCollision(WeatherUI):
		
		objects = c.ls(sl=True);
		for i in range(0,len(objects)):
			c.collision(objects[i], f=0.05, r=0.2);
			c.connectDynamic('rainParticle', c=objects[i]);
			print objects[i];
Beispiel #6
0
 def addDynamics(self,*args):
     for i in self.scene_before:
         self.obj = mc.listRelatives(i, p = True)
         mc.select(self.obj)
         mc.rigidBody( active = True, mass = 10, initialVelocity = (0.0,0.0,0.0), bounciness = 1, dynamicFriction = 0.8, damping = 0.2)
         self.G = mc.gravity(directionX = 0.0, directionY = -1.0, directionZ = 0.0, magnitude = 100)
         mc.connectDynamic(*self.obj, f = self.G)
Beispiel #7
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
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))
Beispiel #9
0
def _unlinkAllEmitters():
    """
    Convenience function to unlink all fluid emitters in scene to ocean used in the app UI
    """
    fluids = [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]
    for eachFluid in fluids:
        for eachEmitter in cmds.ls(type = 'fluidEmitter'):
            cmds.connectDynamic (eachFluid, em = eachEmitter, d = True)
Beispiel #10
0
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]]
Beispiel #11
0
def _unlinkAllEmitters():
    """
    Convenience function to unlink all fluid emitters in scene to ocean used in the app UI
    """
    fluids = [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]
    for eachFluid in fluids:
        for eachEmitter in cmds.ls(type='fluidEmitter'):
            cmds.connectDynamic(eachFluid, em=eachEmitter, d=True)
Beispiel #12
0
def simpleEmitter():
    cmds.file(force=True, newFile=True)
    cmds.currentUnit(linear='centimeter', angle='degree', time='film')

    # Load the plug-in emitter and create an emitter node
    cmds.loadPlugin('simpleEmitter.py')
    cmds.createNode('spSimpleEmitter', name='simpleEmitter')

    # Create particle object and connect to the plugin emitter node
    cmds.particle(name='particles')
    cmds.connectDynamic('particles', em='simpleEmitter')

    cmds.setAttr('simpleEmitter.rate', 200)
    cmds.setAttr('simpleEmitter.speed', 25)

    cmds.playbackOptions(minTime=0.00, maxTime=60.0)
    cmds.currentTime(0)
    cmds.play(wait=True, forward=True)

    # make some keyframes on emitter
    cmds.currentTime(0)
    cmds.select('simpleEmitter', replace=True)
    cmds.setKeyframe('simpleEmitter.tx')
    cmds.setKeyframe('simpleEmitter.ty')
    cmds.setKeyframe('simpleEmitter.tz')
    cmds.setKeyframe('simpleEmitter.rx')
    cmds.setKeyframe('simpleEmitter.ry')
    cmds.setKeyframe('simpleEmitter.rz')
    cmds.currentTime(30)
    cmds.move(-2.011944, 6.283524, -2.668834, relative=True)
    cmds.move(0,
              0,
              12.97635,
              relative=True,
              localSpace=True,
              worldSpaceDistance=True)
    cmds.rotate(0, -75.139762, 0, relative=True, objectSpace=True)
    cmds.setKeyframe('simpleEmitter.tx')
    cmds.setKeyframe('simpleEmitter.ty')
    cmds.setKeyframe('simpleEmitter.tz')
    cmds.setKeyframe('simpleEmitter.rx')
    cmds.setKeyframe('simpleEmitter.ry')
    cmds.setKeyframe('simpleEmitter.rz')
    cmds.currentTime(60)
    cmds.move(0, 0, -14.526107, relative=True)
    cmds.move(0, -8.130523, 0, relative=True)
    cmds.rotate(0, 0, 78.039751, relative=True, objectSpace=True)
    cmds.rotate(0, 0, 53.86918, relative=True, objectSpace=True)
    cmds.setKeyframe('simpleEmitter.tx')
    cmds.setKeyframe('simpleEmitter.ty')
    cmds.setKeyframe('simpleEmitter.tz')
    cmds.setKeyframe('simpleEmitter.rx')
    cmds.setKeyframe('simpleEmitter.ry')
    cmds.setKeyframe('simpleEmitter.rz')

    cmds.playbackOptions(minTime=0.00, maxTime=60.0)
    cmds.currentTime(0)
    cmds.play(wait=True, forward=True)
Beispiel #13
0
 def doIt(self,argList):
     cmds.polyPlane(n='myPlane', h=5, w=2)
     cmds.polySphere(n='mySphere', r=5)
     cmds.select('mySphere')
     cmds.move(0,5,0)
     cmds.rigidBody( n='myRigidBody', active=True, b=0.5, sf=0.4 )
     cmds.select(cl=True)
     cmds.gravity(n='myGravity')
     cmds.connectDynamic('mySphere', fields='myGravity')
Beispiel #14
0
	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)
def createParticleSystem_2():
    # Creates a point emitter, with a collide plane and some PP attributes

    cmds.playbackOptions(maxTime=180)

    emitter = cmds.emitter(dx=1, dy=0, dz=0, sp=0.1, pos=(0, 5, 0),rate=20)[0]

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

    particleSystem, particleSystemShape = cmds.nParticle(n="nParticle_test_2")
    cmds.setAttr('%s.lfm' % particleSystemShape, 2.0) # random range
    cmds.setAttr('%s.lifespan' % particleSystemShape, 3)
    cmds.setAttr('%s.lifespanRandom' % particleSystemShape, 4)
    cmds.setAttr('%s.friction' % particleSystemShape, 0.01)
    cmds.setAttr('%s.bounce' % particleSystemShape, 0.5)
    cmds.setAttr('%s.rotationFriction' % particleSystemShape, 0.98)
    cmds.setAttr('%s.pointMass' % particleSystemShape, 4)
    cmds.setAttr('%s.computeRotation' % particleSystemShape, True)
    cmds.setAttr('%s.particleRenderType' % particleSystemShape, 7) # Blobby, to see radius
    cmds.setAttr('%s.selfCollide' % particleSystemShape, True)
    cmds.connectDynamic( particleSystemShape, em=emitter)


    # add Custom Attributes
    # rgb
    if not cmds.objExists( "%s.rgbPP" % particleSystemShape):
        cmds.addAttr( particleSystemShape ,ln="rgbPP",dt="vectorArray")
    else:
        # Disconnect possible thing in rgbPP
        input = cmds.connectionInfo("%s.rgbPP" % particleSystemShape,sourceFromDestination=True)
        if input:
            cmds.disconnectAttr(input,"%s.rgbPP" % particleSystemShape)

    cmds.dynExpression( particleSystem, s="\nfloat $r = rand(1.0);float $g = rand(1.0);float $b = rand(1.0);\n%s.rgbPP = <<$r,$g,$b>>;" % particleSystemShape, c=True)

    # radius
    if not cmds.objExists( "%s.radiusPP" % particleSystemShape):
        cmds.addAttr( particleSystemShape, ln="radiusPP",dt="doubleArray")
    cmds.dynExpression( particleSystem, s="seed(%s.id);\n%s.radiusPP = .2 + time * .2 * rand(.2,1.5)" % (particleSystemShape,particleSystemShape), runtimeAfterDynamics=True)

    # rotatePP (enabled by "compute rotation", the attribute would be created by attribut editor's first constrcution in a gui maya)
    if not cmds.objExists( "%s.rotationPP" % particleSystemShape):
        cmds.addAttr( particleSystemShape, ln="rotationPP",dt="vectorArray")

    # add collision plane
    plane = cmds.polyPlane( w=30,h=30,sx=10,sy=10,ax=[0, 1, .5], cuv=2)
    cmds.select(plane[0])
    maya.mel.eval("makePassiveCollider")
    cmds.select(clear=True)
    cmds.setAttr( "nRigidShape1.friction", 0.25)
    cmds.setAttr( "nRigidShape1.stickiness", 0.0)

    return particleSystem, particleSystemShape
def _connect_NParticleShape_to_NParticleEmitter(particleShapeNode = '', emitter = ''):
    """
    Helper to connect nParticleShape nodes and nParticleEmitters together
    @param particleShapeNode: The name of the nParticles Shape node
    @param emitter: The name of the nParticle emitter to attach the shape node to
    @type particleShapeNode: String
    @type emitter: String
    """
    debug(None, method = '_connect_NParticleShape_to_NParticleEmitter', message = 'Connecting %s to %s now...' % (particleShapeNode, emitter), verbose = False)
    cmds.connectDynamic(particleShapeNode, em = emitter)
    debug(None, method = '_connect_NParticleShape_to_NParticleEmitter', message = 'Successfully connected particle to emitter',  verbose = False)
Beispiel #17
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
Beispiel #18
0
def simpleEmitter():
    cmds.file (force=True, newFile=True)
    cmds.currentUnit (linear='centimeter', angle='degree', time='film')

    # Load the plug-in emitter and create an emitter node
    cmds.loadPlugin ('simpleEmitter.py')
    cmds.createNode ('spSimpleEmitter', name='simpleEmitter')

    # Create particle object and connect to the plugin emitter node
    cmds.particle (name='particles')
    cmds.connectDynamic ('particles', em='simpleEmitter')

    cmds.setAttr ('simpleEmitter.rate', 200 )
    cmds.setAttr ('simpleEmitter.speed', 25 )

    cmds.playbackOptions (minTime=0.00, maxTime=60.0)
    cmds.currentTime (0)
    cmds.play (wait=True, forward=True)

    # make some keyframes on emitter
    cmds.currentTime (0)
    cmds.select ('simpleEmitter', replace=True)
    cmds.setKeyframe ('simpleEmitter.tx')
    cmds.setKeyframe ('simpleEmitter.ty')
    cmds.setKeyframe ('simpleEmitter.tz')
    cmds.setKeyframe ('simpleEmitter.rx')
    cmds.setKeyframe ('simpleEmitter.ry')
    cmds.setKeyframe ('simpleEmitter.rz')
    cmds.currentTime (30)
    cmds.move (-2.011944, 6.283524, -2.668834, relative=True)
    cmds.move (0, 0, 12.97635, relative=True, localSpace=True, worldSpaceDistance=True)
    cmds.rotate (0, -75.139762, 0, relative=True, objectSpace=True)
    cmds.setKeyframe ('simpleEmitter.tx')
    cmds.setKeyframe ('simpleEmitter.ty')
    cmds.setKeyframe ('simpleEmitter.tz')
    cmds.setKeyframe ('simpleEmitter.rx')
    cmds.setKeyframe ('simpleEmitter.ry')
    cmds.setKeyframe ('simpleEmitter.rz')
    cmds.currentTime (60)
    cmds.move (0, 0, -14.526107, relative=True)
    cmds.move (0, -8.130523, 0, relative=True)
    cmds.rotate (0, 0, 78.039751, relative=True, objectSpace=True)
    cmds.rotate (0, 0, 53.86918, relative=True, objectSpace=True)
    cmds.setKeyframe ('simpleEmitter.tx')
    cmds.setKeyframe ('simpleEmitter.ty')
    cmds.setKeyframe ('simpleEmitter.tz')
    cmds.setKeyframe ('simpleEmitter.rx')
    cmds.setKeyframe ('simpleEmitter.ry')
    cmds.setKeyframe ('simpleEmitter.rz')

    cmds.playbackOptions (minTime=0.00, maxTime=60.0)
    cmds.currentTime (0)
    cmds.play (wait=True, forward=True)
def addNewRigidBodies(id):

    srb = cmds.ls('myActiveRigidBody' + str(id))
    cmds.delete(srb)

    selected = cmds.ls("*_chunks_" + str(id))

    array = cmds.listRelatives(selected)
    for rb in array:
        cmds.select(rb)
        #cmds.select(rb)
        cmds.connectDynamic(rb, f='gravityField*')
 def deleteLine(self):
     # For whatever the shit reason, I have to have this check. If I don't, I get an error in rare cases.
     if self:
         if self.getStartItem().dictKey.count("force"):
             cmds.connectDynamic(self.getStartItem().getWidgetMenu().getParticleShape(), delete=True, fields=self.getStartItem().getWidgetMenu().getObject())
         if self.getStartItem().dictKey is "behaviorCat" or self.getStartItem().dictKey is "lookCat":
             self.getStartItem().getWidgetMenu().particleName.setText(" ")
         if self.getStartItem().dictKey is "collisionEvent":
             self.getStartItem().getWidgetMenu().deleteEvent()
         self.getEndItem().getWidgetMenu().receiveFrom(self.getStartItem(), delete=True)
         self.getStartItem().getWidgetMenu().sendData(self.getStartItem().getWidgetMenu().packageData())
         self.getStartItem().removeReferences()
         self.scene().removeItem(self)
         self.myStartItem.connectedLine.remove(self)
         self.myEndItem.connectedLine.remove(self)
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
Beispiel #22
0
def _rebuildAllEmmiters():
    """
    Helper to rebuild all the referenced rigged emitters in the FX shot
    """
    getAllReferenceEmitters = [
        eachEmitter for eachEmitter in cmds.ls(type='fluidEmitter')
        if cmds.referenceQuery(eachEmitter, isNodeReferenced=True)
    ]
    for eachRefEm in getAllReferenceEmitters:
        cmds.select(clear=True)
        ns = eachRefEm.split(':')[0]
        newName = '%s_%s_fx' % (ns, eachRefEm.split(':')[-1])
        if not cmds.objExists(newName):
            _buildFluidEmitter(newName, eachRefEm)
        else:
            cmds.delete(newName)
            _buildFluidEmitter(newName, eachRefEm)

        getAttrs = _getValidAttrs(eachRefEm)
        ignoreAttrs = [
            'message', 'binMembership', 'isHierarchicalConnection',
            'needParentUV', 'translateX', 'translateY', 'translateZ',
            'rotateX', 'rotateY', 'rotateZ', 'visibility'
        ]
        for eachAttr in getAttrs:
            if eachAttr not in ignoreAttrs:
                try:
                    cmds.connectAttr('%s.%s' % (eachRefEm, eachAttr),
                                     '%s.%s' % (newName, eachAttr),
                                     f=True)
                except RuntimeError:  # already connected
                    pass

        ## Hide the original emtter
        cmds.setAttr('%s.visibility' % eachRefEm, 0)
        ## Unlink the original emtter
        fluids = [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]
        for eachFluid in fluids:
            cmds.connectDynamic(eachFluid, em=eachRefEm, d=True)

        ## Now build the scene emitter group
        if not cmds.objExists('FLUID_EMITTERS_hrc'):
            cmds.group(n='FLUID_EMITTERS_hrc', em=True)

        try:
            cmds.parent(newName, 'FLUID_EMITTERS_hrc')
        except RuntimeError:
            pass
Beispiel #23
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 addDynamicConnectHook():
    global connectDynamicCB_ID
    if connectDynamicCB_ID:
        removeDynamicConnectHook()
    if gMayaVersion > 2014:
        connectDynamicCB_ID = cmds.connectDynamic(
            addScriptHandler=connectDynamicCB)
Beispiel #25
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' )
    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 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
Beispiel #28
0
	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)
Beispiel #29
0
    def add_rigid_body(self, objects, magnitude=50):

        cmds.rigidBody(objects, active=False, m=magnitude, collisions=False)

        cmds.gravity(pos=[0, 0, 0],
                     m=magnitude,
                     att=0,
                     dx=0,
                     dy=-1,
                     dz=0,
                     mxd=-1,
                     vsh='none',
                     vex=0,
                     vof=[0, 0, 0],
                     vsw=360,
                     tsr=0.5)
        gravity_dag = oopmaya.DAG_Node()
        cmds.connectDynamic(objects, fields=gravity_dag.name())
def _connect_NParticleShape_to_NParticleEmitter(particleShapeNode='',
                                                emitter=''):
    """
    Helper to connect nParticleShape nodes and nParticleEmitters together
    @param particleShapeNode: The name of the nParticles Shape node
    @param emitter: The name of the nParticle emitter to attach the shape node to
    @type particleShapeNode: String
    @type emitter: String
    """
    debug(None,
          method='_connect_NParticleShape_to_NParticleEmitter',
          message='Connecting %s to %s now...' % (particleShapeNode, emitter),
          verbose=False)
    cmds.connectDynamic(particleShapeNode, em=emitter)
    debug(None,
          method='_connect_NParticleShape_to_NParticleEmitter',
          message='Successfully connected particle to emitter',
          verbose=False)
Beispiel #31
0
    def CreateObjects(self):
        SphereRadius = 1

        cmds.polySphere(n='Sphere', sx=10, sy=10, r=SphereRadius)
        cmds.polySphere(n='SpherePin', sx=10, sy=10, r=SphereRadius)
        cmds.setAttr('Sphere.translateY', 6)
        cmds.setAttr('Sphere.translateZ', 8)

        cmds.constrain('Sphere', 'SpherePin', pin=True, i=True, n='pin')

        cmds.constrain('SpherePin', nail=True, n='nail')
        cmds.select(clear=True)
        newtonfield = cmds.newton(m=1000.0)
        cmds.connectDynamic('Sphere', f=newtonfield[0])

        cmds.select(clear=True)
        dragfield = cmds.drag(m=10.0)
        cmds.connectDynamic('Sphere', f=dragfield)

        #setting
        cmds.setAttr(newtonfield[0] + '.volumeShape',
                     2)  #set volume shape to sphere
        cmds.select(newtonfield[0])
        ouside_sphere_radius = 10
        cmds.scale(ouside_sphere_radius + SphereRadius,
                   ouside_sphere_radius + SphereRadius,
                   ouside_sphere_radius + SphereRadius)

        cmds.setAttr(dragfield[0] + '.volumeShape',
                     2)  #set volume shape to sphere
        cmds.select(dragfield[0])
        ouside_sphere_radius = 10
        cmds.scale(ouside_sphere_radius + SphereRadius,
                   ouside_sphere_radius + SphereRadius,
                   ouside_sphere_radius + SphereRadius)

        #group
        cubelist = [newtonfield[0], dragfield[0], u'nail']
        print(cubelist)
        cmds.group(cubelist, n='GroupAnime')

        cubelist = [u'Sphere', u'SpherePin', u'pin', u'GroupAnime']
        print(cubelist)
        cmds.group(cubelist, n='barrier')
Beispiel #32
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
Beispiel #33
0
def _addWakeEmitter():
    """
    Quick add additional linked emitter for the app UI only
    This builds a linked emitter to the scene for custom wakes such as around buildings etc
    """
    debug(None, method = '_addWakeEmitter', message = 'Adding wake emmiter now..', verbose = False)
    #get camera from current view
    currentPanel = cmds.getPanel(withFocus= True) or 'modelPanel4'
    debug(None, method = '_addWakeEmitter', message = 'currentPanel: %s' % currentPanel, verbose = False)

    panelType = cmds.getPanel(typeOf= currentPanel )
    debug(None, method = '_addWakeEmitter', message = 'panelType: %s' % panelType, verbose = False)

    if panelType !=  "modelPanel":
        print "Model panel not selected, please make view port live and try again"
    else:
        camera=cmds.modelPanel(currentPanel, q=True, camera = True)
        debug(None, method = '_addWakeEmitter', message = 'camera: %s' % camera, verbose = False)

        cameraShape =cmds.listRelatives(camera) or camera
        debug(None, method = '_addWakeEmitter', message = 'cameraShape: %s' % cameraShape, verbose = False)

        position = cmds.camera(cameraShape, q=True, worldCenterOfInterest= True)

        #build a new vector
        import maya.OpenMaya as om
        vec = om.MVector(position[0],0,position[2])

        # create a fluid emitter
        emitter = cmds.fluidEmitter( pos=vec, name = "additionalEmitter_WAKE#",  type='volume', densityEmissionRate=-3000, heatEmissionRate=50000, fuelEmissionRate=0, fluidDropoff=0.1, rate=150.0, cycleEmission='none', cycleInterval=1, maxDistance=1, minDistance=0, volumeShape = "sphere" )
        # connect to fluids
        cmds.connectDynamic(CONST.FOAM_FLUID_SHAPENODE, em = emitter)
        cmds.connectDynamic(CONST.WAKE_FLUID_SHAPENODE, em = emitter)
        # set some presets
        cmds.setAttr('%s.rate' % emitter[0], 150)
        cmds.setAttr('%s.fluidDensityEmission' % emitter[0], -3000)
        cmds.setAttr('%s.fluidHeatEmission' % emitter[0], 50000)
        cmds.setAttr('%s.fuelMethod' % emitter[0], 0)
        cmds.setAttr('%s.fluidJitter' % emitter[0], 0)
        cmds.setAttr('%s.motionStreak' % emitter[0], 1)

    debug(None, method = '_addWakeEmitter', message = 'FINISHED..', verbose = False)
Beispiel #34
0
def torusField():
	cmds.file(force=True, new=True)
	cmds.currentUnit(linear="centimeter", angle="degree", time="film")

	# Create the new field node
	cmds.createNode("spTorusField", name="torus")

	# create particle object.
	#
	cmds.particle(jbp=(0.0, 0.0, 0.0), nj=250, jr=5, c=1, name="particles")

	# connect torus field node with the particle object.
	#
	cmds.connectDynamic("particles", f="torus")
	cmds.setAttr("torus.attractDistance", 10)
	cmds.setAttr("torus.repelDistance", 5)

	cmds.playbackOptions(e=True, min=0.00, max=600.0)
	cmds.currentTime(0, e=True)
	cmds.play(wait=True, forward=True)
Beispiel #35
0
def torusField():
    cmds.file(force=True, new=True)
    cmds.currentUnit(linear="centimeter", angle="degree", time="film")

    # Create the new field node
    cmds.createNode("spTorusField", name="torus")

    # create particle object.
    #
    cmds.particle(jbp=(0.0, 0.0, 0.0), nj=250, jr=5, c=1, name="particles")

    # connect torus field node with the particle object.
    #
    cmds.connectDynamic("particles", f="torus")
    cmds.setAttr("torus.attractDistance", 10)
    cmds.setAttr("torus.repelDistance", 5)

    cmds.playbackOptions(e=True, min=0.00, max=600.0)
    cmds.currentTime(0, e=True)
    cmds.play(wait=True, forward=True)
Beispiel #36
0
def _linkWakeEmitters(fluids = [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE], wakeFluid = CONST.WAKE_FLUID_SHAPENODE, foamFluid = CONST.FOAM_FLUID_SHAPENODE):
    """
    Function to link all fluid emitters in scene to ocean used in the app UI
    """
    ## Build a list of the referenced emitters
    getAllReferenceEmitters = [eachEmitter for eachEmitter in cmds.ls (type = 'fluidEmitter') if cmds.referenceQuery(eachEmitter, isNodeReferenced = True)]
    debug(None, method = '_linkWakeEmitters', message = 'getAllReferenceEmitters: %s' % getAllReferenceEmitters, verbose = False)

    fluids = fluids
    debug(None, method = '_linkWakeEmitters', message = 'fluids: %s' % fluids, verbose = False)

    ## Now run through every emitter in the scene that isn't referenced and link it to the ocean fluid textures
    for eachFluid in fluids:
        for eachEmitter in cmds.ls(type = 'fluidEmitter'):
            try:
                if eachEmitter not in getAllReferenceEmitters:
                    if 'oceanWakeFoamTextureShape' in eachEmitter and eachFluid == foamFluid:
                        debug(None, method = '_linkWakeEmitters', message = 'FOAM emitter found: %s' % eachEmitter,  verbose = False)
                        cmds.connectDynamic (eachFluid, em = eachEmitter)
                        debug(None, method = '_linkWakeEmitters', message = 'Linked: %s to %s' % (eachFluid, eachEmitter), verbose = False)
                        print
                    elif 'oceanWakeTextureShape' in eachEmitter and eachFluid == wakeFluid:
                        debug(None, method = '_linkWakeEmitters', message = 'WAKE emitter found: %s' % eachEmitter,  verbose = False)
                        cmds.connectDynamic (eachFluid, em = eachEmitter)
                        debug(None, method = '_linkWakeEmitters', message = 'Linked: %s to %s' % (eachFluid, eachEmitter), verbose = False)
                        print
                    elif 'hullEmitter' in eachEmitter and eachFluid == wakeFluid:
                        debug(None, method = '_linkWakeEmitters', message = 'HULL emitter found: %s' % eachEmitter,  verbose = False)
                        cmds.connectDynamic (eachFluid, em = eachEmitter)
                        debug(None, method = '_linkWakeEmitters', message = 'Linked: %s to %s' % (eachFluid, eachEmitter), verbose = False)
                        print
                    else:
                        pass
            except RuntimeError:
                pass
Beispiel #37
0
 def deleteLine(self):
     # For whatever the shit reason, I have to have this check. If I don't, I get an error in rare cases.
     if self:
         if self.getStartItem().dictKey.count("force"):
             cmds.connectDynamic(
                 self.getStartItem().getWidgetMenu().getParticleShape(),
                 delete=True,
                 fields=self.getStartItem().getWidgetMenu().getObject())
         if self.getStartItem(
         ).dictKey is "behaviorCat" or self.getStartItem(
         ).dictKey is "lookCat":
             self.getStartItem().getWidgetMenu().particleName.setText(" ")
         if self.getStartItem().dictKey is "collisionEvent":
             self.getStartItem().getWidgetMenu().deleteEvent()
         self.getEndItem().getWidgetMenu().receiveFrom(self.getStartItem(),
                                                       delete=True)
         self.getStartItem().getWidgetMenu().sendData(
             self.getStartItem().getWidgetMenu().packageData())
         self.getStartItem().removeReferences()
         self.scene().removeItem(self)
         self.myStartItem.connectedLine.remove(self)
         self.myEndItem.connectedLine.remove(self)
Beispiel #38
0
def _rebuildAllEmmiters():
    """
    Helper to rebuild all the referenced rigged emitters in the FX shot
    """
    getAllReferenceEmitters = [eachEmitter for eachEmitter in cmds.ls (type = 'fluidEmitter') if cmds.referenceQuery(eachEmitter, isNodeReferenced = True)]
    for eachRefEm in getAllReferenceEmitters:
        cmds.select(clear = True)
        ns = eachRefEm.split(':')[0]
        newName = '%s_%s_fx' % (ns, eachRefEm.split(':')[-1])
        if not cmds.objExists(newName):
            _buildFluidEmitter(newName, eachRefEm)
        else:
            cmds.delete(newName)
            _buildFluidEmitter(newName, eachRefEm)

        getAttrs = _getValidAttrs(eachRefEm)
        ignoreAttrs = ['message', 'binMembership', 'isHierarchicalConnection', 'needParentUV', 'translateX', 'translateY', 'translateZ', 'rotateX', 'rotateY', 'rotateZ', 'visibility']
        for eachAttr in getAttrs:
            if eachAttr not in ignoreAttrs:
                try:
                    cmds.connectAttr('%s.%s' % (eachRefEm, eachAttr), '%s.%s' % (newName, eachAttr), f = True)
                except RuntimeError: # already connected
                    pass

        ## Hide the original emtter
        cmds.setAttr('%s.visibility' % eachRefEm , 0)
        ## Unlink the original emtter
        fluids = [CONST.FOAM_FLUID_SHAPENODE, CONST.WAKE_FLUID_SHAPENODE]
        for eachFluid in fluids:
            cmds.connectDynamic (eachFluid, em = eachRefEm, d = True)

        ## Now build the scene emitter group
        if not cmds.objExists('FLUID_EMITTERS_hrc'):
            cmds.group(n = 'FLUID_EMITTERS_hrc', em = True)

        try:
            cmds.parent(newName, 'FLUID_EMITTERS_hrc')
        except RuntimeError:
            pass
Beispiel #39
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")
Beispiel #40
0
def defaultButtonPush04(*args):
	charSelection = cmds.ls(sl=True)
	SelectionError()

	charName = charSelection[0]
	objectSplit = charName.split(':')
	FinalCharName = objectSplit[0]
	CharGeo_Duplicate01 = cmds.duplicate(charName)
	cmds.parent(world=True)
	mainGroup = cmds.group(n = "%s_wake_foam" % FinalCharName)

	groupPolygon = []
	for x in cmds.listRelatives(mainGroup, children = True, fullPath = True):
		for f in ['hull_geo', 'body_geo', 'geo','HubcapOld_geo']:
			if f in x:
				groupPolygon.append(x)
	
	cmds.select(groupPolygon, replace = True)
	EmitterObject = cmds.fluidEmitter(type='surface', der=1, her=2, fer=3, fdr=1.5, r=100.0, cye='none', cyi=1, mxd=0, mnd=0 )
	cmds.connectDynamic("oceanWakeTextureShape", em = EmitterObject[1])
	cmds.connectDynamic("oceanWakeFoamTextureShape", em = EmitterObject[1])
	cmds.setAttr('%s.maxDistance' % EmitterObject[1], 1)
	cmds.setAttr('%s.densityMethod' % EmitterObject[1], 2)
	cmds.setAttr('%s.fluidDensityEmission' % EmitterObject[1], 100)
	cmds.setAttr('%s.heatMethod' % EmitterObject[1], 2)
	cmds.setAttr('%s.fluidHeatEmission' % EmitterObject[1], 500)
	cmds.setAttr('%s.fluidFuelEmission' % EmitterObject[1], 1)
	cmds.setAttr('%s.fluidDropoff' % EmitterObject[1], 4.5)
	cmds.setAttr('%s.motionStreak' % EmitterObject[1], 1)
	cmds.setAttr('%s.fluidJitter' % EmitterObject[1], 0)
	cmds.setAttr('%s.turbulenceSpeed' % EmitterObject[1], 0)
	cmds.setAttr('%s.turbulenceFrequencyX' % EmitterObject[1], 0)
	cmds.setAttr('%s.turbulenceFrequencyY' % EmitterObject[1], 0)
	cmds.setAttr('%s.turbulenceFrequencyZ' % EmitterObject[1], 0)

	print "%s:cog_ctrl" % FinalCharName

	cmds.parentConstraint( "%s:cog_ctrl" % FinalCharName, mainGroup, maintainOffset = True )
Beispiel #41
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')
 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()
Beispiel #43
0
def connectDynamic(*args, **kwargs):
    if len(args):
        doPassSelf = kwargs.pop('passSelf', False)
    else:
        doPassSelf = False
    for key in ['addScriptHandler', 'ash']:
        try:
            cb = kwargs[key]
            if callable(cb):
                kwargs[key] = _factories.makeUICallback(cb, args, doPassSelf)
        except KeyError:
            pass
    res = cmds.connectDynamic(*args, **kwargs)
    return res
    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
Beispiel #45
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);
Beispiel #46
0
def _dynamicField(field = "uniform", opts = {}):
	## Only proceed if nParticle(s) in selection
	selection = _filter_type_on_selection(type = 'nParticle', toShape = True)
	if selection:

		cmds.select(clear = True)
		try:
			## Field creation
			node = eval( 'cmds.%s(**%s)' %(field, opts) )
		except:
			node = None

		if node:
			for each in selection:
				cmds.connectDynamic(each, fields = node[0])

			## Set expression to all nParticle (runtimeAfterDynamics)
			inputForce = cmds.listConnections('%s.outputForce' % node[0], type = 'nParticle', plugs = True)
			if inputForce:
				inputForce = list( set( inputForce ) )

				for each in inputForce:
					## Get expression's current string to add-on inputForce line
					nParticleShape = each.split(".")[0]

					currentStr = cmds.dynExpression(nParticleShape, query = True, rad = True, string = True)
					inputForceStr = 'if (mag(%s) >= 0.001){%s.lifespanPP = 0.0;}\n' %(each, nParticleShape)
					if not currentStr.endswith('\n'):
						currentStr = '%s\n' % currentStr
						currentStr += inputForceStr

					cmds.dynExpression(nParticleShape, edit = True, rad = True, string = currentStr)
		else:
			mel.eval('warning "Failed to create killField!";')
	else:
		mel.eval('warning "Please select proper nParticle(s)!";')
Beispiel #47
0
	def init(WeatherUI,self):
		c.select(cl=True);
		c.turbulence(n='turb',m=1);
		c.air(n='air', m=30.0, mxd=20.0, pos=[20, 15, -40], vco=True);
		c.floatSliderGrp('snowTurbSlider', en=True, e=True);
		c.floatSliderGrp('airMSlider', en=True, e=True);
		c.floatSliderGrp('airMxdSlider', en=True, e=True);
		
		if c.objExists('snowParticle'):
			c.connectDynamic('snowParticle',f='turb');
		
		if c.objExists('snowParticle'):
			c.connectDynamic('snowParticle',f='air');
			
		if c.objExists('rainParticle'):
			c.connectDynamic('rainParticle',f='turb');
			
		if c.objExists('rainParticle'):
			c.connectDynamic('rainParticle',f='air');
Beispiel #48
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);
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])
Beispiel #50
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)
Beispiel #51
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])
Beispiel #52
0
def voxel(victime):

    #definition
    step = cmds.intSliderGrp('StepSlider', query=True, value=True)

    #Bounding box
    bbox = cmds.exactWorldBoundingBox()

    #Remplit un mesh de particule
    if (len(cmds.ls(sl=1))):
        obj = cmds.ls(sl=1)[0]
        try:
            cmds.particleFill(rs=step,
                              maxX=1,
                              maxY=1,
                              maxZ=1,
                              minX=0,
                              minY=0,
                              minZ=0,
                              pd=1,
                              cp=0)
        except:
            pass

    #Met les particules das une liste
    part = cmds.ls(sl=1)[0]
    closest = cmds.createNode("closestPointOnMesh")
    cmds.connectAttr(obj + ".outMesh", closest + ".inMesh")
    points = cmds.getAttr(part + ".position")
    cmds.delete(part)

    #Recupere tous les rayons
    rayons = []
    for point in points:
        setAttr(closest + ".inPosition", point)
        rayons.append(mag(point, getAttr(closest + ".position")))
    delete(closest)

    max = 0
    #Recherche le MAX entre 2 particules (distance la plus grande)
    for i in range(len(points)):
        if rayons[i] > max:
            max, p, maxId = rayons[i], points[i], i

    #print max;
    amount = 0
    nbCube = 0.0
    cmds.progressWindow(title='Legosification',
                        progress=amount,
                        status='Legosification',
                        isInterruptable=True)

    #Compte le nombre de lego dans la scene
    objList1 = ls("lego*", geometry=True, l=True)
    if (len(objList1) == 0):
        cmds.polyCube(n="lego")
        objList1 = ls("lego*", geometry=True, l=True)
    objList2 = cmds.listRelatives(objList1, p=True)
    #print len(objList1)
    name = len(objList2) - 1
    #Cree des cubes
    for point in points:
        # Check if the dialog has been cancelled
        if cmds.progressWindow(query=True, isCancelled=True):
            break
        # Check if end condition has been reached
        if cmds.progressWindow(query=True, progress=True) >= 100:
            break
        name += 1
        dimension = (float)(bbox[3] - bbox[0]) / (float)(step + 1.0)
        #cmds.duplicate("lego")
        #cmds.select("lego"+`i`)
        #cmds.polyCube(w=dimension, h=dimension, d=dimension)
        #cmds.select("lego")
        #cmds.move(point[0],point[1],point[2])
        createLego(point[0], point[1], point[2], name, dimension, victime)
        nbCube += 1
        amount = (nbCube / len(points)) * 100
        cmds.progressWindow(edit=True,
                            progress=amount,
                            status=('Please Wait ! '))
    cmds.progressWindow(endProgress=1)

    #Gravity and animation
    if cmds.checkBox("physics", query=True, value=True) and cmds.checkBox(
            "animation", query=True, value=True) == False:
        objList1 = ls("lego*", geometry=True, l=True)
        objList2 = cmds.listRelatives(objList1, p=True)
        cmds.select(cl=1)
        grav = cmds.gravity()
        #Connect gravity to list of objects
        cmds.connectDynamic(objList2, fields=grav[0])
    #Menage
    if cmds.objExists('lego'):
        cmds.delete("lego")
    #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)
#                0                  1
attrNames = ['depthSort', 'particleRenderType']
attrValues = [True, 0]
Beispiel #54
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
Beispiel #55
0
def create_jiggle_locator(position_object, base_name):
    """Create jiggle rig at the specified postion, you will then need to make sure
    this jiggle rig is hooked up to be driven by the source rig

    Usage:
        create_jiggle_locator('ball', 'my_jiggle')
    """
    if cmds.objExists(position_object):
        # Get position of input object
        pos = cmds.xform(position_object, q=True, ws=True, t=True)

        # Create single particle
        part = cmds.particle(p=[pos[0], (pos[1]), pos[2]],
                             c=1,
                             name='{}_particle'.format(base_name))
        cmds.setAttr("{}.particleRenderType".format(part[1]), 4)

        # Goal particle to source object
        cmds.goal(part[0], goal=position_object, w=0.5, utr=True)

        # Create output transform
        jiggle_output = cmds.spaceLocator(name="{}_ctl".format(base_name))[0]
        cmds.connectAttr("{}.worldCentroid".format(part[1]),
                         '{}.translate'.format(jiggle_output))

        # Create jiggle control
        for attr in ['rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']:
            cmds.setAttr('{}.{}'.format(jiggle_output, attr),
                         k=False,
                         lock=True)

        # Add gravity
        grav = \
        cmds.gravity(name='{}_gravity'.format(base_name), pos=[0, 0, 0], m=100, att=0, dx=0, dy=-1, dz=0, mxd=-1)[
            0]  # , vsh=none -vex 0 -vof 0 0 0 -vsw 360 -tsr 0.5 ;
        cmds.connectDynamic(part, f=grav)

        # Add attrs: isDynamic=on, conserve=1.0, goalWeight[0]=1.0, goalSmoothness=3, gravity=9.8
        cmds.addAttr(jiggle_output, ln="JIGGLE", at="enum", en="__:")
        cmds.setAttr('{}.JIGGLE'.format(jiggle_output), cb=True)

        # Enabled
        cmds.addAttr(jiggle_output, ln="enabled", at="bool")
        cmds.setAttr('{}.enabled'.format(jiggle_output), k=True, l=False)
        cmds.setAttr('{}.enabled'.format(jiggle_output), 1)
        cmds.connectAttr('{}.enabled'.format(jiggle_output),
                         '{}.isDynamic'.format(part[1]))

        # Dynamics Weight
        """
        cmds.addAttr(jiggle_output, ln="dynamicsWeight", at="double", min=0, max=1, dv=1)
        cmds.setAttr('{}.dynamicsWeight'.format(jiggle_output), k=True, l=False)
        cmds.connectAttr('{}.dynamicsWeight'.format(jiggle_output), '{}.dynamicsWeight'.format(part[1]))
        """
        # Conserve
        cmds.addAttr(jiggle_output,
                     ln="conserve",
                     at="double",
                     min=0,
                     max=1,
                     dv=1)
        cmds.setAttr('{}.conserve'.format(jiggle_output), k=True, l=False)
        cmds.connectAttr('{}.conserve'.format(jiggle_output),
                         '{}.conserve'.format(part[1]))

        # Goal Smoothness
        cmds.addAttr(jiggle_output,
                     ln="goalSmoothness",
                     at="double",
                     min=0,
                     dv=3)
        cmds.setAttr('{}.goalSmoothness'.format(jiggle_output),
                     k=True,
                     l=False)
        cmds.connectAttr('{}.goalSmoothness'.format(jiggle_output),
                         '{}.goalSmoothness'.format(part[1]))

        # Goal Weight
        cmds.addAttr(jiggle_output,
                     ln="goalWeight",
                     at="double",
                     min=0,
                     max=1.0,
                     dv=.5)
        cmds.setAttr('{}.goalWeight'.format(jiggle_output), k=True, l=False)
        cmds.connectAttr('{}.goalWeight'.format(jiggle_output),
                         '{}.goalWeight[0]'.format(part[1]))

        cmds.addAttr(jiggle_output, ln="GRAVITY", at="enum", en="__:")
        cmds.setAttr('{}.GRAVITY'.format(jiggle_output), cb=True)

        # Gravity
        cmds.addAttr(jiggle_output,
                     ln="gravityMagnitude",
                     at="double",
                     min=0,
                     dv=100)
        cmds.setAttr('{}.gravityMagnitude'.format(jiggle_output),
                     k=True,
                     l=False)
        cmds.connectAttr('{}.gravityMagnitude'.format(jiggle_output),
                         '{}.magnitude'.format(grav))

        # Gravity Direction
        cmds.addAttr(jiggle_output, ln="gravityDirection", at="double3")
        cmds.addAttr(jiggle_output,
                     ln="gravityDirectionX",
                     at="double",
                     p="gravityDirection",
                     dv=0)
        cmds.addAttr(jiggle_output,
                     ln="gravityDirectionY",
                     at="double",
                     p="gravityDirection",
                     dv=-1)
        cmds.addAttr(jiggle_output,
                     ln="gravityDirectionZ",
                     at="double",
                     p="gravityDirection",
                     dv=0)

        cmds.setAttr('{}.gravityDirection'.format(jiggle_output),
                     k=True,
                     l=False)
        cmds.setAttr('{}.gravityDirectionX'.format(jiggle_output),
                     k=True,
                     l=False)
        cmds.setAttr('{}.gravityDirectionY'.format(jiggle_output),
                     k=True,
                     l=False)
        cmds.setAttr('{}.gravityDirectionZ'.format(jiggle_output),
                     k=True,
                     l=False)

        cmds.connectAttr('{}.gravityDirectionX'.format(jiggle_output),
                         '{}.directionX'.format(grav))
        cmds.connectAttr('{}.gravityDirectionY'.format(jiggle_output),
                         '{}.directionY'.format(grav))
        cmds.connectAttr('{}.gravityDirectionZ'.format(jiggle_output),
                         '{}.directionZ'.format(grav))

        # Cleanup
        jiggle_group = cmds.group(empty=True,
                                  name="{}All_grp".format(base_name))
        cmds.parent(part[0], jiggle_output, grav, jiggle_group)

        cmds.select(jiggle_output)
        return jiggle_output
def removeDynamicConnectHook():
    global connectDynamicCB_ID
    if gMayaVersion > 2014:
        cmds.connectDynamic(removeScriptHandler=connectDynamicCB_ID)
Beispiel #57
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 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."