Chapter 17. MEL and Python

MEL is a powerful scripting language that can be used to automate many tasks within Maya. As a matter of fact, The Maya interface itself is actually the result of many MEL scripts working together. Using MEL you can create your own scripts, which can save you time and labor and extend the capabilities of Maya. If you already know the popular scripting language Python, then you can use Python to run MEL commands, which makes Maya more compatible with other software packages that use Python.

In this chapter you will learn to:

  • Use a MEL command

  • Use MEL scripting techniques

  • Create a procedure

  • Use Python

Use a MEL Command

MEL stands for Maya Embedded Language. MEL is a scripting language similar to a programming language such as C++ or Java. An important difference between a programming language such as Java and a scripting language such as MEL is that a programming language must be compiled into an executable program, whereas a scripting language already resides within a program and does not need to be compiled.

A scripting language uses a series of commands that tell a running program what to do. What you may not realize is that you already use MEL all the time. The entire Maya interface is created using MEL commands. When you choose an option from a menu in Maya, Maya actually executes a command. To demonstrate this, try the following exercise.

MEL Interfaces

There are a number of ways to enter MEL commands. You can use the command shell, the command line, or the Script Editor.

  1. Open Maya to a new, empty scene. Choose Window

    MEL Interfaces
  2. Type sphere and press the Enter key on the keyboard.

    A NURBS sphere appears at the center of the grid; you'll also see some text in the command shell describing the result of the command. This text includes the nurbsSphere1 node and the history node named makeNurbsSphere1 (see Figure 17.1).

  3. With the sphere selected, type delete in the command shell and press the Enter key; the sphere disappears. Close the command shell.

    Entering the sphere command in the command shell creates a sphere on the grid.

    Figure 17.1. Entering the sphere command in the command shell creates a sphere on the grid.

    At the bottom of the Maya interface on the left side you should see the label MEL and a blank line. This is the command line; it is another place where you can enter MEL commands. If you don't see this, choose Display

    Entering the sphere command in the command shell creates a sphere on the grid.
  4. Type sphere in the command line and press the Enter key (Figure 17.2). Once again, a new sphere appears on the grid.

  5. With the sphere selected, type delete and press the Enter key to delete the sphere.

  6. On the bottom, far-right side of the Maya interface, click the Script Editor button to open the Script Editor. This is another interface you can use to enter MEL commands.

    Enter the sphere command in the command line at the bottom left of the Maya interface.

    Figure 17.2. Enter the sphere command in the command line at the bottom left of the Maya interface.

    The Script Editor has two stacked windows. The top half of the editor shows the history of the commands entered and executed while Maya is open. This persists even when you close the scene file and open a new one. The bottom half of the Script Editor is an area where you can enter and edit MEL scripts. The two tabs in the bottom half of the editor allow you to switch between MEL and Python (see Figure 17.3).

  7. Make sure the MEL tab is active in the bottom half of the Script Editor. Type sphere and press the Enter key on the keyboard.

    The Script Editor is divided into the upper area, which lists the command history, and the lower area, where you can enter multiline scripts.

    Figure 17.3. The Script Editor is divided into the upper area, which lists the command history, and the lower area, where you can enter multiline scripts.

    When you press the Enter or Return key on the keyboard, instead of executing the command, the Script Editor moves to a new line. This may be confusing at first. The Script Editor is designed to allow you to create multiline scripts. The Enter key on the keyboard starts a new line. To execute the commands in the Script Editor, press the Enter key on the numeric keypad of the keyboard. Some computers, such as laptops, do not have numeric keypads. If this is the case, use the Ctrl+Return key combination, or look to see if there is a smaller, separate Enter key on another part of the keyboard.

  8. Press the Enter key on the numeric keypad to execute the script. A sphere should appear on the grid once again.

You'll notice in the history of the Script Editor that a semicolon is appended at the end of the sphere command. In practice, you should always place a semicolon at the end of each command. This lets Maya know that the command should be executed and, if the Script Editor contains a second line of commands, Maya needs to move on to execute the next line of the script. A semicolon in MEL is analogous to a period at the end of a sentence in English. Get into the habit of adding a semicolon to the end of each command or line in your scripts. In most cases, if you leave the semicolon off the end of a line, you'll get an error message and the script will not execute.

The Script Editor has a number of features available in the Script Editor menu bar. You can save selected lines of code to the shelf as a button. The buttons execute the lines of code whenever you click them, which is useful for commands that you repeat a lot. You can use the File menu to load MEL scripts that have been saved to text files. Any plain text file saved using the .mel extension can be loaded as a MEL script. You can also save selected lines of code in the Script Editor as a MEL script.

The File

Enter versus Return

The options in the Edit menu can be used to copy and paste MEL commands as well as to clear the history visible in the top section of the Script Editor. Search and replace features are also available here.

The Command menu lets you create new tabs in the Script Editor in case you want to enter new commands without disturbing any of the commands entered in another tab. This is useful as a testing area.

To keep things simple, you'll use the Script Editor for most of this chapter as opposed to the command shell or the command line. Many of the common features found in the Script Editor menus, such as creating shelf buttons, loading scripts, and sourcing scripts, are used in the examples in this chapter.

MEL Scripting Techniques

You can become an accomplished Maya animator without ever writing a single MEL script. If this is the case, why should you concern yourself with learning MEL? MEL is a way to save time and labor. You may not be interested in advanced MEL scripting features, such as creating custom plug-ins or your own Maya interfaces, which are certainly possible using MEL. But sooner or later you'll run into a situation in which you need to perform the same complex task multiple times, which can quickly become tedious and time consuming.

Consider the following scenario, which is very common in a production environment. You just spent the better part of a week setting up a complex nParticle simulation. Variations of this simulation are used in ten different shots, each shot has its own scene and each scene contains five or six separate nParticle objects that have similar attributes. The particle motion has been approved, but suddenly the client requests that, instead of simple colored spheres, all the shots now need to use animated logos. The client also wants to see the new version using the logos first thing on Monday morning. It's now Friday and you have planned a weekend getaway with your friends. You realize that the best way to turn the colored nParticle balls into animated logos is to use sprites.

A sprite is a special type of particle that places a flat, rectangular plane at the position of each nParticle. The plane is always oriented so it is perpendicular to the camera. Using a shader and expressions, an image is mapped to the plane. The images can be animated to create particle effects that would be difficult to generate using the other particle types. For instance, an animated sequence of flames can be mapped to the sprites to generate realistic fire. Since sprites are two-dimensional planes, they do not have a Radius attribute, instead they use Scale X and Scale Y. Likewise, sprites rotate only around the Z axis. This rotation is controlled using the Sprite Twist attribute. Custom attributes and expressions need to be created for each of the nParticle objects so the sprite images animate correctly.

You can choose to go into each scene and manually add attributes and expressions for each nParticle object, which will most likely destroy your weekend plans, or you can create a MEL script that automates the conversion of all particle objects in each scene, which may only take a few hours. In this situation, having even a basic understanding of simple MEL commands can save your weekend and your sanity.

In this section of the chapter, you'll add custom attributes and expressions to an nParticle object so it renders as sprites as the basis for creating your own MEL script. You'll save this script as a shelf button and also as a separate MEL file. You'll gain an understanding of some useful MEL tricks and hopefully an appreciation for MEL that inspires you to learn more about MEL scripting.

Learning From the Script Editor

One of the best MEL scripting resources available is the Script Editor itself. As you execute commands in Maya using the menu, the Script Editor prints a history of the commands and their results in the history section of the Script Editor. By observing the feedback in the history section, you can learn common commands, and you can then use these commands in your scripts.

You need to be aware of two important concerns about the way Maya lists the command history: The first is that by default, Maya does not list every single command in the history section. If you'd like to see every command executed during a Maya session, go to the Script Editor window and choose History

Learning From the Script Editor

The example used in this chapter is a hypothetical commercial spot. Your task is to create a script that makes converting the existing particles into sprites easier so you can simply select one or more of the existing nParticle systems, run a script, and automatically create the necessary attributes and expressions. Let's look at the first shot in the commercial.

  1. Open the shot1_v01.ma scene from the chapter 17scenes directory on the DVD. Switch to the renderCam camera in the perspective view. Rewind and play the scene.

    The scene starts with dark blue nParticle spheres appearing inside a cylindrical volume emitter. A vortex field pushes the nParticles along in circular motion. The dark blue nParticles are sucked into a volume axis curve field, which spirals upward. As the camera tracks upward, a second set of pink nParticles is being born. They are sucked into a second spiraling volume axis curve field (see Figure 17.4).

    Pink and blue nParticles follow along the spiral paths created by two volume axis curve fields.

    Figure 17.4. Pink and blue nParticles follow along the spiral paths created by two volume axis curve fields.

    The script you will write automates the process of converting the nParticle spheres into sprites and attaching attributes and expressions to alter their behavior. To learn how to create the script, you'll perform actions as you normally would. In this case, you'll convert the blue_nParticle into sprites, and then you'll observe what happens in the Script Editor and use this to build a script. You'll then use the script to convert the pink_nParticle into sprites.

  2. Open the Script Editor window (Window

    Pink and blue nParticles follow along the spiral paths created by two volume axis curve fields.
  3. Choose Edit

    Pink and blue nParticles follow along the spiral paths created by two volume axis curve fields.
  4. Select the blue_nParticle node in the Outliner, and open its Attribute Editor to the blue_nParticleShape tab. Scroll to the Shading section and set the Particle Render Type menu to Sprites.

    The Script Editor displays a number of lines in the history section. The first line says select −r blue_nParticle;. This is the command that was executed when you selected the blue_nParticle object in the first part of step 4. The command is followed by many additional commands, each of which sets up the basic sprite nParticle type attributes (see Figure 17.5).

    Changing the nParticle type to sprites produces a number of lines of code in the Script Editor.

    Figure 17.5. Changing the nParticle type to sprites produces a number of lines of code in the Script Editor.

    The command syntax for many commands is command flag nodeName;, so the command in this case is select. The flag is -r, the node is blue_nParticle, and the command is ended using a semicolon. Most of this is fairly straightforward except for the command flag. What does -r mean? Flags are preceded by a hyphen and often abbreviated, so you have to find out what the r flag stands for. You can find out what a flag does by opening the help files and doing a search for the particular command in question, or you can type help and the name of the command directly in the Script Editor.

  5. Type help select; in the lower half of the Script Editor, and press the Enter key. In the history section of the Script Editor you'll see a list of flags (see Figure 17.6).

    According to the help on the select command, the -r flag stands for replace. The -r flag tells the select command to replace the current selection with the object specified in the command. So, as you select objects in the scene, the -r flag is used each time the selection is changed. The other flags listed in the Script Editor can be used with the select command as well. For example, if you wanted to create a script in which all DAG (directed acyclic graph) objects are selected, you can use the -ado flag. The command looks like this: select -ado;. Executing this command using this syntax selects all DAG nodes in the scene at once.

    Typing help and the name of the command you need help with into the Script Editor displays a list of available flags.

    Figure 17.6. Typing help and the name of the command you need help with into the Script Editor displays a list of available flags.

    The second line in the Script Editor history reads setAttr blue_nParticleShape.particleRenderType 5;. In this line the command being executed is setAttr, which sets an attribute for a particular node. The node receiving the setAttr command is the blue_nParticleShape node, which was selected in the first line of the Script Editor history. The attribute being set on the blue_nParticleShape is the particleRenderType and the value applied to the particleRenderType is 5. So what does this mean?

    When accessing a node's attribute the dot syntax is used. To set the particle render type of the blue_nParticle shape node, you must specify the syntax using nodeName.attributeName. Hence you have blue_nParticleShape.particleRenderType specified in the setAttr command. The value of the setting depends on the attribute. In this case, particleRenderType requires a numeric setting to convert the nParticle from a sphere into a sprite.

    Maya uses a numbered sequence for some attributes, such as particleRenderType. The way in which an attribute setting is listed in a menu in the Maya interface gives a clue as to how Maya numbers the attribute's settings. Take a look at the Particle Render Type menu in the shading section of the particle shape node. The menu options are MultiPoint, MultiStreak, Numeric, Points, Spheres, Sprites, Streak, BlobbySurface, Cloud, and Tube. The numbers Maya uses in the command are not listed, but if you change the particle render type to one of the choices in the menu and observe the script history, you'll see a different number applied at the end of the setAttr blue_nParticleShape.particleRenderType line. The particleRenderType attribute uses 0 for MultiPoint, 1 for MultiStreak, 2 for Numeric, 3 for Points, and so on. Hence, to change the particle render type to sprites, the command is setAttr blue_nParticleShape.particleRenderType 5;.

    The next few lines in the Script Editor use the addAttr command. This command adds attributes to the selected node. The syntax is the same as the setAttr command; however, in this case there are a few flags as well. These flags specify the settings that will be used for the added attribute. In the history section of the Script Editor the third line says:

    addAttr -is true -ln "spriteTwist" -at "float" -min −180 -max 180 -dv 0.0
         blue_nParticleShape;

    In this case the attribute being added is the spriteTwist command, which is used only by the sprite particle type (and not by any of the other types such as sphere, blobby surface, or point). The -is flag means "internal set." This is an internal flag used for updating the user interface. This is not something you need to specify every time you use this command. In fact, many flags that Maya lists in the history section can be left out when you use them in your own scripts. This is another aspect of scripting that you'll understand more with experience.

    To find out what's going on with the four addAttr commands and their various flags that appear in the Script Editor, you can do a little detective work. The lines read:

    addAttr -is true -ln "spriteTwist" -at "float" -min −180 -max 180 -dv 0.0
         blue_nParticleShape;
    addAttr -is true -ln "spriteScaleX" -dv 1.0 blue_nParticleShape;
    addAttr -is true -ln "spriteScaleY" -dv 1.0 blue_nParticleShape;
    addAttr -is true -ln "spriteNum" -at long -dv 1 blue_nParticleShape;

    Take a look at the Attribute Editor for the blue_nparticleShape node. If you scroll down to the Sprite Attributes rollout and expand this section, you'll see there are Sprite Num, Sprite Scale X, Sprite Scale Y, and Sprite Twist attributes.

  6. Rewind the animation, and then play it for 50 frames and click Stop. Experiment with changing the values for the Sprite Twist, Sprite Scale X, and Sprite Scale Y settings in the Attribute Editor, and observe the results in the camera view (see Figure 17.7).

    Sprite Num changes the image used for the sprite itself. Since no image is assigned, currently this attribute has no effect. Sprite Twist changes the rotation of the sprites around the sprite's local Z axis. Sprite Scale X changes the horizontal size of the sprites, and Sprite Scale Y changes the vertical size.

  7. Select the pink_nParticle object in the Outliner and open its Attribute Editor. You'll notice that under Sprite Attributes these settings do not exist. Therefore, you can surmise that these attributes were added to the blue_nParticle shape when Maya executed the four addAttr commands when the particle render type was changed to sprites in step 4.

    The four attributes listed in the Sprite Attributes section of the Attribute Editor were added using the addAttr command. These settings change the behavior of the sprites.

    Figure 17.7. The four attributes listed in the Sprite Attributes section of the Attribute Editor were added using the addAttr command. These settings change the behavior of the sprites.

    The point of this exercise is to give you an understanding of what happens behind the scenes when you change settings for various node attributes in Maya. What you've learned from these observations is that changing the particle render type to sprites in the Attribute Editor not only sets the particle type to sprites but also executes several lines of code, which adds several attributes specific to sprites.

    The Sprite Num, Sprite Twist, Sprite Scale X, and Sprite Scale Y attributes added to the blue_nparticleShape node affect all blue nParticles equally. In the animation you're creating, you'll want to override these settings with Per Particle, Num, Twist, and Scale attributes so each individual nParticle has its own behavior. This means that in the script you're creating you won't need to use the four addAttr commands listed in the Attribute Editor.

  8. Undo any changes made to the Sprite Attributes settings for blue_nParticle. Save the scene as shot1_v02.ma. To see a version of the scene so far, open the shot1_v02.ma scene from the chapter17scenes directory on the DVD.

Create a MEL Script File

The term MEL script refers to the lines of commands typed and executed in the Script Editor or a series of commands saved in a text file that uses the .mel extension. You can create MEL scripts in the Script Editor, but it is often a better idea to create your scripts in a separate text editor program. One reason for this is that whenever you type a MEL command into the bottom half of the Script Editor and press the Enter key, the text disappears (as long as there are no errors). This means you have to hunt through the history to find the commands that were executed. Another argument for creating your scripts in a second file is that keeping the script open in a text editor prevents you from losing your work if Maya crashes.

When creating a MEL script file, use a standard text editor such as Notepad or WordPad (in Windows, or TextEdit on the Mac) and make sure the encoding is set to plain text. If you use a word processor such as Microsoft Word, hidden characters copied and pasted from Word into the Script Editor can cause errors in your script, so do not use Microsoft Word to create MEL scripts!

  1. Continue with the scene from the previous section or open the shot1_v02.ma scene from the chapter17scenes directory on the DVD.

  2. Open a text editor such as Notepad or TextEdit. In a blank text file type the following:

    //set the particle render type of the current selection to sprite
    setAttr blue_nParticleShape.particleRenderType 5;

    These are the first two lines of your first MEL script, the script that will convert a selected nParticle's render type from spheres to sprites. The first line of the script starts with the double slash followed by some descriptive text. This is a comment line. Maya ignores everything on this line of the script that follows the double slash. The text is a comment that tells you what the next line in the script does. It's a good practice to use comment lines as much as possible to help you keep track of what's going on in the script, especially if you may be returning to the script later on and might forget what the script does.

    The second line is the command that sets the particle render type to sprites. This line is copied from the Script Editor. You may have guessed at a potential problem in the way this line is written. Since the command specifies that the particle render type of blue_nParticleShape will be set to 5, only nodes named exactly blue_nParticleShape will be affected by the command. You'll need to edit the script so any nParticleshape that is selected will be affected by the setAttr command. To accomplish this you'll use an array.

    An array is a list contained within a variable. Array variables are often used to hold a list of the currently selected nodes in a scene.

  3. Edit the script so it says the following:

    //create an array containing the current selection
    string $mySelection[] = 'ls -selection';
    
    //set the particle render type of the current selection to sprite
    //setAttr blue_nParticleShape.particleRenderType 5;

    Notice that the double slash has been added to the setAttr command. This turns this line into a comment so it is ignored when the script is run. This is a way to save the commands you know you'll be using later in the script.

    The command that creates the array is the second line, which reads string $mySelection[] = "ls -selection";. The first part of the command to the left of the equal sign creates the array variable. The variable type is a string. String variable types contain letters as opposed to float or integer variable types, which contain numeric values. The variable is named $mySelection[]. Variables are preceded by dollar signs. You can name a variable anything you want, but it's best to make the name descriptive of what the variable contains. The square brackets indicate that the variable is an array. Think of the double brackets as a box that holds the list.

    The equal sign is used to assign data to the variable. Notice the slanted accent (") marks. This symbol is created using the key below the Esc key and to the left of the number keys on most keyboards. It is not an apostrophe. If you used an apostrophe in your script, change it to the accent mark; otherwise you'll get an error when you run the script. The text between the two accent marks is the list command. In this case the selection flag (-selection) is added to the list command (ls), so the list that will be created is the currently selected objects in the scene. Hence the command is written as ls -selection;. The -selection flag is often abbreviated as sl. At the start of many scripts you'll see a line that reads ls -sl;. This means "list selected objects."

    So why is the list command contained within the accent marks? The second line of the script creates a variable array named $mySelection[] and then, using the list command, it places all of the selected objects in the scene into $mySelection[]. The accent marks are used to assign the results of an executed command to a variable. The order of the selected objects in the list is based on the order in which they were selected before the script is executed.

  4. Edit the script so that it says the following:

    //create an array containing the current selection
    string $mySelection[] = "ls -selection";
    
    //set the particle render type of the current selection to sprite
    setAttr ($mySelection[0]+".particleRenderType") 5;

    It may look as though the setAttr command has been drastically changed, but in reality it has only been edited slightly. The text has been changed, so blue_nParticleShape has been replaced with the variable $mySelection[0]. The 0 contained in the square brackets of $mySelection[] refers to the first item listed in the $mySelection[] array. The numbering of lists in Maya always begins with 0, not 1.

    Since a variable is being used instead of a node, the syntax must be changed so Maya does not search for a node named $mySelection[0]. The proper syntax for accessing the attribute of a node contained within a variable requires that the variable name is placed within parentheses and that the attribute name is appended with a plus sign and surrounded by quotes. So instead of $mySelection[0].particleRenderType, you have to type ($mySelection + ".particleRenderType").

  5. At this point you can test the code. Select the code in the text editor and copy it. Switch to Maya. In the Outliner, select the pink_nParticle object.

  6. Paste the copied text into the work area of the Script Editor, and press the Enter key (Figure 17.8).

    If all goes well, you'll see no error messages and the pink_nParticle node will display as sprites. If there are error messages, double-check your script for typos and make sure only pink_nParticle is selected when the script is run.

    Copy the text from the text editor and paste it into the Script Editor. Select pink_nParticle and execute the script.

    Figure 17.8. Copy the text from the text editor and paste it into the Script Editor. Select pink_nParticle and execute the script.

    Notice that if you select the pink_nParticleShape node, Maya also adds the four addAttr lines to the script, creating the spriteTwist, spriteScaleX, spriteScaleY, and spriteNum attributes automatically.

  7. Save the text file as mySpriteScript.mel. Make sure the encoding is plain text and that the extension is .mel. Some text editors will ask you if you want to append .txt to the end of the filename; do not do this.

  8. Save the scene as shot1_v03.ma. To see a version of the scene, open the shot1_v03.ma scene from the chapter17scenes directory on the DVD.

Add Attributes with MEL

If you recall from the section on nParticle expressions in Chapter 14, expressions can be used to control the behavior of individual nParticles within an nParticle object. In the simulation you are editing, you need to create a random rotation and size for the nParticles (based on the hypothetical client's request). To do this you'll create a per-particle twist attribute and per-particle Scale X and Scale Y attributes.

  1. Continue with the scene from the previous section or open the shot1_v03.ma scene from the chapter17scenes directory on the DVD. Continue editing the mySpriteScript.mel file in your text editor.

    Once again, we can use the Script Editor to find out the precise syntax for adding these attributes.

  2. In the Outliner, select the blue_nParticle object, and open its Attribute Editor to the blue_nParticleShape tab. Scroll down and expand the Add Dynamic Attributes section below the Per Particle Array Attributes list. Click the General button to open the Add Attribute window.

  3. In the Add Attribute window, switch to the Particle tab. Scroll toward the bottom of the list, and Ctrl+click on spriteNumPP, spriteScaleXPP, SpriteScaleYPP, and spriteTwistPP. The PP indicates that each attribute is a per-particle attribute (see Figure 17.9).

    Select the per-particle sprite attributes in the Add Attribute menu.

    Figure 17.9. Select the per-particle sprite attributes in the Add Attribute menu.

  4. Click the Add button to add these attributes. The new attributes should appear in the Per Particle (Array) Attributes list. If they do not, click the Load Attributes button at the bottom of the Attribute Editor to refresh the window.

  5. Open the Script Editor and take a look at the history. At the top you'll see that the addAttr command is used to add the attributes to the blue_nParticleShape object. Notice that each attribute uses two addAttr commands to add the attribute (see Figure 17.10).

    You can copy these lines of code and adapt them to the script based on what you've learned so far.

    The Script Editor reveals the syntax for adding the per-particle array attributes.

    Figure 17.10. The Script Editor reveals the syntax for adding the per-particle array attributes.

  6. Edit the mySpriteScript.mel file so it says:

    //create an array containing the current selection
    string $mySelection[] = "ls -selection";
    
    //set the particle render type of the curremt selection to sprite
    setAttr ($mySelection[0]+".particleRenderType") 5;
    
    //add per-particle spriteNum, scale, and twist attributes
    
    addAttr -ln spriteNumPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteNumPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteScaleXPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteScaleXPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteScaleYPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteScaleYPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteTwistPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteTwistPP0 -dt doubleArray $mySelection[0];

    In this case the pasted code from the Script Editor was changed so that blue_nParticleShape is now the variable $mySelection[0];.

  7. Test the script. First, save the mySpriteScript.mel file in the text editor. Save the Maya scene as shot1_v04.ma. Go back to an earlier version of the Maya scene, before pink_nParticle was converted to a sprite, so you can test the entire script. Open the shot_v02.ma scene for the chapter17scenes folder on the DVD.

  8. In the Outliner, select pink_nParticle. Copy all the text in the mySpriteScript.mel file and paste it into the work area of the Script Editor. Click the Enter key to run the script.

    When you run the script, you should have no error messages. If you do see an error in the Script Editor, double-check the text of the script and make sure there are no mistakes.

    Even though there are no errors, you may have noticed that something is not quite right. Select pink_nParticle and open its Attribute Editor to the pink_nParticleShape tab. In the Per Particle (Array) Attributes section you'll notice that the per-particle attributes do not appear, even when you click the Load Attributes button at the bottom of the Attribute Editor. What happened?

  9. In the Attribute Editor, click the pink_nParticle tab to switch to the nParticle's transform node. Expand the Extra Attributes section. Here you'll find the per-particle attributes. They have been added to the wrong node (see Figure 17.11).

    The per-particle array attributes have been added to the transform node by mistake.

    Figure 17.11. The per-particle array attributes have been added to the transform node by mistake.

    This is a common mistake that is easy to make. When you write a MEL script, you must keep in mind the potential problems that can occur when you or another user applies the script in a scene. In this case the MEL script did exactly what you asked it to: It added per-particle attributes to the selected node, which in this case is the pink_nParticle node. Your intent is to add the attributes to the shape node. You have two options: You can make sure that you—and anyone else who uses the script—remember to always select the shape nodes of the nParticles every time you use the script, or you can build in a command that ensures that the attributes are applied to the shape node. The second option is more desirable and actually involves little coding.

  10. Edit the text at the top of the script in the mySpriteScript.mel file so it says:

    //create an array containing the shape nodes of the current selection
    pickWalk -d down;
    string $mySelection[] = "ls -selection";

    A new line has been added to the top of the script using the pickWalk command. This command moves the current selection down one node (notice the -d flag, which stands for direction, and that the flag is set to down) in the node hierarchy, which means that if a user selects the nParticle node, the pickWalk command at the top of the script will move the selection down to the shape node and then load the selected shape node into the $mySelection[] array variable. If the user has already selected the shape node before running the script, it will still function properly since there are almost always no other nodes below the shape node in the node hierarchy. Later on you'll see how to add a conditional statement so the user will get an error if he or she picks anything other than an nParticle object. Anticipating user errors is a big part of becoming an accomplished MEL script author.

  11. Repeat steps 7 and 8 to test the script. This time the new attributes should appear in the Per Particle (Array) Attributes list of the pink_nParticleShape node, as shown in Figure 17.12.

  12. Save the mySpriteScript.mel file.

When you correct the script, the new attributes are added to the Per Particle (Array) Attributes section of the pink_nParticleShape tab.

Figure 17.12. When you correct the script, the new attributes are added to the Per Particle (Array) Attributes section of the pink_nParticleShape tab.

Add an Image Sequence to the Sprites

At this point you can apply the animated image sequence of the logos to the blue_nParticle sprites.

  1. Open the shot1_v04.ma scene from the chapter17scenes folder on the DVD.

  2. Open the Hypershade window and create a new Lambert shader. Name the shader spriteShade.

  3. Select blue_nParticle in the Outliner. In the Hypershade, right-click on spriteShade and choose Assign Material To Selection.

  4. Rewind and play the animation to frame 50. The sprites appear as blue squares.

  5. Open the Attribute Editor for spriteShade. Add a file texture node to the Color channel by clicking on the checkered box next to Color and choosing File from the Create Render Nodes window.

  6. In the options for the file node, click on the folder next to File Name, and select the logo.1.iff file from the chapter17sourceimages folder on the DVD.

    The image appears as a small pentagon with a hole in it. When you rewind and play the scene, each of the blue_nParticles should look like the small pentagon. The image has an alpha channel that is automatically used in the Transparency channel of spriteShade. This image is actually the first in an animated sequence of 60 frames. The process for adding image sequences to sprites is a little odd. The next steps explain how this is done.

  7. Open the Attribute Editor for the file1 node that has been applied to the Color channel of spriteShade. Expand the Interactive Sequence Caching options.

  8. Turn on Use Interactive Sequence Caching. Set Sequence Start to 1, Sequence End to 60, and Sequence Increment to 1.

  9. Turn on the Use Image Sequence option above the Interactive Sequence options (Figure 17.13 shows this). Rewind and play the scene. The sprites don't look any different, and you'll see a warning in the Script Editor complaining that images cannot be found once the animation passes frame 60.

    Turn on Use Interactive Sequence Caching and Use Image Sequence to apply the animated images to the spriteShade material.

    Figure 17.13. Turn on Use Interactive Sequence Caching and Use Image Sequence to apply the animated images to the spriteShade material.

    The spriteNumPP attribute controls how the image sequence is applied to each sprite. Until you create an expression for this attribute, you won't see the image sequence properly on the sprites.

  10. Open the Attribute Editor for the blue_nParticleShape node. In the Per Particle (Array) Attributes section, right-click on the field next to spriteNumPP, and choose Creation Expression to open the Expression Editor.

  11. In the Expression section of the Expression Editor type the following:

    spriteNumPP=1;
  12. Click the Create button to make the expression.

  13. In the Expression Editor, click the Runtime Before Dynamics button to switch to runtime expression mode. Type the following:

    spriteNumPP=spriteNumPP+1;
  14. Click the Create button to make the expression.

  15. Rewind and play the animation. Now you'll see each of the blue logos appears as a small pentagon that grows into the snowflake logo as it is born (see Figure 17.14).

  16. Save the scene as shot1_v05.ma. To see a version of the scene to this point, open the shot1_v05.ma scene from the chapter17scenes folder on the DVD.

The snowflake logo is animated as each sprite nParticle is born into the scene.

Figure 17.14. The snowflake logo is animated as each sprite nParticle is born into the scene.

Add Expressions Using MEL

The previous section described the standard manner in which the spriteNumPP attribute is used to animate sprite images. In this section you'll add commands to your MEL script that will apply the same expressions to selected nParticles. In addition, you'll add expressions to control the twist and scale of the nParticles.

  1. Continue with the scene from the previous section or open the shot1_v05.ma scene from the chapter17scenes directory on the DVD. Open the mySpriteScript.mel file in a text editor.

    If you look in the Script Editor when you add the creation expression for blue_nParticle's spriteNumPP, you'll see the following command:

    dynExpression -s "blue_nParticleShape.spriteNumPP=1;" -c blue_nParticleShape;

    The runtime expression looks like this:

    dynExpression -s "blue_nParticleShape.spriteNumPP=blue_nParticleShape.spriteNumPP+1;"
         -rbd blue_nParticleShape

    The expression is added using the dynExpression command. The -s flag specifies a string that is the expression itself surrounded by quotes. You'll see that the creation expression uses the -c flag, and the runtime before dynamics expression uses the -rbd flag.

  2. Edit the text in the mySpriteScript.mel file so it reads:

    //create an array containing the shape nodes of the current selection
    pickWalk -d down;
    string $mySelection[] = 'ls -selection';
    //set the particle render type of the curremt selection to sprite
    setAttr ($mySelection[0]+".particleRenderType") 5;
    
    //add per-particle twist, scale, and spriteNum attributes
    
    addAttr -ln spriteNumPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteNumPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteScaleXPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteScaleXPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteScaleYPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteScaleYPP0 -dt doubleArray $mySelection[0];
    
    addAttr -ln spriteTwistPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteTwistPP0 -dt doubleArray $mySelection[0];
    
    //add expressions for per-particle attributes
    
    dynExpression -s "spriteNumPP=1;" -c $mySelection[0];
    dynExpression -s "spriteNumPP=spriteNumPP+1;" -rbd $mySelection[0];

    You'll notice that in the expression text itself, within the quotes, you can print just the name of the attribute spriteNumPP without adding the array variable. Maya understands that the expression will be added to the selected particle object.

  3. Test the script by selecting the pink_nParticle object in the Outliner. Copy all the text in the text file, and paste it into the work area of the Script Editor. Press the Enter key.

  4. In the Hypershade, select spriteShade and apply it to the pink_nParticle object.

  5. If there are no error messages, rewind and play the scene.

    You'll see the pink_nParticle object now has the animated sprites applied. The sprites are pink thanks to the pink color that was originally applied to the spheres in the first version of the scene.

  6. Select the blue_nParticle object and edit the creation expression. Add the following and click the Edit button (see Figure 17.15):

    spriteTwistPP=rand(360);
    
    spriteScaleXPP=rand(0.5,2);
    spriteScaleYPP=spriteScaleXPP;
  7. Edit the runtime before dynamics expression. Add the following line and click the Edit button:

    spriteTwistPP=spriteTwistPP+1;
  8. Rewind and play the scene. The blue_nParticles are rotated randomly as they fly through the scene. They are also sized randomly.

    Edit the creation expression for the blue_nParticleShape in the Expression Editor.

    Figure 17.15. Edit the creation expression for the blue_nParticleShape in the Expression Editor.

    Note that when you set a scaleXPP value for a sprite, you should then set the scaleYPP attribute equal to the scaleXPP attribute. This way the sprites are scaled uniformly and remain square shaped.

  9. To add these changes to the script, edit the text in the mySpriteScript.mel file so the expressions look like this (the expressions printed in this book span more than one line; when you place them in your script, you should paste them onto a single line without adding returns):

    //add expressions for per-particle attributes
    
    dynExpression -s "spriteNumPP=1; 
    
    spriteTwistPP=rand(360);
         
    
    spriteScaleXPP=rand(.5,2);
         
    spriteScaleYPP=spriteScaleXPP;" -c $mySelection[0];
    
    dynExpression -s "spriteNumPP=spriteNumPP+1;
         
    
    spriteTwistPP=spriteTwistPP+1;"
         -rbd $mySelection[0];

    Figure 17.16 shows the script text in a text editor. The and that you see in the expression stand for "return" ( ) and "newline" ( ). Adding these to the expressions in your MEL script creates spaces between the expressions in the Expression Editor, which makes the expressions organized and easy to read.

    Edit the text in the MEL script to update the expressions.

    Figure 17.16. Edit the text in the MEL script to update the expressions.

  10. Edit the text and save the mySpriteScript.mel file. Select pink_nParticle. Copy and paste the text from the text file into the work area of the Script Editor, and press the Enter key.

  11. To see a version of the scene, open the shot1_v06.ma scene from the chapter17scenes folder on the DVD.

Create a Conditional Statement

Conditional statements are used to direct the commands of a script toward one action or another. If a certain condition is met, then the script performs an action; if not, the script does something else. Conditional statements work very well for error detection. In the case of the current example, you'll use a conditional statement to make sure the script works only when an nParticle object is selected. This can prevent errors from occurring in the script or in the scene.

You will add a conditional statement to the mySpriteScript.mel file that tests to make sure the selected object is an nParticle object. If it is, then the script will run and perform all the commands you've created in the previous section. If it is not, the script will print an error message that says that the selected object is not an nParticle.

There are several types of conditional statements. In this example you'll use the most common if/then conditional. The syntax for this type of conditional looks like this:

If (condition to test is true)
     {
     Execute commands;
     }
else
     {
     Print error message or execute a different set of commands;
     }

The statement within the parentheses at the start of the conditional is the statement that needs to be tested. If this statement is true, then the commands within the first set of curly braces are executed. Notice that these commands are indented. Using indentation in your script makes the script appear organized and legible.

If the statement within the parentheses is false, then Maya skips down to the else statement and executes the set of commands in the second set of curly braces. This can be an error message or even additional conditional statements. In this section you'll add a conditional statement that uses the objectType command to test whether the selected object is an nParticle.

  1. Open your most recent version of the mySpriteScript.mel file.

  2. At the top of the script, edit the text so that it says the following:

    //create an array containing the shape nodes of the current selection
    pickWalk -d down;
    string $mySelection[] = 'ls -selection';
    
    //make sure selected object is an nParticle
    if ('objectType -isType "nParticle" $mySelection[0]'){

    The objectType command uses the isType flag to test whether $mySelection[0] is an nParticle. Notice that this command is surrounded by the accent marks within the parentheses. These accent marks are used whenever one command is nested within another. Compare this line with the line that creates the $mySelection[] array variable and assigns it to a list of the selected objects. How is the use of the accent marks similar in these two lines?

    When you use the if statement, the condition within the parentheses is tested to be either true or false. If the statement is true, a value of 1 is returned. If the statement is false, a value of 0 is returned.

  3. Use the Tab key to indent the commands you created in the previous section. Add the else statement and the error message at the bottom. The entire script should look like this:

    //create an array containing the shape nodes of the current selection
    pickWalk -d down;
    string $mySelection[] = 'ls -selection';
    
    //make sure selected object is an nParticle
    if ('objectType -isType "nParticle" $mySelection[0]'){
    
         //set the particle render type of the current selection to sprite
         setAttr ($mySelection[0]+".particleRenderType") 5;
    
         //add per-particle twist, scale, and spriteNum attributes
    
         addAttr -ln spriteNumPP -dt doubleArray $mySelection[0];
         addAttr -ln spriteNumPP0 -dt doubleArray $mySelection[0];
    
         addAttr -ln spriteScaleXPP -dt doubleArray $mySelection[0];
         addAttr -ln spriteScaleXPP0 -dt doubleArray $mySelection[0];
    
         addAttr -ln spriteScaleYPP -dt doubleArray $mySelection[0];
         addAttr -ln spriteScaleYPP0 -dt doubleArray $mySelection[0];
    
         addAttr -ln spriteTwistPP -dt doubleArray $mySelection[0];
    addAttr -ln spriteTwistPP0 -dt doubleArray $mySelection[0];
    
         //add expressions for per-particle attributes
    
         dynExpression -s "spriteNumPP=1;
    
    spriteTwistPP=rand(360);
              
    
    spriteScaleXPP=rand(.5,2);
              
    spriteScaleYPP=spriteScaleXPP;" -c $mySelection[0];
    
         dynExpression -s "spriteNumPP=spriteNumPP+1;
              
    
    spriteTwistPP=spriteTwistPP+1;"
              -rbd $mySelection[0];
    
    }
    else
    {
         error "Sorry, you must select an nParticle to use this script";
    }
  4. To test the script, open the shot2_v01.ma scene from the chapter17scenes directory on the DVD. This is the second shot in the commercial spot. It uses five nParticle objects.

  5. Select the orange_nParticle object in the Outliner.

  6. Select and copy all of the text in the mySpriteScript.mel file, and paste it into the Script Editor.

  7. Press the Enter key to run the script. If there are no errors, the orange_nParticle object will turn into a sprite.

  8. Select the emitter1 object in the Outliner. Copy and paste the script into the Script Editor, and run the script again. This time you should see an error message that says, Sorry, you must select an nParticle to use this script.

  9. Save the mySpriteScript.mel file in your text editor.

Create a Loop

As it stands, the script is designed to convert one nParticle object at a time. By adding a simple loop to the script, running the script a single time will convert all of the selected nParticles at the same time.

There are many types of loop statements you can use in MEL. One of the most common and easiest to create is the for loop. It uses the following syntax:

for ($i=0;$i<length of loop;$i++){ loop commands }

There are three commands within the parentheses separated by semicolons. The first command creates a variable named $i. The new $i variable is set to equal 0, which is the starting value of the loop. The second command in the parentheses sets the limit of the loop. So long as the variable $i is less than a particular value, the loop continues to run. The third statement in the parentheses increases the variable $i by increments of 1. Another way of saying $i = $i + 1 is to use $i++.

The commands that will be executed each time the loop runs are contained within curly braces, just like the conditional statement. Once again, using the Tab key to indent statements within the braces can help you keep the script visually organized, especially if multiple nested loops are used.

  1. Open the mySpriteScript.mel file in your text editor. Edit the script so it matches the following:

    //create an array containing the shape nodes of the current selection
    pickWalk -d down;
    string $mySelection[] = 'ls -selection';
    
    //create a loop based on the number of selected object
    for ($i=0;$i<size($mySelection);$i++){
    
         //make sure selected object is an nParticle
         if ('objectType -isType "nParticle" $mySelection[$i]'){
    
              //set the particle render type of the curremt selection to sprite
              setAttr ($mySelection[$i]+".particleRenderType") 5;
    
              //add per-particle twist, scale, and spriteNum attributes
    
              addAttr -ln spriteNumPP -dt doubleArray $mySelection[$i];
              addAttr -ln spriteNumPP0 -dt doubleArray $mySelection[$i];
    
              addAttr -ln spriteScaleXPP -dt doubleArray $mySelection[$i];
              addAttr -ln spriteScaleXPP0 -dt doubleArray $mySelection[$i];
    
              addAttr -ln spriteScaleYPP -dt doubleArray $mySelection[$i];
              addAttr -ln spriteScaleYPP0 -dt doubleArray $mySelection[$i];
    
              addAttr -ln spriteTwistPP -dt doubleArray $mySelection[$i];
              addAttr -ln spriteTwistPP0 -dt doubleArray $mySelection[$i];
    
              //add expressions for per-particle attributes
    
              dynExpression -s "spriteNumPP=1;
    
    spriteTwistPP=rand(360);
                   
    
    spriteScaleXPP=rand(.5,2);
                   
    spriteScaleYPP=spriteScaleXPP;" -c $mySelection[$i];
    
             dynExpression -s "spriteNumPP=spriteNumPP+1;
                   
    
    spriteTwistPP=spriteTwistPP+1;"
                   -rbd $mySelection[$i];
    
         }
         else
         {
              error "Sorry, you must select an nParticle to use this script";
         }
    }

    The loop is set to run as long as $i is less than the size of $mySelection. The size of $mySelection is based on the number of items selected before the script is run. For each iteration of the loop $i is increased by an increment of 1.

    The first time the loop runs $i is equal to 0, the second time the loop runs $i is equal to 1, the third time the loop runs run $i is equal to 2, and so on until $i is equal to the number of items selected in the scene.

    Notice that the 0 in the brackets of the $mySelection variable is now changed to the $i variable throughout the script. Recall that the items in the list contained in the $mySelection array variable are numbered based on the order in which they are selected and that this numbering starts with 0. By changing the code so that $mySelection[0] is now $mySelection[$i], the commands are run on each of the objects contained in the array variable.

    Before completing the script there is one final line of code you can add to the loop. This line simply turns on the Depth Sort option for sprites, which is usually off by default. Depth Sort ensures that the sprites closest to the camera appear in front of the sprites farthest from the camera.

  2. In the script add a line after the command that sets the particle render type to sprites but before the lines that add the per-particle render attributes. The new line should read:

    //Turn on Depth Sort
    setAttr ($mySelection[$i]+".depthSort") 1;

    Figure 17.17 shows the final script as it appears in Notepad.

    The screen grab shows the final script as it appears in Notepad.

    Figure 17.17. The screen grab shows the final script as it appears in Notepad.

  3. Save the mySpriteScript.mel file to your local directory. Save the script in the Mayascripts directory found in the My Documents folder.

    Scripts are usually saved in the My DocumentsMayascripts folder on your local drive. You may also save scripts to the My DocumentsMaya2009scripts directory, or if they are specific to your project, you can save them in the mel folder of the current project.

    You can compare your version of the script with the mySpriteScript.mel file in the chapter17mel directory on the DVD.

  4. To test the script, open the shot2_v01.ma scene from the chapter17scenes folder on the DVD. If it is already open, reload the scene.

  5. In the Outliner, Shift+click on the green_nParticle, red_nParticle, yellow_nParticle, purple_nParticle, and orange_nParticle objects.

  6. Open the Script Editor and choose File

    The screen grab shows the final script as it appears in Notepad.
  7. The script loads in the work area of the Script Editor window. Press the Enter key to run the script. If there are errors, open the mySpriteScript.mel file from the chapter17mel folder on the DVD. Compare your code with the code in this file; keep a sharp eye for typos, because even the smallest mistake can cause an error. Unfortunately, debugging scripts for small errors is a rite of passage for beginning MEL scripters.

  8. Select the nParticle objects, open the Hypershade, and apply the spriteShade material to the selected nParticle objects.

  9. Save the scene as shot2_v02.ma. To see a finished version of the scene, open the shot2_v02.ma scene from the chapter17scenes folder on the DVD.

If everything works, congratulations on creating your first MEL script. With more practice and study you'll find that creating scripts saves you a great deal of time and labor.

Procedures

A complex MEL script is often made up of procedures. A procedure is a small section of code that may be called upon by the script one or more times. You can think of a procedure as a mini-MEL script within a script. Procedures are a useful and efficient way to organize a script.

Make a Procedure from a Script

In this example you'll create a procedure from a script.

  1. In your text editor, open the shakeMe.mel file from the chapter17mel folder on the DVD.

    The shakeMe.mel script is a very simple loop that attaches an expression to the Translate channels of selected objects. Take a look at the code:

    string $mySel[] = 'ls -sl';
    
    for ($i=0;$i<size($mySel);$i++){
    
         makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 $mySel[$i];
    
         expression -s "translateX=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
         expression -s "translateY=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
         expression -s "translateZ=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
    
    };

    The script starts by making an array of the selected objects in the scene (the -sl flag is an abbreviation for selection). The loop then uses the makeIdentity command to freeze all of the transformations for the selected objects. The three expression commands attach an expression to each of the Translate channels, which randomizes the position of the translation between −1 and 1.

    The flags in the expression command are -s (string), -o (object), -ae (always evaluate), and –uc (unit conversion).

  2. To test the script, make a new blank scene in Maya. Create a number of polygon cubes, and place them randomly in the scene.

  3. Select the cubes and open the Script Editor. Copy and paste the code from the shakeMe.mel file into the work area of the Script Editor, and then press the Enter key.

  4. Rewind and play the scene. The cubes should shake randomly around their original location.

  5. To turn the script into a procedure, edit the text file so it looks like the following:

    proc shakeMe(){
    
         string $mySel[] = 'ls -sl';
    
         for ($i=0;$i<size($mySel);$i++){
    
              makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 $mySel[$i];
    
              expression -s "translateX=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
              expression -s "translateY=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
              expression -s "translateZ=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
    
         }
    }

    At the start of the script, the text proc shakeMe() is added. This creates a new procedure named shakeMe. The procedure is contained within the set of curly braces.

  6. Create a new scene in Maya. Create a number of randomly placed polygon cubes.

  7. Copy and paste the edited text into the Script Editor. Select the cubes and press the Enter key. Nothing happens.

    Nothing happens because instead of executing a script, you've actually sourced the procedure. In other words, you've made this snippet of code available as part of Maya.

  8. With the cubes selected, type shakeMe into the command line and press the Enter key. The script is now applied to the selected cubes.

    This is useful because you can run the script any number of times on any number of selected objects by selecting the objects and then typing shakeMe into the command line.

  9. Save this file as shakeMeProc.mel. To see a version, open the shakeMeProc.mel file from the chapter17mel folder on the DVD.

Use a Procedure within a Script

The real usefulness of a procedure is when it is contained as part of a script. The procedure can be called on within the script at any time, which is a way of reusing the same bit of code whenever it is needed. Procedures should always appear at the start of the script so that, when the script is run, the procedures are sourced into Maya's memory before the rest of the script executes.

As a simple example, suppose that instead of randomly moving the selected objects between a value of −1 and 1, you wanted to create a range for the expression that itself is based on a random value.

  1. Open a text editor to a new file and type in the following:

    //create a random number between 0 and 3
    float $randVal = rand(3);

    This is an extremely simple script that generates a random number between 0 and 3.

  2. Copy the text shakeMe proc from the shakeMeProc.mel file in the chapter17mel folder. Paste this text above the lines you have typed in the text editor so the script looks like the following:

    proc shakeMe(){
    
         string $mySel[] = 'ls -sl';
    
         for ($i=0;$i<size($mySel);$i++){
    
              makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 $mySel[$i];
    
              expression -s "translateX=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
              expression -s "translateY=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
    expression -s "translateZ=rand(−1,1);"  -o $mySel[$i] -ae 1 -uc all ;
    
         }
    }
    
    //Create a random number between 0 and 3
    float $randVal = rand(3);
  3. Edit the first line of the script to read proc shakeMe($num){. This adds a variable that allows the script to pass information to the procedure.

  4. Even though the variable is stated in the procedure, you still need to declare its type as a float. Edit the first three lines of the script like this:

    proc shakeMe(float $num){
    
         float $num;
    
         string $mySel[] = 'ls -sl';
  5. Within the loop, below the makeIdentity command, add two new lines:

    float $lowRange = −0.5*$num;
              float $highRange = 0.5*$num;

    These lines create two new variables that represent the low and high ranges of the random value that will be used in the next lines of the script. So if the initial $num is equal to 3, the low range will be −1.5 and the high range will be 1.5. Thus, the object will move randomly within a total range of three units when the expression is applied.

  6. Edit the expression lines of the script:

    expression -s ("translateX=rand(" + $lowRange + "," + $highRange +");")
      -o $mySel[$i] -ae 1 -uc all ;
    expression -s ("translateY=rand(" + $lowRange + "," + $highRange +");")
      -o $mySel[$i] -ae 1 -uc all ;
    expression -s ("translateZ=rand(" + $lowRange + "," + $highRange +");")
      -o $mySel[$i] -ae 1 -uc all ;

    It is very important to pay attention to how these lines are written because it illustrates an important aspect of using MEL to create expressions. On the surface it may seem logical to place the $lowRange and $highRange variables directly into the expression so that the line looks like this:

    expression -s "translateX=rand($lowRange, $highRange );"
         -o $mySel[$i] -ae 1 -uc all ;

    But this will not work. If you run the script using this syntax, you will get an error that says that $lowRange and $highRange have not been declared as variables. At first this makes no sense—clearly you declared the variables in the two lines added before the expression lines. So why is Maya complaining about undeclared variables?

    You have to understand what the expression command actually does. When you use the expression command, it is like you are telling MEL to write the expression for you in the Expression Editor. Variables within the Expression Editor are local. They have no relationship or connection to the variables created within MEL scripts (one alternative is to declare the variables as global variables, however, for the sake of understanding how to write expressions with MEL, let's pretend global variables do not exist). When you run the script, MEL creates the expressions exactly as they appear between the quotes in the expression command. Therefore, if you place variables within these quotes that have not been declared in the expression itself, Maya won't understand where these variables came from. To work around this, you concatenate the expression using the plus sign. This is the same syntax you used earlier in the chapter when you set an attribute for an object contained within a variable. The syntax looks like this:

    Expression -string "The first part of the expression text" +
         the variable created in mel +
         "the second part of the expression text";
  7. Finally, at the very end of the script add a line that calls the procedure so the entire script, with procedure, looks like this:

    proc shakeMe(float $num){
    
         float $num;
    
         string $mySel[] = 'ls -sl';
    
         for ($i=0;$i<size($mySel);$i++){
    
              makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 $mySel[$i];
    
              float $lowRange = −0.5*(0.5+$num);
              float $highRange = 0.5*(0.5+$num);
    
    
              expression -s ("translateX=rand(" + $lowRange + "," + $highRange +");")
                -o $mySel[$i] -ae 1 -uc all ;
              expression -s ("translateY=rand(" + $lowRange + "," + $highRange +");")
                -o $mySel[$i] -ae 1 -uc all ;
              expression -s ("translateZ=rand(" + $lowRange + "," + $highRange +");")
                -o $mySel[$i] -ae 1 -uc all ;
    
         }
    };
    
    //Create a random number between 0 and 3
    float $randVal = rand(3);
    shakeMe($randVal);

    When you select objects in a scene and run the script, the shakeMe procedure is loaded into memory. This is everything within the curly braces. Then the variable $randVal is created and assigned a number between 0 and 3 randomly. The last line of the script calls the shakeMe procedure and passes the procedure the random value held in the $randVal variable. In the procedure, the $num variable is set to be equivalent to the $randVal value, and the procedure is executed.

  8. To see a finished version of the script, open the shakeMeProc_v02.mel file from the chapter17mel folder on the DVD.

Global Procedures

The procedure created in the previous section is a local procedure. The procedure is available only within the script that uses it. A global procedure is one that can be called upon by any script in Maya. Maya uses global procedures to create the interface and perform the tasks necessary to make Maya functional. To make a procedure global, you simply start the procedure using the text global proc instead of just proc.

You should be very careful when creating your own global procedures. It is possible to overwrite one of Maya's own global procedures, which can disrupt the way Maya works. The safest bet is to name the global procedure using your own name or initials in a way that will most likely not interfere with one of Maya's global procedures.

Scripts containing global procedures can be saved in the My DocumentsMayaScripts folder on your local drive. These scripts should load automatically when Maya starts, making the procedures available for use within a Maya session.

You can source a procedure using the File menu in the Script Editor. This loads the procedures contained within a MEL script file into memory so they are available when working in Maya. You can then run the procedure by typing the name of the procedure on the command line. The author of the procedure will usually include instructions on how to use the procedure within comment tags at the top of the procedure. When you source a procedure, you won't notice an immediate change in Maya until you actually call the procedure in a script or on the command line. It's usually a good idea to open the script file that contains the procedure and read the instructions at the top before trying to source and run the procedure.

Use Python

Python is a scripting language developed independently of Maya. Python is used for a wide variety of computing tasks well beyond 3D animation and modeling. In recent years, Python has been incorporated into a number of 3D animation packages, making it easier for the various software programs to work together within a studio pipeline.

Use Maya Commands within Python

If you are familiar with Python, you can use Python to run MEL commands within a Python script. To run or write a Python script within Maya, switch to the Python tab in the Script Editor. This tells Maya to interpret any commands as Python and not MEL. Likewise, you can switch the command line and the command shell to Python mode.

Before you can use Maya commands within Python scripts, you must first import the Maya commands into Python. To do this, switch to the Python tab in the Script Editor and type:

import maya.cmds

Press the Enter key to execute the command.

You can test a Maya command by typing the following:

maya.cmds.sphere (radius=1, name='myBall')

Note that the syntax for the Python command is different from the MEL syntax. Apostrophes are used around the myBall variable instead of quotes or accent marks, and the line does not end in a semicolon.

The Bottom Line

Use a MEL command.

MEL commands are used to perform many tasks within Maya. There are numerous ways to enter MEL commands in the Maya interface. These include the command shell, the command line, and the Script Editor.

Master it

Create a polygon cube using the command shell. Create a NURBS cone using the command line. Create a polygonSphere using the Script Editor.

Use MEL scripting techniques.

Many basic MEL techniques can be used to reduce the number of repetitive tasks performed during a Maya session. Using commands, conditional statements, and loops, you can make simple scripts that make working in Maya faster and more efficient.

Master it

Write a more efficient version of the mySpriteScript file that automatically selects all of the nParticle objects in a scene without the need for a conditional statement to test the type of the selected nodes.

Create a procedure.

Procedures are sections of code that can be called upon at any time within a script. Procedures can help make longer scripts more efficient by eliminating the need to repeat sections of code.

Master it

Write a procedure that adds an expression to selected objects that use the noise function to randomly scale objects over time.

Use Python.

Python can be used within the Script Editor to execute Python commands or to execute MEL commands within a Python script. The Maya commands must be imported at the start of Python script if you want to incorporate MEL into the Python code.

Master it

Use Python to make a NURBS torus.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset