Programming The language for building web pages

Women Who Code:  Sydney and Meetup

Sydney Python User Group (SyPy) Monthly Meetup

EAT 3D Autodesk Maya Scripting – An introduction and Applications Luiz Kruel





Do all the boring tutorials like creating calculations and “hello world”, understand what functions, loops, arrays and conditional statements are, what passing by reference vs passing by value means.  Then there are all the python high-level specific things like maps and dictionaries and you need to understand all of this before you can start mixing python with maya.

Lecture 0: Introduction – Computing 1 – Richard Buckland UNSW

Introduction to Python Scripting in Maya – Available at


Unix Network Programming by Richard Stevens

Hacking the art of exploitation BY JON ERICKSON


Use long names when writing your code  Dragos Ionel

Unfortunately, we have been used to the fact that a name has nothing to do with the object it names. JohnMary, and Steve say almost nothing about the people it names. Maybe just that they all speak English. We don’t know if the are tall or short if they are good with computers or know how to paint or play the piano.

Of course, the reason for that is that their parents had no idea how would their kids behave when they would grow up.

But, fortunately, it is different when we write the code. When we create an element of our code, it does not matter if it is a constant, variable, method or a class, we know for sure what it will be used for. So we are in a better position to choose a name. And even if we are wrong and the purpose of the element will evolve, we can change the name anytime. Most of the modern IDE-s have a refactoring option that can change a name across the project.

Another great feature the IDE-s of today have is that they prepopulate the names. You start typing a couple of letters and they give you a dropdown to select the best options for the specific context. So we don’t really type the whole names anymore.

And because of this, there is no reason to save the space and use short names. We can use names as long as we want if they are useful.

Let’s see few examples:

age -> userAge

error -> connectionErrorCode

name -> dogName

User -> UserView

Login -> LoginViewController

message -> errorMessageAfterLogin

The advantage is obvious. So go crazy!


MEL and PYTHON scripting

my assessment and a collection of notes

An interesting article in iiNet’s September 2015 eNewsletter:  Should students learn how to code?


Screen Shot 2015-11-14 at 4.51.36 pm

“””Script Name: DCE3D UV Layout
Vincent Rossini & Therese O’Leary 221015
UV Layout completd for model/s, the user is able to name and create shell/s
from the UV mapped model/s by selecting UV/s in the interface.The user is then able to move the shell/s around the UV Editor to different
UV tiles.When a shell/s is overlapping between Tiles a UI warning is displayed
TOPDOWN DESIGN- import MEL command library so python knows what they are- run a list to see if a set/s list already exist
– clear sets in ui
– capture set/s names in list
– lists sets- user selects uv/s, can be anywhere on model/s
– the selected us/s
– converts selected uv/s to shell/s
– user names set in ui
– creates a set from selection and assigns name
– list all existing sets and adds created set
– list of set/s is updated and name displayed in ui window and outliner- caputure position of uv/s in shell/set in uv layout editor tile
– gets the name of user selected shell/set
– select this set with u and v values captured
– user enters in ui the number value to move the set in u and v of uv layout editor
– moves set the number of tiles values entered in the uv layout editor- user selects in ui set to be check for overlapping tiles
– select users selection
– store content of selection
– select this selection
– list content of set in list and flattern
– find, select and store first uv for each set, always zero as refernce for u and v
– check position of each u and v in set, run through list of set
– identify if uvs are in different tiles,
– if yes display a warning window in ui for set overlapping tiles
# backendimport maya.cmds as mc # import MEL command library so python knows what they are, use mc.
import maya.mel as mel # to run an internal mel command inside python, use mel.# proc/definition to run the list first to populate if set/s already existdef update_list(*args): # any number of parameters, load up the set list.
mc.textScrollList(“set_list_Control”,edit=True, removeAll=True) # edit the scrol list then remove all to clear unwated sets in list before running
setList = # lists sets
for i in range(0, len(setList), 1): # loop populate the list in ui, get everything
if ‘DCE3D_UV_’ in setList[i]: # needs a prefex in the name because all nodes listed in list setList, will add if has prefex
mc.textScrollList(“set_list_Control”, edit=True, append=setList[i]) # name for ui textScrollList, appends adds an item to end of list called setList# proc to convert selected uv to shell and creat a setdef make_set(*args): # makes set from currently selected uv’s with user entered name
mel.eval(“polySelectBorderShell 0;”) # user selects uv & this selects the shell. Converts the selection.
userSetName = mc.textField(‘userSetName’, query=True, text=True) # ui user entered values, will get the name
shell_set = mc.sets(name= “DCE3D_UV ” + userSetName + “_set”) # creates a set from selected uv/s, assigns name including from userSetName in ui. Appears in outliner by default.
update_list() # updates the list with new set/s# proc for selected set, user enters move values and moves in uv layout editordef move_set(*args): # moves sets to user selected grid positions on uv layout editor
u_value = mc.floatField(“U_Value”, query=True, value=True) # get u value from float field named “U_Value” and return to u_value, query the selection
v_value = mc.floatField(“V_Value”, query=True, value=True) # get v value from float field named “V_Value” and return to v_value, query the selection
selectedSet = mc.textScrollList(“set_list_Control”, query=True, selectItem=True) # selected set in ui window returned to selectedSet, query the selection (is a string) # want to select selectedSet, variable with what user has selected
mc.polyEditUV(u=u_value, v=v_value); # moves the selected shell to tile space in variable from user entered value in floatField. polyEditUV to move selected shell/s to selected tile on grid – -U-1, -V-0. # clears what user has selected

# proc checking if set is positioned over tiles, positioned in more than one tile.

def crossing_tiles(*args):

total = 0; # ui warning window was displaying for all uvs in the set, used total variable at the end so warning window is not displayed when the number is greater than 0

selected_set = mc.textScrollList(“set_list_Control”, query=True, selectItem=True) # selected sets in ui text scrol list
# print selected_set

uvs = mc.sets(selected_set, query=True) # for set named ‘DCE3D_UV_face_set’, store content of set in variable uvs # selects the contents of variable uvs
flattened_uvs =, selection=True, flatten=True) # list from selction in uvs, flattern changes from a range to listing all
# cannot run a loop with a range, flatterned uv positions
# Flatten from range to everyone. u’[231:329]’, in uvs to store in flattened_uvs variable u’[231]’, u’[232]’,

reference_UVs= mc.polyEditUV( uvs[0], query=True, uValue=True, vValue=True) # where is zero, every mesh has zero, the first one. Returns the uv values associated with the specified components and have current location.
referenceU = int(reference_UVs[0]) # makes the float for reference_UVs an integer for the U value. Reference_UVs are # Result: [1.5022433996200562, 1.1742322444915771] # 0 position is now referenceU # Result: 1 #
referenceV = int(reference_UVs[1]) # makes the float for reference_UVs an integer for the V value. 1 for second value – now referenceV # Result: 1 #

for uv_point in range(0, len(flattened_uvs), 1): # Range funcion, between 0 and the end value, all of them, len returning how many values, flattened_uvs is the variable containing the uv list from the selected uvs in the set.
mc.polyEditUV(flattened_uvs[uv_point], query=True, uValue=True, vValue=True) # what the loop is repeating. Querying the uv positions with polyEditUV and returning the u and v values from the flattened_uvs list.

# print flattened_uvs[uv_point] # prints list of flattened uv position values, each individual one.

target_UVs = mc.polyEditUV(flattened_uvs[uv_point], query=True, uValue=True, vValue=True) # find uvs of set
targetU = int(target_UVs[0]) # returns targetU float as an int
targetV = int(target_UVs[1]) # returns targetV float as an int

if referenceU != targetU or referenceV != targetV: # if reference value is not equel to target value for U and V then print the following warning
total += 1 # total will now be greater than 0 and used for if statement to display warning window only once for set overlapping tiles

if total > 0: # when total is greater than 0 then the warning ui window is dispalyed
mc.confirmDialog (title=’WARNING’, message=”UVs are crossing over tiles_” + str(selected_set), icon = ‘warning’) # ui warning window when set is positioned over more than one uv layout editor tile

# frontend

if mc.window(“DCE3D_UV_set”, exists=True): # if window already exists called “DCE3D_face_UV_set”
mc.deleteUI(“DCE3D_UV_set”, window=True) # then delete window “DCE3D_face_UV_set” before opening new window

mc.window(“DCE3D_UV_set”) # create window titled “DCE3D_face_UV_set”
mc.columnLayout(“mainLayout”, adj=True) # create a column layout called “mainLayout” that arratnes its children, have one and is user adjustable
mc.frameLayout(“enter set name:”)#, borderVisible=True)
mc.textField(‘userSetName’) # unique name used for make_set function, user enters the set name where setName in ui text field
mc.frameLayout(“list of created sets:”) # name displays up on ui
mc.textScrollList(“set_list_Control”, allowMultiSelection=True) # name “set_list_Control”, flag for multi or single selection
mc.button(label=”Create UV Set”, command=make_set) # creates button “Create UVSet”, uses the def function make_set

mc.frameLayout(“enter U and V values to move selected set:”) # name displays on ui

mc.rowLayout(nc=2) # number of columns for u and v values
mc.floatField(“U_Value”, value=0.0) # ui place where user enters u value to move shell on the grid
mc.floatField(“V_Value”, value=1.0) # ui place where user enters v value to move shell on the grid
mc.button(label=”Move Selected Set”, parent=”mainLayout”, command=move_set) # creates button called “Move Selected Set”, parented to column layout called ‘mainLayout’ using def function move_set
mc.button(label=”check Shell crossing Tiles”, command=crossing_tiles, parent=”mainLayout”) # user can check if the selected shell/set is positions over more than one tile. If it is than a warning is dispayed in ui

mc.showWindow(“DCE3D_UV_set”) # show window called “DCE3D_face_UV_set” in ui



PYTHON  SCRIPTING – Programming 2


Develop a customised tool for improving workflows or pipeline requirements and document your major programming project.  This tool will ensure that artists are using the UV layout required by the DCE3D pipeline

Tool Requirements:

  • Shells should only be generated along the U parameter
  • This tool will layout UVs so that there are no-overlaps
  • It must have a user friendly UI

What is causing the problem: brief description of the pipeline issue, a paragraph describing the problem I have to solve and diagrams can be included.  

What actions can be done to manually solve the problem: research done to find a solution, a few paragraphs listing any research done to find a solution and diagrams can be included.

Propose a solution designed to overcome the issues at hand: design of proposed solution, outline using paragraphs, dot point, diagrams and/or images to describe how this custom tool will look and work. 

A tool which is going to put each face/shell of a polygon model or models into its own UV tile.

I needed to revisit Maya’s UV Texture Editor to see how this could work.

The UV layout tool is used to apply colours, details and textures from a 2D image to the surface of the 3D model.  3D is based on XYZ, showing where the object is located in 3D space while texture mapping uses 2D images, with U (horizontal axis) or width and V (vertical) or height surface coordinates that shows where these points appear on the 3D surface and how the texture is applied.


For this tool the shells have already been created.  The 3D surface to broken up into segments or shells which are groups of UV points with interconnecting lines that are used to created the best possible shape for texturing. The Shell’s seams, where the textures will be jointed, need to be positioned to minimise stretching and warping when applying the 2D images to the 3D surface.


The UV layout tool’s default is to fit the 3D object’s shells within the 0 to 1 coordinates of the grid or tile.  This may or may not be the best layout position for the image resolution on the 3D object. It is not necessarily a matter of extending beyond these coordinates as the textures will appear to repeat, loop or wrap.

The UV layout grid can be extended in either the U or V creating more tiles, with more UV regions of the same 0 to 1 scale for texturing. This will increase the resolution of the textures or how much of the object’s surface the texture will cover per tile.  This tool will apply one shell per texture tile on the UV layout grid in the U direction, allowing for high resolution texturing. There is to be no overlapping which would cause repeating on corresponding vertices.


images from autodesk and

The UV layout grid can be extended in either the U or V creating more tiles, with more UV regions of the same 0 to 1 scale for texturing. This will increase the resolution of the textures or how much of the object’s surface the texture will cover per tile.  This tool will apply one shell per texture tile on the UV layout grid in the U direction, allowing for high resolution texturing. There is to be no overlapping which would cause repeating on corresponding vertices.

During my research some ideas have come up that I need to consider:

Selection – will the user select one or multiple 3D objects at a time and how will they be selected?  How will the shells be selected and layed out in the UV Texture editor? Select a single UV and tell Maya to select the shell boarder to grab a single shell and move it to the next tile across or will the whole object be selected.

Tiles – will the UV shells be positioned to lie within a user-defined number of tiles or will the number of shells determine how many gird tiles there will be?

History – mesh with history may revert to old UV’s?

Shells – need to work out how many shells make up the selected models then to be able to put each shell into sequential tiles.

Layout – the position of each shell in the tile along the U axis.

Shape, Size and Scale – to roughly correlate to each other and the faces of the polymodel, unless want more or less detail or maximise the resolution by filling the image area or UV tile as much as possible.

When unfolding multiple shells, do they need a consistent size or will the shell fill the 0 to 1 texture space,

Overlapping – smooth UV tool which smooths out the overlapping with Unfold untangling UV’s while attempting to match the shape of the 3D surface.

Positioning – in regions other than the default 0 to 1 tile, Scale Mode affects the way shells are arranged on the grid with None arranging the shells to fit within a the specified number of tiles. Uniform arranges the shells to fit within only the number of tiles that are needed. Nearest Region positions the UV shells to lie within the nearest tile.  What if I want the shells in the exact same UV position of the tiles, same UV coordinating space on a different tile?

Empty Region – around the outside perimeter, especially if the shell’s UVs boarders the tiles edge, empty region (4 to 6 pixels), UV boarders from the tile edge – script 5% scale reduction.

Unfold – constraint to none will unfold in both U & V. Do the shells have a consistent size or are they filling the 0 to 1 texture tile. Scale Factor. Uniform scale, the shell to fit the 0 to 1 texture space without changing the aspect ratio and is the default.  Inside the UV range in each tile and no crossing of boarders.

Normals – how to flip shells that have normals pointing in opposite directions. Not sure if this relates to the blue and red colours for the shells.

At this point I went looking in the Maya Help Files to find Python Commands that could be used in the UV Layout Tool script and how they might be used.

To start with it was overwhelming, then bit by bit there were some that looked like they could work which started me thinking of possibilities for scripting solutions. I have listed them below.

polyEvaluate command

Returns the required counts on the specified objects.

Flag: shell(s) returns the number of shells shells (disconnected pieces) as an int


Command edits uvs on polygonal objects. When used with the query flag, it returns the uv values associated with the specified components.

relative(r)Specifies whether this command is editing the values relative to the currently existing values. Default is true;

uValue(u)Specifies the value, in the u direction – absolute if relative flag is false..

vValue(v)Specifies the value, in the v direction – absolute if relative flag is false..

rotation(rot)Specifies whether this command is editing the values with rotation values

scale(s)Specifies whether this command is editing the values with scale values

pivotU(pu)Specifies the pivot value, in the u direction, about which the scale or rotate is to be performed.

pivotV(pv)Specifies the pivot value, in the v direction, about which the scale or rotate is to be performed.

scaleU(su)Specifies the scale value in the u direction.


floatSpecifies the scale value in the v direction.

angle(a)Specifies the angle value (in degrees) that the uv values are to be rotated by.


stringSpecifies the name of the uv set to edit uvs on. If not specified will use the current uv set if it exists.

polyEditUV Shell

Command edits uv shells on polygonal objects. When used with the query flag, it returns the transformation values associated with the specified components.

uValue(u) Specifies the value, in the u direction – absolute if relative flag is false..

vValue(v) Specifies the value, in the v direction – absolute if relative flag is false..


Flip (mirror) the UVs (in texture space) of input polyFaces, about either the U or V axis..

flipType(ft)Flip along U or V direction.  0 Horizontal 1Vertical, Default is 0. 

local(l)Flips in the local space of the input faces. Default is on. 


This command takes selected polygonal vertices or vertex-faces and changes their normals. If the option userNormal is used, the new normal values will be the face normals around the vertices/vertex-faces. Otherwise the new normal values will be default values according to the internal calculation.


iterations(i)Maximum number of iterations for each connected UV piece.

stoppingThreshold(ss)Minimum distortion improvement between two steps in %.

useScale(us)Adjust the scale or not.

scale(s)Ratio between 2d and 3d space.

areaWeight(aw)Surface driven importance. 0 treat all faces equal. 1 gives more importance to large ones.


This command will aid in the creation of non-overlapping regions (i.e. polygons) in texture space by untangling texture UVs.

relax(r)Relax all UVs in the shell of the selected UV’s. The relaxation is done by simulating a spring system where each UV edge is treated as a spring. There are a number of different methods characterised by the way the UV edges are weighted in the spring system. These weightings are determined by STRING. 

Valid values for STRING are:

uniform – every edge is weighted the same. This is the fastest method.

inverse_length – every edge weight is inversely proportional to it’s world space length.

inverse_sqrt_length – every edge weight is inversely proportional the the square root of it’s world space length.

harmonic – this weighting can yield near optimal results in matching the UV’s with the geometry, but can also take a long time.

relaxTolerance(rt)This sets the tolerance which is used to determine when the relaxation process can stop. Smaller tolerances yield better results but can take much longer.

maxRelaxIterations(mri)The relaxation process is an iterative algorithm. Using this flag will put an upper limit on the number of iterations that will be performed.


Move UVs in the texture plane to avoid overlaps.


place the UVs of the selected polygonal objects so that they do not overlap.

layout(l)How to move the UV pieces, after cuts are applied: 

0 No move is applied. 1 Layout the pieces along the U axis. 2 Layout the pieces in a square shape. 3 Layout the pieces in grids. 4 Layout the pieces in nearest regions.

gridU(gu)The U size of the grids.

gridV(gv)The V size of the grids.

rotateForBestFit(rbf) How to rotate the pieces, before move: 0 No rotation is applied. 1 Only allow 90 degree rotations. 2 Allow free rotations.

Scale(sc)How to scale the pieces, after move: 0 No scale is applied. 1 Uniform scale to fit in unit square. 2 Non proportional scale to fit in unit square.

layoutMethod(lm)0 Block Stacking.1 Shape Stacking.

offsetU(ou)Offset the layout in the U direction by the given value.

offsetV(ov)Offset the layout in the V direction by the given value.

sizeU(su)Scale the layout in the U direction by the given value.

sizeV(sv)Scale the layout in the V direction by the given value.

prescale(psc)Prescale the shell before laying it out. 

0 No scale is applied. 1 Object space scaling applied. 2 World space scaling applied.

flipReversed(fr)If this flag is turned on, the reversed UV pieces are fliped.

percentageSpace(ps)When layout is set to square, this value is a percentage of the texture area which is added around each UV piece. It can be used to ensure each UV piece uses different pixels in the texture. Maximum value is 5 percent.

uvSetName(uvs)string Specifies the name of the uv set to edit uvs on. If not specified will use the current uv set if it exists.


constructionHistory(ch)Remove the construction history on the objects specified or selected.


This command is used to create a UV Editor and to query or edit the texture editor settings.


Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).


All these commands became a bit overwhelming, really need some feedback and to look at the practical side of how they might work and could be applied to the script.

The script would start with these ideas:

  • The user selects the UV Mapped model or models in the Maya viewport which returns the number of shells in the selection to the script.
  • The number of shells will determine how many UV tiles there will be along the U axis.
  • The UV Texture Editor’s settings and coordinates including the number of tiles to be build into the script and determined by the number of shells.
  • Each shell to be scaled to fit the UV tile , unwrapped with consideration to preserving the ratio of the shape.
  • Open the UV texture editor when putting each shell into the tile so the user can see and access the UV texture editor’s.

On further reading of the python commands I would start the script by considering the following ones:

polyEvaluate: can return the number of shells as an int

polyEditUV:  edits UV on polygonal objects.  The query flag returns the uv values associated with the specified components.  Also has scale(s) which specifies whether this command is editing the values with scale values.

polyEditUV Shell: edits uv shells on polygonal objects. When used with the query flag, it returns the transformation values associated with the specified components.

untangles: non-overlapping regions in texture space. Uniform – every edge is weighted the same.

polyMultiLayoutUV:  places UV’s of the selected polygonal objects so they do not overlap. Layout the pieces in the U axis, with the option for not rotation, scale to uniform to fit the unit saucer, flip reversed so the reversed UV pieces are flipped.

delete: has a construction history for objects specified or selected.

The suggested UI window below with the user to follow the yes or no options.

uvToolLayout_UIwindowWEEKLY  TASKS

Week 1 Task

  1. Who is the creator of Python?

The creator of Pyton is the Dutch man, Guido van Rossum, developed in the late eighties and early nineties at the National Institute for Mathematics and Computer Science in the Netherlands and being first released in 1991.

2. How did Python get its name?

Guido van Possum named the Python language after the BBC comedy show “Monty Python’s Flying Circus”.

3Name some of benefits of the  Python language?

Some of the benefits of the Python language are that it is a simple and minimalistic language, easy to read and use, with few keywords and a simple structure with clearly defined syntax rather than the syntax and structure of some other languages.  A free and open source language, it can be copied and modified and is based on the concept of a community which shares knowledge.

Python is portable, translating into the native language of the computer thus working on many platforms and using the same interface, platform independent .  It is also referred to as a ‘Glue’ language meaning it can be integrated with other languages such as C, C++ and Java.

DYNAMICALLY  TYPED  LANGUAGE, python works out the data type as opposed to strongly typed languages that require the data type to be specified. An example would be when programming languages represent data types such as integers, in dynamically typed languages this does not need to be specified e.g. x = 10, while strongly typed languages do need to specify the date type in the script e.g. int x = 10, before declaring the variable. Python works out that 10 is an integer.

WHITE  SPACE is used to surround and create boundaries, using empty characters or spacing to create the boundaries that surrounds code, delimiter white space is created with tabs or a series of spaces. It denotes and controls the block structure with significant spacing and indentation as opposed to using brackets and curly brackets.

When indenting it becomes a child of the previous line and the parent has a colon which creates 4 spaces following it or the use of the tab key. The indentation, instead of curly brackets, is the same level of hierarchy, the same compound statement and the code responds based on these boundaries.  If indentation is lost or lines are broken the code will not work as intended.

It is visually readable and when the line or statement finishes python assumes there is nothing afterwards without the need to put the semi-colon.

INTERPRETED LANGUAGE  does not need compilation or converting to binary or machine-code with various flags and options in order to work.  It executes instructions directly, runs directly from the source code converting to bytecodes and is translated to the native language of the computer it is running on.  As it is complied into machine-friendly formats on the fly it can be slower and less efficient though it is more portable for use on computers, platform independent.

Last but not lease python is an OBJECT ORIENTED PROGRAMMING LANGUAGE (OOP) that supports classes, instances and methods which we have not covered yet. It is a way of organising the code as opposed to procedural programming which is like a recipe, a set of instructions to complete a task that is built around procedures or functions or reusable pieces of programs.

In object-oriented languages, objects are the centre of the process, building the program around them which combines data and functionality, instead of using them as necessary containers for information.

Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.’ page

Week 2 Task

I have 2 variables:

number = 87.459998899

version = 3

Using string formatting operators:

  1. Write the code required to give the number variable a floating-point precision of  3 digits

number = ‘%.3f’ % 87.459998899

>>> print number


2.Write the code required to give the version variable a padding of ‘0003’

version = ‘%04d’ % 3

>>> print version



Week 3 Task 

Identify the differences between a List and a Tuple.

Lists, like tuples are sequences containing any kind of date with some major differences:

  1. Lists use square brackets []  and tuples use parenthesis ().
  2. List are mutable, meaning the data can be modified or changed at anytime after it has been created.  Tuples are immutable, meaning after the content or data has been declared or defined it cannot be modified or changed.

If data is separated by a common then python will automatically make it a tuple.

It is possible to change the information in a tuple by passing a tuple back into a list, change or modify the list than pass back into a tuple.

Week 4 Task 

  1. In around 150 words describe what the Flow of Execution is?

The Flow of Execution is the order in which statements are executed, how conditions are meet.  This order is important, not necessarily being from top to bottom as a sequence, referred to as straight-line programming.

Statements can be executed using conditionals such as if-statements and loops to create some logic.  This controls the execution and creates branching or looping, like a detour back to previous statements, in the Flow of Execution to get the desired result.

Boolean logic, true or false values, is a way of making decisions and

meeting conditions, resulting in comparing values, asking questions and performing other actions.

To have options to make decisions, test and compare data types, Python uses operators allowing a sequence of values to be tested in a tuple. Examples of conditional operators are ==, !=, >, <,  >=, <=.

Python is adept at keeping track of where it is enabling the script to evaluate truth values for more than one operation.

2. L ist some statements/keywords that are used to control this Flow of Execution?

Python provides various tools for flow control including if, elif, else which was covered this week.

The If Statement has if as a keyword followed by a text for the truth of a condition, what is going to be tested and is ended with a colon.  A condition is being evaluated, if something happens then do this.  It is a way of handling conditions, if it is true python prints out the required result and does not go on to the else or elif.

The else comes into play if something is false, asking if a condition is meet.  If false the script’s branches or streams are followed which is where the flow is directed.

There is also the elif giving additional options and the script will continue to check if other tests are true or false.  A chain of tests can be created, enabling a multitude of conditions to be tested or evaluated only if the result is False.

Conditionals and loops

Week 5 Task 

Some loop types can make use of the options:



Explain what these options do, and why we would use them.

Break and continue statements control the ability to alter the flow of execution over the block of code of some loop types.

The break statement is used to break out of a loop when a condition is meet, the loop does not continue, does not finish and is stopped from continuing to look through the rest of the loop regardless of weather the following conditions are true or false.  The iterations are terminated within the loop containing the break, stopping the execution of the loop immediately, including the else statement.  If it is inside a nested loop the break will terminate the innermost loop. The script resumes execution at the next statement, going to the statement after the last statement of the loop.

A break statement could be used when some external condition is triggered requiring an exit from the loop.  Another example is while loops have the possibility of running infinitely, using a break statement guarantees this will not occur thus preventing the system crashing and losing the script.

The continue statement is used to skip the rest of the code inside a loop for the current iteration only when a condition is true. The loop does not terminate but continues on with the next iteration by going back to the top of the loop and starting again.  It is returning control to the top of the loop without executing the current iteration, rejecting all the remaining statements in the current iteration of the loop and moving control back to the top of the loop.

A continue statement could be used when an external condition, such as input from a user, is triggered, then needing to skip a part of the loop and start the next execution at the beginning of the loop.

We have used the break and continue statements with while and for loops.

Python break and continue Statement

Python break, continue and pass Statements

 Week 6 Task

Write an example of a  Function based on the following:

1. is named – half_of

2. is able to take any amount of numerical arguments

3. adds all these arguments together

4. after adding them together, it  will divide the value by half

5. returns the final value

>>> def half_of(*args):

number = 0

for arg in args:

number += arg

total = number / 2

return total

>>> half_of(10,10,10)



def half_of(*args):

total = 0.0

for arg in args:

total += arg

total /= 2

return total

Week 7 Task 

Research Question:

Discover what the following built-ins are used for in Python version 2.7.

1. input()

2. raw_input()

The input( ) and raw_input( ) functions are awaiting input, the user to enter something, then taking their input when the enter key is pressed. They are processed the input in different ways, returning different results from the same input.

In python 2.x:

input( ) evaluates the input, whatever has been put into it. It is taking the input and performing and eval(), getting the raw input, sending it to eval and then returning the result.

input( )

3 * 4 **5


Expects a syntactically correct python statement and attempts to understand the data entered by the user. If hello world is entered it shows an error, needs to be ‘hello world’ and returns a string.

>>> input( )

hello world

Traceback (most recent call last):

File “<pyshell#2>”, line 1, in <module>

input( )

File “<string>”, line 1

hello world


SyntaxError: unexpected EOF while parsing

>>> input( )

‘hello world’

‘hello world’


raw_input( ) takes exactly what the user has typed and passes it back as a string. All it considers is that the entered data will be a string whether it is a string or anything, returning a string.  Returning the input in an unprocessed form.

raw_input( )

3 * 4 **5

‘3 * 4 **5’

Because of how input( ) works it has been considered a security risk, possible source of bugs and confusing. In python 3 the original input( ) has been scrapped and the function previously known as raw_input( ) is now input( ).  You can manually do what was the previous input( ), by using eval(input()) if you want the old functionality.

python 2.x python3.x

raw_input( ) ———-> input( )

input( )   ———-> eval(input( ))   ?or eval(raw_input(prompt))?

TEST – multiple choice answers

Question 1:  What would the statement “ring ‘%.2f’ % 123.456” print out?

Question 2:  Which of the following examples is the valid way to write a function in Python?

Question 3:  Which of the following examples is a valid Python if statement?

Question 4:  What keyword would you use to add an alternative condition to an if statement?

Question 5:  What symbol can be used to comment out a single line of code in Python?

Question 6:  Which one of the following examples would be used to check the type of data that variable “x” is linked to?

Question 7:  Which of the following statements is not true about Python?

Question 8:  In Python what keyword is used to output information to the console

Question 9:  What symbols can be used in pairs to comment out multiple lines of code?

Question 10:  What would the following function do?

def add_values(*args):


Question 11:  Which one of the following statements is valid for creating a tuple in Python?

Question 12:  Variable “x” is linked to a string value of  “10”.

Which of the following statements is the correct way to convert the contents of variable “x” to an integer?

Question 13:  Which one of the following examples provides the most efficient way to add 1 to an existing integer in Python?

Question 14:  Which one of the following statements is valid for creating a dictionary in Python?

Question 15:  Whiten of the following examples is the valid way to write a while loop in Python?

Question 16:  Which one of the following examples is a valid way to pass an integer stored in the variable “number” over to a string in Python?

Question 17:  Which one of the following examples would you use to print out the third item in the list variable “my_list”?

Question 18:  Variable “x” is linked to a int value of 20

Which of the following statements is the correct way to convert the contents of variable “x” to a string?

Question 19:  How would you add the string “DCE3D” to a variable called “name”?

Question 20:  Which one of the following statements is valid for creating a list in Python?


Text editor for code, markup and prose. 


from MEL Scripting for Maya Animators by Mark R. Wilkins and Chris Kazmier


Screen Shot 2015-02-03 at 11.03.22 pm

vector $pos = particleShape1.position;//creates a vector variable called $pos and sets it s value to the current particle’s position

float $posY = ($pos.x*$pos.x) + ($pos.z)*($pos.z);//new floating-point variable

particleShape1.position = <<$pos.x, $posY, $pos.z>>;//assemble the position vector again

vector $vel = particleShape1.velocity;//the initial velocity takes a frame to die and solve this

particleShape1.velocity = <<$vel.x, 0, $vel.z>>;


Programming for 3D: Studio 1 – MEL Report:  Top-Down Development Process

Top Down Development Process for MEL Project

Top down development is the process of designing a script from scratch.  My idea is for the user is be able to enter a predetermined number and have the timeline playhead move that number of frames either forward or backwards from the current playhead position.

  • identify the current position of the playhead
  • enter a value to move the playhead either forward or backwards
  • choose between forward or backwards when moving the playhead
  • calculate the offset timeline position from the current playhead position
  • move the playhead to the new current time position
  • store this as the current time
  • update as the new current playhead position
  • enter another number to move the new playhead position either forwards or backwards
  • create a display window for the user to enter the number for either forward or backwards
  • include in this display the option to select either forwards or backwards for the amount of frames entered

MEL Project



Script Name: tol_scriptFrameIncrimentMover.mel
Vincent Rossini & Therese O’Leary 291014
This script moves the timeline playhead forward or backwards
from the current playhead position by the number of frames
entered by the user through the displayed window


proc frameMover(string $direction)//the proc called frameMover requires a string as its arguement and the string is called $direction
float $offset = `floatField -query -value offsetFrame`;//the value entered by the user is queried
//offsetFrame being + or – of the playhead position and the offset

if($direction == “forward”)//the direction selected is equel to forward then the first part will happen, if false then the else part will happen
float $selectedFrame = `currentTime -q`; //will query the selected frame of the current position of the playhead
//pass the information to the named variable
float $offsetFrame = ($offset + $selectedFrame);//will add the offset value to the frame of the playhead position
//passes the value into the named variable
currentTime $offsetFrame;//the new current playhead position
else//when the direction is not forward then it will be backwards
float $selectedFrame = `currentTime -q`;//will query the selecte frame at the current time
float $offsetFrame = ($selectedFrame – $offset);//will subtract the offset value from the current playhead position
currentTime ($offsetFrame);//reads the new playhead position

if (`window -exists myWin`)//checks if the myWin exists
deleteUI -window myWin;//if true delete the existing myWin window

window -title “Frame Incriment”//flag for the name of the window as displayed
-minimizeButton false//turns the window’s minimize button off
-maximizeButton false//turns the window’s maximize button off
-sizeable true//makes the window interactively resizable
myWin; //use window command to create a window with a title called Frame Increment

rowLayout -numberOfColumns 3;//defines the layout of controls displayed in the window, three spaces across in a row
symbolButton -image “timeprev” -command “frameMover(\”backward\”)”;//the backwards arrow symbol from maya database in first space of row
//new idea here with string excape characters, two strings
//user presses the button the command flat to proc called frameMover to go backwards the value entered in the floatfield
floatField -value 10 -precision 1 -width 130 offsetFrame;//ability to enter numbers with one decimal place, has a default number and size, name
symbolButton -image “timenext” -command “frameMover(\”forward\”)”;//the forward arrow symbol from maya database in third space of row
//as for backwards only forward this time
showWindow myWin;//command to display the window in Maya interface


Week 6 Task

Based on the class exercise of the Average Position script and the following reading. In around 50-100 words, describe what Top-Down Design is?

Top-Down Design is the process of designing a script by breaking it down into steps, a list, a set of instructions that will tell Maya what to do and in what order.  Like using a recipe to make a cake.

Initially work out what is the intended outcome, what is the problem the script is going to solve, what does the user do?

Then before writing the code think through the plan, how is it going to work and list the details in the order of the scripts process. When considering how the script is going to work this order is important otherwise it will not work, the list is the order. Would I ice the cake before I baked it in the oven?

When scripting work through the list breaking down the steps further for each instruction or line of code.

The script will run into problems as you go and there will be more than one way to solve the problems. In class we had a script that worked for polys then what if we wanted to for nurbs?

Wilkins, M & Kazmier, C. (2005). Procedures and Functions. In: Cox, T MEL Scripting for MAYA Animators. 2nd ed. San Fransisco, CA: Morgan Kaufmann. 171-174.

Week 5 Task

In around 50-100 words, explain why you might want to use the Eval command?

 The eval command allows the user to execute MEL commands when using valid lines or statements of MEL. It is done when the MEL command is highlighted and Maya runs it as code at runtime.

Before the eval command is used the MEL command entered into the textfield is not being run as MEL. For example, the polyCube requested is not being displayed in the user’s scene. Maya is not running polyCube as code.

The eval command will create the polyCube in the scene thus executing the MEL command polyCube.  I am able to construct a valid statement and/or command in a string, run the string as an argument and the result is passed into the string, variable.  With the eval command we are now able to execute a string as a MEL command when a valid MEL command is entered into the user’s textfield.

Another thing we did in class:   We also run single statements, put them in quotes and the command flag will automatically see the string and do an eval. We used this when we were making our window, this cleared the type entered into the scrollField.

menuItem -label “Clear” -command “scrollField -edit -clear MSScrollField’;

Wilkins, M & Kazmier, C. (2005). Using MEL Commands. In: Cox, T MEL Scripting for MAYA Animators. 2nd ed. San Fransisco, CA: Morgan Kaufmann. 142.

Vince’s video

Week 4 Task

In around 100 words explain what Variable Scope (sometimes refered to as local and global variables) is?

A variable such as a float called $myAge can be declared as a local or global variable, this is its variable scope.

When I declare the float called $myAge as a local variable, using compound braces it is defined within that procedure, not affecting anything outside the compound statement. It is only visible within the procedure and separate from global variables.  If I create another local variable with the same name in another procedure the two variables are separate, unrelated and have no effect on each other’s value. The local variable overrides a global variable with the same name within the procedure.

When I declare the float called $myAge as a global variable it is defined outside the area of the scripts procedures, outside the curly braces.  A value is assigned to the global variable the first time Maya reads the script, after it is declared the global variable is visible to all MEL commands. This means that the global variable can be used and modified by any MEL command.

If I type print outside the curly braces, the local variable inside the compound statement will not print, it is not available.  If I type print inside the curly braces it will work.


float $myAge = 10;

print $myAge //will print


print $myAge //will not print

I can make variables inside a procedure visible globally by typing global inside the curly braces and declaring it as a global variable. The script will create and maintain a variable in one procedure and also make it available globally, outside that procedure.

global float $myAge = 10;

I cannot access this global variable from a completely different local variable, without typing global inside its set of compound braces.  This then traces the data back via the global scope to where the original local variable was declared.

Generally avoid global variables as it can be difficult to determine what variables your procedures and functions might change.  There are often multiple scripts with different variable data types using the same name which can causing variable clashing.

Wilkins, Mark R. MEL Scripting for Maya Animators. 2nd ed. Morgan Kaufmann Series in Computer Graphics and Geometric Modeling. Amsterdam ; Boston: Morgan Kaufmann, 2005.

Maya User Guide:,topicNumber=d30e793074

Vincent’s videos

Week 3 Task

Give a brief description of what each of the following property modes do when working with MEL command flags.

  • Create
  • Edit
  • Query

MEL command flags can be run in different modes using properties which are listed in the command documentation under properties. For example under the Cylinder command, the flags such as radius and spans are listed with the properties of C, Q and E meaning these can be run in Create, Query and Edit modes.

Create:  means to create.  It is not necessary to specify this in the script because when a MEL command is used to create something the create mode is the default. Maya assumes this, putting it in create mode if I do not specify that I want to edit or query an object. For the command cylinder, when I run it a cylinder is created using the default flag settings.  The command documentation list what the default settings are such as a radius of 1. When making a display window with a button, when I type button in the script and run it MEL will make a button.  When a MEL command is used to create an object, that MEL command is said to be used in create mode.

Edit:  is another mode that I can specify in the script to be able to edit or change something that already exists.  Some of the flags belonging to the commands that were used to create can also be run in edit mode to make changes in some way.  I could change the default radius or number of spans for the cylinder or the width or label of the button.  When doing this I need an argument because it is going to change the value. The argument types are listed in the command documentation eg to edit radius the argument type is linear.

Query: is used to retrieve the values of those attributes that have command-line arguments.  When the script is run querying a flag it will go and look for the value that is inside the command and return the value of something that already exists. I may need to query something in order to see what the user typed in, what is inside a field and/or a value used to create something.

In class we used a floatFieldGrp in our script to display the x value part only from the possible options to display the x, y, z in our front end window.  Later we were able to use query mode to find out which of these x, y, z display options we had used. For the create cylinder command it is possible to create a cylinder with a radius of 3 and later using the query mode ask the command flag, radius what is this value.

Week 2 Task

In around 100 words describe what the purpose of using operator precedence is?

You should also include one code example based upon your findings.

Maya follows rules to determine the order of operations, not knowing the order in which an expression will be calculated can and does give  wrong results.

Without any operator precedence the following calculation is read from left to right, in the order they appear, returning 30.

10 + 5 * 2 = 30.

When this script is run in Maya it returns a value of 20, because maya is evaluating the multiplication operation first, then the addition.  The multiplication has the greater of the precedences or operator precedence.

Using mel’s operator precedence, reference from Maya user guide below, the * will be calculated before the + and now the calculation = 20 with 5 * 2 being calculated first then 10 being added to the result.

To force a calculation to be done first, or override the default it can be done by grouping them using parentheses.  Being the first in the order of operator precedence  and having the highest precedence.

(10 + 5) * 2 = 30

When operators with the same precedence are encountered in a statement, they are grouped from left to right in the order they appear and evaluated left to right. 

Complete Maya Programming: An Extensive Guide to MEL and C++ API, By David Gould, page 90 & 91 of the link.

For example

7 – 1 + 4 = 10

to override this it is possible to do the addition first using parentheses.

7 – (1 +4) = 2

Maya User Guide:

The following shows the order of operator precedence in MEL. Operators on the same row have equal precedence. If a statement has two or more operators with the same precedence, the left-most operator is evaluated first. Unary and assignment operators are right associative; all others are left associative.



Week 1 Task

Based upon this weeks readers, and what you have learned in class. Please anwser the following questions.

  • What type of variable would you use to store alpha-numeric charactors in?


  • An array’s first index value is always what?

Zero, whatever the data is the first slot is always zero.

  • What happens if you redclare a variable name as a different type?

When declaring a variable the space in ram is crated with the data type eg int, when redeclaring a different variable data type because the space in ram was designed as an int and now I may want a float it will redeclare  it as ‘invalid redeclaration’.  A couple of options to deal with this is to either restart the program or use a different name.


Scripting for Computer Graphics

MEL and Expressions version 6

Movilizer Expression Language

Variables in MEL


Wilkins, M & Kazmier, C. (2005). Procedures and Functions. In: Cox, T MEL Scripting for MAYA Animators. 2nd ed. San Fransisco, CA: Morgan Kaufmann. 171-174.

Karmic Hariharan

WEB:  – MEL Scripting for Maya Animators by Mark R Wilkins and Chris Kazmier – Creative Crash – CG Society – Alias, Autodesk


Question 1

a) What does the acronym MEL stand for?

b) Give a brief explanation of one reason to use MEL

Question 2

What is the definition of a variable?

Question 3

Name (4) variable data types found in MEL

Question 4

a) If you wish to store a whole number in a variable, which data type would be used?

b) If you wish to store a series of words in a variable, which data type would you use?

Question 5

a) What resource would you use to check the synopsis of a particular MEL command?

b) What does the “M” property mean with regard to a command’s flag?

Question 6

a) What is operator precedence?

b) Using the Print command and Operator Precedence; fix the statement below to ensure that:

10 + 5 x 10 will equate to 150

Question 7

You want to create a NURBS sphere with a radius of 10 and store the name of the newly created sphere in a string array variable called $ballName, however there are 2 syntax errors in the following MEL statement:

string ballName[] = sphere -radius 10;

Re-write the statement with the required corrections.

Question 8

a) Name MEL’s primary conditional statement keyword?

b) Give a brief description for the purpose of a conditional statement?

Question 9

Give a brief description of what variable scope is?

Question 10

You need to run multiple MEL statements with a single word.

a) Name the MEL feature you would use to take care of the above situation?

b) Name the button -flag you would use to execute some MEL when your button is pressed?


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: