Tuesday, January 06, 2009

float2 and float3 in Maya Python API

Staying true to form, Autodesk sure has made a mess of the Maya Python API. Something I ran into recently was dealing with float2:s (for MFnMesh::getUVAtPoint()). Turns out you need to go through MScriptUtil like so:
import maya.OpenMaya as om
# this creates the float2
pArray = [0,0]
x1 = om.MScriptUtil()
x1.createFromList( pArray, 2 )
uvPoint = x1.asFloat2Ptr()
# (call to OpenMaya.MFnMesh.getUVAtPoint( ..., uvPoint, ... ) 
# goes here)
# retrieve results
uv0 = om.MScriptUtil.getFloat2ArrayItem( uvPoint, 0, 0 )
uv1 = om.MScriptUtil.getFloat2ArrayItem( uvPoint, 0, 1 )

Curiously enough the '2' in float2ptr and float2array refers to 2-dimensional arrays, hence the extra 0 in the call to the latter. We're only dealing with float2& (which typedefs to float[2]) in our getUVAtPoint call, but frankly: did you expect anything else than a hackfest when you popped that Maya 2009 box open?

Python stack trace

Outputting the stack trace can be immensely useful in certain situations.


import traceback, sys

def bar():
raise Exception('Booboo')

def foo():
bar()

try:
foo()
except:
traceback.print_exc()
print 'Got here.'


Result:

Traceback (most recent call last):
File "./foo.py", line 14, in
foo()
File "./foo.py", line 11, in foo
bar()
File "./foo.py", line 8, in bar
raise Exception('Booboo')
Exception: Booboo
Got here.