Python For Maya P.1

Hello, everyone. I am trying to relocate my old blog technical articles to this new website. Hopefully, these articles can be helpful to you… This time, I am going to show you some basic things about writing python scripts for maya.

OK, first thing first, why python?

Just my personal opinion, I believe Python can be applied to much broader areas. Even if you do not write maya script, Python can still be a powerful and flexible programming language, which can be used as a script language in Nuke, 3DSMax, Fusion, Cinema4D, or used to write your own server etc. Besides this, compared to C/C++, Python is easier to learn and understand.

Why maya scripting?

Basically, you could create almost everything with built-in commands in maya. No matter you are doing modeling, rendering or even particle simulation, Maya is powerful enough to handle most situation. If you are an experienced maya user, you may find that you may need to do some command repetitively. For example, you may want to create a 3D tree, we all know that tree has many leaves, we may want the leaves have several UV settings in a single 0-1 UV coordinate, so you could create only one texture, which can be applied to different leaves and ensure some variations. Just as the image shows below. Since each leave have similar topology, so we just need to shift their UV to different locations in UV coordinate, we could create one texture and map to different leaves.

TIM截图20180217105052

Yes, indeed, you can do it manually. However, let’s say, you have a thousand leaves and you just want to create 4-5 UV mapping settings, which means you have to randomly assign one UV location to several of the leaves. If you do it manually, it will be a disaster! Even worse, if you create a different tree, with different leave topology, you have to start again. So, a better solution is to write your own tools, you could use this tool to re-difine UVs for almost every tree. That’s why you need maya script, it can boost the whole efficiency and save a lot of repetitive work!

This first article, I will just show some basic settings and grammar related to maya python. I tested it in maya 2012, so there may be some changes in later versions. Anyway, it’s still a good chance to take a first glance at maya scripting. Let’s start!



Scripting Environment

We can just write our code in maya python script editor and compile it instantly in maya. It is very convenient. We can find the editor in the bottom left and bottom right area of maya software.

MayaEditorArea

By default, the bottom left area is the mel command window, which means you can write mel command and execute here. By clicking the MEL icon, we can switch to python. Here is a good place to execute short command.

A more useful window is python editor, you can open it by clicking script editor icon:

TIM截图20180302205230

Once the script editor is open, we can switch the tag to Python. The bottom area is where we will write our actual code. The script editor can highlight the syntax. One of the most useful features is that you could select several lines of code and execute only selected code, this makes execute and debug code more flexible.

0030QiC3ty6LD1k8zJMc2

Let’s begin our first example:

0030QiC3ty6LD23Y3tA86

In this simple example,  I wrote only 3 lines of code, I applied the “print” key word. Print is used to print your information to console window. It’s similar to C++ std::cout or C printf. The next thing is how to execute the code?

Basically, if you want to execute all the commands altogether, you can simply using hotkey Ctrl+ Enter or just num keyboard Enter. After press the hotkey, the whole code will execute and delete from code area and result will display in console window (in my case). Like the picture below:

0030QiC3ty6LD2mQWCzff

If we do not want our code to be deleted after execution, what should we do? That’s simple, we can just select our code and execute, then our code will remain in coding area. If we want to execute part of the code, just select part of the code and then execute.

Tips: we can scroll mouse middle key to scale the code font size. Adjust the working area and make the font size suitable for your monitor.

Basic Grammar

1 print key word

We have already covered how to use print keyword to print content to console window. These contents can be string, integer and float data type, they can also be the object name in the scene. The usage of print is relative simple:

print “string name”           —- print corresponding strings

print numbers/variables  —- print corresponding numbers and variable values

print expression                 —- print the values of the expression

Examples:

0030QiC3ty6LD3N9yUMf0

Tips: Python language is case sensitive, so if you write print as Print, you will get an error when compiling the code. If you are not so familiar with programming language, be careful about this.

2 Type conversion

When you do math calculation, be careful about the data type. Like many other programming language. Python can convert integer to float by making one of the parameters float. If you calculate integer division, 5/3 will give you the result 1. However, you will get 1.66666… if you write the expression 5.0/3 or 5/3.0.

Integer— General integer, which means you will only have value like -1, 0, 1, 2… In the above example, 5/3 is 1.6666… However, the value of math expression from two integer calculation will be an integer, so 1.6666… is truncated and only the integer part remains.

Float and Double — In contrast to integer, this represents decimal values. Double type typically consumes 8 bytes in memory while float will consume 4 bytes. If you are just writing script for maya, you may not need to know too much details about this, all you need to know, double type can store much more precise decimal numbers, if you need to large numbers or just want very precise numbers, you should consider using double. Otherwise you can stick to float.

Python can do the integer and float conversion for you, however, if you do math between different types(other than numbers), it may cause problems. For example:

print “Hello!” + 5

The compiler will issue an error for it does not know how to connect string type with integer.

0030QiC3ty6LD4xsfkZ41

So, how can we modify this script and get the correct result? we can modify the code like below:

print “Hello! %d” %5

Then compile it!

0030QiC3ty6LD4XR1bh87

Here , we add %d after Hello! string, which means we are going to insert an integer type here, while % + 5 tells the compile the exact value we want to insert. If you want to insert a float number, use %f instead.

Tips: When you use string type, you should include the double quotation marks, because in python, if you add the double quotation marks, it tells the compiler that the characters inside the quotation marks are strings. If you carelessly omit the quotation marks, the characters will be interpreted as variable name, and under most circumstances, you will get an error that the variable is undefined.

Tips2: If you want to refer to an object in the scene, you should include double quotation marks in the object name as well. Object names should be treated as string.

3 Comments

Like many other programming language, we can write comments in our python scripts. Writing comments are critical when we write our code. First, comments can ensure that other people can easily understand your code, you could use the comments to demonstrate the functionality of your code, how the parameters are defined, how the workflow is generated etc. The second thing is your comment can help you maintain your code in the future, if your code is well documented, you can easily expand or modify it in the future.

Basically, a comment is an some explanation sentences which will be ignored by the compiler when we compile our code. Unlike most other languages, python using ‘#’ to denote the comment.

0030QiC3ty6LD5KeGa327

In the above picture, the red sentence is a comment, if we compile the code, this sentence is ignored by the compiler.

4 Import command

If we want to use python in maya, we have to connect python code with maya command. In order to connect them, we have to import maya command first.

The import keyword is like include keyword in C++, if the code gets compiled, it will include outer library into our code, so we can utilize the code stored in the library.

If we want to call maya commands, we first need to import maya command to our code:

import maya.cmds

When we want to call maya command, we have to add the prefix maya.cmds. It’s just like we want to use standard library code in C++, std:: cout.  An example about how to call maya command, this command will create a new sphere object in the scene:

0030QiC3ty6LD7OaRHD95

But you can see that maya.cmds is so long, can we make it shorter so we can conveniently refer to it.  Yes! we can! we can give the prefix an alias, so we can use that alias to replace its original name. The code is like below:

import maya.cmds as XXX

XXX.polySphere()

0030QiC3ty6LD83Fumbff

Tips: We can even get rid of these prefix by import maya.cmds as *, however, I do not recommend you to do this. It may cause some scope problems. So in the following articles, I will stick to the short alias mc.

5 Convert maya command to python code

How can we convert normal maya command to python code? That’s simple.

Let’s look at a simple example first:

If we create a sphere in maya using normal way(maybe click the sphere icon in bookshelf), you can see the maya command in console window like below:

0030QiC3ty6LD8oU1sMfc

You can see from the picture above, the maya command is polySphere, and it uses -r 1 -sx 20 etc. to set the attribute of the sphere, we can change this to python code as below:

0030QiC3ty6LD8QtEYIec

It’s similar, right? Basically, it generate the same sphere like the maya code. And you can even skip some attributes, for the attributes have default values. Look at the code below, it generate a sphere which radius is 2.5:

0030QiC3ty6LD9kqHQke8

So, basically, you can observe maya command and convert it to python code to get most of the staff. Let’s see another example, I set up the parent-child relationship between object A and B :

0030QiC3ty6LD9Vgya428

0030QiC3ty6LD9ViHvw6e

Tips: When you want to write your own python code, a good way is to guess how to write it from maya command.

Every maya command and how to use them are listed in Autodesk official manual, you can search them by key word, you can get access to the manual from the link below (maya2012, there maybe some changes in the latest version):

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

If you look at the above code, and check the manual, you will know A represents the source object, B is target object. Mo represents maintain offset, which we assign 1 (true) to it, so we can retain the object location while generate parent-child constraint.

That’s all for section 1, hopefully, I can post other sections soon… If you have any questions, feel free to leave comments here.

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 )

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