Quantcast
Channel: mel wiki
Viewing all 610 articles
Browse latest View live

PyMel : Basics


How can I execute Maya's version of Python outside of Maya?

$
0
0
Note: Wing can interact with Maya in three different ways. This is one of the three. See an overview here on the whole system: Interaction between Wing and Maya.

See Wing Setup Notes below for how to setup Wing to use this information.

Maya comes with its own cut of Python (see Python & Qt versions in Maya). The executable for that lives here on Windows:
c:\Program Files\Autodesk\Maya<version>\bin\mayapy.exe
Or here on Mac:
/Applications/Autodesk/maya<version>/Maya.app/Contents/bin/mayapy
You can execute this directly to launch an interactive prompt of Python (most commonly for batching purposes). Or, if you're running a Python IDE external to Maya, but you want Maya's Python calls to exist in it, you can point your IDE To that exe. There is often an option in your IDE to allow for this (Wing allows you to do this, for example).
Once that executable has been started, you still need load and initialize Maya into that session. Per Maya's docs: "These commands take a significant amount of time to execute as they are loading all of the Maya's libraries and initializing the scene." This is the code I use:
try:
    import maya.standalone
    maya.standalone.initialize()
    print "Imported maya.standalone\n"
except:
    print "Couldn't find 'maya.standalone' for import\n"
If you want that code to execute every time you launch Maya's version of Python (I do this in Wing), you can author the above code as a module, and point Python's PYTHONSTARTUP environment variable to it:
PYTHONSTARTUP = <somePath>\<somePythonStartupModule>.py
I have Wing execute this code for my 'Maya Python coding sessions'.


The maya.cmds() library is actually empty on disk (go take a look for yourself) other than the __init__.py module that defines that dir structure as a library:
C:\Program Files\Autodesk\Maya<VER>\Python\lib\site-packages\maya\cmds\
Although you can fully access all Maya commands through Python like 'maya.cmds.ls()', the Python ls() command wrapper has no physical location on disk: Until you execute the above code example (import maya.standalone ...), Python won't see any of the commands. If you want to get a better understanding, see the subject How does Maya populate maya.cmds?.

Wing Setup Notes

  • In Wing, create a new Project, and access the "Project Properties".
  • In the Environment tab:
    • Set "Python Executable" to "Custom", and browse to the path mentioned above with mayapy.exe in it.
    • Set "Environment" to "Add to inherited environment", and paste in the PYTHONSTARTUP path you authored above.
    • If you want Wing to be able to analyze your Maya-Python modules and give you functionality like "Go To Selected Symbol Definition" (ctrl+LMB on a symbol name, F4 hotkey on a symbol, etc), you can add the paths where they're stored to the "Python Path" section of the ui. If you're using Python's packaging system, you only need to add the root dir of each package to this field.
    • Hit OK
  • Be sure to "Save Project" ;)

Query Maya Executable Location

$
0
0
Querying this in a Python script ran in Maya is pretty trivial: maya.exe and mayapy.exe (the Python executable) live in the same directory for Windows:
import os
import sys
maya = os.path.join(os.path.split(sys.executable)[0], 'maya.exe')
print maya
C:\Program Files\Autodesk\Maya<version>\bin\maya.exe
On Mac, it's a bit different:
import os
import sys
maya = os.path.join(os.path.split(sys.executable)[0], 'maya')
print maya
/Applications/Autodesk/maya<version>/Maya.app/Contents/MacOS/maya
Since the mayapy app lives here:
/Applications/Autodesk/maya<version>/Maya.app/Contents/bin/mayapy

Via PyMel (Mac result)
import pymel.mayautils as pmu
print pmu.getMayaLocation()
/Applications/Autodesk/maya2013/Maya.app/Contents

Welcome

$
0
0
About mel wiki (go here first)
Instructions For Use (go here second)
Check out the latest updates (go here third).
...Always refresh your cache (F5 on most PC browsers) to see the latest stuff...

Browse \ Search using:

<--- Major Categories (or 'All Subjects') in the Left column
Key-word Tags in the Right column (press Ctrl+f to open your browser's search, makes it very easy) --->


Running tiddlywiki v2.4.0
If you find this wiki useful, let the author know :-)
Copyright Information


If you want to copy a link to a specific tiddler (post) on this wiki:
  • Open the tiddler in question
  • In the top-right corner of the tiddler, press the 'close others' button: It should be the only tiddler visible now.
  • In the top-right corner of the wiki, press the 'permaview' button.
  • The full path to this specific tiddler will now be in the address bar: You can copy\paste it.

Why is my Script Editor slow to open?

$
0
0
A number of people have reported their Script Editor windows taking a 'long time' to open, and once open, seem to have poor performance.

As it turns out, it looks like they're running out of hard drive space, and this seems to be an odd side effect.

Why do I loose uv's when combining objects?

$
0
0
Recently one of my modelers would consistently loose uv's on one of two mesh objects being combined.
As it turns out, one of the mesh was from a much older version of Maya (2007?), and it's uv's would just vaporize when combined with the 'newer' mesh. To fix, he had to export the old mesh as an obj, re-import it into Maya. Then it would combine and not loose uv's.

what....?

PyMel : Finding parent nodes

$
0
0
I thought it would be useful to track how to find different parental nodes based on different selection types.

Vertex

import pymel.core as pm

# Select a single vertex
vert = pm.ls(selection=True)[0]  # MeshVertex
meshShape = vert.node()  # Mesh
transform = meshShape.getParent() # Transform

Docs:

PyMel node-types:

API: How can I loop over component selections?

$
0
0
Pulled a bunch of below from this post:
http://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/maya/MSelectionList2.html

The below example has all the variable names set to their object types. I did this just to illustrate how the objects were returned and used, don't recommend it for regular coding sessions...

The below example will loop over each object, and the components selected on that object. It will print the worlds-pace position of each point that is part of the component selection.
# Python code
import maya.OpenMaya as om

# Make a MSelectionList container object:
MSelectionList = om.MSelectionList()
# Fill with selection, as MObjects
om.MGlobal.getActiveSelectionList(MSelectionList)
# Create an iterator to loop over our selection:
MItSelectionList = om.MItSelectionList(MSelectionList)

while not MItSelectionList.isDone():
    # The mesh node:
    MDagPath = om.MDagPath()
    # The components, if any:
    MObject = om.MObject()

    # Define the path to our object and components.
    MItSelectionList.getDagPath(MDagPath, MObject)

    # Create a function set for this MDagPath.  MDagPath.node() returns an MObject.
    MFnDependencyNode = om.MFnDependencyNode(MDagPath.node())
    # We can now do work on the object if we want to.

    print MDagPath.fullPathName()

    # If we have components:
    if not MObject.isNull():
        # Make an iterator for them:
        MItGeometry = om.MItGeometry(MDagPath, MObject)
        while not MItGeometry.isDone():
            # Make a point object for the current loop:
            MPoint = MItGeometry.position(om.MSpace.kWorld)
            # And print its info:
            print "\t-vert index: %s   -pos: %s %s %s"%(MItGeometry.index(),
                                                        MPoint.x, MPoint.y, MPoint.z)
            MItGeometry.next()

    MItSelectionList.next()

Python & Qt versions in Maya

$
0
0
MayaPythonQtCompatible PyQtCompatible PySide
8.52.4.3
20082.5.1
20092.5.1
20102.6.1
20112.6.44.5.3??
20122.6.44.7.1??
20132.6.44.7.14.9.1?
20142.7.34.8.24.101.1.2 - Ships with Maya!
Starting in 2011, Maya's entire ui back-end was converted to Qt. You still use the same Maya commands to author UI's, but behind the scenes Qt is appearing on your screen.

This is not to be confused with PyQt or PySide, which are Python (not Maya) implementations of Qt. You can also get PyQt& PySide working in Maya, if you jump through some hoops, if using versions before 2014: Starting in 2014, PySide started shipping with Maya: No more needing to compile PyQt.

How can I add the selected items to the selected sets?

$
0
0
Say you have a set hierarchy in the Outliner, and you want to quickly pick one or more sets, add select one or more objects, and add the selected objects to the selected sets. Maya has the 'Sets Relationship Editor', but I find it's implementation very clunky.
# Python code
import maya.cmds as mc

sel = mc.ls(selection=True)
nodes = []
sets = []
for item in sel:
    if mc.objectType(item) == "objectSet":
        sets.append(item)
    else:
        nodes.append(item)
        
for s in sets:
    mc.sets(nodes, addElement=s)
A slightly different way: Add selected items to the single selected set. If more than one set is picked, error. Done in PyMel:
# Python / PyMel
import maya.OpenMaya as om
import pymel.core as pm

sel = pm.ls(selection=True)

allsets = []
nonset = []
for item in sel:
    if isinstance(item, pm.nt.ObjectSet):
        allsets.append(item)
    else:
        nonset.append(item)

if not len(allsets)==1:
    om.MGlobal.displayError("Please select exactly one set node")
else:
    pm.sets(allsets[0], forceElement=nonset) 
    print "Added items to set '%s':"%theset, [item.name() for item in nonset]

How can I open a window for a given directory:

$
0
0
Starting in Maya 2014, they added a -directory flag to the launch command:
// mel
launch -directory "c:/temp"
# Python
import maya.cmds as mc
mc.launch(directory="c:/temp")
Optionally you can do this in pure Python. Note on Windows the paths need to be backslashed:
import os
import subprocess

os.system('explorer c:\\temp')
# or:
subprocess.Popen(['explorer', 'c:\\temp'])
On Windows this should open Explorer, on Mac, Finder.

Very easily, you can write code that will open a window for the currently (saved) scene:
import os
import maya.cmds as mc

sceneName = mc.file(query=True, sceneName=True)
sceneDir = os.path.dirname(sceneName)
mc.launch(directory=sceneDir)

How can I find the namespace of a file when referenced?

$
0
0
When referencing multiple files into the same scene while passing each the same namespace, Maya will automatically increment the namespace name. But via code, this can be tricky to find out. PyMel makes this pretty easy via its createReference command: It returns back a FileReference object on which you can query a .namespace attr, that holds the namespace name that was used (and possibly incremented):
import pymel.core as pm

assetPath = "c:/temp/myAwesomeAsset.ma"
ns = "myAwesomeNamespace"
myRef = pm.createReference(assetPath,namespace=ns)
newNS = myRef.namespace
PyMel Docs :

Thanks to Mason Sheffield for the tip.

How can I snap keyframes to integer frames?

$
0
0
I started to write some code for this and... there's already a command: snapKey

What script holds the commands the Channel Box executes?

$
0
0
\Autodesk\Maya20XX\scripts\startup\channelBoxCommand.mel
For example, if you RMB on an entry and choose "Freeze -> Translate", the command for that is in here.

Rigging Demos


How can I make an object (transform) stick to a vertex (component)?

PyMel : Filtering selection types

$
0
0
Often you want to detect what type of thing is selected and filter that into different lists: transform, vertex, edge, joint, etc.
This is pretty easy to do via PyMel's internal types. For example, filter by vertex and joint selection:
import pymel.core as pm

verts = []
joints = []
sel = pm.ls(selection=True, flatten=True)
for item in sel:
    if isinstance(item, pm.MeshVertex):
        verts.append(item)
    elif isinstance(item, pm.nt.Joint):
        joints.append(item)

print verts
print joints
The various node & component types can be found under these two docs:

PyMel : Querying a nodes existence

$
0
0
This PyMel doc shows how you can query a nodes existence using a try/except clause, trying to create a PyNode. In my head, this seemed like a really slow option compared to using the objExists command, so I thought I'd do a speed test on them.

As you can see from the below results: calling to Python objExists command was 3x faster than the equivilant PyMel and mel command, and it was 171x faster than the try/except/PyNode clause.
import maya.cmds as mc
import pymel.core as pm

import time

class Timer(object):
    def __init__(self, f):
        self.f = f
    def __call__(self):
        start = time.time()
        for i in range(1000):
            self.f()
        end = time.time()
        total = end - start
        print ("Completed 1000 iterations of %s() in %.6f seconds, %.6f per loop"+
               "")%(self.f.__name__, total, total/1000.0)
        return [total, self.f.__name__]
        
@Timer
def pymelTestExistence():
    try:
        pm.PyNode("asdf")
    except:
        pass

@Timer       
def pymelCmdTestExistence():
    pm.objExists("asdf")
 
@Timer   
def cmdTestExistence():
    mc.objExists("asdf")

speedTest = []        
speedTest.append(pymelTestExistence())
speedTest.append(pymelCmdTestExistence())
speedTest.append(cmdTestExistence())

speedTest.sort()
for speed in speedTest:
    print speed
// Here's a mel version too:
timer -startTimer;
for($i=0;$i<1000;$i++){
    objExists("asdf");
}
float $elapsedTime = `timer -endTimer`;
float $eachLoop = $elapsedTime / 1000.0;
print ("Completed 1000 iterations of mel 'objExists' in " + $elapsedTime + " seconds, " + $eachLoop + " per loop.\n");
Completed 1000 iterations of pymelTestExistence() in 0.856000 seconds, 0.000856 per loop
Completed 1000 iterations of pymelCmdTestExistence() in 0.018000 seconds, 0.000018 per loop
Completed 1000 iterations of cmdTestExistence() in 0.005000 seconds, 0.000005 per loop
[0.004999876022338867, 'cmdTestExistence']
[0.017999887466430664, 'pymelCmdTestExistence']
[0.8559999465942383, 'pymelTestExistence']
Completed 1000 iterations of mel 'objExists' in 0.015 seconds, 0.000015 per loop.

PyMel: Mesh methods

$
0
0
Also see: PyMel : Mesh access

Condensation of the PyMel Mesh docs:
Methods, from 2014 docs:
  • addHoles : Adds holes to a mesh polygon.
  • area : returns the surface area of the object’s faces in local space as a float
  • assignColor : This method maps all colors for the mesh.
  • assignUV : Maps a texture coordinate to a specified vertex of a polygon
  • assignUVs : This method maps all texture coordinates for the mesh.
  • cleanupEdgeSmoothing : updates the mesh after setEdgeSmoothing has been done
  • clearColors : clears out all color for the mesh, and leaves behind an empty color set.
  • clearUVs : clears out all texture coordinates for the mesh, and leaves behind an empty UVset.
  • createColorSet : Create a new empty color set for this mesh.
  • createUVSet : Create a new empty uv set for this mesh.
  • deleteColorSet : Deletes a named color set from the object.
  • deleteUVSet : Deletes a named uv set from the object.
  • getAssignedUVs : Get assigned UVs. This method finds all texture coordinates for the mesh that have been mapped, and returns them in the same format as the assignUVs.
  • getAssociatedUVSetTextures : Get a list of texture nodes which are using a given uv set.
  • getBinormals : Return the binormal vectors for all face vertices.
  • getCheckSamePointTwice : Return true if checking for duplicate points is turned on. Return false otherwise.
  • getClosestNormal : Returns the closest point on this surface to the given point. This method also returns the surface normal at that point.
  • getClosestPoint : Returns the closest point on this surface to the given point.
  • getClosestPointAndNormal : Returns the closest point on this surface to the given point. This method also returns the surface normal at that point.
  • getColor : Get the value of the specified texture coordinate from this mesh’s color list.
  • getColorRepresentation : returns the color representation (RGB/RGBA/A) of a color set.
  • getColorSetFamilyNames : Get the names of all of the color set families on this object.
  • getColorSetNames : Get the names of all of the colors sets on this object.
  • getColors : copies the color array for this mesh into the given color array.
  • getCurrentColorSetName : Get the name of the “current” or “working” color set.
  • getCurrentUVSetName : Get the name of the “current” uv set.
  • getDisplayColors : Determine if the mesh node is set to display vertex colors.
  • getEdgeVertices : retrieves the object-relative (mesh-relative/global) vertex indices corresponding to the specified edge.
  • getFaceNormalIds : Return normal indices for all vertices for a given face.
  • getFaceUVSetNames : returns the list of UV sets mapped to a face.
  • getFaceVertexBinormal : Return the binormal vector at a given face vertex.
  • getFaceVertexBinormals : Return all per-vertex-per-face binormals for a given face.
  • getFaceVertexColorIndex : Get an index into the array returned by getFaceVertexColors.
  • getFaceVertexColors : Get colors for all vertex/faces of the given color set.
  • getFaceVertexNormal : Return a per-vertex-per-face normal for a given face (polygon) and given vertex.
  • getFaceVertexTangent : Return the normalized tangent vector at a given face vertex.
  • getFaceVertexTangents : Return all per-vertex-per-face tangents for a given face.
  • getHoles : Retrieves a list of the holes in the polygon.
  • getNormalIds : Return normal indices for all vertices for a all faces.
  • getNormals : This method copies the normal list for this mesh into the given array.
  • getPoint : Get the position of the specified vertex in this mesh’s vertex list.
  • getPointAtUV : Return the position of the point at the given UV value in the current polygon.
  • getPoints : copies the vertex list for this mesh into the given point array.
  • getPolygonNormal : Return the normal at the given polygon
  • getPolygonTriangleVertices : retrieves the object-relative (mesh-relative/global) vertex indices for the specified triangle in the specified polygon
  • getPolygonUV : Get the value of the specified texture coordinate for a vertex in a polygon.
  • getPolygonUVid : Get the id of the specified texture coordinate for a vertex in a polygon.
  • getPolygonVertices : retrieves the object-relative (mesh-relative/global) vertex indices for the specified polygon.
  • getTangentId : Return the tangent index for a given face vertex.
  • getTangents : Return the tangent vectors for all face vertices.
  • getTriangles : Returns the number of triangles for every polygon face and the vertex Ids of each triangle vertex.
  • getUV : Get the value of the specified texture coordinate from this mesh’s uv list.
  • getUVAtPoint : Find the point closet to the given point, and return the UV value at that point.
  • getUVSetFamilyNames : Get the names of all of the uv set families on this object.
  • getUVSetNames : Get the names of all of the uv sets on this object
  • getUVSetsInFamily : Get the names of the uv sets that belong to this set family.
  • getUVs : copies the texture coordinate list for this mesh into the given uv arrays.
  • getUvShellsIds : Constructs an array of unique integer for each UV shell.
  • getVertexNormal : Return the normal at the given vertex.
  • getVertices : retrieves the object-relative (mesh-relative/global) vertex indices for all polygons.
  • hasAlphaChannels : returns true if the color set has Alpha component.
  • hasColorChannels : returns if the color set has RGB components.
  • intersect : Determines whether the given ray intersects this polygon and if so, returns the points of intersection
  • isColorClamped : returns if the color set has its R,G,B,and A components clamped in the range from 0 to 1.
  • isColorSetPerInstance : Return true if this color set is per-instance, and false if it is shared across all instances.
  • isEdgeSmooth : determines if the specified edge is smooth (soft).
  • isNormalLocked : Test if the normal for a face/vertex pairs is locked (user defined).
  • isPolygonConvex : determines if the specified polygon is convex.
  • isUVSetPerInstance : Return true if this set is per-instance, and false if it is shared across all instances.
  • lockFaceVertexNormals : Lock Normals for these face/vertex pairs
  • lockVertexNormals : Lock Shared Normals for these vertices.
  • numColorSets : Returns the number of color sets for an object.
  • numColors : Returns the number of (vertex) color for this mesh.
  • numEdges : returns the number of edges as an int
  • numFaceVertices : Returns the number of face-vertices for this mesh.
  • numFaces : returns the number of faces as an int
  • numNormals : Returns the number of per-polygon per-vertex normals for this mesh.
  • numPolygonVertices : Returns the number of vertices for the specified polygon.
  • numSelectedEdges : returns the object’s number of selected edges as an int
  • numSelectedFaces : returns the object’s number of selected faces as an int
  • numSelectedTriangles : returns the number of triangles of selected components as an int
  • numSelectedVertices : returns the object’s number of selected vertices as an int
  • numTriangles : (no docs)
  • numUVSets : Returns the number of uv sets for an object.
  • numUVs : Returns the number of texture (uv) coordinates for this mesh.
  • numVertices : returns the number of vertices as an int
  • onBoundary : determines whether the specified face in the mesh is a boundary face.
  • removeFaceColors : Remove previously set color these faces.
  • removeFaceVertexColors : Remove colors for these face/vertex pairs
  • removeVertexColors : Remove color from these vertices.
  • renameUVSet : Renames a uv set from one name to another for this mesh.
  • setCheckSamePointTwice : This method allows the turning on or off of duplicate point checking when polygons are created or added using this class.
  • setColor : Sets the specified color values.
  • setColorClamped : Set the color set to be clamped.
  • setColors : Sets all of the colors for this mesh.
  • setCurrentColorSetName : Set the “current” or “working” color set for this object.
  • setCurrentUVSetName : Set the “current” uv set for this object.
  • setDisplayColors : Set whether the mesh node should display vertex colors.
  • setEdgeSmoothing : This method sets the specified edge to be hard or smooth (soft)
  • setFaceColor : Set vertex-face Color for all vertices on this face.
  • setFaceColors : Set color for these faces.
  • setFaceVertexColor : Set color for this vertex in this face.
  • setFaceVertexNormal : Set Normal for this face/vertex pair
  • setNormals : Set the normal array (user normals)
  • setPoint : Sets the position of specified vertex in the vertex list for this mesh.
  • setPoints : copies the points in the given point array to the vertices of this mesh.
  • setSomeColors : Sets the specified colors for this mesh.
  • setSomeUVs : Sets the specified texture coordinates (UV’s) for this mesh.
  • setUV : Sets the specified texture coordinate.
  • setUVs : Sets all of the texture coordinates (uv’s) for this mesh.
  • setVertexColor : Set color for this vertex.
  • setVertexNormal : Set Shared Normal for this vertex
  • syncObject : If a non-api operation happens that many have changed the underlying Maya object wrapped by this api object, make sure that the api object references a valid maya object.
  • unlockFaceVertexNormals : Unlock Normals for these face/vertex pairs
  • unlockVertexNormals : Unlock Shared Normals for these vertices
  • updateSurface : Signal that this polygonal mesh has changed and needs to redraw itself.
  • worldArea : returns the surface area of the object’s faces in world space as a float
Classmethods:
  • polyTriangulate : Triangulates a polygon.

PyMel : MeshVertex methods

$
0
0
Also see: PyMel : Mesh access

Condensation of the PyMel MeshVertex docs:
Methods, from 2014 docs:
  • connectedEdges : Return MeshEdge list.
  • connectedFaces : Return MeshFace list.
  • connectedVertices : Return MeshVertex list.
  • geomChanged : Reset the geom pointer in the MItMeshVertex .
  • getColor : No docs
  • getColorIndices : returns the colorIndices into the color array
  • getColors : This method gets the colors of the current vertex for each face it belongs to.
  • getNormal : Return the normal or averaged normal if unshared of the current vertex.
  • getNormalIndices : This method returns the normal indices of the face/vertex associated with the current vertex.
  • getNormals : Return the normals of the current vertex for all faces
  • getPosition : Return the position of the current vertex in the specified space.
  • getUV : Get the shared UV value at this vertex
  • getUVIndices : returns the uv indices into the normal array
  • getUVs : Get the UV values for all mapped faces at the current vertex.
  • hasColor : This method determines whether the current Vertex has a color set for one or more faces.
  • isConnectedTo : pass a component of type MeshVertex, MeshEdge, MeshFace, with a single element
  • isConnectedToEdge : This method determines whether the given edge contains the current vertex
  • isConnectedToFace : This method determines whether the given face contains the current vertex
  • isOnBoundary : This method determines whether the current vertex is on a Boundary
  • numConnectedEdges : This Method checks for the number of connected Edges on this vertex
  • numConnectedFaces : This Method checks for the number of Connected Faces
  • numUVs : This method returns the number of unique UVs mapped on this vertex
  • setColor : No docs.
  • setPosition : Set the position of the current vertex in the given space.
  • setUV : Set the shared UV value at this vertex
  • setUVs : Set the UV value for the specified faces at the current vertex.
  • translateBy : Translate the current vertex by the amount specified by the given vector.
  • updateSurface : Signal that this polygonal surface has changed and needs to redraw itself.
Viewing all 610 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>