Пример #1
0
def quickDyn(spread=5, num=10, joints=False, bake=False):
    target = []
    g = py.gravity()

    for i in range(0,num):
        c = py.polyCube()
        target.append(c)
        x = rnd(-spread,spread)
        y = rnd(-spread,spread) + 10
        z = rnd(-spread,spread)
        py.move(x,y,z)
        py.rotate(x,y,z)

    s(target)
    py.rigidBody()

    for i in range(0,len(target)):
        py.connectDynamic(target[i],f=g)

    if(joints==False and bake==True):
        bakeAnimation(target)
        
    if(joints==True):
        target2 = []

        for i in range(0,len(target)):
            s(target[i])
            jnt = py.joint()
            target2.append(jnt)
            
        if(bake==True):
            bakeAnimation(target2)

        for i in range(0,len(target2)):
            unparent(target2[i])
Пример #2
0
    def __init__(self, fluidName='', baseRes=32, emitObj=None):
        """
        Create Fluid Container and Emitter
        :param fluidName: str
        :param baseRes: int
        :param emitObj: str
        """
        # Create Fluid Container and Emitter
        cont = mayaLib.fluidLib.base.baseContainer.FluidContainer()
        emit = mayaLib.fluidLib.base.baseEmitter.FlEmitter(obj=emitObj)

        self.fluidShape = cont.getContainer()[0]
        self.fluidEmit = emit.getEmitter()[0]
        self.fluidTransform = pm.listRelatives(self.fluidShape, parent=True)

        if fluidName != None:
            if fluidName != '':
                pm.rename(self.fluidTransform, fluidName)

        # Connect Emitter to Fluid Container
        pm.connectDynamic(self.fluidShape, em=self.fluidEmit)
        pm.parent(self.fluidEmit, self.fluidShape)

        # Setup
        self.setupFluidShape(baseRes)
Пример #3
0
def connect(fluid=None):
    '''
    Select fluid container and emitters
    Connect emitters to fluid
    '''
    sel = pm.ls(sl=1)
    fluid = sel[0]
    emitters = sel[1:]
    for each in emitters:
        pm.connectDynamic(fluid, em=each, d=True)
        pm.connectDynamic(fluid, em=each)
Пример #4
0
 def _create_particle(self,value,*argv):
     global n_particle_create
     pmel.emitter( r=value,dx=1, dy=0, dz=0, sp=0, nsp=0, n='myRandomEmitter' ,type='surface')
     n_particle_create = pmel.nParticle( n='emittedParticles' )
     n_particle_create[1].maxCount.set(value)
     nucleus = pmel.listConnections(n_particle_create,t='nucleus')
     nucleus[0].gravity.set(0)
     pmel.connectDynamic( 'emittedParticles', em='myRandomEmitter')
     self.list_emitter_delete.append('myRandomEmitter')
     self.list_emitter_delete.append(n_particle_create)
     self.list_emitter_delete.append(nucleus)
Пример #5
0
    def rig(self, component_node, control, bake_controls=False, default_space=None, use_global_queue=False, **kwargs):
        # Create the dynamic pendulum to be used as the Aim space for the overdriver
        self.network = self.create_meta_network(component_node)
        #self.zero_character(self.network['character'], use_global_queue)

        aim_up_group_name = "{0}pre_dynamics_{1}_grp".format(self.namespace, self.prefix)
        pre_dynamic_group = pm.group(empty=True, name=aim_up_group_name)
        pre_dynamic_group.setParent(self.network['addon'].group)
        pm.parentConstraint(self.character_world, pre_dynamic_group, mo=False)

        cur_namespace = pm.namespaceInfo(cur=True)
        pm.namespace(set=":")
        time_range = (pm.playbackOptions(q=True, min=True), pm.playbackOptions(q=True, max=True))

        object_space = pm.polySphere(r=8, sx=20, sy=20, ax=[0,1,0], cuv=2, ch=1, n="pendulum")[0]
        object_space.setParent(pre_dynamic_group)

        ws_pos = pm.xform(control, q=True, ws=True, t=True)
        pm.xform(object_space, ws=True, t=ws_pos)

        rigid_body = pm.rigidBody(object_space, b=0, dp=5)
        rigid_body_nail = pm.PyNode(pm.constrain(rigid_body, nail=True))
        rigid_body_nail.setParent(pre_dynamic_group)
        rigid_point_constraint = pm.pointConstraint(control, rigid_body_nail, mo=False)

        pm.select(None)
        gravity_field = pm.gravity(m=980)
        gravity_field.setParent(pre_dynamic_group)
        pm.connectDynamic(object_space, f=gravity_field)

        self.reset_pendulum(object_space)

        if not super(Pendulum, self).rig(component_node, control, [object_space], bake_controls=bake_controls, default_space=default_space, use_global_queue=use_global_queue, **kwargs):
            return False
        
        driver_control = self.network['controls'].get_first_connection()

        driver_control.addAttr("damping", type='double', hidden=False, keyable=True)
        driver_control.damping.set(rigid_body.damping.get())
        driver_control.damping >> rigid_body.damping

        driver_control.addAttr("bounciness", type='double', hidden=False, keyable=True)
        driver_control.bounciness.set(rigid_body.bounciness.get())
        driver_control.bounciness >> rigid_body.bounciness

        driver_control.addAttr("gravity", type='double', hidden=False, keyable=True)
        driver_control.gravity.set(gravity_field.magnitude.get())
        driver_control.gravity >> gravity_field.magnitude

        self.reset_pendulum(object_space)
Пример #6
0
	def _initialize(self,args):
		#Initialize
		partTarget = self.inputBar.getText()
		partNameBase = self.inputName.getText()
		if partTarget=='' or partNameBase=='':
			pm.error("Must input both fields to continue...")
		partName = partNameBase + '_NPARTICLE'
		partNucleus = partNameBase + '_NUCLEUS'
		partEmitter = partNameBase + '_EMITTER'
		#First thing we will do is Emit from Surface with an Emiter
		self.emitter = pm.emitter(partTarget, type='surface',name=partEmitter,r=5000,sro=0,nuv=0,cye='none',cyi=1,spd=0,srn=0,nsp=0,tsp=0,mxd=0,mnd=0,dx=1,dy=0,dz=0,sp=0)

		emitter=self.emitter
		self.nparticle = pm.nParticle(n=partName)
		npart=self.nparticle
		if '2012' in str(pm.versions.current()):
			import maya.cmds as cmds
			self.nucleus = cmds.listConnections(self.nparticle[1].name(), type='nucleus')[0]
			cmds.setAttr((self.nucleus+'.gravity'), 0)
			cmds.setAttr((self.nucleus+'.startFrame'), pm.playbackOptions(q=True,ast=True))
			cmds.rename(self.nucleus, partNucleus)
			self.nucleus=partNucleus
		elif '2015' in str(pm.versions.current()) or '2014' in str(pm.versions.current()):
			self.nucleus=pm.PyNode(set(npart[1].listConnections(type='nucleus')).pop())
			nucleus=self.nucleus
			nucleus.rename(partNucleus)
			nucleus.gravity.set(0)
			nucleus.startFrame.set(pm.playbackOptions(q=True,ast=True))
		else:
			pm.error("This maya version is unsupported by this script")
		#Set the Nucleus to no gravity + start time to first frame
		pm.currentTime( pm.playbackOptions(q=True,ast=True), e=True )
		pm.connectDynamic(npart, em=emitter)
		#Set up the nParticle:
		#add per particle attributes
		vattrs = ['posPP', 'rotPP', 'scalePP']
		for vattr in vattrs:
			npart[1].addAttr(vattr, k=1, dt='vectorArray')
			npart[1].addAttr(vattr+'0', dt='vectorArray')
		fattrs = ['indexPP']
		for fattr in fattrs:
			npart[1].addAttr(fattr, k=1, dt='doubleArray')
			npart[1].addAttr(fattr+'0', k=1, dt='doubleArray')
		#add dynamic expressions ala Vicky Osborne
		self._dynExpr()
		#Change shading type to points
		npart[1].particleRenderType.set(3)
Пример #7
0
def lookFluidEmitter():
    '''{'del_path':'Dynamics/Fluid Effects/lookFluidEmitter( )',
'icon':':/fluidCreate3DEmitter.png',
'tip':'帮助查看fluidEmitter的设置',
'usage':'$fun( )'
}
'''
    fluEm = pm.ls(sl=True, exactType='fluidEmitter')
    if not fluEm:
        raise IOError('Select a fluidEmitter!')
    fluEm = fluEm[0]
    fluEm = pm.ls(sl=True, exactType='fluidEmitter')[0]
    type = cmds.getAttr(fluEm.name() + '.emitterType')
    if type == 2 or type == 4:
        temp = fluEm.visibility.get()
        fluEm.v.set(True)
        size = cmds.getAttr(fluEm.name() + '.bbsi')[0]
        fluEm.v.set(temp)
        if type == 2:
            temp = fluEm.getParent().v.get()
            fluEm.getParent().v.set(True)
            size = cmds.getAttr(fluEm.getParent().name() + '.bbsi')[0]
            fluEm.getParent().v.set(temp)
        size = dt.Vector(math.ceil(size[0]), math.ceil(size[1]),
                         math.ceil(size[2]))
        shape = pm.createNode('fluidShape')
        papa = shape.getParent().rename(fluEm.name() + '_attr')
        papa.setTranslation(fluEm.getTranslation('world'), space='world')
        shape = papa.getShape()
        cmds.connectAttr('time1.outTime', shape.name() + '.currentTime')
        pm.connectDynamic(shape, em=fluEm)
        cmds.setAttr(shape.name() + '.velocityMethod', 0)
        shape.setSize(20, 20, 20, size.x, size.y, size.z, False)
        shape.ambientBrightness.set(1)
        shape.selfShadowing.set(True)
        shape.primaryVisibility.set(False)
    else:
        raise IOError(
            'fluid emitter work when emitterType is Surface and Volume only')
Пример #8
0
    def makeInk(self):
        """ create ink drops"""

        inkShape = pm.mel.eval('create3DFluid(50, 50, 50, 10, 20, 10)')
        mc.move(0, 10, 0)
        inkShape = pm.PyNode(inkShape)
        self.ink.append(inkShape)
        inkemitter = pm.fluidEmitter(pos=(0, 20, 0),
                                     type='omni',
                                     der=20,
                                     her=1,
                                     fer=1,
                                     fdr=2,
                                     r=100.0,
                                     cye='none',
                                     cyi=1,
                                     mxd=1,
                                     mnd=0)
        inkemitter = pm.PyNode(inkemitter)
        self.inkEmi.append(inkemitter)

        inkemitter.setParent(inkShape)
        pm.connectDynamic(inkShape, em=inkemitter)

        inkShape.highDetailSolve.set(3)
        inkShape.densityBuoyancy.set(-1)
        inkShape.color[0].color_Color.set(0, 0, 0)
        inkShape.incandescence[2].remove()
        inkShape.incandescence[1].remove()

        inkShape.renderInterpolator.set(3)
        inkShape.selfShadowing.set(1)
        inkShape.realLights.set(0)

        mc.setKeyframe(inkemitter + ".fde", v=20, t=20)
        mc.setKeyframe(inkemitter + ".fde", v=0, t=21)

        pm.select(deselect=True)
        inkShape.select()
Пример #9
0
def create_emitter(container=None, name=None, pos=None):  # PyNode
    em = pm.fluidEmitter(pos=pos, type='omni', der=1, r=100.0)
    em.rename(name)
    pm.connectDynamic(container, em=em)
    return name
Пример #10
0
    def createParticleEmitter(self, meshEmitter, collider):

        # Force nParticle balls at creation
        pm.optionVar(sv=("NParticleStyle", "Balls"))

        self.particle, self.partShape = pm.nParticle(n=str(meshEmitter) + "_particle")
        # Add attribute in particleShape
        pm.addAttr(self.partShape, ln="indexPP", dt="doubleArray")
        pm.addAttr(self.partShape, ln="rotatePP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="scalePP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="rgbPP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="fixPosPP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="opacityPP", dt="doubleArray")

        pm.addAttr(self.partShape, ln="typePP", dt="doubleArray")

        self.nameEmitter = str(meshEmitter) + "_emitter"
        pm.emitter(meshEmitter, type="surface", name=self.nameEmitter, r=float(self.ui.simulationEmit_le.text()))
        pm.connectDynamic(self.partShape, em=self.nameEmitter)

        # Used maya command because pymel crash when find nucleus node
        self.nucleusName = mel.eval('listConnections -type "nucleus" ' + self.partShape + ";")[0]

        pm.parent(self.partShape, self.worldParent)
        pm.parent(self.nameEmitter, self.worldParent)
        pm.parent(self.nucleusName, self.worldParent)

        self.setParamaters(self.partShape, self.particleParameter)
        self.setParamaters(self.nameEmitter, self.emitterParameter)
        self.setParamaters(self.nucleusName, self.nucleusParameter)
        pm.addAttr(self.partShape, ln="radiusPP", dt="doubleArray")

        # Create Rigid
        pm.select(collider, r=1)
        pm.runtime.nClothMakeCollide(collider)
        self.nrigid = pm.listConnections(collider.listRelatives(s=1, c=1)[0], type="nRigid")[0]
        self.setParamaters(self.nrigid.listRelatives(s=1, c=1)[0], self.rigidParameter)
        pm.parent(self.nrigid, self.worldParent)
        self.nrigid.setAttr("v", 0)

        # Create instancer
        self.instancer = pm.particleInstancer(
            self.partShape,
            a=True,
            object=self.listInstance,
            n=str(meshEmitter) + "_instancer",
            cycle="sequential",
            age="indexPP",
            rotation="rotatePP",
            scale="scalePP",
            visibility="opacityPP",
        )
        pm.parent(self.instancer, self.worldParent)

        # Create proc Colision
        expression = """
global proc forestGeneratorEvent(string $particleObject,int $particleId, string  $geometryObject) 
{

    vector $rgb = `nParticle -attribute rgbPP -id $particleId -q $particleObject`;

    if ($rgb != << 1,1,1 >>)
    {
        nParticle -e -attribute rgbPP -id $particleId -vv 0 1 0 $particleObject;
    }
    
    vector $pos = `nParticle -attribute position -id $particleId -q $particleObject`;
    
    vector $lastPos = `nParticle -attribute lastPosition -id $particleId -q $particleObject`;
    
    
    
    nParticle -e -attribute opacityPP -id $particleId -fv 1 $particleObject;

    if (mag($pos - $lastPos) >= 10 && $rgb != << 1,1,1 >>){
    
        nParticle -e -attribute lifespanPP -id $particleId -fv 0 $particleObject;
    }
}"""
        pm.expression(s=expression, n="forestGenerator_exp")
        # Create  Colision event

        pm.event(self.partShape, die=0, count=0, proc="forestGeneratorEvent")
Пример #11
0
    def createParticleEmitter(self, meshEmitter, collider):

        # Force nParticle balls at creation
        pm.optionVar(sv=("NParticleStyle", "Balls"))

        self.particle, self.partShape = pm.nParticle(n=str(meshEmitter) +
                                                     "_particle")
        #Add attribute in particleShape
        pm.addAttr(self.partShape, ln="indexPP", dt="doubleArray")
        pm.addAttr(self.partShape, ln="rotatePP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="scalePP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="rgbPP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="fixPosPP", dt="vectorArray")
        pm.addAttr(self.partShape, ln="opacityPP", dt="doubleArray")

        pm.addAttr(self.partShape, ln="typePP", dt="doubleArray")

        self.nameEmitter = str(meshEmitter) + "_emitter"
        pm.emitter(meshEmitter,
                   type="surface",
                   name=self.nameEmitter,
                   r=float(self.ui.simulationEmit_le.text()))
        pm.connectDynamic(self.partShape, em=self.nameEmitter)

        #Used maya command because pymel crash when find nucleus node
        self.nucleusName = mel.eval("listConnections -type \"nucleus\" " +
                                    self.partShape + ";")[0]

        pm.parent(self.partShape, self.worldParent)
        pm.parent(self.nameEmitter, self.worldParent)
        pm.parent(self.nucleusName, self.worldParent)

        self.setParamaters(self.partShape, self.particleParameter)
        self.setParamaters(self.nameEmitter, self.emitterParameter)
        self.setParamaters(self.nucleusName, self.nucleusParameter)
        pm.addAttr(self.partShape, ln="radiusPP", dt="doubleArray")

        #Create Rigid
        pm.select(collider, r=1)
        pm.runtime.nClothMakeCollide(collider)
        self.nrigid = pm.listConnections(collider.listRelatives(s=1, c=1)[0],
                                         type='nRigid')[0]
        self.setParamaters(
            self.nrigid.listRelatives(s=1, c=1)[0], self.rigidParameter)
        pm.parent(self.nrigid, self.worldParent)
        self.nrigid.setAttr("v", 0)

        #Create instancer
        self.instancer = pm.particleInstancer(self.partShape,
                                              a=True,
                                              object=self.listInstance,
                                              n=str(meshEmitter) +
                                              "_instancer",
                                              cycle="sequential",
                                              age="indexPP",
                                              rotation="rotatePP",
                                              scale="scalePP",
                                              visibility="opacityPP")
        pm.parent(self.instancer, self.worldParent)

        #Create proc Colision
        expression = """
global proc forestGeneratorEvent(string $particleObject,int $particleId, string  $geometryObject) 
{

    vector $rgb = `nParticle -attribute rgbPP -id $particleId -q $particleObject`;

    if ($rgb != << 1,1,1 >>)
    {
        nParticle -e -attribute rgbPP -id $particleId -vv 0 1 0 $particleObject;
    }
    
    vector $pos = `nParticle -attribute position -id $particleId -q $particleObject`;
    
    vector $lastPos = `nParticle -attribute lastPosition -id $particleId -q $particleObject`;
    
    
    
    nParticle -e -attribute opacityPP -id $particleId -fv 1 $particleObject;

    if (mag($pos - $lastPos) >= 10 && $rgb != << 1,1,1 >>){
    
        nParticle -e -attribute lifespanPP -id $particleId -fv 0 $particleObject;
    }
}"""
        pm.expression(s=expression, n="forestGenerator_exp")
        #Create  Colision event

        pm.event(self.partShape, die=0, count=0, proc="forestGeneratorEvent")
Пример #12
0
def run(sliderSize, sliderDensity, sliderHeight, textSequence, ckboxTexture, ckboxSequence, ckboxCover, directionX, directionY, directionZ, snowPieceBrowser):
    '''
    This function is the main function to generate the snowy scene.
    
    Args:
        avgSize from sliderSize: The average size of all snow piece
        density from sliderDensity: The density of the snow
        maxDistance from sliderHeight: The highest distance the user want the snow to fall
        snowTexture from ckboxTexture: Whether using the texture for snowflakes
        snowSequence from textSequence: The length of the sequence of images as texture
        directionX: directionX of gravity field
        directionY: directionX of gravity field
        directionZ: directionX of gravity field
        
        coverFlag(coverObj) from ckboxCover: Decide whether the snow will cover the models and which models to cover
        windFlag(windDirection, windStrength): Decide whether there are winds and the directions and strength
        
    GLobal variables used:
        startArea: The surface area the user want the snow fall from
        snowPath: The file path of the snowflake texture
        coverObj: The objects the particles will make collision with
        
    Result: 
        a generated snowy scene animation
        
    Return: 
        none
    
    '''
    ## check whether the user has selected the start Area    
    if isset('startArea') == 0:        
        logger.error('Please choose a plane to start snow!')
        pm.PopupError('Please choose a plane to start snow!')
        return
    ## check whether the user has selected the objects to make collision with
    if ckboxCover.getValue():
        if isset('coverObj') == 0:
            logger.error('Please select the objects to make collision with!')
            pm.PopupError('Please select the objects to make collision with!')
            return
    ## check whether the user has selected files for textures
    snowPath = snowPieceBrowser.getText()
    if ckboxTexture.getValue():
        if snowPath == '':            
            logger.error('Please select the images for textures!')
            pm.PopupError('Please select the images for textures!')
            return            
        
    logger.info('Start generating the snowy scene')

    snowSize = sliderSize.getValue()
    snowDensity = sliderDensity.getValue()
    snowHeight = sliderHeight.getValue()
    
    snowTexture = ckboxTexture.getValue()
    snowSequenceTmp = textSequence.getText()
    snowSequence = int(snowSequenceTmp)
    gdXs = directionX.getText()
    gdYs = directionY.getText()
    gdZs = directionZ.getText()
    
    gdX = float(gdXs)
    gdY = float(gdYs)
    gdZ = float(gdZs)

    pm.playbackOptions(ps = 0.4)
    
    offsetSize = snowSize * 0.3
    minSize = snowSize - offsetSize
    maxSize = snowSize + offsetSize
    
    
    startFace = startArea
    emitter1 = pm.emitter(startFace, sro = True, type = 'surface', rate = snowDensity, minDistance = 0.5, mxd = 1)
    particle_snow2 = pm.particle()
    pm.connectDynamic(particle_snow2, em = emitter1)
    
    ## using image textures for particles
    if ckboxTexture.getValue():
        logger.info(' particle render type: sprite ')
        pm.setAttr('%s.particleRenderType'%particle_snow2[0], 5)
        pm.addAttr(particle_snow2[1], internalSet = True, longName = 'spriteTwist', attributeType = 'float', minValue = -180, maxValue = 180, defaultValue = 0.0)
        pm.addAttr(particle_snow2[1], internalSet = True, ln = 'spriteScaleX', dv = 0.2)
        pm.addAttr(particle_snow2[1], internalSet = True, ln = 'spriteScaleY', dv = 0.2)
        pm.addAttr(particle_snow2[1], internalSet = True, ln = 'spriteNum', at = 'long', dv = 1)
        pm.addAttr(particle_snow2[1], internalSet = True, ln = 'useLighting', at = 'bool',dv = False)
    
        shader2 = pm.shadingNode('lambert', asShader = True)
        file_node2 = pm.shadingNode('file', asTexture = True)
        pm.setAttr('%s.fileTextureName'%file_node2, snowPath, type = 'string')
        shading_group2 = pm.sets(renderable = True, noSurfaceShader = True, empty = True)
        pm.setAttr('%s.ambientColor'%shader2, 1.0, 1.0, 1.0, type = 'double3')
        pm.connectAttr('%s.outColor'%shader2, '%s.surfaceShader'%shading_group2, force = True)
        pm.connectAttr('%s.outColor'%file_node2, '%s.color'%shader2, force = True)
        pm.connectAttr('%s.outTransparency'%shader2, '%s.surfaceShader'%shading_group2, force = True)
        pm.connectAttr('%s.outTransparency'%file_node2, '%s.transparency'%shader2, force = True)
        pm.sets(shading_group2, e = True, forceElement = '%s'%particle_snow2[0])
        
        if ckboxSequence.getValue():
            pm.setAttr('%s.useFrameExtension'%file_node2, 1)
            pm.setAttr('%s.useHardwareTextureCycling'%file_node2, 1)
            pm.setAttr('%s.endCycleExtension'%file_node2, snowSequence)
         
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteScaleXPP')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteScaleXPP0')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteScaleYPP')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteScaleYPP0')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteTwistPP')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteTwistPP0') 
        pm.dynExpression(particle_snow2[1], s = 'spriteScaleXPP = rand(%f,%f);\nspriteScaleYPP = spriteScaleXPP;\nspriteTwistPP = rand(0,30);'%(minSize, maxSize), c = True)
        
        if ckboxSequence.getValue():
            pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteNumPP')
            pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'spriteNumPP0')
            pm.dynExpression(particle_snow2[1], s = 'spriteScaleXPP = rand(%f,%f);\nspriteScaleYPP = spriteScaleXPP;\nspriteTwistPP = rand(0,30);\nspriteNumPP = rand(0,%f);\nspriteNumPP = (spriteNumPP+1)%%%f;'%(minSize, maxSize, snowSequence, snowSequence+1), c = True) 
    ## don't using textures
    else:
        logger.info(' particle render type: cloud ')
        pm.setAttr('%s.particleRenderType'%particle_snow2[0], 8)
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'radiusPP')
        pm.addAttr(particle_snow2[1], dataType = 'doubleArray', ln = 'radiusPP0')
        pm.addAttr(particle_snow2[1], dataType = 'vectorArray', ln = 'rgbPP')
        pm.addAttr(particle_snow2[1], dataType = 'vectorArray', ln = 'rgbPP0')        
        pm.dynExpression(particle_snow2[1], s = 'radiusPP = rand(%f,%f);\nrgbPP = <<1,1,1>>;'%(minSize, maxSize), c = True)
    
    ## if make collision
    if ckboxCover.getValue():
        for j in range(len(coverObj)):
            pm.collision(coverObj[j], particle_snow2[1], r = 0, f = 1)
    
    ## add gravity
    snowGravity = pm.gravity('%s'%particle_snow2[0], dx = gdX, dy = gdY, dz = gdZ, magnitude = 1.0)
    pm.connectDynamic('%s'%particle_snow2[0], f = snowGravity)    
    
    
    logger.info('Scene generation finished!')
    return
Пример #13
0
    def makeWord(self, in_word):
        """ create particle word"""

        #    in_word='maya'
        #    font = 'Arial'
        #    font = self.fontChoose.currentFont()
        #    print self.font[-1]
        tCrvs = pm.textCurves(t=in_word, f=self.font, ch=0)
        tCrvs = pm.PyNode(tCrvs[0])

        letterNum = tCrvs.numChildren()
        letter = []
        grpWord = pm.group(em=True)
        for n in range(0, letterNum):
            letterShape = pm.listRelatives(tCrvs.getChildren()[n],
                                           type='nurbsCurve',
                                           ad=True,
                                           path=True)
            letter.append(
                pm.planarSrf(letterShape, ch=1, tol=0.01, o=1, po=1)[0])
        pm.parent(letter, grpWord)

        # pm.select(grpWord)
        wordshape = pm.polyUnite(ch=1, muv=1)[0]
        mc.DeleteHistory()
        wordshape = pm.PyNode(wordshape)
        self.word.append(wordshape)
        # see(wordshape)

        pm.setAttr(tCrvs + ".visibility", 0)
        wordshape.centerPivots()
        # pm.move(-8,0,0)
        pm.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1)
        wordshape.makeLive()

        wordshape.select()
        pm.emitter(type='surface', r=1000, spd=0)
        wordEmitter = wordshape.getChildren()[1]
        wordEmitter = pm.PyNode(wordEmitter)
        wordEmitter.cycleEmission.set(1)
        wordEmitter.maxDistance.set(5)
        # see(wordEmitter)
        # wordEmitter.select()
        wordParticle = pm.particle()[0]
        wordParticle = pm.PyNode(wordParticle)
        wordPaShape = wordParticle.getShape()
        self.wordPar.append(wordPaShape)
        pm.connectDynamic(wordParticle, em=wordEmitter)
        mc.setKeyframe([wordEmitter + ".rate"], v=200, t=100)
        mc.setKeyframe([wordEmitter + ".rate"], v=0, t=101)

        wordPaShape.lifespanMode.set(2)
        wordPaShape.attr("lifespan").set(5)
        wordPaShape.lifespanRandom.set(3)

        wordPaShape.particleRenderType.set(0)
        wordPaShape.addAttr('colorAccum',
                            dv=True,
                            at='bool',
                            internalSet=True,
                            keyable=True)
        wordPaShape.addAttr('useLighting',
                            dv=False,
                            at='bool',
                            internalSet=True)
        wordPaShape.addAttr('multiCount',
                            at='long',
                            min=1,
                            max=60,
                            dv=2,
                            internalSet=True)
        wordPaShape.addAttr('multiRadius',
                            at='float',
                            min=1,
                            max=60,
                            dv=0.3,
                            internalSet=True)
        wordPaShape.addAttr('normalDir',
                            min=1,
                            max=3,
                            at='long',
                            internalSet=True,
                            dv=2)
        wordPaShape.addAttr('pointSize',
                            min=1,
                            max=60,
                            at='long',
                            internalSet=True,
                            dv=2)
        wordPaShape.colorAccum.set(1)
        wordPaShape.multiCount.set(7)
        wordPaShape.pointSize.set(1)

        wordPaShape.addAttr('goalU', dt='doubleArray', keyable=True)
        wordPaShape.addAttr('goalV', dt='doubleArray', keyable=True)
        pm.dynExpression(wordPaShape,
                         s='goalU=rand(0,1);\ngoalV=rand(0,1);',
                         c=1)
        wordPaShape.addAttr('rgbPP', dt='vectorArray', keyable=True)
        pm.dynExpression(wordPaShape, s='rgbPP=position;', rbd=1)

        pm.goal(wordParticle, g=wordshape, w=1, utr=0)
        pm.setKeyframe(wordParticle, attribute='goalWeight[0]', v=1, t=90)
        pm.setKeyframe(wordParticle, attribute='goalWeight[0]', v=0, t=100)
        pm.setAttr(wordshape + ".visibility", 0)

        field = pm.turbulence(pos=(0, 0, 2), m=10)
        pm.connectDynamic(wordParticle, f=field)
        pm.setKeyframe(field, attribute='tx', v=12, t=100)
        pm.setKeyframe(field, attribute='tx', v=0, t=110)
        pm.parent(field, wordshape)

        lambert = pm.shadingNode('lambert', asShader=1)
        lambertSG = pm.sets(renderable=True,
                            empty=1,
                            noSurfaceShader=True,
                            name=lambert + "SG")
        pm.connectAttr(lambert + ".outColor",
                       lambert + "SG.surfaceShader",
                       f=1)
        # pm.sets(wordParticle,forceElement='lambert6SG',e=True)
        wordParticle.select()
        pm.hyperShade(a=lambertSG)
        self.wordTexture.append(lambert)
        pm.setAttr(lambert + ".transparency", 0.7, 0.7, 0.7, type='double3')
        pm.setAttr(lambert + ".incandescence", 0.6, 0.6, 0.6, type='double3')
        pm.setAttr(lambert + ".incandescence", 0.5, 0.5, 0.5, type='double3')
        pm.setAttr(lambert + ".glowIntensity", 0.6)

        wordshape.select()
Пример #14
0
    def makeFire(self):
        """ create fire effects"""

        fluidShape = pm.mel.eval('create3DFluid(20, 30, 20, 15, 20, 15)')
        mc.move(0, 8, 0)
        fluidShape = pm.PyNode(fluidShape)
        self.fire.append(fluidShape)
        # see(fluidShape)

        fluidemitter = pm.fluidEmitter(pos=(0, 1, 0),
                                       type='omni',
                                       der=1,
                                       her=2,
                                       fer=4,
                                       fdr=2,
                                       r=100.0,
                                       cye='none',
                                       cyi=1,
                                       mxd=1,
                                       mnd=0)
        fluidemitter = pm.PyNode(fluidemitter)
        # see(fluidemitter)

        fluidemitter.setParent(fluidShape)
        pm.connectDynamic(fluidShape, em=fluidemitter)

        fluidShape.boundaryY.set(2)
        fluidShape.temperatureMethod.set(2)
        fluidShape.fuelMethod.set(2)
        fluidemitter.fluidHeatEmission.set(2)
        fluidemitter.fluidFuelEmission.set(4)
        # fluidShape.viscosity.set(0.01)
        # fluidShape.velocityDamp.set(0.02)
        # fluidShape.simulationRateScale.set(2)

        fluidShape.densityScale.set(0.5)
        fluidShape.densityBuoyancy.set(5)
        # fluidShape.densityDissipation.set(0.5)
        # fluidShape.densityDiffusion.set(0.1)
        # fluidShape.densityNoise.set(0.2)
        # fluidShape.densityTension.set(0.2)
        # fluidShape.densityGradientForce.set(-1)

        fluidShape.velocitySwirl.set(10)
        fluidShape.velocityNoise.set(0.5)

        # fluidShape.turbulenceStrength.set(0.03)
        # fluidShape.turbulenceFrequency.set(0.1)

        fluidShape.temperatureScale.set(1)
        fluidShape.buoyancy.set(5)
        fluidShape.temperatureDissipation.set(0.3)
        # fluidShape.temperatureDiffusion.set(0.1)
        # fluidShape.temperatureTurbulence.set(0.4)
        fluidShape.temperatureNoise.set(0.03)
        # fluidShape.temperatureTension.set(0.15)

        fluidShape.fuelScale.set(3)
        fluidShape.reactionSpeed.set(1)
        fluidShape.lightReleased.set(0.3)
        fluidShape.maxReactionTemp.set(10)

        # see(fluidShape.transparency)
        fluidShape.transparency.set(0.22, 0.22, 0.22)
        fluidShape.color[0].color_Color.set(0, 0, 0)

        fluidShape.incandescence[3].incandescence_Color.set(1, 1, 1)
        fluidShape.incandescence[3].incandescence_Position.set(0.994)
        fluidShape.incandescence[2].incandescence_Position.set(0.96)
        fluidShape.incandescence[1].incandescence_Position.set(0.56)
        fluidShape.incandescence[0].incandescence_Position.set(0.03)
        fluidShape.incandescenceInputBias.set(0.25)

        fluidShape.opacity[1].opacity_Interp.set(1)
        fluidShape.opacity[1].opacity_FloatValue.set(0.41)
        fluidShape.opacity[1].opacity_Position.set(0.31)
        fluidShape.opacity[2].opacity_Interp.set(1)
        fluidShape.opacity[2].opacity_FloatValue.set(0.9)
        fluidShape.opacity[2].opacity_Position.set(0.51)
        fluidShape.opacity[3].opacity_Interp.set(1)
        fluidShape.opacity[3].opacity_FloatValue.set(0.55)
        fluidShape.opacity[3].opacity_Position.set(0.64)
        fluidShape.opacity[4].opacity_Interp.set(1)
        fluidShape.opacity[4].opacity_FloatValue.set(0.51)
        fluidShape.opacity[4].opacity_Position.set(0.8)
        fluidShape.opacity[5].opacity_Interp.set(1)
        fluidShape.opacity[5].opacity_FloatValue.set(0.23)
        fluidShape.opacity[5].opacity_Position.set(1)
        fluidShape.opacityInput.set(6)
        fluidShape.opacityInputBias.set(-0.1)

        fluidShape.select()
Пример #15
0
def ph_mainCode(extraHeight, particleRate, getInitialInfo, minSlope,
                minSlopeVariance, setBoundingBox, maxTilt, objectScale,
                objectScaleVariance, objectHeightVariance):

    displayWindow = True
    windowError = py.window(title="Notice", mxb=False, s=False)
    errorLayout = py.rowColumnLayout(numberOfColumns=3, parent=windowError)

    #initialise varibables
    originalTime = py.currentTime(query=True)
    deleteCount = 0
    decimalPoints = 2

    #file validation
    storeSelection = py.ls(selection=True)

    try:
        validFile = True
        myfile = open('storedobjects.txt')
        objectList = myfile.readlines()
        myfile.close()
        py.select(clear=True)
        for i in range(len(objectList)):
            py.select(objectList[i], add=True)
        1 / len(objectList)

    except:
        validFile = False

    #get original selection
    py.select(clear=True)
    for i in range(len(storeSelection)):
        py.select(storeSelection[i], add=True)

        #deselect non polygons
        if type(storeSelection[i]) != py.nodetypes.Transform:
            py.select(storeSelection[i], deselect=True)

        #deselect objects in the text file
        if getInitialInfo == False:
            for j in range(len(objectList)):
                selectionEdit = storeSelection[i] + objectList[j][
                    -2] + objectList[j][-1]
                if objectList[j] == selectionEdit:
                    py.select(storeSelection[i], deselect=True)

    storeSelection = py.ls(selection=True)

    startTime = time()
    listOfPoints = []
    totalNum = 0

    if len(storeSelection) == 0:
        displayMessage = "Nothing is selected. Please select an object and try again."
        ph_displayWindow(displayWindow, displayMessage)

    elif getInitialInfo == True:

        #write to file
        selection = py.ls(selection=True)
        myfile = open('storedobjects.txt', 'w')
        for i in range(len(selection)):
            myfile.write("" + selection[i] + "\r\n")
        myfile.close()
        if len(selection) > 0:
            print str(len(selection)) + " object(s) successfully stored."
            if displayWindow == True:
                py.text(label="  ")
                py.text(label="  ")
                py.text(label="  ")
                py.text(label="  ")
                py.text(label=str(len(selection)) +
                        " object(s) successfully stored.",
                        align="center")
                py.text(label="  ")
                py.text(label="  ")
                py.text(label="  ")
                py.text(label="  ")
                py.showWindow()

        else:
            displayMessage = "Please select the objects you wish to store."
            ph_displayWindow(displayWindow, displayMessage)

        for i in range(len(storeSelection)):
            py.select(storeSelection[i], add=True)

    elif validFile == False:
        displayMessage = "Error with stored list. Please choose new object(s) to duplicate."
        ph_displayWindow(displayWindow, displayMessage)

    elif len(objectList) == 0:
        displayMessage = "No objects stored. Please choose new object(s) to duplicate."
        ph_displayWindow(displayWindow, displayMessage)

    else:
        for loops in range(len(storeSelection)):

            particleID = []
            particleLoc = []
            particleVelocity = []

            #get information about selected object
            py.select(storeSelection[loops], r=True)
            originalObj = py.ls(selection=True)
            originalObjLoc = originalObj[0].getTranslation()
            originalObjX = originalObjLoc.x
            originalObjY = originalObjLoc.y
            originalObjZ = originalObjLoc.z

            #duplicate object to work on
            tempObj = py.instance(originalObj)

            #make emitter
            particleEmitter = py.emitter(n='tempEmitter',
                                         type='surface',
                                         r=particleRate * 24,
                                         sro=0,
                                         speed=0.0001)
            particles = py.particle(n='emittedParticles')
            py.connectDynamic('emittedParticles', em='tempEmitter')
            py.setAttr(particles[1] + '.seed[0]', rd.randint(0, sys.maxint))

            #get list from file
            myfile = open('storedobjects.txt')
            objectList = myfile.readlines()
            objectListCopy = []
            myfile.close()

            for i in range(len(objectList)):
                copyObj = py.duplicate(objectList[i])
                objectListCopy.append(copyObj)

            #fixes the seed always being 0
            py.currentTime(originalTime + 1, edit=True, update=True)
            py.currentTime(originalTime, edit=True, update=True)
            py.currentTime(originalTime + 1, edit=True, update=True)
            numOfParticles = particles[1].num()

            for i in range(numOfParticles):

                #get particle info
                particleInfo = particles[1].Point('emittedParticles', i)
                particleID.append(particleInfo)
                particleLoc.append(particleInfo.position)
                particleVelocity.append(particleInfo.velocity)

            for i in range(len(particleID)):

                #place objects
                randomNum = rd.randint(0, len(objectListCopy) - 1)
                instanceObj = objectListCopy[randomNum]
                dupObj = py.instance(instanceObj)
                yDir = particleVelocity[i][1] * 10000

                #get height of object
                py.select(instanceObj, r=True)
                py.scale(1, 1, 1)
                height = py.ls(selection=True)[0].getBoundingBox().height()

                #reselect instance
                py.select(dupObj[0], r=True)
                py.move(dupObj[0], particleLoc[i][0],
                        particleLoc[i][1] + extraHeight, particleLoc[i][2])
                py.rotate(dupObj[0],
                          rd.uniform(-maxTilt, maxTilt),
                          rd.randint(0, 360),
                          rd.uniform(-maxTilt, maxTilt),
                          os=True)
                scaleX = rd.uniform(objectScale - objectScaleVariance,
                                    objectScale + objectScaleVariance)
                scaleY = rd.uniform(objectScale - (objectHeightVariance / 2),
                                    objectScale + objectHeightVariance)
                scaleZ = rd.uniform(objectScale - objectScaleVariance,
                                    objectScale + objectScaleVariance)
                py.scale(dupObj[0], scaleX, scaleY, scaleZ)

                if yDir <= rd.uniform(minSlope - minSlopeVariance,
                                      minSlope + minSlopeVariance):
                    py.delete(dupObj)
                    deleteCount = deleteCount + 1
                else:
                    listOfPoints.append(dupObj)

                #display percent completed
                maxValue = int(pow(len(particleID), 0.5))
                if float(i / maxValue) == float(i) / maxValue:
                    print str(
                        int((float(i) * 100 / len(particleID)) * 100.0) /
                        100.0) + "% completed"

            totalNum = totalNum + numOfParticles

            #delete temp objects
            py.select(tempObj, 'tempEmitter', 'emittedParticles')
            py.delete()
            py.currentTime(originalTime, edit=True, update=True)
            for i in range(len(objectListCopy)):
                py.delete(objectListCopy[i][0])

    #place objects in display layer
    py.select(clear=True)
    if len(listOfPoints) > 0:
        if setBoundingBox == True:
            displayLayerName = 'duplicatedObjectsBB'
        else:
            displayLayerName = 'duplicatedObjectsMesh'

        #add to display layer
        try:
            for i in range(len(listOfPoints)):
                py.editDisplayLayerMembers(displayLayerName, listOfPoints[i])

        #create display layer first
        except:
            py.createDisplayLayer(noRecurse=True, name=displayLayerName)
            for i in range(len(listOfPoints)):
                py.editDisplayLayerMembers(displayLayerName, listOfPoints[i])

            #display objects as bounding box
            if setBoundingBox == True:
                py.setAttr(displayLayerName + '.levelOfDetail', 1)
            py.setAttr(displayLayerName + '.color', 17)

        #add to group
        for i in range(len(listOfPoints)):
            py.select(listOfPoints[i][0], add=True)
        py.group(n='duplicatedObjectsGroup')

        #output time taken
        endTime = time()
        ph_timeOutput(startTime, endTime, decimalPoints)
        secondsDecimal, sec = ph_timeOutput(startTime, endTime, decimalPoints)
        displayMessage = str(totalNum -
                             deleteCount) + " objects created in " + str(
                                 secondsDecimal) + str(sec)
        ph_displayWindow(displayWindow, displayMessage)

    #select original selection
    py.select(clear=True)
    for i in range(len(storeSelection)):
        py.select(storeSelection[i], add=True)
# Fluid Shape
fluidTransform = pm.createNode('transform', n='fluidTransform')
# BUG - The following statement creates two fluid shapes.  I don't know why.
fluidShape = pm.nodetypes.FluidShape().create3D(60, 60, 6, 30, 30, 3, parent=fluidTransform)
# TODO - Add translucent yellow color
# Rotate the fluid shape by 90 degrees along the x axis
fluidTransform.rotateBy(pm.datatypes.Quaternion().setToXAxis(-1.5708), space='object')
fluidTransform.translateBy(pm.datatypes.Vector(0, -1.0, 0), space='object')
mc.select('fluidTransform')
mc.setAttr('fluidTransform.densityMethod', 0) # off
#fluidShape.setDensityMode(method='zero', gradient='')
mc.setAttr('fluidTransform.velocityMethod', 0) # off
mc.setAttr('fluidTransform.temperatureMethod', 2) # dynamic grid
mc.setAttr('fluidTransform.shadedDisplay', 3) # temperature
mc.setAttr('fluidTransform.temperatureDiffusion', 0.5);  # Diffusion coefficient
# Can also affect temperature (do not understand though)
mc.setAttr('fluidTransform.temperatureTension', 0.0);  # Tension

# Fluid Emitter
# TODO - Convert fluid emitter into a cylinder
fluidEmitterName = pm.fluidEmitter(pos=(0, 0, 0), type='omni', cye='none', der=1, fdr=1.5, fer=3, her=2, mxd=0, mnd=0, r=50.0, n='theFluidEmitter')
mc.setAttr('theFluidEmitter.rate', 500)
mc.setAttr('theFluidEmitter.densityMethod', 0)
mc.setAttr('theFluidEmitter.fuelMethod', 0)
mc.setAttr('theFluidEmitter.heatMethod', 1)

# Connect the fluid shape to the fluid emitter
pm.connectDynamic(fluidShape.nodeName(), em=fluidEmitterName)