Chapter 4: An Introduction to Programming Concepts


click to expand

MEL is a programming language, and follows many of the rules and structures of any programming language. Unfortunately, most artists have no idea what even the most basic elements of a computer program are. This chapter hopes to introduce these programming concepts and is rather intensive technically. However, it is the foundation of all scripting, so it is important that we gain a complete understanding of these concepts before moving on to subsequent chapters.

Variables

A variable is essentially defined by its name . A variable is a placeholder for data within a MEL script. Confused? Don t be. It s easiest to explain it as you would any language.

Let s tell a little story about a guy named Bob. He goes into a room. He then picks up a wonderful book on MEL scripting.

If someone were asked who picked up the book, there is little doubt that he would have no problem knowing it was Bob, even though we only referred to him using a nondescript pronoun. See, we just did it again, and still we had no problem knowing we were speaking of Bob. What we did is define who the he was before we ever referred to Bob as he.

Within MEL, it s very much the same. We create a placeholder, and then put data in it. We can then access and manipulate that data, including changing that value. This is what gives scripts their flexibility and power. In MEL, a variable is defined by any word that begins with $. It s that simple. Almost. When we first tell MEL we want a variable, or declare it, we have to tell it what type of variable we want. Of course, first we need to understand what types of variables are available within MEL.

The Variable Types

In MEL, there are five types of declarable variables:

  • Integer numbers

  • Floating-point numbers

  • Vector numbers

  • Strings

  • Matrices

Integers

Within MEL, integers are referred to simply as int . Integers are especially useful while dealing with Boolean or enum attributes, since even though within the Maya interface we see words such as on or off , when queried Maya returns an integer. For Booleans, this means 0 for off, no, or false, and 1 for on, yes, or true. For enumerated attributes, Maya will return an integer of what s known as the index value , which is simply the item's position in the list, beginning with 0. Index values are covered in more depth later in this chapter. The declaration of an integer variable, $i, is seen in Example 4.1.

Example 4.1: Declaration of an integer variable.

 int $i = 4; 

Floating Points

Floating-point numbers are the type of number we will most often encounter in Maya. All transform values are floating-point values, as well as things like skin weight values, and even colors. Within MEL, a floating-point number is called a float . Even values that are often perceived as integer numbers, such as the current frame, are treated as floating points because we never know when a user might set that value to something fractional .

There are two issues we should be aware of when dealing with floating-point numbers. First, is their memory requirements, or footprint. A floating point takes up significantly more RAM than an integer does. Now, when we re dealing with a single number, this difference is insignificant. To any system that runs Maya, the difference is trivial. However, multiply that difference a thousand-fold or more, and we start talking about a serious memory disparity. The other issue with floating points is their precision. Internally, Maya treats floating points with a great deal of precision. However, when we ask Maya to print a float value either to the interface or to a file, Maya truncates it to 6 points of decimal precision. A workaround for this limitation is covered later in this chapter under data type conversion, as well as in Chapter 13. Example 4.2 declares the irrational number as a float variable.

Example 4.2: Declaring as a float variable.

 float $pi = 3.1415926536 ; 

Vectors

Vectors in MEL are both entered and returned as three floats separated by commas, surrounded by angled brackets, as seen in Example 4.3.

Example 4.3: The declaration of a vector variable.

 vector $up = << 0, 1, 0 >> ; 

Often within Maya, values we would like or even assume would be returned as a vector ”like position values, colors, or ironically an IK handle s pole vector ”are instead returned as a series of floats. A majority of the time it is worthwhile to convert those numbers to vector variables. Because vectors allow us to store three values in one variable, it makes tracking information that has three float components easier, as well as allowing us to use vector-based math functions like dot and cross . Vectors also allow a wily scripter to exploit the system, as it were, as the ability to store multiple values in one variable is quite useful.

Strings

A string variable contains text information. That text can be anything from an object s name to the name of a UI element to a command we dynamically build within a MEL script.

Of course, it s never just that simple. There are two issues we should always be cognizant of when working with strings.

The first is an issue of case sensitivity. As with variable names , the word cat is not the same as the word Cat or CAT. It is a simple enough concept, and can be easily overcome with either the toUpper or toLower commands, which converts strings to either all uppercase letters or all lowercase letters , respectively.

Strings can also contain text-formatting information, such as a carriage return or a tab indent. These are done with escape characters . Within MEL, the character \ is used to escape a character. When Maya parses a string, if it encounters a \ it looks at the next character either as a special function, such as a \n that signifies a carriage return, or a tab-over, as in \t . The other function of an escape character is to explicitly be that character. Since when we declare a string we place it within quotes, if we want to place quote marks or for that matter the \ character in a string, we simply preface it with \. In Example 4.4, we use the escape character \n to place a carriage return at the end of our string.

Example 4.4: A string variable with the escape character \n, representing a new line, as well as using the escape to include the quotation marks in the string.

 string $sentence = "Please set the                         visibility to \"on\".\n" ; 

The escape characters most often used in scripts are:

  • \ n: new line

  • \ r : carriage return

  • \ t: tab character

Arrays

Before we cover the fifth type of variable, the matrix, we should become familiar with the concept of an array . An array allows us to store multiple values in a single variable, as a list. Integers, floating points, vectors, and strings can all be declared as an array, so in actual practice there are essentially nine types of variables.

To declare a variable as an array, we place block brackets at the end of a variable name. When we declare an array, we can either explicitly declare the size of the array, or allow it to be built dynamically. There is no right or better way to do it, as there are reasons why we would want to do each. In Example 4.5, we declare two arrays, one that can be dynamically sized , and the other of a predetermined size.

Example 4.5: Declaration of array variables.

 int $numObj[] ;      float $position[3] ; 

Arrays are incredibly useful, and we will often find ourselves using arrays rather than singular variables. After declaration, when we need to access an individual item in the array, or an element , we use its index value. One aspect of arrays that can confuse people new to programming is that of the 0 index. That is to say, the first item in any array is index 0. The second is index 1, and so on. In Table 4.1, we see a visualization of a string array that has five items in it.

Table 4.1: Visualization of an Array Variable

$object[0]

polySurface1

$object[1]

polySurface3

$object[2]

polySurface9

$object[3]

polySurface14

$object[4]

polySurface2

Matrices

We declare a matrix variable by explicitly stating its size in a fashion similar to an array, by using square brackets to state the size of the matrix. If we think of a matrix as an array of arrays, the first number states the number of arrays in the matrix, and the second number declares the number of elements in each of those arrays. Assignment of values is either done during declaration, or by assigning each element a value individually, seen in Example 4.6.

Example 4.6: Assignment of matrix values.

 matrix $firstMatrix[3][2] = << 3.8,19.73; 4.14,19.75; 25.6,94.01 >>;     matrix $secondMatrix[5][5]; 

The second matrix variable from Example 4.6, $secondMatrix, has 25 elements, each assigned a value of 0. After declaration, we can assign values as we would with any variable, seen in Example 4.7.

Example 4.7: Assigning a value to a single element of a matrix.

 $secondMatrix[2][4] = 3.4521224; 

Matrices have a major limitation within MEL, and it puts severe restrictions on their usefulness within a MEL script. That limitation is that the dimensions of a matrix have to be set explicitly during declaration of the variable, and cannot be sized dynamically. Under some circumstances, such as storing transformation information for a single object, it s not an issue because we know exactly how many numbers will be needed. However, in many situations, having to explicitly set the dimensions of a matrix limits the flexibility of a script.

Local and Global Variables

Variables can be declared as either local or as global . A local variable is temporary, and is cleared out of memory as soon as the script using it is done using it. A global variable is held within memory until the current Maya session is ended. Wherever possible we should use local variables instead of global to save on memory usage. It is important to remember that any variables we declare within the Maya interface, unless contained within a group , are global. Please refer to the section, Command Groups, later in this chapter for specifics on groups.

The global of local nature of a variable is important because once a variable of a given name is declared as one type, it cannot be re-declared as another. This includes going between simple variables and variable arrays. Therefore, if we are working within the Maya interface, such as in the Script Editor, and declare an integer variable called $temp, and then try to declare a floating-point array variable called $temp, Maya returns an error as seen in Example 4.8.

Example 4.8: The error from attempting to re-declare a variable as a different type.

 int $temp;     float $temp[];  //Error: float $temp[]; //   //Error: Line 1.13 Invalid redeclaration of variable  "$temp" as a different type // 

There is no way to undeclare or clear a variable from memory, so it s best to keep track of the variables used, and to reuse them whenever possible. A good practice is to develop a standard list of variables, such as $tempInt , $tempFloatArray[] , and $selectionList[] , and use them within any code executed within the Maya interface. This avoid issues with memory, and standards can help by making code more readable.

Variable Conversion

Variables can be converted from one type to another by using the variable as the value to be assigned to a variable of the type we want to wind up with. In Example 4.9, we convert the data stored in the float variable to a string.

Example 4.9: Converting a float to a string.

 float $tempFloat = 5.874 ;     string $tempString = $tempFloat ; 

Conversion from one type to another is not always exact, for obvious reasons. Some number types simply contain more data than others, as floats have more data than integers, while others are formatted differently, such as vectors and matrices. However, conversion can be extremely useful for comparison of data, writing data to files, or the simplest of vector calculations. Table 4.2 details how each variable behaves when converted to another type.

Table 4.2: Data Conversion
 

int

float

vector

string

matrix

int

perfect

<< int, int, int >>

perfect

No conversion

float

int, rounded down

<< float, float, float >>

nine digits of precision

No conversion

vector

Magnitude, rounded down

Magnitude

vector.x vector.y vector.z

If matrix is [1][3], perfect; else, no conversion

string

If begins with number, same as float; else, 0

If begins with number, perfect; else, 0

If begins with vector or floating-point numbers, perfect; remaining elements 0

No conversion

matrix

For [1][3] matrix or smaller, same as vector

For [1][3] matrix or smaller, same as vector

For [1][3] matrix or smaller, same as vector

No conversion

In our discussion of floating-point variables, we mentioned the precision errors when writing floating points out to files, rounding the float to six points of decimal precision. AliasWavefront currently suggests converting the number to a string, but that actually can make the situation worse . Doing so gives us nine digits of precision, which is actually more precise when dealing with numbers between 1000 and “1000, but anything larger absolute value and we start to lose decimal precision. Referring to Table 4.2, we can see that converting a float to an int strips off the fractional information. If we then subtract the resulting integer from the original float, we get only the fractional information. Convert this to a string with nine digits of precision, and combine it with the integer to get a fairly precise string. While not ideal, without the use of more advanced scripting it is the best that can be done.

Another useful conversion trick is to convert a vector to a float. The resulting number is the vector s magnitude, assuming that the vector begins at the origin. This is a simple way to find an object s distance from the origin or, by simply finding the resultant vector of subtracting two vectors, the distance of two objects from each other. Of course, we can use a vector equation to find the vector length, but as with many things in Maya, the problem has multiple solutions.




The MEL Companion
The MEL Companion: Maya Scripting for 3D Artists (Charles River Media Graphics)
ISBN: 1584502754
EAN: 2147483647
Year: 2003
Pages: 101

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net