Python For Maya P.2

OK! Welcome back, now it’s part 2. In the last article, I introduced some basic work flow related maya python. In this article, I will introduce some common maya commands for scripting. I will also talk about Python list, python functions, and branches and loops. Hope this article may be useful for you.

Common Commands

Here, I will talk about some common commands, for more commands, you could convert yourself using the methodology I discussed in previous article. I discuss more about this because some of you guys may not be so experienced with programming language, hope more examples will give a better idea about how to convert maya command.

This is the official manual, for more details, please refer:

http://download.autodesk.com/global/docs/maya2012/en_us/index.html?url=files/Python_Using_Python.htm,topicNumber=d28e688294

1 Create Objects

The first thing I want to discuss is how to create basic geometry in maya using python script. The general format:

mc.baseGeometry() #I have already discussed mc in my previous article

For example:

mc.polySphere() can be used to create a default sphere geometry, I did not assign any attributes so that the attributes for this sphere will be default, the radius should be 1, it will locate at (0, 0, 0).

You can also change the default attribute of the sphere when creating it. For example:

mc.polySphere(r=1, sx =8, sy = 8)

Using the above command, we can create a sphere geometry with 8 segments along each axis. Remember, the default segments for sphere in maya should be 20, if you do not change the default settings.

0030QiC3ty6LEOATYq206

setAttr command can be used to modify the attributes of existing objects. Here I change the existing sphere radius value to 2 from 1. Be careful about the name here, when we set the attribute value, we are in fact changing the attributes from the input node. Make sure the name in your code matches the name from the name from input window.

mc.setAttr(“Objectname.attr”, val)

0030QiC3ty6LEOZI2Ze8c

You could use similar syntax to create other base geometry:

mc.polyCube()  # create a default cube

mc.polyCone()  # create a default cone

Tips: In case you are not so familiar with Object oriented programming language, I want to give more explanations about polySphere1.radius. Basically, in object oriented language, if you have a class or structure and you want to get access to the elements in this class or structure, you can use ‘ . ‘ between class name and specific element. A great metaphor for this is that you can consider class or structure as a container, may be like a box. In this box, you can put many elements. Let’s say you name this box as “Basket”, and you put three elements in this box, which respectively named as “apple”, “banana” and “grape”. Now, you can refer to this container by calling its name, “Basket”. If you want to get access to the element “apple”, you should write like this “Basket.apple”.

2 Transform objects

We can use Python script to transform geometry objects (transform includes translate, rotation and scale). Let’s take a look at move function:

mc.move(X offset, y offset, z offset, [object name(s)], [optional attributes])

The xyz offset represents the offset distance. object names represent objects which will be transformed. Yes, we can have multiple objects. If you notice there are square brackets in this function, which mean these attributes are optional (You do not need to specify this parameter, it has a default value). For example:

mc.move(1,2,3)

This is totally OK for Python script. Basically, if you already selected an object, this code will apply transformation to the selected object. Even if you do not have a selected object, this code will not issue an error, it just does nothing. However, the following code is invalid:

mc.move(1)

Because Offset X, Y, Z are required.

This is how official manual explain about move() command:

0030QiC3ty6LEQGE1Fj65

You can see there are a bunch of optional parameters in this move function, and most of them are boolean type. (I will explain how to use official manual at the end of this article)

You can see, that in this move function, we have a parameter names relative. This parameter controls whether the transform values are relative to object current location. For example, if we have a sphere located in (2, 0, 0). When we set the relative to true, then move this object along x axis one unit, the object coordinate will be (3, 0, 0). If the relative is set to false, then the object coordinate will be (1, 0, 0), the value will be absolute value. This is true for scale and rotate. Each parameters have an abbreviation form, for this relative value, it is ‘ r ‘ (you can also write as relative = True). So we can write code like below:

0030QiC3ty6LERg4d9r3d

You can see the corresponding value and abbreviation value in official manual, and it also contains description about this parameter and its type.

0030QiC3ty6LERTJto834

So, I will stop here. Give it a try and you can search for all the commands you want in official manual.

Variables

What’s is a variable? Basically, a variable is like a container, where you can put specific data values in it. Variable has different types, like integer, float or bool. However, unlike many other object oriented language, python does not need to declare a variable first, you can save any values in your variable when you initialize it. Python  will try to interpret the correct variable type itself.

For example:

0030QiC3ty6LEV25q307a

From this picture, we can see if we assign different types of values to these four variables, the final output is the same type like the assigned values. This conversion is implicit.

Tips: A little explanation for variable declaration and definition. In C++, when you want to use a variable, you need to declare it (you can initialize it when declaring it, or you can do it later). When you declare a variable, you tell the compiler the variable name and type, so when the program runs, it will allocate memory for this variable based on its type. For example:

int Mybox; // declare an int variable names Mybox

Mybox = 4;// assign an integer to this variable

 

Why variable?

The main reason for us to use variable may be create our own tools. If we type a specific object name in our code, you can imagine, that our codes can only manipulate that specific object. Let’s say if we put this code into a new maya project, it will be useless unless we manually change the object name again. Considering this situation, we can use variables as containers to hold different object names or other useful staff. Combined with functions, we can easily put all the current selected object names in different variables and use these variables  to do more calculation or modifications of these selected objects, so we can reuse our own scripts in different situations.

When you define your own variables, some important programming conventions must follow:

1. Make your variable name meaningful. If you can get the possible meaning of this variable just based on its name, that will be great, which will make your code more readable and easy to maintain.

2. Never use the same name for different staffs. This can easily cause weird problems.

Lists and Arrays

List is similar to arrays in C++. However, it is more flexible compared to C++ array. It can save multiple types of values. For example:

OurFirstList = [“Awesome”, 9.3, True]

You can see, in this case, our list stores three different types: string, float and bool.

While in C++, if you want to define an array, you should write like below:

int MyArray[3] = {0, 2, 3}; //define an integer array with length 3

In this case, we defined an integer array whose length is 3. What does this mean? It means our array can only hold 3 elements, and all these elements must be integer. If we write string or other type values to this array, compiler may issue an error.You may notice, in C++, when you define an array, you may need to specify its length or compiler will try to calculate the actual length based on the number of array elements, but a normal array with undefined length is not allowed. In Python, the list length is always calculated by the number of elements.

How to get access to the element of array? Based on its index. If you have an array with length 10, so all the elements in the array has indices range from 0-9 (starts from 0, ends with numbers -1). If we want to retrieve the value of the array, we could use this index:

int k = a[0]; // Get the first element of array a and assign it to variable k

This is the same in Python:

0030QiC3ty6LFtmbSbuc8

You can see, the first element is Awesome.

How can we utilize the list? A straightforward way to do so is to store all the objects  or all the selected objects in the scene in a list and do some manipulations to all these objects.

We can use Is command to save all our selected objects to the list, The ls command returns the names (and optionally the type names) of objects in the scene. The most common use of ls is to filter or match objects based on their name (using wildcards) or based on their type. Here is an example, I selected all three objects in the scene:

0030QiC3ty6LFvOgm4oe8

You can see from the picture, that our Ls command returns all the selected object names and stores in the list sequentially. This command is very important, because once we have a list with all the name of  selected objects, we can apply so many other commands to these objects.

Branches and For Loop

Branches and loops are very important concepts in almost every programming language.

“Branch” is a flow control terminology. Basically, a branch keyword is pretty straightforward. We will use “if/else” keyword in Python to switch to different branches. As for loops, we will use “for” keyword to execute commands multiple times. A loop, just like its name, we will execute a bunch of codes several times, and then we exit the loop and continue our normal code execution.

Let’s assume the following situation, (I will give you some pseudo codes to demonstrate the general idea) I have a box of apples (an array which stores apple elements), now I want to find the bad apples among all these apples, if I find bad apples, I will do something to handle them, or I will put them in a hidden safe place. The code will involve both for loop and if/else branch:

for(int counter; counter<= number of apples; counter++)

{

String current apple = apple[counter]; // select a new apple in the box

if(current apple == good apple)//compare whether it’s good or bad

{

Hide the apple in a safe place;

}

else // If the apple is bad…

{

Using this apple to make apple juice;

Sell the juice out;

}

Basically, you can see this is how for loop works. In python, if we want to define a for loop. The syntax is a little bit tricky:

for counterName in range (startingValue, LoopTimes, stepSize) :

XXXX

You can see, in this short code, you set up a counter (with name =”counterName”, value = startingValue ) to count how many times should the loop execute, whenever a loop execute one time, the count will add stepSize value. If the counter value exceeds LooPtimes value, the loop will stop. Otherwise, it will keep executing the code “XXXX”.

Be careful about the colon in the end of first line. This is mandatory, part of the syntax and cannot omit. The next thing is that Python is space sensitive code, for the actual code “XXXX”, you have to insert a TAB characters length space before the code (Most code editor will help you add this, so do not delete it). If you delete the white space before the code, python will recognize this as a parallel code to the for loop, so the for loop body will be empty.

Let’s look at an example:

0030QiC3ty6LFxZoJVf41

From the above picture, you can see we first select several objects in the scene, then we use Is command to save all the object name in a list named ThisObj, then we calculate the length of this list (This will be used to determine how many times will the for loop execute). Then I start the loop and print all the names of the selected object. You can see we print the name one by one, and the order is the order of the name in the list.

If we modify the stepSize from 1 to 2, then we will only print first and third object in the list. In the for loop, the counter name can be arbitrary (in this case, it is named as Icounter),  I recommend you to make a meaningful name for code readability purpose.

We can even add if/else branch in the for loop. Be careful about the colon in the end of if/else:

0030QiC3ty6LFyIaRYp65

Function

Function is like a customized tools. It is very important in programming language. I will give a brief example here. In the next article, I may explain more when I talk about python script applications. The general form for function is:

def functionName() :

XXXX

It is similar to for loop. If you call this function, it will execute the XXXX code once.

Be careful about the colon and white space before actual code.



How to use official manual?

Here, I will give you a quick guide about how to use official manual. Here is the link:

http://download.autodesk.com/global/docs/maya2012/en_us/index.html?url=files/Python_Using_Python.htm,topicNumber=d28e688294

0030QiC3ty6LFA4j7UEbc

First, select the command python book mark, so you can see that all the key word is listed here.

0030QiC3ty6LFA9XAHW2c

You can search the key word by alphabet, or by search box.

0030QiC3ty6LFAmzY8r83

0030QiC3ty6LFAu4z3d53

If we search ls command. You can all the explanation related to ls is shown. All you need is to carefully read all these instructions. Utilize this manual, and you can get almost all the explanations about maya commands. Try it yourself !

I believe that’s all about this article. In the following article, I will give you some explanations about how to define your own maya tools and  I will show you two practical applications about maya python script.

By Jun

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s