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))
Exemplo n.º 2
0
def pub_spawnPoints():
	_sel = mc.ls(sl=True)
	if len(_sel) > 0:
		# template the object
		mc.setAttr ( _sel[0] + ".template", 1)
		# get object BB and position in worldspace
		_objBB = mc.xform( _sel[0], q=True, bb=True)
		_objPos = mc.xform( _sel[0], ws=True, q=True, rp=True)
		# set the position of the plane under the object
		_poz = [0, 0, 0]
		_poz[0] = _objPos[0]
		_poz[1] = _objPos[1] - (( _objBB[4] - _objBB[1]) / 1.75)
		_poz[2] = _objPos[2]
		# scale the plane larger than the bounding box
		_scale = [0, 0, 0]
		_scale[0] = ( _objBB[0] - _objBB[3]) * 1.2
		_scale[2] = ( _objBB[2] - _objBB[5]) * 1.2
		# create, place, scale and rename the plane
		mc.nurbsPlane( p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=1, v=1, ch=0)
		mc.move( _poz[0], _poz[1], _poz[2])
		mc.scale( _scale[0], 0, _scale[2])
		_nPlane = mc.rename( "emissionPlane_" + _sel[0] )
		# create the emitter
		mc.emitter( _nPlane, type='surface', r=20, sro=0, nuv=1, cye='none', cyi=1, spd=2, srn=1, nsp=1, tsp=0, mxd=0, mnd=0, sp=0)
		_emitter = mc.rename( "emitter_" + _sel[0] )
		# create the particle object
		mc.particle( n="xxx")
		_pParticle = mc.rename( "particle_" + _sel[0] )
		# connect the emitter to the particle object
		mc.connectDynamic( _pParticle, em=_emitter )
		# template the plane and the particle object
		mc.setAttr ( _nPlane + ".template", 1)
		mc.setAttr ( _pParticle + ".template", 1)
	else:
		assert "No object selected!"
def testParticle(partObj,particleId):

    try:
        cmds.particle( partObj, q=True, id=int(particleId), attribute="age" )
        return 1
    except:
        return 0
Exemplo n.º 4
0
 def storePositionBy_particle(self):
     particleSys = self.memoData["particle"]
     cnt = cmds.particle(particleSys, q=1, ct=1)
     pos = []
     for i in range(cnt):
         pos.append(
             tuple(cmds.particle(particleSys, q=1, at="position", id=i)))
     self.memoData["posList"] = pos
Exemplo n.º 5
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)
Exemplo n.º 6
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)
Exemplo n.º 7
0
def locatorParticles(locList,
                     particle,
                     radius=1,
                     selfCollide=False,
                     rotatePP=False,
                     scalePP=False):
    """
    """
    # Check locator list
    if not locList: return

    # Check particles
    if not particle: particle = 'particle1'
    if not cmds.objExists(particle):
        particle = cmds.nParticle(n=particle)[0]

    # Set Particle Object Attrs
    cmds.setAttr(particle + '.particleRenderType', 4)
    cmds.setAttr(particle + '.radius',
                 cmds.floatSliderGrp('locParticle_radiusFSG', q=True, v=True))
    cmds.setAttr(
        particle + '.selfCollide',
        cmds.checkBoxGrp('locParticle_selfCollideCBG', q=True, v1=True))

    # Create particles
    ptList = [cmds.pointPosition(i) for i in locList]
    cmds.emit(o=particle, pos=ptList)

    # Add and Set RotatePP/ScalePP Values
    if rotatePP:

        # Check rotatePP attrs
        if not cmds.objExists(particle + '.rotatePP'):
            addRotatePP(particle)

        # Set rotatePP attrs
        for i in range(len(locList)):
            rot = cmds.getAttr(locList[i] + '.r')
            cmds.particle(particle, e=True, at='rotatePP', id=i, vv=rot[0])

    if scalePP:

        # Check scalePP attrs
        if not cmds.objExists(particle + '.scalePP'):
            addScalePP(particle)

        # Set scalePP attrs
        for i in range(len(locList)):
            scl = cmds.getAttr(locList[i] + '.s')
            cmds.particle(particle, e=True, at='scalePP', id=i, vv=scl[0])

    # Save Initial State
    cmds.saveInitialState(particle)
Exemplo n.º 8
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)
Exemplo n.º 9
0
def attachLoneShaders():
    shading_groups = getLoneSG()

    if shading_groups:
        log.info("Got SG to attach : {}".format(shading_groups))

        grp = "dummy_attachments"
        if cmds.objExists(grp):
            log.info(". delete dummy group {}".format(grp))
            cmds.delete(grp)

        objects = list()

        for sg in shading_groups:
            log.info("... {}".format(sg))
            obj = cmds.particle()
            obj = cmds.ls(obj, transforms=True)[0]

            objects.append(obj)
            cmds.sets(obj, e=True, forceElement=sg)

        grp = cmds.group(objects, name=grp)

        result = cmds.ls(type='renderLayer')
        for renderLayer in result:
            cmds.editRenderLayerMembers(renderLayer, grp)

        cmds.scale(0.00001, 0.00001, 0.00001, grp)
    else:
        log.info("SG attachments ok !")
Exemplo n.º 10
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
Exemplo n.º 11
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]}
Exemplo n.º 12
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' )
Exemplo n.º 13
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
Exemplo n.º 14
0
    def importPointCloud(self, filePath):
        """ Read data from file and generate point cloud.
			This function uses numPy to process the data for a huge speedup.
			The old function should be used as a fallback when numPy is not available.
		"""
        if os.path.isfile(filePath):  # Check file exists

            # Read data into numpy array
            startTime = time.time()
            data = np.genfromtxt(filePath)
            count = data.shape[0]

            # Create group and particles etc.
            fileName = os.path.splitext(os.path.basename(filePath))[0]
            pCloudGroup = mc.group(name="%s_grp" % fileName, empty=True)
            pCloudParticle = mc.particle(name="%s_pCloud" % fileName)

            mc.addAttr(pCloudParticle[1],
                       longName="rgbPP",
                       dataType="vectorArray")
            mc.addAttr(pCloudParticle[1],
                       longName="rgbPP0",
                       dataType="vectorArray")

            pos = data[:, 0:3]
            pos1D = pos.reshape(pos.size)
            posStr = "%s" % pos1D.tolist()
            posStr2 = re.sub(r'[\n\[\],]', '', posStr)
            posExec = 'setAttr ".pos0" -type "vectorArray" %s %s ;' % (count,
                                                                       posStr2)
            #print posExec
            mel.eval(
                posExec
            )  # this fails silently sometimes, seemingly when the string is too long - needs investigation

            rgb = data[:, 3:6] / 255
            rgb1D = rgb.reshape(rgb.size)
            rgbStr = "%s" % rgb1D.tolist()
            rgbStr2 = re.sub(r'[\n\[\],]', '', rgbStr)
            rgbExec = 'setAttr ".rgbPP0" -type "vectorArray" %s %s ;' % (
                count, rgbStr2)
            #print rgbExec
            mel.eval(
                rgbExec
            )  # this fails silently sometimes, seemingly when the string is too long - needs investigation

            #mc.saveInitialState(pCloudParticle[0])
            mc.currentTime(1)
            mc.setAttr("%s.isDynamic" % pCloudParticle[1], 0)
            mc.parent(pCloudParticle[0], pCloudGroup)

            # Complete progress bar and end clock
            totalTime = time.time() - startTime
            print "Read %d points in %f seconds.\n" % (count, totalTime)

            return pCloudGroup
        else:
            mc.error("File doesn't exist: %s" % filePath)
            return False
Exemplo n.º 15
0
def mesh_uvToWorld():
    '''{'path':'Polygons/EditMesh/mesh_uvToWorld( )ONLYSE',
'icon':':/mesh.svg',
'usage':"""
#选择两个mesh物体,将第一个按uv匹配到第二个
$fun(  )""",
}
'''

    fromObj = cmds.ls(sl=True)[0]  #'pPlane1'

    toObj = cmds.ls(sl=True)[1]  #'pPlane2'
    iterVertex = om.MItMeshVertex(nameToNode(fromObj, old=True))

    try:
        uv_util = om.MScriptUtil()
        uv_ptr = uv_util.asFloat2Ptr()
        uArray, vArray = [], []
        posArray = []
        while not iterVertex.isDone():
            posArray.append(tuple(iterVertex.position(om.MSpace.kWorld))[:3])
            iterVertex.getUV(uv_ptr)
            uArray.append(uv_util.getFloat2ArrayItem(uv_ptr, 0, 0))
            vArray.append(uv_util.getFloat2ArrayItem(uv_ptr, 0, 1))
            iterVertex.next()
        parName = cmds.particle()[1]
        cmds.goal(parName, g=toObj, w=1)
        cmds.setAttr(parName + '.goalSmoothness', 0)
        cmds.setAttr(parName + ".conserve", 0)
        startFrame = cmds.playbackOptions(q=True, min=True)
        cmds.setAttr(parName + ".startFrame", startFrame)
        cmds.currentTime(startFrame, e=True)
        parName = qm.qsEmit(object=parName,
                            position=posArray,
                            attributes=[("goalU", "floatValue", uArray),
                                        ("goalV", "floatValue", vArray)])

        #cmds.setAttr(parName+".collide", 0)
        #cmds.setAttr(parName+".ignoreSolverGravity", 1)
        #cmds.setAttr(parName+".ignoreSolverWind", 1)
        #cmds.setAttr(parName+".drag", 0)
        #nculeus = cmds.listConnections(parName + '.nextState')[0]
        #startFrame = cmds.getAttr( nculeus+".startFrame")
        cmds.currentTime(startFrame, e=True)
        cmds.currentTime(int(startFrame + 1), e=True)

        targetPos = cmds.getParticleAttr(parName, at='position', array=True)

        targetPos = [
            newom.MPoint(targetPos[i], targetPos[i + 1], targetPos[i + 2])
            for i in range(0, len(targetPos), 3)
        ]

        fromMesh = newom.MFnMesh(nameToNode(fromObj))
        fromMesh.setPoints(targetPos, newom.MSpace.kWorld)
    except:
        cmds.delete(cmds.listRelatives(parName, parent=True))
        raise IOError('Got a error!')
    cmds.delete(cmds.listRelatives(parName, parent=True))
Exemplo n.º 16
0
def particle_pixelizer():
	#grab object name
	objname = cmds.ls(sl=True).pop()
	
	#selects all vertices
	cmds.ConvertSelectionToVertices()
	listofvertices = cmds.ls(selection=True, flatten=True)
	
	#get the number of total vertices
	totalvertices = len(listofvertices)
	
	print 'Total Vertices: ' + str(totalvertices)
	
	#create a list that stores 3-slot arrays that tell position of a vertex already drawn
	drawnvtxList = []
	
	#store number of boxes drawn
	partnum = 0
	vertexRead = 0
	
	#for loop through number of vertices
	#for vtxnum in range(0, totalvertices):
	for vtx in listofvertices:
		cmds.select(vtx)
		#to get value of position (a 3 slot array), make the new instanced cubename, then create an array of the int values
		pos = cmds.xform(ws=True, q=True, t=True)
		x1 = str(int(pos[0]))
		y1 = str(int(pos[1]))
		z1 = str(int(pos[2]))
		intposList = [x1, y1, z1]
		 
		#check if list empty!!!!!! 
		if (drawnvtxList.__len__() == 0):
			drawnvtxList.append(intposList)
			partnum+=1
		else:
			if (not intposList in drawnvtxList):
				drawnvtxList.append(intposList)
				partnum += 1
		vertexRead += 1
		print str(partnum) + ' positions kept : ' + str(vertexRead) + ' of ' + str(totalvertices) + ' done'
	
	print drawnvtxList
		
	
	cmds.particle(p=drawnvtxList, n='instancePositions')
Exemplo n.º 17
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]]
    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')
Exemplo n.º 19
0
 def testStaticParticlePropReadWrite(self):
     root = MayaCmds.particle(p=[(0, 0, 0), (1, 1, 1)])
     nodeName = root[0]
     shapeName = root[1]
     self.setProps(shapeName)
     self.__files.append(util.expandFileName('staticPropParticles.abc'))
     MayaCmds.AbcExport(j='-atp -root %s -f %s' % (nodeName, self.__files[-1]))
     self.verifyProps(shapeName, self.__files[-1])
Exemplo n.º 20
0
    def executeButton( self, *args ):

        #get value of lidar path
        lidarPath = cmds.textField( self.widgets[ "lidarPathField" ], query=True, text=True )

        #get skip number
        skipNumber = cmds.intField( self.widgets[ "skipField" ], query=True, value=True )

        i=1

        if lidarPath != "":

            lidarFile = open( lidarPath, 'r' )
            coordLines = lidarFile.readlines()

            lineCount = len( coordLines )
            cmds.progressBar( self.widgets[ "progressBar" ], edit=True, maxValue=(lineCount/skipNumber) )

            for line in coordLines[1::skipNumber]:

                #increment progress bar
                cmds.progressBar( self.widgets[ "progressBar" ], edit=True, progress=i )
                i = i+1

                #split coords up into x y z
                coords = line.split( " " )

                coordX = coords[0]
                coordY = coords[1]
                coordZ = coords[2]

                cmds.particle( position=[coordX, coordY, coordZ] )


            #group the points for cleaniness
            selectedPart = cmds.select( 'particle*' )
            cmds.group( name='LIDAR_grp', world=True )

            #reset progress bar
            cmds.progressBar( self.widgets[ "progressBar" ], edit=True, progress=0 )



        else:
            cmds.warning( "No LIDAR file is selected." )
Exemplo n.º 21
0
def locatorParticles(locList, particle, radius=1, selfCollide=False, rotatePP=False, scalePP=False):
    """
    """
    # Check locator list
    if not locList: return

    # Check particles
    if not particle: particle = 'particle1'
    if not cmds.objExists(particle):
        particle = cmds.nParticle(n=particle)[0]

    # Set Particle Object Attrs
    cmds.setAttr(particle + '.particleRenderType', 4)
    cmds.setAttr(particle + '.radius', cmds.floatSliderGrp('locParticle_radiusFSG', q=True, v=True))
    cmds.setAttr(particle + '.selfCollide', cmds.checkBoxGrp('locParticle_selfCollideCBG', q=True, v1=True))

    # Create particles
    ptList = [cmds.pointPosition(i) for i in locList]
    cmds.emit(o=particle, pos=ptList)

    # Add and Set RotatePP/ScalePP Values
    if rotatePP:

        # Check rotatePP attrs
        if not cmds.objExists(particle + '.rotatePP'):
            addRotatePP(particle)

        # Set rotatePP attrs
        for i in range(len(locList)):
            rot = cmds.getAttr(locList[i] + '.r')
            cmds.particle(particle, e=True, at='rotatePP', id=i, vv=rot[0])

    if scalePP:

        # Check scalePP attrs
        if not cmds.objExists(particle + '.scalePP'):
            addScalePP(particle)

        # Set scalePP attrs
        for i in range(len(locList)):
            scl = cmds.getAttr(locList[i] + '.s')
            cmds.particle(particle, e=True, at='scalePP', id=i, vv=scl[0])

    # Save Initial State
    cmds.saveInitialState(particle)
Exemplo n.º 22
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)
Exemplo n.º 23
0
def xformToParticles(xformList=[]):
	'''
	Create particles from the specified list of transforms
	@param xformList: List of transforms to create particles from
	@type xformList: list
	'''
	if not xformList: xformList = mc.ls(sl=True,type='transform')
	ptList = [mc.xform(i,q=True,ws=True,rp=True) for i in xformList]
	particle = mc.particle(p=ptList)
	return particle
Exemplo n.º 24
0
def xformToParticles(xformList=[]):
    """
    Create particles from the specified list of transforms
    @param xformList: List of transforms to create particles from
    @type xformList: list
    """
    if not xformList: xformList = cmds.ls(sl=True, type='transform')
    ptList = [cmds.xform(i, q=True, ws=True, rp=True) for i in xformList]
    particle = cmds.particle(p=ptList)
    return particle
Exemplo n.º 25
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)
Exemplo n.º 26
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)
Exemplo n.º 27
0
Arquivo: Nebula.py Projeto: TakaXu/-
    def create(self, *args):
        agle = None
        try:
            path = '|'.join(['box', 'getagle'])
            agle = float(cmds.textField(path, q=True, text=True))
        except:
            raise

        abgle = (math.pi / 180) * agle

        self.kkk = int(180 / agle)

        high = None
        try:
            high_path = '|'.join(['box', 'gethigh'])
            high = float(cmds.textField(high_path, q=True, text=True))
        except:
            raise

        pnumber = None
        try:
            pnumber_path = '|'.join(['box', 'getpnumber'])
            pnumber = int(cmds.textField(pnumber_path, q=True, text=True))
        except:
            raise

        for i in range(pnumber):
            self.eel.append(
                (random.uniform(-1, 1), random.uniform(-1 * high, high),
                 random.uniform(-1 * self.long, self.long)))
        for i in range(self.kkk):
            for i in range(pnumber):
                cos = math.cos(abgle * i)
                sin = math.sin(abgle * i)
                self.eel.append((self.eel[i][0] * cos + self.eel[i][2] * sin,
                                 self.eel[i][1],
                                 self.eel[i][2] * cos - self.eel[i][0] * sin))

        cmds.particle(jbp=self.eel, n=self.name, c=1)

        cmds.setAttr("%sShape.particleRenderType" % self.name, 4)
Exemplo n.º 28
0
def readASC(ascPath,partObj):
    print ascPath
    ascFile = open(ascPath, 'r')
    tmpDict = {}
    
    for line in ascFile:
        if re.search("frame",line):
            tmpList = line.split(" ")
            frame = tmpList[-1].rstrip('\n')
        if re.search("particles",line):
            tmpList = line.split(" ")
            particles=tmpList[-1].rstrip('\n')
        lineList = line.split(" ")
        if len(lineList) == 10:
            objDict = {}
            objDict['id'] = lineList[0]
            objDict['x'] = lineList[1]
            objDict['y'] = lineList[2]
            objDict['z'] = lineList[3]
            objDict['vx'] = lineList[4]
            objDict['vy'] = lineList[5]
            objDict['vz'] = lineList[6]
            objDict['radius'] = lineList[7]
            objDict['density'] = lineList[8]
            objDict['pressure'] = lineList[9].rstrip("\r\n")
            tmpDict[lineList[0]] = objDict
    cmds.currentTime(int(frame))
    
    for key in tmpDict.values():
        particleId = key['id']
        particleX = key['x']
        particleY = key['y']
        particleZ = key['z']
        try:  
            if testParticle(partObj,int(particleId)) == 0:
               cmds.emit( object=partObj, pos=(float(particleX),float(particleY),float(particleZ)))
            else:
               cmds.particle( partObj, e=True, attribute='position', id=int(particleId), vectorValue= (float(particleX),float(particleY),float(particleZ)))
        except:
            pass
    ascFile.close()
Exemplo n.º 29
0
	def followParticle(self):
		translateX = cmds.getAttr(self.leadername + ".tx") 
		translateY = cmds.getAttr(self.leadername + ".ty")
		translateZ = cmds.getAttr(self.leadername + ".tz") 

		self.leaderparticle = cmds.particle(p=(translateX, translateY, translateZ), n=self.leaderParticleName)
		cmds.xform(cp=True)

		self.leaderParticleExpression = cmds.expression(s=("vector $position= `getAttr " + self.leaderParticleName + ".position`;\n" +
			self.leadername + ".translateX = $position.x;\n" +
			self.leadername + ".translateY = $position.y;\n" +
			self.leadername + ".translateZ = $position.z;"), o=self.leadername, ae=1, uc="all", n=self.leaderParticleExpresionName)
Exemplo n.º 30
0
def simulation(object, target, conserve, weight):

    start = cmds.playbackOptions(min=True, query=True)
    end = cmds.playbackOptions(max=True, query=True)

    front = "{0}_temp_front_indicator".format(object)

    temp_cons = cmds.parentConstraint(object,
                                      target,
                                      n="temp_cons",
                                      maintainOffset=True)

    #temp_cons2 = cmds.parentConstraint(object , front, n = "temp_cons2",maintainOffset = True )

    cmds.bakeResults(target, sb=1, t=(start, end), simulation=True)

    cmds.delete(temp_cons)

    temp_particle = cmds.particle(n="{0}_temp_particle".format(object),
                                  p=[0, 0, 0],
                                  c=conserve)[0]

    cmds.setAttr("{0}.particleRenderType".format(temp_particle), 4)

    #match position of particle to target
    matchTransform(temp_particle, target, True, True)

    #particle to move with target
    cmds.goal(temp_particle, g=target, w=weight)

    #partical will not be baked, a null need to creatge to transfer the animation data from particle to null
    target_control = cmds.spaceLocator(
        n="{0}_temp_target_control".format(object))[0]

    cmds.connectAttr("{0}.cachedWorldCentroid".format(temp_particle),
                     '{0}.translate'.format(target_control))

    object_parent = cmds.listRelatives(object, parent=True)

    if object_parent:

        cmds.parent(front, object_parent)

    new_constraint = cmds.aimConstraint(target_control,
                                        object,
                                        n="{0}_temp_aim".format(object),
                                        maintainOffset=True,
                                        worldUpType="object",
                                        worldUpObject=front)
    #new_constraint = cmds.aimConstraint(target_control, object , n = "{0}_temp_aim".format(object),maintainOffset = True,worldUpType = "scene")

    cmds.hide(target)
    cmds.hide(target_control)
Exemplo n.º 31
0
def get_particle_attributes(node):
    """Get all dynamic attributes of the nParticle node

    Args:
        node(str): name of the nParticle node

    Returns:
        list

    """

    return cmds.particle(node, query=True, dynamicAttrList=True)
Exemplo n.º 32
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')
Exemplo n.º 33
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);
Exemplo n.º 34
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);
Exemplo n.º 35
0
    def __run(self, *args, **kwargs):
        pos = kwargs.get("position", [])
        col = kwargs.pop("color", [])

        particle = cmds.particle(**kwargs)[1]

        if col and len(col) == len(pos):
            cmds.addAttr(particle, ln="rgbPP", dt="vectorArray")
            cmds.addAttr(particle, ln="rgbPP0", dt="vectorArray")
            color_exp = "vector $vectorList[] = {%s};" % (",".join(
                map(lambda x: "<<{},{},{}>>".format(x[0], x[1], x[2]), col)))
            color_exp += "\nint $id = id;\n%s.rgbPP = $vectorList[$id];" % (
                particle)
            cmds.dynExpression(particle, c=1, s=color_exp)

        return particle
    def testPointPrimitiveReadWrite(self):

        # Creates a particle object with four particles
        name = MayaCmds.particle( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7),
            (9, 9, 9)])

        posVec = [0, 0, 0, 3, 5, 6, 5, 6, 7, 9, 9, 9]

        self.__files.append(util.expandFileName('testPointPrimitiveReadWrite.abc'))
        MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1]))

        # reading test
        MayaCmds.AbcImport(self.__files[-1], mode='open')
        pos = MayaCmds.getAttr(name[1] + '.position')
        ids = MayaCmds.getAttr(name[1] + '.particleId')

        self.failUnlessEqual(len(ids), 4)
        for i in range(0, 4):
            index = 3*i
            self.failUnlessAlmostEqual(pos[i][0], posVec[index], 4)
            self.failUnlessAlmostEqual(pos[i][1], posVec[index+1], 4)
            self.failUnlessAlmostEqual(pos[i][2], posVec[index+2], 4)
Exemplo n.º 37
0
    def testPointPrimitiveReadWrite(self):

        # Creates a particle object with four particles
        name = MayaCmds.particle(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9,
                                                                      9)])

        posVec = [0, 0, 0, 3, 5, 6, 5, 6, 7, 9, 9, 9]

        self.__files.append(
            util.expandFileName('testPointPrimitiveReadWrite.abc'))
        MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1]))

        # reading test
        MayaCmds.AbcImport(self.__files[-1], mode='open')
        pos = MayaCmds.getAttr(name[1] + '.position')
        ids = MayaCmds.getAttr(name[1] + '.particleId')

        self.failUnlessEqual(len(ids), 4)
        for i in range(0, 4):
            index = 3 * i
            self.failUnlessAlmostEqual(pos[i][0], posVec[index], 4)
            self.failUnlessAlmostEqual(pos[i][1], posVec[index + 1], 4)
            self.failUnlessAlmostEqual(pos[i][2], posVec[index + 2], 4)
Exemplo n.º 38
0
 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()
    #directionY
    -dy 0

    #directionZ
    -dz 0

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

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


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

Exemplo n.º 40
0
def particleLocators(particle, bakeSimulation=False, rotate=False, scale=False, start=0, end=-1, prefix=''):
    """
    """
    # Check Particle
    if not cmds.objExists(particle):
        raise Exception('Object "' + nParticle + '" is not a valid particle or nParticle object!')

    # Check Prefix
    if not prefix: prefix = particle

    # Get particle count
    count = cmds.getAttr(particle + '.count')
    if not count: raise Exception('Invalid particle count! (' + count + ')')

    # Create locators
    partiLocs = [cmds.spaceLocator(n=prefix + '_loc' + str(i))[0] for i in range(count)]
    partiLocsGrp = prefix + '_locGrp'
    if not cmds.objExists(partiLocsGrp): partiLocsGrp = cmds.group(em=True, n=partiLocsGrp)
    cmds.parent(partiLocs, partiLocsGrp)

    # For each particle, set locator position
    for i in range(count):
        pt = cmds.pointPosition(particle + '.pt[' + str(i) + ']')
        cmds.setAttr(partiLocs[i] + '.t', *pt)
        if rotate:
            rt = cmds.particle(particle, q=True, at='rotatePP', id=i)
            cmds.setAttr(partiLocs[i] + '.r', *rt)
        if scale:
            sc = cmds.particle(particle, q=True, at='scalePP', id=i)
            cmds.setAttr(partiLocs[i] + '.s', *sc)

    # Bake Simulation
    if (bakeSimulation):

        # Append particle expression
        expStr = '\n\n//--\n'
        expStr += 'int $id = id;\n'
        expStr += 'vector $pos = pos;\n'
        expStr += 'string $loc = ("' + prefix + '_loc"+$id);\n'
        expStr += 'if(`objExists $loc`){'
        expStr += '\t move -a ($pos.x) ($pos.y) ($pos.z) $loc;\n'
        if rotate:
            expStr += '\tvector $rot = rotatePP;\n'
            expStr += '\t rotate -a ($rot.x) ($rot.y) ($rot.z) $loc;\n'
        if scale:
            expStr += '\tvector $scl = scalePP;\n'
            expStr += '\t scale -a ($scl.x) ($scl.y) ($scl.z) $loc;\n'
        expStr += '}'

        # Old expression string
        oldRadStr = cmds.dynExpression(particle, q=True, s=True, rad=True)

        # Apply particle expression
        cmds.dynExpression(particle, s=oldRadStr + expStr, rad=True)

        # Bake to keyframes
        if end < start:
            start = cmds.playbackOptions(q=True, min=True)
            end = cmds.playbackOptions(q=True, max=True)
        bakeAttrs = ['tx', 'ty', 'tz']
        if rotate: bakeAttrs.extend(['rx', 'ry', 'rz'])
        if scale: bakeAttrs.extend(['sx', 'sy', 'sz'])
        cmds.bakeSimulation(partiLocs, at=bakeAttrs, t=(start, end))

        # Restore particle expression
        cmds.dynExpression(particle, s=oldRadStr, rad=True)
import maya.cmds as cmds

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

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

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

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

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

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

for attr, value in part_attrs.items():
    cmds.setAttr('%s.%s' %(part[1], attr), value)
   
#The code for Current Render Type button inside the particleShape
#ln=longName, at=attributeType, dv=defaultValue, min=minValue, max=maxValue
#When activating the Current Render Type button, make sure the code is part[1],
#this is the particleShape node that will need to be selected when editing attrs and not [0]
#[0] is the particle.
cmds.addAttr(part[1], internalSet=True, ln="colorAccum", at="bool", dv=False )
cmds.addAttr(part[1], internalSet=True, ln="useLighting", at="bool", dv=False )
cmds.addAttr(part[1], internalSet=True, ln="pointSize", at="long", min=1, max=60, dv=2 )
cmds.addAttr(part[1], internalSet=True, ln="multiCount", at="long", min=1, max=60, dv=10 )
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] )
Exemplo n.º 43
0
def qsEmit(object, position, attributes, clearAndSaveState=True, **kwargs):
    '''{'del_path':'Dynamics/Particles/qsEmit("particleShape", position=posLi, attributes=(("cus_bbsi", "vectorValue", bbsiLi), ("cus_area", "floatValue", areaLi) ), clearAndSaveState=True  )ONLYSE',
'icon':':/particle.svg',
'tip':'创建粒子',
'usage':'\
objects = cmds.listRelatives(cmds.ls(sl=True, exactType="transform", l=True), type="transform",f=True)\\n\
posLi, radiusLi, atULi, atVLi = [], [], [], []\\n\
for tfNode in objects:\\n\
    objPos = cmds.objectCenter(tfNode)\\n\
    bbsize = cmds.getAttr(tfNode+".bbsi")[0]\\n\
    radius = qm.vectorLen(bbsize)/2\\n\
    atU = cmds.getAttr(tfNode+".atU")\\n\
    atV = cmds.getAttr(tfNode+".atV")\\n\
    posLi.append(objPos)\\n\
    radiusLi.append(radius)\\n\
    atULi.append(atU)\\n\
    atVLi.append(atV)\\n\
$fun(object = "new", position=posLi, attributes=[("cus_bbsi", "floatValue", radiusLi), ("cus_area", "floatValue", areaLi) ]    )',
'help':'对emit command重新进行了一下打包',
}
'''

    createNew = True
    parType = ('particle', 'nParticle')
    if cmds.objExists(object):
        if cmds.objectType(object) in parType:
            createNew = False
        else:
            shapes = cmds.listRelatives(object, shapes=True)[0]
            if cmds.objExists(shapes) in parType:
                object = shapes
                createNew = False

    if createNew:
        if kwargs.get('type', None) == 'particle':
            nPar = cmds.particle()
        else:
            nPar = cmds.nParticle()
        object = nPar[1]

    #if cmds.objectType(object) != 'nParticle':
    #raise IOError('%s is not nParticle object'%object)

    posLen = len(position)

    for attr in list(attributes):
        if len(attr[2]) != posLen:
            if createNew:
                cmds.delete(cmds.listRelatives(object, parent))
            raise IOError('%s count is difence with position count' %
                          (attr[0]))

    for attr in attributes:
        if cmds.attributeQuery(attr[0], node=object, exists=True) == False:
            print attr[1]
            if attr[1] == 'floatValue': attrType = 'doubleArray'
            elif attr[1] == 'vectorValue': attrType = 'vectorArray'
            else:
                raise IOError('value type is not floatValue or vectorValue')
            cmds.addAttr(object, ln=attr[0] + '0', dt=attrType)
            cmds.addAttr(object, ln=attr[0], dt=attrType)

    emitStr = 'emit -object %s ' % (object)
    for data in position:
        emitStr += ' -pos %s %s %s ' % (data[0], data[1], data[2])

    if clearAndSaveState:
        startF = cmds.playbackOptions(q=True, min=True)
        cmds.currentTime(startF + 1, e=True)
        mel.eval("clearParticleStartState %s" % (object))
        cmds.currentTime(startF, e=True)

    for attr in attributes:
        emitStr += '\n\n-attribute %s ' % (attr[0])
        if attr[1] == 'floatValue':
            for data in attr[2]:
                emitStr += ' -%s %s  ' % (attr[1], data)
        elif attr[1] == 'vectorValue':
            for data in attr[2]:
                emitStr += ' -%s %s %s %s  ' % (attr[1], data[0], data[1],
                                                data[2])
        else:
            raise IOError('value type is not floatValue or vectorValue')
    #return emitStr
    mel.eval(emitStr)
    if clearAndSaveState:
        cmds.saveInitialState(object)
    return object
Exemplo n.º 44
0
from maya import cmds
from maya import mel

frames = 50

data = {}

import pymel.core as pm

pm.select(hi=True)
part = pm.selected(type='particle')[0]
print(part.name())
print(dir(part))
ids = part.particleIds()
print(ids)

for f in range(frames):
    cmds.currentTime(f + 1)
    print('frame: %d' % f)
    for i in ids:
        #print('id: %d' % i)
        if not data.has_key(i):
            data[i] = []
        pos = cmds.particle(part.name(), q=True, attribute='position', id=i)
        #print(pos)
        data[i].append(pos)

for i in ids:
    if len(data[i]) > 0:
        print(len(data[i]))
        cmds.curve(d=3, p=data[i])
Exemplo n.º 45
0
def particle(*args, **kwargs):
    res = cmds.particle(*args, **kwargs)
    if not kwargs.get('query', kwargs.get('q', False)):
        res = _factories.maybeConvert(res, _general.PyNode)
    return res
    -dy 0

    #directionZ
    -dz 0

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

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


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

'''
# Parellel Lists (Array)
#                0                  1
Exemplo n.º 47
0
def loadShotPoints(sector, *args):
    '''This function will load the generated point cloud in Maya via Houdini Engine.
	It will then copy each point and their attribute to a new point cloud to get rid of Houdini Engine.'''

    # Load Houdini Engine
    if loadHoudiniEngine() == False:
        return

    # Check if point bgeo file exists
    # currentWorkspace = os.path.abspath(cmds.workspace(sn=True,q=True))
    # currentShot = str(os.path.split(currentWorkspace)[1])
    # bgeoPath = '//Merlin/3d4/skid/05_shot/%s/geo/fileCache/%s_instancerPts.bgeo.sc'%(currentShot,currentShot)
    bgeoPath = '//Merlin/3d4/skid/04_asset/set/setForest/geo/pointCloud_sector%s.bgeo.sc' % sector

    # Set persp far clip plane
    cmds.setAttr('perspShape.farClipPlane', 1000000)

    # Set current time to first frame
    fstart = cmds.playbackOptions(ast=True, q=True)
    cmds.currentTime(fstart)

    # Load the bgeo importer
    toolBgeoToMaya = os.path.abspath(
        '//merlin/3d4/skid/04_asset/hda/toolBgeoToMaya_v2.hdanc')
    cmds.houdiniAsset(la=[toolBgeoToMaya, 'Object/toolBgeoToMaya'])
    # Set file path to shot points
    cmds.setAttr('toolBgeoToMaya1.houdiniAssetParm.houdiniAssetParm_file',
                 bgeoPath,
                 type="string")
    # Sync asset
    # cmds.evalDeferred('cmds.houdiniAsset(syn="toolBgeoToMaya1")')
    cmds.houdiniAsset(syn="toolBgeoToMaya1")

    # Duplicate point cloud to get rid of houdini engine
    pointCloud = 'file_bgeoToMaya_0'
    pointCloud_s = pointCloud + 'Shape'

    # Get particle count
    nbPart = cmds.particle(pointCloud, q=True, ct=True)

    # Create new particle system with suffix
    tmp = cmds.particle(n=pointCloud + '_dupli')
    dupliPartXf = tmp[0]
    dupliPartShp = tmp[1]

    cmds.setAttr(dupliPartShp + '.isDynamic', False)

    # Create rgbPP attribute on the new system
    cmds.addAttr(dupliPartShp, ln='rgbPP', dt='vectorArray')
    cmds.addAttr(dupliPartShp, ln='rgbPP0', dt='vectorArray')
    # Create radiusPP attribute
    cmds.addAttr(dupliPartShp, ln='radiusPP', dt='doubleArray')
    cmds.addAttr(dupliPartShp, ln='radiusPP0', dt='doubleArray')
    # Create index attribute
    cmds.addAttr(dupliPartShp, ln='index', dt='doubleArray')
    cmds.addAttr(dupliPartShp, ln='index0', dt='doubleArray')

    # Fill new particle system with positions
    for i in range(nbPart):
        wPos = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i),
                                    at='position',
                                    array=True)
        cmds.emit(o=dupliPartXf, pos=[wPos[0], wPos[1], wPos[2]])

    # Transfer rgbPP
    for i in range(nbPart):
        attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i),
                                         at='rgbPP',
                                         array=True)
        cmds.particle(e=True,
                      at='rgbPP',
                      order=i,
                      vectorValue=[attrValue[0], attrValue[1], attrValue[2]])

    # Transfer radiusPP
    for i in range(nbPart):
        attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i),
                                         at='radiusPP',
                                         array=True)
        cmds.particle(e=True, at='radiusPP', order=i, floatValue=attrValue[0])

    # Transfer index
    for i in range(nbPart):
        attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i),
                                         at='index',
                                         array=True)
        cmds.particle(e=True, at='index', order=i, floatValue=attrValue[0])

    # Delete unwanted nodes
    cmds.delete('toolBgeoToMaya1')

    # Rename particle system and group
    newname = 'forest_instancing_pc'
    cmds.rename(tmp[0], newname)
    masterGRP = 'FOREST_INSTANCING_GRP'
    try:
        cmds.select(masterGRP, r=True)
    except ValueError:
        cmds.group(newname, name=masterGRP)
    else:
        cmds.parent(newname, masterGRP)

    # Set nucleus (yes we have to keep it for some reason)
    cmds.setAttr('nucleus1.startFrame', fstart)
    cmds.parent('nucleus1', masterGRP)
Exemplo n.º 48
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
Exemplo n.º 49
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
Exemplo n.º 50
0
         defaultButton='OK',
         cancelButton='Cancel',
         dismissString='Cancel')
     if particlenamePrompt == 'OK':
         particlesName = mc.promptDialog(query=True, text=True)
         if particlesName == '':
             particlenamePrompt = mc.confirmDialog(
                 icn='warning',
                 title='Careful...',
                 message='No particle name was entered',
                 button=['Try Again'],
                 defaultButton='Try Again',
                 cancelButton='Try Again',
                 dismissString='Try Again')
         else:
             mc.particle(name=particlesName)
             mc.file(save=1)
             # Get shape name of particle object. This name will be used for naming the PDC files.
             pdcBasename = [
                 n for n in mc.ls(shapes=1) if n.startswith(''.join(
                     i for i in particlesName if not i.isdigit()))
             ][0]  # Get particle shape name. The following command is much faster: mc.particle(q=1,n=1)
             print('*** Particle "{0}" was created. '.format(particlesName))
             break
     elif particlenamePrompt == 'Cancel':
         surePrompt = exitPrompt()
 while surePrompt:
     ### Make a list of the source files and analyze data structure to clean up
     #Extract information from the first file
     if len(
             sourceFiles
    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."
Exemplo n.º 52
0
    def buildSplash(self):            
        objectName = str(self.getObject.text())
        if self.checkWake.isChecked()==True:
            wakeEmitter = str(self.getWake.text())
        else:
            wakeEmitter = "OceanWakeEmitter1"
        if self.checkOcean.isChecked()==True:
            oceanShader = str(self.getOcean.text())
        else:
            oceanShader = "oceanShader1"
        
        ###Bcreating Splash Disc
        objectNameAxis = generator.getMaxAndMinAxis(objectName)
        #generator_Return: 0-maxX, 1-minX, 2-maxY, 3-minY, 4-maxZ, 5-minZ
        avrgX = objectNameAxis[0] - objectNameAxis[1]
        avrgZ = objectNameAxis[4] - objectNameAxis[5]
        avrgY = objectNameAxis[2] - objectNameAxis[3]
        if avrgX > avrgZ:
            SplashCurve = avrgX
        else:
            SplashCurve = avrgZ
        baseCurve = cmds.circle(name="base",normal=[0,1,0],radius=SplashCurve/1.5)
        headCurve = cmds.circle(name="head",normal=[0,1,0],radius=SplashCurve/2)
        cmds.move(0,(avrgY/4),0,headCurve)
        cmds.rebuildCurve ("base", ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=0, kt=0, s=100, d=7, tol=0.01)
        cmds.rebuildCurve ("head", ch=1, rpo=1, rt=0, end=1, kr=0, kcp=0, kep=0, kt=0, s=100, d=7, tol=0.01)
        splashDisc = cmds.loft ("base", "head",name="%s_SplashDisc"%objectName, ch=1, u=1, c=0, ar=1, d=3, ss=int(avrgY+1), rn=0, po=0, rsn=True)
        #Return: 0-SplashDisc, 1-loft1
        cmds.delete(baseCurve,headCurve)    
        cmds.setAttr("%s.visibility"%splashDisc[0], False )
        objectPosition = cmds.xform(objectName, query=True, translation=True, worldSpace=True )
        cmds.move(objectPosition[0], 0, objectPosition[2], splashDisc[0])
        
        ###adding emitter and particle to Object
        objectNameEmitter = cmds.emitter(objectName,type='surface',rate=0,scaleRateByObjectSize=False,needParentUV=False,cycleEmission="none",
                           cycleInterval=1,speed=1,speedRandom=0,normalSpeed=1,tangentSpeed=0,maxDistance=0,minDistance=0,
                           directionX=1,directionY=0,directionZ=0,spread=0,name="%s_emitter"%objectName)
        #Return: 0-objectName, 1-objectName_emitter
        objectNameParticle = cmds.particle(name="%s_particle"%objectName)
        cmds.connectDynamic(objectNameParticle[0],emitters=objectNameEmitter[0])
        ###adding emitter and particle to Splash Disc
        splashDiscEmitter = cmds.emitter(splashDisc[0],type='surface',rate=0,scaleRateByObjectSize=False,needParentUV=False,cycleEmission="none",
                           cycleInterval=1,speed=1,speedRandom=1.5,normalSpeed=1,tangentSpeed=0,maxDistance=0,minDistance=0,
                           directionX=1,directionY=0,directionZ=0,spread=0,name="%s_emitter"%splashDisc[0])
        #Return: 0-SplashDisc, 1-SplashDisc_emitter
        splashDiscParticle = cmds.particle(name="%s_particle"%splashDisc[0])
        cmds.connectDynamic(splashDiscParticle[0],emitters=splashDiscEmitter[0])
        
        #connecting the X and Z object position to Splash Disc to follow 
        cmds.connectAttr("%s.translate.translateZ"%objectName, "%s.translate.translateZ"%splashDisc[0])
        cmds.connectAttr("%s.translate.translateX"%objectName, "%s.translate.translateX"%splashDisc[0])
        
        #setting up the splash Disc particle Setting 
        cmds.setAttr("%s.lifespanMode"%splashDiscParticle[1],3)
        cmds.setAttr("%s.lifespanRandom"%splashDiscParticle[1],0.5)
        cmds.setAttr("%s.conserve"%splashDiscParticle[1],0.983)
        cmds.setAttr("%s.inheritFactor"%splashDiscParticle[1],0.2)
        cmds.setAttr("%s.particleRenderType"%splashDiscParticle[1],5)
        cmds.addAttr(splashDiscParticle[1], keyable=True, ln="useLighting", at="bool", dv=False)
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleYPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleYPP0", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleXPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteScaleXPP0", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteTwistPP", dt="doubleArray")
        cmds.addAttr(splashDiscParticle[1], ln="spriteTwistPP0", dt="doubleArray")
        #creating Ramp for Splash Disc particle
        splashDiscParticle_spriteScaleXPP = cmds.arrayMapper(target=splashDiscParticle[1], destAttr="spriteScaleXPP", inputV="ageNormalized", type="ramp")
        ramp_spriteScaleXPP = cmds.listConnections(splashDiscParticle_spriteScaleXPP, type="ramp")
        ramp_spriteScaleXPP = cmds.rename(ramp_spriteScaleXPP[1], "%s_spriteScaleXPP_Rampe"%splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_spriteScaleXPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_spriteScaleXPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_spriteScaleXPP, 0.5,0.5,0.5)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_spriteScaleXPP, 0.165)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_spriteScaleXPP, 1,1,1)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_spriteScaleXPP, 0)
        
        splashDiscParticle_spriteScaleYPP = cmds.arrayMapper(target=splashDiscParticle[1], destAttr="spriteScaleYPP", inputV="ageNormalized", type="ramp")
        ramp_spriteScaleYPP = cmds.listConnections(splashDiscParticle_spriteScaleYPP, type="ramp")
        ramp_spriteScaleYPP = cmds.rename(ramp_spriteScaleYPP[1], "%s_SpriteScaleYPP_Rampe"%splashDiscParticle[1])
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_spriteScaleYPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_spriteScaleYPP, 1)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_spriteScaleYPP, 0.5,0.5,0.5)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_spriteScaleYPP, 0.165)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_spriteScaleYPP, 1,1,1)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_spriteScaleYPP, 0)
         
        #setting up the object particle Setting 
        cmds.setAttr("%s.lifespanMode"%objectNameParticle[1],3)
        cmds.setAttr("%s.particleRenderType"%objectNameParticle[1],7)
        cmds.addAttr(objectNameParticle[1], keyable=True, ln="threshold", at="float", min=0, max=10, dv=0.7)
        cmds.addAttr(objectNameParticle[1], keyable=True, ln="radius", at="float", min=0, max=10, dv=0.5)
        cmds.addAttr (objectNameParticle[1], ln="radiusPP", dt="doubleArray")
        #creating Ramp for object particle
        objectNameParticle_radiusPP = cmds.arrayMapper(target=objectNameParticle[1], destAttr="radiusPP", inputV="ageNormalized", type="ramp")
        ramp_radiusPP = cmds.listConnections(objectNameParticle_radiusPP, type="ramp")
        ramp_radiusPP = cmds.rename(ramp_radiusPP[1], "%s_RadiusPP_Rampe"%objectNameParticle[1])
        cmds.setAttr("%s.colorEntryList[3].color"%ramp_radiusPP, 0.056,0.056,0.056)
        cmds.setAttr("%s.colorEntryList[3].position"%ramp_radiusPP, 1)
        cmds.setAttr("%s.colorEntryList[2].color"%ramp_radiusPP, 0.223,0.223,0.223)
        cmds.setAttr("%s.colorEntryList[2].position"%ramp_radiusPP, 0.690)
        cmds.setAttr("%s.colorEntryList[1].color"%ramp_radiusPP, 0.178,0.178,0.178)
        cmds.setAttr("%s.colorEntryList[1].position"%ramp_radiusPP, 0.455)
        cmds.setAttr("%s.colorEntryList[0].color"%ramp_radiusPP, 0,0,0)
        cmds.setAttr("%s.colorEntryList[0].position"%ramp_radiusPP, 0)
         
        #adding gravity to SplashDisc
        splashDiscGravity = cmds.gravity(name="%s_GravityField"%splashDiscParticle[0], pos=[0,0,0], m=9.8, att=0, dx=0, dy=-1, dz=0, mxd=-1, vsh="none", vex=0, vof=[0,0,0], vsw=360, tsr=0.5)
        cmds.connectDynamic(splashDiscParticle[0], fields=splashDiscGravity)
         
        #adding gravity to Object
        objectNameGravity = cmds.uniform(name="%s_UniformField"%objectNameParticle[0], pos=[0,0,0], m=5, att=1, dx=1, dy=-1, dz=0, mxd=-1, vsh="none", vex=0, vof=[0,0,0], vsw=360, tsr=0.5)
        cmds.connectDynamic(objectNameParticle[0], fields=objectNameGravity)
        print objectNameGravity
        cmds.setAttr("%s.directionX"%objectNameGravity[0],0)
        cmds.setAttr("%s.directionY"%objectNameGravity[0],1)
        cmds.setAttr("%s.directionZ"%objectNameGravity[0],0)
        cmds.setAttr("%s.magnitude"%objectNameGravity[0],28)
         
        #adding Expression for Object and SplashDisc
        generator.objectNameParticleExpressionBeforeDynamics(objectNameParticle[1], oceanShader)
        generator.splashDiscParticleExpressionBeforeDynamics(splashDiscParticle[1], oceanShader)
        generator.splashDiscParticleExpressionAfterDynamics(splashDiscParticle[1])
        generator.splashDiscParticleExpressionCreation(splashDiscParticle[1])
        if "ocean_MainExpression" not in cmds.ls() :
            generator.createMainExpression(objectNameEmitter[1])
        if "ocean_MainExpression" in cmds.ls() :
            generator.editMainExpression(objectName, splashDiscEmitter[0], oceanShader, objectNameEmitter[1], wakeEmitter, splashDiscEmitter[1])
#         num=0 
        if "mainSplashDisc_Shader" not in cmds.ls():
            generator.shaderSetup()
#             cmds.select(splashDiscEmitter[0], replace=True)
#             cmds.sets(edit=True,forceElement="mainSplashDisc_ShaderSG")
            cmds.sets(splashDiscParticle, edit = True, forceElement = 'mainSplashDisc_ShaderSG')
        else:
            cmds.sets(splashDiscParticle, edit = True, forceElement = 'mainSplashDisc_ShaderSG')
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         else:     
#             while cmds.connectionInfo("mainSplashDisc_ShaderSG.dagSetMembers[%s]"%num,getExactDestination=True) != "":
#                 num+=1
#             cmds.connectAttr(splashDiscEmitter[1] + ".instObjGroups[0]", "mainSplashDisc_Shader.dagSetMembers[%s]"%num, force = True)
#         pSphere1_SplashDisc.translateX = pSphere1.translateX;
#         pSphere1_SplashDisc.translateZ = pSphere1.translateZ;
        return  
    def create_rain(self, *args):
        # Create the initial rain surface
        rainSurface = cmds.polyPlane(n="rainSurface",
                                     sx=10,
                                     sy=10,
                                     width=10,
                                     height=10)
        cmds.move(10, "rainSurface", y=True)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Add the gravity field to newly split particles
        cmds.select(gravityName, r=True)
        cmds.select(splitShape, add=True)
        cmds.connectDynamic(splitShape, f=gravityName)
        print "Gravity field added."
Exemplo n.º 54
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])
Exemplo n.º 55
0
emptyCirFolder = mc.group(em=True, n="circleCreation")	
empty_ACirFolder = mc.group(em=True, n="circleGeo")
empty_curveFolder = mc.group(em=True, n="curveExtrusions")

minFrames = mc.playbackOptions( q=True, min=True)
maxFrames = mc.playbackOptions( q=True, max=True)

for currentFrame in range(0, int(maxFrames)):
	#print('Frame=' + str(currentFrame))
	mc.currentTime(currentFrame, update=True, edit=True)
	mc.select('nParticle1')

	theParticle = mc.ls(sl=True, type='transform')

	for part in theParticle:
		for particleCount in range(0,mc.particle(part, q=True,ct=True)):

			particleName = mc.particle(part, q=True, order=particleCount, at='id')
			particlesPosition = mc.particle(part, q=True, order=particleCount, at='position')

			#print (particleName, particlesPosition, particleCount)

			particleDictionary = {}
			if str(particleName[0]) in allParticleDictionary.keys():
				particleDictionary = allParticleDictionary[str(particleName[0])]

			particleDictionary[currentFrame] = particlesPosition 
			allParticleDictionary[str(particleName[0])] = particleDictionary

		
for curveParticleId in allParticleDictionary.keys():
Exemplo n.º 56
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
Exemplo n.º 57
0
###############################################2############################
import maya.cmds as mc

allParticleDictionary = {}
minFrames = mc.playbackOptions(q=True, min=True)
maxFrames = mc.playbackOptions(q=True, max=True)

for currentFrame in range(0, int(maxFrames)):
    #print('Frame=' + str(currentFrame))
    mc.currentTime(currentFrame, update=True, edit=True)
    mc.select('nParticle1')

    theParticle = mc.ls(sl=True, type='transform')

    for part in theParticle:
        for particleCount in range(0, mc.particle(part, q=True, ct=True)):

            particleName = mc.particle(part,
                                       q=True,
                                       order=particleCount,
                                       at='id')
            particlesPosition = mc.particle(part,
                                            q=True,
                                            order=particleCount,
                                            at='position')

            #print (particleName, particlesPosition, particleCount)

            particleDictionary = {}
            if str(particleName[0]) in allParticleDictionary.keys():
                particleDictionary = allParticleDictionary[str(