Skip to main content

Adding Per Particle Script to Maya Particles via MEL

Submitted by root on

A friend of mine was wondering about how to attach per particle expressions to particles via mel

so I wrote this script



global proc int doesPPVectorAttrExist( string $attrName, string $particleShape)
{
	//We check to see if the PP attribute is here
	string $allPPVectors[] = `particle -q -perParticleVector $particleShape`;
	for ($i in $allPPVectors)
		{
			if ($i == $attrName)
			{
				return 1;
			}
		}
		return 0;
}

global proc string myFancyParticles( string $inputShapeNode, string $particleSystemName)
{
	string $returnValue = "Success";
	string $namesOfShapeNodes[] = `ls $inputShapeNode`;
	if (size($namesOfShapeNodes) > 0)
	{
		//Create a new particle system using the name entered into the function, use the first occurance inputShapeNode as the emmitter
		string $newParticles[] = `particle -n ($particleSystemName) -sn ($namesOfShapeNodes[0])`;
		//this returns an array, first entry is the transform, second is the shape node
		string $particleTransform = $newParticles[0];
		//the shape node may already exist multiple times, so using ls we get the all of them
		string $allParticleShapes[] = `ls $newParticles[1]`;

		int $lastEntry = size($allParticleShapes) - 1;
		//this is a trick to get the length of the array
		string $currentParticleShape = $allParticleShapes[$lastEntry];
		//now we have the lastEntry in the array
		if (doesPPVectorAttrExist("rgbPP",$currentParticleShape)//See procedure above)
		{
			//If the Per particle attribute exists our work is done
			print "rgbPP found!!!";
		}
		else
		{
			//Because the Per Particle Attribute Doesnt exist, we have to make ie
			print "No rgbPP here!!!, Lets add it!\n";
			//Adding a attribute is pretty straight forward
			addAttr -ln rgbPP -dt vectorArray $currentParticleShape;
			//Initialise the array to white
			setParticleAttr -at rgbPP -vv 1 1 1 $currentParticleShape;
			if (doesPPVectorAttrExist("rgbPP",$currentParticleShape))
			{
				print "rgbPP added all is well!!!\n";
			}

		}
		//Now bang on the particle expression! as a runtime before dynamics
		dynExpression -rbd -s "rgbPP = rgbPP * .9;" $currentParticleShape;
	}
	else
	{
		$returnValue = "Failure";
	}
	return $returnValue;

}

So if you want to test it out

Save it to a location like

/home/samh/exampleScriptingParticles.mel

Then you can try it out with the follow mel snippet in the script window


source "/home/samh/exampleScriptingParticles.mel"; //Update the script
file -f -new; //Emptry file
polySphere; //Create pSphereShape1
myFancyParticles( "pSphereShape1", "dustSphere"); //Call the function