Maya 3D - Mel Scripting
Maya 3D - Mel Scripting
APPENDIX A
MEL Scripting
by Jesse Andrewartha and Matt Ontiveros
his appendix is divided into two parts.The first section, An Introduction to MEL Scripting, written by Jesse Andrewartha, is a basic introduction to some MEL concepts. Jesse has added example scripts for you to experiment with, along with explanations of tools and descriptions of various MEL functions.This section of the appendix gives you an idea of how Maya Embedded Language (MEL) is organized and provides insight into the proper syntax and operations of MEL. The second section, Custom Window Control Setups, is written by Matt Ontiveros. It takes you to the next level of MEL, in that you can put to use the introduction material of the first section to see how MEL works for building a custom window and controls for a character. The main thing to realize is that this chapter is an introduction to MEL and is by no means the only approach to the tool.You should further your study in this area of Maya by gathering as much information and examples as possible in MEL and scripting.The more you use MEL, the better you will understand its potential. Soon you will be able to write your own scripts for your own projects that not only create solutions, but ones that are truly unique.That is the goal of MEL.
a p p e n d i x A : MEL scripting
Figure A.1
Located in the lower-left corner of the Maya interface, the command line allows simple execution of one-line commands without having to open the Script Editor window.
Command line
A typical example of a script used in the command line, to move a primitive sphere, Ball, 90 degrees around the Z axis, would be written in the command line as follows:
Rotate r 0 0 90 Ball;
Figure A.2
Accessible either through the Windows menu or by clicking the Script Editor button, located in the lower-right side of the Maya interface, the Script Editor allows the execution of highly complex scripts, and records all actions in MEL.
The Script Editor is also accessed from the UI, represented by a small button immediately to the right of the playback controls at the base of the screen. The Script Editor is split into two parts.The bottom portion, or Input Field, is used to enter MEL scripts, and the top portion, or History Field, displays executed MEL scripts and the corresponding results or errors.You can also use the Script Editor to save, import, and find script files from your database. When an action is executed using the Maya UI, the corresponding MEL scripts used to carry out this same action are usually echoed in the Script Editors History Field.To ensure that all MEL commands are echoed to the Script Editor, click the option Echo All Commands, which can be executed through Script Editor, Edit, Echo All Commands. This provides an excellent method to become familiar with MEL commands; use the Maya UI to perform your work and observe the corresponding MEL as it appears in the Script Editor.With the Echo All Commands option on, the MEL commands for almost any action that the user executes are displayed in the History Field. Note that there is not always a one-to-one correspondence between what the user executes and what is relayed to the Script Editor, regardless of whether the Echo All Commands option is on or off. It is often useful to copy commands out of the History Field and paste them in the Shelves or in the Input Field (Shelves are discussed in more detail later in this chapter). The copied script can be executed, or the information you need can be pasted into other scripts to save time in typing.
a p p e n d i x A : MEL scripting
is where the expression is written and displayed. It is often better to write the MEL in the Script Editor or another text editor, such as jot, vi, or Word, and then copy and paste the text into the Expression Editor. If the expression is executed, or if the text is accidentally deleted from the interface, it is easy to repaste from the Script Editor and re-write the script.
Figure A.3
The Expression Editor allows the user to assign MEL commands to specific objects or groups.
A.1.3.1 Hotkeys
One of the easiest ways to customize Maya is to create custom hotkeys. Hotkeys are keyboard keys that execute a MEL command, and enable the user to instantly access any functionality within Maya with a single keystroke. User-created MEL scripts may be added to the hotkeys as required. To create a new hotkey, select Options, Customize UI, Hotkeys.The Hotkey Editor will then appear, in which new hotkeys can be assigned and created.
Figure A.4
Keeping in line with Mayas complete extensibility, hotkeys may be customized to meet specific needs. The Hotkey Editor is used to add or remove hotkeys.
You can also create a button for writing MEL scripts. For instance, suppose you want to create a series of spheres that are moved 25 units in the X axis, rotated 90 degrees in the Z axis, and then made into a hemisphere by limiting the endSweep attribute. Rather than repeat this series of steps every time you need this primitive, simply highlight and drag to the Shelf the script that was relayed to the Script Editor while you initially created the sphere. After it goes to the Shelf, it becomes a button.When you click the button, it executes the associated script and creates another sphere.You can do this with any script. Indeed, you can even create a fully rigged skeleton (be careful not to delete the history!), highlight the corresponding MEL in the Script Editor, and drag it to the Shelf. Now that it is a button, you can click it to create another identical skeleton at any time throughout your project.
a p p e n d i x A : MEL scripting
Having all Shelf buttons on a single Shelf can become confusing, and users may also simply run out of room for all the new buttons they create for different tasks. Maya enables the creation of multiple Shelves, which can be visualized as a drawer of a filing cabinet, each folder containing its own bundle of buttons.You can easily create new Shelves through Options, Customize UI, Shelves. Using this tool, you can make Shelves that organize the Shelf area into different types of tools and functions.
10
Highlight the text of the script, and then press the Enter key on the alphanumeric keypad to execute. Using the Enter key on the main keyboard executes the script and removes it from the Script Editor. By using the Enter key on the alphanumeric keypad you can make corrections if the script returns an error.This method is preferable because the script is kept in the Script Editor after it is executed. If you accidentally lose your script by pressing the main Enter key, you can always access it from the History Field. If you ever need to execute this script again, you dont have to re-type the script. Simply drag the highlighted text, using the middle mouse button, to Mayas Shelf. Once there, it becomes a button. MEL is also capable of quite complex procedures that can create everything from custom special effects to character animation.This requires a
a p p e n d i x A : MEL scripting
11
new level of scripting, involving a whole range of commands and functions to create the desired effect.To create more complex MEL scripts, you need to define various inputs to feed the program the required parameters. A number of data types are used to input values into MEL scripts.The inputs can be classified in one of the following categories: n Variables n Comment markers n Operators n Flow controls
A.1.4.1 Variables
A variable is a symbolic name that represents a modifiable value. All variables begin with a dollar sign, cannot include spaces or special characters, and are case sensitive. Underscores can be used, but only as long as the variable name does not begin with a number. Declaring a variable indicates that a variable with a certain name is a certain data type. Assigning a variable gives a declared variable a specific value.You should always declare a variable before it is used in the script. Not doing so incurs an error when the script is executed. MEL does have six predefined variables that do not need to be declared, but their values cannot be changed.The On,Yes, and True predefined variables represent 1; the Off, No, and False predefined variables represent 0.These variables are most often used in Boolean, or true and false, statements. Many MEL commands return a value.To capture this return value, enclose a MEL command within left-hand single quotes ().This button is located to the left of the #1 key on the keyboard.You can then assign this output to a variable. Consider the following command:
String $solar[]; $solar = particle p 5 0 5 name Sun; print($solar);
Getting a specified script to return a value can also be very valuable when creating scripts and troubleshooting routines, and can assist the user in understanding how MEL functions. MEL contains a number of different types of variables, and there are several similarities among the variables for the data types.The int, float, and string variables are the most frequently used, but there are also vector
12
and matrix variables. Use of the assignment operator, represented by the equal sign (=), sets the value for a variable.The variable to the left of the equal sign is assigned to the value to the right of the equal sign. It is not always necessary to define a variable type when a value is declared, but MEL will assume any given variable is a float variable unless otherwise stated.
A.1.4.1.1 int and float Variables int and float variables consist of numbers.The former are integers, or full numbers, and the latter are fractional numbers. Examples of an int and float variable follow:
int $valueA = 5; float $valueB = 5.6;
A.1.4.1.2 String Variables String variables are sequences of alphabetical, numerical, or special characters.The + operator can be combined with strings. An example of a string variable, to create a title with contents Minds Eye Media, follows:
string $Edge = Media; string $title = Minds + Eye + $Edge;
Vector variables contain numeric data grouped into a set of three components. For example, vector variables may hold RGB or XYZ data.To access the first, second, or third component of a vector, use a period (.) followed by x, y, or z. However, if the user attempts to assign a number to a vector component, an error will be incurred. Consider the following example:
vector $offset = <<5, float $componentOne = float $componentTwo = float $componentThree //not: $offset = 3; //You cannot redeclare with this value. 10, 15>>; $offset.x; $offset.y; = $offset.z; // Assigned 5 // Assigned 10 // Assigned 15
An array variable is an array of int, float, string, or vector variable types. For example, the following script comprises three string variables, and the three print declarations will print first\n, second\n, and third\n, consecutively:
string $array[3] = { one\n, two\n, three\n}; print ($array[0]); print ($array[1]); print ($array[2]);
a p p e n d i x A : MEL scripting
13
Array variables will increase automatically as required, and the user can also remove elements, using the Clear function. For example, the output of the preceding script is as follows:
There were 3 fish. But now there are 0. string $fish[3] = {big, small, tiny}; print (There were + size($fish) + fish.\n); clear ($hats); print (But now there are + size($fish) + .\n);
Matrix variables are arrays of float arrays, or they can be visualized as a two-dimensional array of floats. Unlike arrays, however, the size of a matrix must be specified when it is created and cannot be altered thereafter. Any attempt to do so will incur an error. For example, the following script contains two separate float arrays:
The first float array consists of 2, 24, 16.25, and 1, and the second consists of 2.7, 5, and 576.
A.1.4.1.6 Variables in Action
These different variables can be mixed within a given script to vary its results.The following script is used frequently to create vibration in an affected object.This script is run as an expression and must be put in to the Expression Editor. Make sure you have a sphere named sphere1. Sphere1 must be selected so the script is applied to the sphere1 node in the Expression Editor:
This script works by stating that for any given axis (X,Y, or Z), the object (sphere1) will translate random values between 1 and 1. But rather than actually moving between the different positions, it literally jumps from point to point.The speed of this jumping also cannot be altered with this script.To set the motion between points and to be able to manipulate the speed of vibration, a new script needs to be created and entered into the Expression Editor. Comments have been provided to explain the function of the script as it progresses (use of // in a script allows these notes; anything included after this operator is ignored by MEL):
14
// This section uses float variables to define the values for the // amplitude and frequency of the vibration, and also the offset in the // X and the Y axis. float float float float $amplitude $frequency $xoffset = $yoffset = = 2; = 5; 11; 22;
// In this section, a vector variable is used to define $noise, which // is then defined as a float variable as $amplitude * dnoise($noise). // vector $noise = <<time, time + $xoffset, time + $yoffset>> * $frequency; // In this section, the dnoise is a function that actually replaces a //rand statement and prevents the object from jumping from one position // // to another. $noise = $amplitude * dnoise($noise); sphere1.translateX = $noise.x; sphere1.translateY = $noise.y; sphere1.translateZ = $noise.z;
When executed, this script creates a sphere that will automatically vibrate over time.You can easily change the amplitude and the frequency of the vibration by changing the value of any of the float variables. This particular script has been used to create a sea of molecules that vibrate as they swirl through the molecular soup. Animating these individually using traditional keyframing methods would have been prohibitively time consuming and not necessarily successful. Applying a script such as this automates simple movement such as vibration, which is fluid and difficult to keyframe by hand. This script is also an example of an expression that is executed via the Expression Editor. In the viewport or Hypergraph, select the object to be jittered and open the Script Editor.Type the script into the bottom section of the Editor. It is possible to enter the text into the Expression Editor directly, but Maya will delete the text if the script is erroneous. Open the Expression Editor and drag the script from the Script Editor
a p p e n d i x A : MEL scripting
15
into the Expression Editor using the middle mouse button. Dragging the text from the Script Editor guards against accidental deletion and enables the expression to be saved as a MEL file. After the expression is entered, click Create, and the script is applied to the object.
A.1.4.3 Operators
An operator sets a value to a variable or specifies values or relationships. Simply put, an operator is a symbol, such as the following: =, *, /, %Etc. An equal sign can be used to assign a variable.The operator in the following script is the equals symbol (=):
string $test = I am a operator
The symbol is known as an assignment type.You may come across other types such as arithmetic operators:
int $Test = 3 + 5; //Result: 8
16
The plus sign (+) is the arithmetic operator. Other types of operators are comparison and conditional. Here is an example of a comparison or relational operator:
If (-3.6 < 1) print (true\n); // True
A.1.4.5 Procedures
A procedure is a grouping of MEL commands that can be executed by entering one single command.This is an especially helpful tool, particularly in more advanced scripts that require multiple steps. Furthermore, procedures enable the user to store custom macros and tools in memory, which can then be called with a single command. Procedures have unlimited possibilities in their potential for use, and almost any number of commands can be brought together and executed as a procedure. All of Mayas clip effects, including lightning, fire, and hair, are created using procedures designed to create special effects and dynamics. Transforming a group of commands into a procedure is a remarkably simple process.The procedure can be written directly in the Script Editor, in the same way as non-procedural scripts are entered.The normal form for a MEL procedure is as follows:
global proc procedureName( ) { MELcommands; }
This procedure consists of several parts.The first line declares the global procedure by global proc, which is then followed by the name of that procedure. A global procedure means that it can be seen from anywhere in Mayait is globally available. Most procedures begin with these words.The name of the procedure can be anything, provided it contains no spaces and will be the name that is typed to execute the procedure. The MEL commands are the commands that the procedure will execute.The MEL commands are contained within parentheses, which denote the beginning and end of a procedure. Therefore, a simple procedure that prints the file name of the current Maya file would appear as follows:
a p p e n d i x A : MEL scripting
17
A.1.4.5.1 Entering Procedures in Maya All procedures in Maya must be declared, a process that loads the procedures into memory.This is akin to telling Maya about the procedure so that you can then tell it to execute the commands. Procedures must be declared regardless of how they were created.With the rename script used as above, the workflow to execute this script is straightforward. Simply enter the script into the lower half of the Script Editor and press the alphanumeric Enter key. With any normal script, this would cause the commands to be executed. But with a procedure, this loads the commands into Mayas memory, to be called upon at any time.To execute, key into the lower half of the Script Editor the global procs namein this case, fNamefollowed by a semicolon. Press the alphanumeric Enter key, and the commands execute.You will see that the file name is printed in the top half of the Script Editor as a result.
MEL can also be used to extend the procedure beyond just an execution of MEL commands with no further input from the user. Arguments are values that are supplied to the procedure when it is executedthat is, they are essentially variables.This means that a variable is declared in the argument.You will then assign it a value when you call on the procedure. At this point the argument will be inserted into the script at each instance the variable appears. Each argument consists of an argument type and name, and multiple arguments can be used in a procedure.To execute a procedure that has arguments, you must include the values that you want to assign to the arguments. An example of arguments in a procedure follows:
Global proc hiValue(int $value, string $person) { string $greeting = Hi + $person + , number + $value + .\n; print ($greeting); }
18
For the procedure to work, values to be assigned to the arguments must be included: n If you simply enter n If you enter number 3.
hiValue;, Maya
Many simple yet useful procedures can be utilized in everyday workflow. Several are included as examples in this book and include natural phenomena such as lightning and fire.
A.1.4.5.2 clipFX: Special Effects with Procedures clipFX is the name given to a series of prewritten procedures that are used to create everything from natural phenomena such as lightning, to fire, hair, and other effects that are difficult to achieve by experimentation alone. Many clipFX were written by Alias|Wavefront to assist Maya customers, and they are created in a way that makes them accessible to any level of Maya user.
clipFX procedures are also designed to be customizable, and they feature attributes that can be altered to get the desired effect.The lightning script, for example, enables the user to adjust the thickness and noise of the bolt. Many clipFX have their own interfaces, which makes them very capable and user friendly.The following three clipFX are best known: n Fire clipFX n ArcLightning clipFX n Bubbles clipFX
A.1.4.5.2.1 Fire clipFX
The fire script is a favorite and produces a realistic flame that is fully user customizable. One or more objects can be set alight in any scene, independent of hierarchy; however, keep in mind that the effect relies on dense particle emissions and may quickly choke the computer if applied to too many objects.
a p p e n d i x A : MEL scripting
19
Figure A.7
A wireframe and fully rendered view of fire applied to a sphere.
To execute Fire, open the Script Editor and go to File, Open Script. Find the fire.mel file and open it.The script will appear in the bottom half of the Script Editor. Simply highlight the entire script and press the alphanumeric Enter key.This loads the script into the computers memory, where it will be stored until the script is executed, or called.To call the script, type fire; in the bottom half of the Script Editor and press the alphanumeric Enter key. Nothing will visibly change in the viewport, but the Script Editor will return several lines of script to confirm that the Fire clipFX procedure has been applied to the selected objects.To see the Fire procedure in action, first add a light to the scene; the effect may be flat and unrealistic without some form of lighting.The fire is a software-rendered effect and may be viewed by rendering in the Render View, accessed by selecting Window, Rendering Editors, Render View. RMB in the Render View Window and select Render, Persp in the pop-up menu.
A.1.4.5.2.2 ArcLightning clipFX Unlike other lightning creation scripts,
ArcLightning stands out because of its realism and its animatability. ArcLightning is actually geometry that terminates at each end with a bone and joint arrangement, which allows for easy placement and direction of the bolt.The lightning also has a number of attributes that can be altered to customize the effects appearance, including spikes, thickness, and noise.
20
Figure A.8
The ArcLightning clipFX in action. In this scene, several lightning bolts have been added and animated to create realistic electrocution of two sausages!
To execute the ArcLightning clipFX procedure, open the Script Editor and go to File, Open Script. Find the arclightning.mel file and open it. A short script will appear in the bottom section of the Script Editor. This script will request the location of the script lightning.mel. If the location detailed in the script is inaccurate, retype the path name.Then, simply highlight the entire script and press the alphanumeric Enter key. This will load the script into the computers memory, where it will be stored until called.Type arcLightning; in the bottom half of the Script Editor and press the alphanumeric Enter key. The default lightning will appear in the viewport. Select the bones and reposition them to get the desired effect.To see the ArcLightning clipFX procedure in action, first add a light to the scene; the effect may be flat and unrealistic without some form of lighting.The lightning is a software-rendered effect and may be viewed by rendering in the Render View, accessed by selecting Window, Rendering Editors, Render View. RMB in the Render View Window and select Render, Persp in the pop-up menu.
A.1.4.5.2.3 Bubbles ClipFX The Bubbles script makes all selected
objects in a scene emit bubbles.This particle effect uses images applied to sprites, or image planes, which always face the camera.This also means that the effect must be hardware rendered and composited onto the sequence using a compositing program such as Alias|Wavefronts Composer.
a p p e n d i x A : MEL scripting
21
Figure A.9
Bubbles applied to the surface of a sphere. The particles are actually image planes, or sprites, which always face the camera.
Similarly to the way you created the fire script, to create bubbles open the script in the Script Editor. Highlight the entire script and press Enter on the alphanumeric keypad.This loads the script into memory, at which stage it must be called to be executed.Type bubbles; into the Script Editor, and press Enter on the alphanumeric keypad. Nothing will visibly change in the viewport, but the Script Editor will return several lines of script to confirm that the bubbles have been applied to the selected objects. Play to see the bubbles rise from the selected object(s).The effect must be hardware rendered and may be viewed by rendering in the Hardware Render Buffer, accessed by selecting Window, Rendering Editors, Hardware Render Buffer. Select Attributes to ensure that the render settings are as desired, and then select either Test Render to check a frame or Render Sequence to see your entire animation.
22
surface of 3D objects.When the brush is run over the surface of the object, information from the brush is relayed to the CVs (on NURBS) or the vertices (on polygons).This information visually manifests as the surface points being displaced outward along the normal of the surface, or inward. Hence the surface is deformed and modeled. MEL has become indispensable for extending and maximizing Artisans capabilities. MEL scripts can be created to control every aspect of Artisans functionality.The ability to paint geometry over another surface is just one of the many features made possible with the use of MEL in conjunction with Artisan. It is also possible to paint other objects, such as particle emitters and CVs, by using similar techniques.
Figure A.10
The geometry Cone being painted over the surface of a sphere. This feature uses MEL combined with Artisan to create an invaluable modeling feature.
To paint geometry over a surface, open the scene containing the object that is to be painted. Import the object you want to paint over the surface; for instance, a simple cone, named Cone, which will be painted over a sphere. After you import it, ensure that the object is at the origin; Artisan will not work properly if the painter object is not in position. Find the geometryPaint.mel file and make sure it is in the file ./aw/maya/scripts.When activated through Artisan, Maya will look to the scripts folder in this location to find the geometryPaint script. If the script is not in this file, an error message will be returned. If you do not have this script, it can be downloaded from the CD accompanying
a p p e n d i x A : MEL scripting
23
this book, or from Web sites such as www.highend3d.com. Providing the location of the script is known, this script can also be loaded into the proper folder via Window, General Editors, Plug-In Manager, at which point you should load buildRotationNode.so. After the script is in its proper folder, it can now be activated via Artisan. Go to Modify, Script Paint Tool and click the check box.This will open the tools properties. Click the Setup tab, and in the Tool Setup Cmd field, type geometryPaint. Press Enter, and the script is activated. A second window, Geometry Paint Settings, activates; this window controls the properties of the painted geometry. In the Geometry field, using the cone as the object, type Cone.Then press Enter, and the tool is ready for use. With the object selected, we may now begin painting the sphere. Changing the opacity in the Artisan Tool Settings controls the size of the cone being painted, whereas the grid size in the Geometry Paint Settings controls the density of cones painted. Other objects can also be painted. In the Geometry field in the Geometry Paint Settings, simply type in the names of other objects, separated by a line space. Artisan will randomize between the different objects, creating a more chaotic surface. In this way, an entire forest can be painted, with different types of fully modeled trees as the paint.
24
1. First create a NURBS sphere and name it ball. Bring up the Script Editor and in the input field enter the following:
window title ballRotY; columnLayout; showWindow;
Figure A.11
The window you created with the title ballRotY on the Menu Bar.
2. Highlight the command and press Enter on the numeric keypad to run the script. MEL will create a window titled ballRotY.The columnLayout command is the format in which you want to arrange items in your window.This command will arrange items in rows of columns.The next command just shows the window you have created 3. Now lets create the slider to control the rotation of the sphere in Y.The command is attrFieldSliderGrp.This command creates a slider control that can drive a particular attribute. In this case we will make the slider control the rotation of the ball in Y. 4. In the Script Editor enter the following command:
window title ballRotY; columnLayout; attrFieldSliderGrp min 0 max 360 at ball.ry; showWindow;
What this command creates is first the window and then the slider control.The attrFieldSliderGrp command needs certain flags for it to execute properly.The first flag (min 0) is the point at which you want the minimum value to begin when you slide the slider. The next flag (max 360) is the maximum value you want the slider to stop at.The next flag (at ball.ry) is the node and attribute that you want to control. In this case it is the rotation of the ball in Y from 0 to 360 degrees.
a p p e n d i x A : MEL scripting
25
Figure A.12
The same window ballRotYonly now there is a slider control.
5. By default the slider is labeled ball.translateY. If you change the slider command to attrFieldSliderGrp -l RotateYmin 0 max 360 at ball.ry, the l flag will label the slider RotateY. By default the command includes an automatic menu. If you right-click the field next to Rotate Y in your window, you can set keyframes and driven keys, write expressions, add a texture, or lock the node. Pat yourself on the back; you have created your first control for animation.
Exercise A.2
Lets edit the way your window looks.We can use numerous commands that align and organize the elements in your window. For now we will focus on just a few.The first one is the text command.This command allows you to insert text elements in your windows.You may also use this command to provide space between the elements in the window. 1. Lets expand on the script we already created by inserting text commands. Enter the following in the Script Editor:
window title ballRotY; columnLayout; text l ; text l Ball Spin Control; text l ; attrFieldSliderGrp min 0 max 360 at ball.ry; text l ; showWindow;
If you use the text command with nothing in the quotes for the label(-l) flag, you create a space between elements in your window.
continues
26
2. You can also add a line between elements by using the separator command. Lets rewrite the same script using separators with the width flag to size the line to 500 pixels:
window title ballRotY; columnLayout; text l ; text l Ball Spin Control; text l ; separator w 500; text l ; attrFieldSliderGrp min 0 max 360 at ball.ry; text l ; separator w 500; text l ; showWindow;
Figure A.14
The ballRotY window with separators or lines that break up the window into sections.
Your scripts are getting more complex. Now, on your own add a slider to control the balls translation in Y. Add text and separators to organize your new window. Remember to give this window a new title.
a p p e n d i x A : MEL scripting
27
Before we start making tabs, take a look into a couple of commands that will help you organize what is in the tab.The first command that you should understand is setParent. setParent references a control or layout that is above or at the top of your command hierarchy.This command enables you to add elements or controls to a layout that you have created.This enables you to reference only the part of the window that you want to add an element to. For this example, you are going to use the tabLayout command, and in that layout you will create a tab for each columnLayout. tabLayout is the parent, and for each child you designate under the tabLayout you will have created a tab. 1. In this case each columnLayout will have a tab. Lets first use the setParent command to add elements to only a columnLayout so that you can get the idea of the setParent command. Enter in the following command:
window; columnLayout; text l ; separator w 500; text l ; showWindow;
continues
28
2. Now add another separator and text spaces to this window.With the window you just created still open, enter the following in the Script Editor:
Text l setParent separator setParent Text l setParent ; ..; w 500; ..; ; ..;
Notice that this script adds the text spaces and a separator to the window you originally created.
Figures A.15 and A.16
The before top and after bottom of the window using the setParent command. Notice that the command has created a new text space and separator in the orginal window while the window was still open.
The flag (..) for this command references one level up the hierarchy; in this case, the command columnLayout. If you use a slash character (/) rather than the .. flag, you would reference the top of the hierarchy or the window command.This would be pointless because the window needs a layout command under it so that you would not be able to add separators to just the window. 3. Now lets take this a step further and add tabs to the script you created earlier to rotate a sphere.This time, however, we will create three sliders to rotate the sphere on X,Y,Z and use the setParent command to separate the sliders to their own tabs.To do this, we need to create variables for certain commands.The variables will be seen as objects so that certain flags can operate properly. Remember that you create a variable when you want to store something to call on later. In this case, we will store MEL commands. The comments in the following describe what the script is doing as it is being executed. In the Script Editor enter the following (do not enter the comment descriptions):
// The first line creates a sphere with a radius of 3 units // and names it ball. sphere -r 3 -n ball; // Now lets start building the window. window -t "ballRotXYZ"; // Create the variable with the tabLayout command. string $tabs = 'tabLayout'; // Now we create the variables and sliders for each tab. // Create a variable for each columnLayout, include the // slider command and set the parent. string $child1 = 'columnLayout';
a p p e n d i x A : MEL scripting
29
attrFieldSliderGrp -min 0 -max 360 -at ball.rx; setParent ..; string $child2 = 'columnLayout'; attrFieldSliderGrp -min 0 -max 360 -at ball.ry; setParent ..; string $child3 = 'columnLayout'; attrFieldSliderGrp -min 0 -max 360 -at ball.rz; setParent ..; // Now we need to edit the tabLayout command to rename each // tab accordingly. tabLayout -edit -tabLabel $child1 rotX -tabLabel $child2 rotY -tabLabel $child3 rotZ $tabs; // The -edit flag will edit a command that has already been // entered. By default the tabs will be labeled by the // variables $child1, 2 and 3. We want to rename the // tabLabels to read something that makes sense to us. The // -tabLabel flag needs the object ($child1, 2 or 3) you want // to change and the new label in quotes. The -edit flag // also needs to know which tabLayout to edit so you do not // accidentally edit another tabLayout you created. The // -edit flag needs to see an object, so that is why we // create the variable to hold the command 'tabLayout'. You // can not use a command because the -edit flag would be // unable to distinguish between commands. This is a safe // way to keep you from editing the wrong command. showWindow;
Figure A.17
Your window shows the X, Y, and Z slider rotations of the sphere neatly organized into tabs.
continues
30
4. Now lets add some buttons for keyframing the attribute in the tab. Before you enter the following script, make sure to delete the ball and close the window you just created. Enter in the same scriptonly this time add the button command after the attrFieldSliderGrp to set keyframes for the attribute in the tab:
sphere -r 3 -n ball; window -t ballRotXYZ; string $tabs = 'tabLayout'; string $child1 = 'columnLayout'; attrFieldSliderGrp -min 0 -max 360 -at ball.rx; button -label keyframe -command setKeyframe ball.rx; setParent ..; string $child2 = 'columnLayout'; attrFieldSliderGrp -min 0 -max 360 -at ball.ry; button -label keyframe -command setKeyframe ball.ry; setParent ..; string $child3 = 'columnLayout'; attrFieldSliderGrp -min 0 -max 360 -at ball.rz; button -label keyframe -command setKeyframe ball.rz; setParent ..; tabLayout -edit -tabLabel $child1 rotX -tabLabel $child2 rotY -tabLabel $child3 rotZ $tabs;
The window is re-created and you can now press a button to set keyframes when you need them.
Figure A.18
The window you just created, with the addition of a keyframe button.
a p p e n d i x A : MEL scripting
31
Following is an example of a script used to create a window to control a CG hand.The hand control uses driven keys to drive the fingers curling, spreading, and making a fist. A few drivers are added to adjust finer hand manipulations. A locator is used to drive all the hand attributes, and the window will reference the locator (wristControl).
// GUI for hand controls global proc hand() { window -t Right Hand; string $tabs = 'tabLayout'; string $child1 = 'columnLayout -adj 1'; text -l ; text -l ; attrFieldSliderGrp -l Fist -min 0 -max 10 -at wristLocator.fist; text -l ; button -l keyframe -c setKeyframe wristLocator.fist; setParent ..; string $scroll = 'scrollLayout'; string $childScrl = 'columnLayout -adj 1'; text -l ; text -l ; attrFieldSliderGrp -l IndexCurl -min 0 -max 10 -at wristLocator.indexCurl; text -l ; button -l keyframe -c setKeyframe wristLocator.indexCurl; text -l ; attrFieldSliderGrp -l middleCurl -min 0 -max 10 -at wristLocator.middleCurl; text -l ; button -l keyframe -c setKeyframe wristLocator.middleCurl; text -l ; attrFieldSliderGrp -l ringCurl -min 0 -max 10 -at wristLocator.ringCurl; text -l ; button -l keyframe -c setKeyframe wristLocator.ringCurl; text -l ; attrFieldSliderGrp -l pinkyCurl -min 0 -max 10 -at wristLocator.pinkyCurl; text -l ; button -l keyframe -c setKeyframe wristLocator.pinkyCurl; text -l ;
continues
32
a p p e n d i x A : MEL scripting
33
-tabLabel $child1 Fist -tabLabel $scroll Finger Controls -tabLabel $child3 Translate $tabs; showWindow; }
I have added to this script a scrollLayout for the Finger Controls tab. This enables you to scroll through the layout of the sliders in the Finger Controls tab. It is important to create another layout in the scrollLayout. This will be read as the child of the scrollLayout. I then setParent to $tabs to make sure I reference the correct layout; in this case, the scrollLayout containing the columnLayout for the finger sliders needs to be the child of the tabLayout. I have included this script as a global procedure, which means that when I run this script, Maya will see it contained in the global procedure and then store it to memory. So, later all I have to do is type hand; in the Script Editor and the window will be built. Make sure you first have the hand file open; otherwise, the script will not be able to find the correct nodes and attributes of the hand to build the window.
Figure A.19
A window created by MEL scripting that conrols a hand. The CG hand is shown in the perspective window and the users custom window is in the foreground.