Mel Script - Accessing Parenting Information

 

 

 

Our Maya scenes contain many seperate objects grouped into bone hierarchies. All transform and surface objects therefore have child nodes and parent nodes. We can use the command listRelatives to access parenting information about joints and surfaces.

 

 

 

 

Example 1 : Getting Object Parents

By using the -p flag with listRelatives you are able to retrieve a list of the objects parents.

 

 

	
	{
		// get a list of all meshes
		$meshes = `ls -type "mesh"`;

		// loop through each mesh
		for( $mesh in $meshes ) {

			print("mesh= " + $mesh + " parents= ");

			// get all of the mesh's parents
			$parents = `listRelatives -p $mesh`;

			// print them all out
			for( $parent in $parents ) {
				print($parent + " ");
			}
			print("\n");
		}
	}
	

 

 

Example 2 : Getting Object Children

By using the -c flag with listRelatives you are able to retrieve a list of the objects child nodes.

 

 

	
	{
		// get a list of all transforms in the scene
		$transforms = `ls -type "transform"`;

		// loop through each transform
		for( $transform in $transforms ) {

			print("bone= " + $transform + " kids= ");

			// get all of the bones children
			$kids = `listRelatives -c $transform`;

			// print them all out
			for( $kid in $kids ) {
				print($kid + " ");
			}
			print("\n");
		}
	}
	

 

 

Example 3 : Using Recursion

The most common usage of recusrion in computer graphics is to decend tree structures, ie bone hierarchies. This little example recurses through the scene and prints out the transforms.

 

 

	
	{
		// keeps track of how many tabs we need to indent the text
		global int $tabs=0;

		// this function recurses down through the bone hierarchy
		proc recurseBone(string $name) 
		{
			global int $tabs;
			
			// indent the joint name
			for($i=0;$i!=$tabs;++$i)
				print("\t");

			// print the transform name
			print($name+"\n");
			
			// increment indent
			++$tabs;
			
			// call recurseBone() on each child
			$kids = `listRelatives -c $name`;
			for( $kid in $kids ) 
				recurseBone($kid);
		
			// decrease indent
			--$tabs;
		}	
			
		
		// get a list of all transforms in the scene
		$transforms = `ls -type "transform"`;

		// loop through each transform
		for( $transform in $transforms ) {

			// get all of the bones parents
			$parents = `listRelatives -p $transform`;

			// if the bone has no parents, it must be a root joint
			if( size($parents) == 0 ) {
				recurseBone($transform);
			}
		}
	}