Mel scripting

In the Outliner, select the blue_nParticle object, and open its Attribute Editor to the blue_nParticleShape tab. 3. Scroll down and expand the Add Dynamic Attributes section below the Per Particle Array Attributes list. 4. Click the General button to open the Add Attribute window. 5. In the Add Attribute window, switch to the Particle tab. 6. Scroll toward the bottom of the list, and Ctrl+click spriteNumPP, spriteScaleXPP, spriteScaleYPP, and spriteTwistPP. The PP indicates that each attribute is a per-particle attribute (see Figure€17.9).

pdf105 trang | Chia sẻ: tlsuongmuoi | Lượt xem: 2449 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Mel scripting, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
916 | Chapter 17 Mel sCrIPtIng 2. In the Outliner, select the blue_nParticle object, and open its Attribute Editor to the blue_nParticleShape tab. 3. Scroll down and expand the Add Dynamic Attributes section below the Per Particle Array Attributes list. 4. Click the General button to open the Add Attribute window. 5. In the Add Attribute window, switch to the Particle tab. 6. Scroll toward the bottom of the list, and Ctrl+click spriteNumPP, spriteScaleXPP, spriteScaleYPP, and spriteTwistPP. The PP indicates that each attribute is a per-particle attribute (see Figure 17.9). 7. 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. 8. 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. Figure 17.9 Select the per- particle sprite attributes in the Add Attri- bute menu. Figure 17.10 The Script Editor reveals the syntax for adding the per-particle array attributes. Mel sCrIPtIng teChnIques | 917 9. Edit the mySpriteScript.mel file so it reads as follows: //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; //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];. 10. Test the script. First, save the mySpriteScript.mel file in the text editor. Save the Maya scene as shot1_v04.ma. 11. 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 chapter17\ scenes folder on the DVD. 12. 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. 13. Press 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? 14. In the Attribute Editor, click the pink_nParticle tab to switch to the nParticle’s trans- form node. 15. 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). 918 | Chapter 17 Mel sCrIPtIng 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 •u always select the shape nodes of the nParticles every time you use the script. You can build in a command that ensures that the attributes are applied to the •u shape node. The second option is more desirable and actually involves little coding. 16. Edit the text at the top of the script in the mySpriteScript.mel file so it reads as follows: //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 com- mand moves the current selection down one node (notice the -d flag, which stands for direc- tion, 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 hierar- chy. Later you’ll see how to add a conditional statement so the user will get an error if they pick Figure 17.11 The per-particle array attributes have been added to the transform node by mistake. Mel sCrIPtIng teChnIques | 919 anything other than an nParticle object. Anticipating user errors is a big part of becoming an accomplished MEL script author. Repeat steps 10–12 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. Save the mySpriteScript.mel file. Adding 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 chapter17\scenes 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. 4. In the Hypershade, right-click spriteShade, and choose Assign Material To Selection. 5. Rewind and play the animation to frame 50. The sprites appear as blue squares. 6. Open the Attribute Editor for spriteShade. 7. Add a file texture node to the Color channel by clicking the checkered box next to Color and choosing File from the 2D Textures category under the Maya heading. 8. In the options for the file node, click the folder next to Image Name, and select the logo.1.iff file from the chapter17\sourceimages folder on the DVD. Figure 17.12 When you correct the script, the new attributes are added to the Per Particle (Array) Attributes section of the pink_nPar- ticleShape tab. 920 | Chapter 17 Mel sCrIPtIng 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: 1. Open the Attribute Editor for the file1 node that has been applied to the Color channel of spriteShade. 2. Expand the Interactive Sequence Caching options. 3. Turn on Use Interactive Sequence Caching, and use the following settings: Sequence Start: 1 Sequence End: 60 Sequence Increment: 1 4. Turn on the Use Image Sequence option above the Interactive Sequence options (Figure 17.13 shows this). 5. 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. 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 prop- erly on the sprites. 6. Open the Attribute Editor for the blue_nParticleShape node. 7. In the Per Particle (Array) Attributes section, right-click the field next to spriteNumPP, and choose Creation Expression to open the Expression Editor. Figure 17.13 Turn on Use Inter- active Sequence Caching and Use Image Sequence to apply the ani- mated images to the spriteShade material. Mel sCrIPtIng teChnIques | 921 8. In the Expression section of the Expression Editor, type the following: spriteNumPP=1; 9. Click the Create button to make the expression. 10. In the Expression Editor, click the Runtime Before Dynamics button to switch to runtime expression mode. 11. Type the following: spriteNumPP=spriteNumPP+1; 12. Click the Create button to make the expression. 13. 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). 14. 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 chapter17\ scenes folder on the DVD. Adding Expressions Using MEL The previous section described the standard manner in which the spriteNumPP attribute is used to animate sprite images. Imagine going through that whole process for multiple nParticle objects. This is where scripting with MEL can take much of the tedium out of working in Maya. In this section, you’ll add commands to your MEL script that will apply the same expressions to all selected nParticles in a scene. 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 chapter17\scenes directory on the DVD. Open the mySpriteScript.mel file in a text editor. Figure 17.14 The snowflake logo is animated as each sprite nParticle is born into the scene. 922 | Chapter 17 Mel sCrIPtIng 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 as follows: //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 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;” -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 nParticle object. 3. Test the script by selecting the pink_nParticle object in the Outliner. 4. Copy all the text in the text file, and paste it into the work area of the Script Editor. Press the Enter key. Mel sCrIPtIng teChnIques | 923 5. In the Hypershade, select spriteShade, and apply it to the pink_nParticle object. 6. 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 ver- sion of the scene. 7. 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; 8. Edit the runtime before dynamics expression. Add the following line, and click the Edit button: spriteTwistPP=spriteTwistPP+1; 9. Rewind and play the scene. The blue_nParticles are rotated randomly as they fly through the scene. They are also sized randomly. 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. Figure 17.15 Edit the creation expression for the blue_nParticleShape in the Expression Editor. 924 | Chapter 17 Mel sCrIPtIng 10. 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; \r\n\r\nspriteTwistPP=rand(360); \r\n\r\nspriteScaleXPP=rand(.5,2); \r\nspriteScaleYPP=spriteScaleXPP;“ -c $mySelection[0]; dynExpression -s “spriteNumPP=spriteNumPP+1; \r\n\r\nspriteTwistPP=spriteTwistPP+1;“ -rbd $mySelection[0]; Figure 17.16 shows the script text in a text editor. The \r and \n that you see in the expres- sion stand for “return” (\r) and “newline” (\n). 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. 11. 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. 12. Select the last lines that add the expressions in the Script Editor, and press the Enter key (see Figure 17.17). By selecting just the last few lines and pressing Enter, you will execute only those lines that add the expressions. At this point, the other lines in the script have already been applied to the pink_nParticle object. To see a version of the scene, open the shot1_v06.ma scene from the chapter17\scenes folder on the DVD. Figure 17.16 Edit the text in the MEL script to update the expressions. Mel sCrIPtIng teChnIques | 925 Creating 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 com- mands 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 com- mon 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. Figure 17.17 The lines that add the expres- sion commands are highlighted in the Script Editor. Pressing the Enter key executes just the selected lines of code. 926 | Chapter 17 Mel sCrIPtIng 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 backtick marks within the parentheses. These backtick 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 backtick 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. 4. 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]; Mel sCrIPtIng teChnIques | 927 addAttr -ln spriteTwistPP -dt doubleArray $mySelection[0]; addAttr -ln spriteTwistPP0 -dt doubleArray $mySelection[0]; //add expressions for per-particle attributes dynExpression -s “spriteNumPP=1;\r\n\r\nspriteTwistPP=rand(360); \r\n\r\nspriteScaleXPP=rand(.5,2); \r\nspriteScaleYPP=spriteScaleXPP;” -c $mySelection[0]; dynExpression -s “spriteNumPP=spriteNumPP+1; \r\n\r\nspriteTwistPP=spriteTwistPP+1;” -rbd $mySelection[0]; } else { error “Sorry, you must select an nParticle to use this script”; } 5. To test the script, open the shot2_v01.ma scene from the chapter17\scenes directory on the DVD. This is the second shot in the commercial spot. It uses five nParticle objects. 6. Select the orange_nParticle object in the Outliner. 7. Select and copy all the text in the mySpriteScript.mel file, and paste it into the Script Editor. 8. Press the Enter key to run the script. If there are no errors, the orange_nParticle object will turn into a sprite. 9. 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. 10. Save the mySpriteScript.mel file in your text editor. Remember to assign the spriteShade shader to the orange_nParticle and turn on Hardware Texturing in the Shading menu of the viewport; otherwise, you will not see the image on the sprites applied to the orange_nParticle. Creating 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 } 928 | Chapter 17 Mel sCrIPtIng There are three commands within the parentheses separated by semicolons: The first command creates a variable named •u $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 •u $i is less than a particular value, the loop continues to run. The third statement in the parentheses increases the variable •u $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. Open the mySpriteScript.mel file in your text editor. Add the text to create the loop in the script. The following shows where this text is placed within the script: //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 current 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;\r\n\r\nspriteTwistPP=rand(360); \r\n\r\nspriteScaleXPP=rand(.5,2); \r\nspriteScaleYPP=spriteScaleXPP;” -c $mySelection[$i]; dynExpression -s “spriteNumPP=spriteNumPP+1; \r\n\r\nspriteTwistPP=spriteTwistPP+1;” Mel sCrIPtIng teChnIques | 929 -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, $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 vari- able 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. 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 as follows: //Turn on Depth Sort setAttr ($mySelection[$i]+”.depthSort”) 1; Figure 17.18 shows the final script as it appears in Notepad. Figure 17.18 The final script as it appears in Notepad 930 | Chapter 17 Mel sCrIPtIng Save the mySpriteScript.mel file to your local directory. Save the script in the Maya\scripts directory found in the My Documents folder. Scripts are usually saved in the My Documents\Maya\scripts folder on your local drive. You may also save scripts to the My Documents\Maya\2010\scripts directory (Mac users can place their scripts in the Users\Shared\Autodesk\maya\2011-x64\scripts folder), 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 chapter17\ mel directory on the DVD. 1. To test the script, open the shot2_v01.ma scene from the chapter17\scenes folder on the DVD. If it is already open, reload the scene. 2. In the Outliner, Shift+click the green_nParticle, red_nParticle, yellow_nParticle, purple_nParticle, and orange_nParticle objects. 3. Open the Script Editor, and choose File  Load Script. 4. Find the script on your local drive, and choose it. 5. 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 chapter17\mel 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. 6. Select the nParticle objects, open the Hypershade, and apply the spriteShade material to the selected nParticle objects. 7. Save the scene as shot2_v02.ma. To see a finished version of the scene, open the shot2_v02.ma scene from the chapter17\ scenes folder on the DVD. Make sure Hardware Texturing is on so that you can see the images on the sprites. 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. Create a Shelf Button for a Script You can create a shelf button from selected code in the Script Editor. If the script is something you think you’ll use fairly often in a scene, a shelf button can save even more time. Whenever you need to run the script, you simply click the shelf button. To create a shelf button, switch to the Custom Shelf tab, select the code you want to make into a button, and choose File  Save Script To Shelf. Give the shelf a name as descriptive as you can within the six-character limit. Remember to save the shelves before quitting Maya so that the buttons appear the next time you open Maya. To do this, click the black down-arrow button to the left of the shelves, and choose Save All Shelves. Procedures A complex MEL script often consists 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. ProCedures | 931 Making 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 chapter17\mel 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 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 trans- lation 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. 3. Create a number of polygon cubes, and place them randomly in the scene. 4. 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; then press the Enter key. 5. Rewind and play the scene. The cubes should shake randomly around their original location. 6. 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 ; 932 | Chapter 17 Mel sCrIPtIng 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. 7. Create a new scene in Maya. 8. Create a number of randomly placed polygon cubes. 9. 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 proce- dure. In other words, you’ve made this snippet of code available as part of Maya. 10. 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. 11. Save this file as shakeMeProc.mel. To see a version, open the shakeMeProc.mel file from the chapter17\mel folder on the DVD. Using 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 ran- dom value. 1. Open a text editor to a new file, and type 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 chapter17\mel folder. 3. Paste this text before the lines you have typed in the text editor so the script looks like the following: proc shakeMe(){ ProCedures | 933 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); 4. 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. 5. 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`; 6. 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 ran- dom 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. 7. 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 ; 934 | Chapter 17 Mel sCrIPtIng 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 vari- ables 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”; 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 ; ProCedures | 935 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 pro- cedure and passes the procedure the random value held in the $randVal variable. In the proce- dure, the $num variable is set to be equivalent to the $randVal value, and the procedure is executed. To see a finished version of the script, open the shakeMeProc_v02.mel file from the chapter17\ mel 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 over- write 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 Documents\Maya\Scripts folder on your local drive directory (Mac users can place their scripts in the Users\Shared\Autodesk\ maya\2011-x64\scripts folder). 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 proce- dures 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. 936 | Chapter 17 Mel sCrIPtIng Using Maya Commands Within 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. 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 the following: 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. Mel and python in action: Molecular Maya Maya has a huge reputation as the industry standard for creating visual effects for film, commer- cials, and television. Most studios in Hollywood use Maya as its primary 3D application. But did you know that scientists, specifically molecular biologists, are starting to use Maya to help them visualize their own research in life processes? For many years, scientists using Maya’s animation, dynamic, and rendering capabilities to as a visualization tool, struggled with trying to accurately represent the molecular structures and inter- actions of proteins within the living cell. This involved using a number of scripts and other types of visualization software and a lot of tedious hard work. Most of the time was spent on getting structures of molecules such as DNA into Maya, and then we were limited by how we could display the structure itself to spheres or particles. In the past year, this has all changed thanks to the efforts of Harvard Medical School scientist Gaël McGill and extremely talented Python programmer and biologist Campbell Strong. Together they have created a free plug-in for Maya called Molecular Maya (or mMaya). This plug-in was created using MEL and Python scripting, and it makes many of the tasks that used to be overwhelmingly time-consuming as easy as clicking a button. usIng Maya CoMMands WIthIn Python | 937 Using MEL and Python, McGill and Strong have created a customized interface that appears when- ever Maya starts. The interface consists of a number of panels with tabs and settings, very similar to the Attribute Editor. Through the interface you can load the protein structure that you need directly into Maya. The protein structures are contained in a specially formatted text file known as a Protein Data Bank (PDB) file. What’s more, if you don’t have the file on your computer, the Molecular Maya interface can connect directly to the online Protein Data Bank at www.pdb.org, and if you know the specific protein ID number, you can type this into molecular Maya, and, without having to leave Maya, the protein will be downloaded and appear in the viewport within just a few seconds. Beyond just acquiring the protein, Molecular Maya allows you to easily switch between various represen- tational styles so you can view the structure as ribbons, as ball and stick, or as a mesh. Molecular Maya automatically creates these various representations and puts them in a group. The heart of the structure uses nParticles, and currently a system is being developed to take advantage of Maya’s nDynamics so that interactions between molecular structures can be accurately simulated. The goal of this plug-in is to allow scientists to take advantage of the animation and dynamic capa- bilities of Maya so that they can, even with limited experience using Maya, import whatever protein they may be working on and create and render very simple animations. Artists like myself can spend more time creating visualizations of molecular processes for scientists and less time struggling with importing the structures. All of this is made possible thanks to MEL and Python. Everything from the interface to the web connectivity to the modeling and dynamics is handled with well-written MEL and Python scripts and allows Maya to be utilized for amazing purposes beyond the entertainment industry. As an artist, you may be interested only in creating simple time-saving scripts; however, it’s impor- tant to understand that the power of MEL and Python can allow you to accomplish almost anything in Maya. The Molecular Maya plug-in is available as a free download from www.molecularmovies.org. 938 | Chapter 17 Mel sCrIPtIng 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 create 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 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 the Python scripting interface Python can be used within the Script Editor to execute Python commands or to execute MEL commands within a Python script. The Maya com- mands 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. Appendix A The Bottom Line Chapter 1: Working in Maya Understand transform and shape nodes DAG nodes have both a transform node and a shape node. The transform node tells where an object is located; the shape node describes how it is made. Nodes can be parented to each other to form a hierarchy. Master it Arrange the nodes in the miniGun_v03.ma file in a hierarchical structure so the barrels of the guns can rotate on their z-axis, the guns can be aimed independently, and the guns rotate with the turret. Solution In the Outliner, MMB-drag the left_gunBarrels node onto the left_housing node. MMB-drag the left housing node onto left_mount, and then MMB-drag the left mount onto the turret node. Do the same for the right gunBarrels, housing, and mount nodes. Graph the node structure on the Hypergraph, and examine the network. Create a project Creating a project directory structure keeps Maya scene files and con- nected external files organized to ensure the animation project is efficient. Master it Create a new project named Test, but make sure the project has only the scene, source images, and data subfolders. Solution Use the Options box in the Create New Project command to make a new project named Test; leave all the fields blank except for scenes, source images, and data. Name the folders in these fields scenes, sourceImages, and data, respectively. Use assets An asset is a way to organize the attributes of any number of specified nodes so that their attributes are easily accessible in the Channel Box. This means that members of each team in a pipeline only need to see and edit the attributes they need to get their job done, thus streamlining production. Master it Create an asset from the nodes in the miniGun_v04.ma scene in the chapter1\ scenes folder. Make sure that only the Y rotation of the turret, the X rotation of the guns, and the Z rotation of the gun barrels are available to the animator. Solution Create a container that holds the turretAim curve and turret nodes (and their child nodes). Use the Asset Editor to publish the Rotate Y, Rotate X, and Barrel Spin attri- butes of the turretAim curve node to the container. Set the container to black box mode so the animator can’t access any of the attributes of the contained nodes. 940 | appeNDIX a the BottoM lIne Create file references File references can be used so that as part of the team works on a model, the other members of the team can use it in the scene. As changes to the original file are made, the referenced file in other scenes will update automatically. Master it Create a file reference for the miniGun_v04.ma scene; create a proxy from the miniGun_loRes.ma scene. Solution Create a new scene, and reference the miniGun_v04.ma file in the chapter1\ scenes directory. Use the Reference Editor to make a proxy from the miniGun_loRes .ma scene in the same folder on the DVD. Chapter 2: Virtual Film Making with Maya Cameras Determine the image size and film speed of the camera You should determine the final image size of your render at the earliest possible stage in a project. The size will affect every- thing from texture resolution to render time. Maya has a number of presets that you can use to set the image resolution. Master it Set up an animation that will be rendered to be displayed on a high-definition progressive-scan television. Solution Open

Các file đính kèm theo tài liệu này:

  • pdfmastering_autodesk_maya_201100010_8312.pdf
Tài liệu liên quan