Object Utilities¶
Alignutils¶
- matchObjTransRot(alignObj, srcObj, message=True)¶
Matches an alignObj to srcObj. Tries:
Try 2017 and above new match
Maya Constraint and delete constraint method
- matchObjTransRotSelection()¶
Match Align based on selection (rotation and translation) Tries:
Try 2017 and above new match
Maya Constraint and delete constraint method
Matches to the first selected object, all other objects are matched to the first in the selection
- matchObjTransRotLists(alignObjList, srcObjList, message=False)¶
Matches an alignObj list to srcObj list, tries new match 2017+ if fail use Maya del parent constraint method
Try 2017 new match
Maya Constraint and delete constraint method
- matchObjRot(alignObj, srcObj)¶
Matches the rotation of a single obj to a srcObj.
Tries new match 2017+ if fail use Maya del parent constraint method Will break if values objToAlign are already managed, connected/constrained
- matchObjTrans(alignObj, srcObj)¶
Matches the translation of a single obj to a srcObj.
Tries new match 2017+ if fail use Maya del parent constraint method Will break if values objToAlign are already managed, connected/constrained
- Parameters:
alignObj – string The object to align
src – string the master object that the obj will align to
- matchObjScale(alignObj, srcObj)¶
Matches the scale of a single obj to a srcObj.
Tries new match 2017+ if fail use Maya del parent constraint method Will break if values objToAlign are already managed, connected/constrained
- Parameters:
objToAlign – string The object to align
srcObj – string the master object that the obj will align to
- matchObjPivot(alignObj, srcObj)¶
Matches the pivot of the alignObj to the srcObj, Only compatible 2017+
- matchAllSelection(translate=False, rotate=False, scale=False, pivot=False, message=True)¶
Match all selection, works for 2017 and above only
- findLowestVert(objLongName, worldSpace=True)¶
Finds the lowest point in world or local space, useful for snapping. Can be mesh curve or nurbs
- Parameters:
- Return index:
the index of the current vertex
- Rtype index:
int
- Return min:
The y value, will be in local or world space depending on the worldSpace kwarg
- Rtype min:
float
- placeObjectOnGround(obj)¶
Places an object on the ground.
The code builds a plane then matches the object to a plane, then deletes the plane
- Parameters:
obj (str) – A maya transform object name
- placeObjectOnGroundList(objList)¶
Places a list of objects on the ground.
- Parameters:
objList (list) – A list of maya transform object names
- placeObjectOnGroundSel(message=True)¶
Places selected objects on the ground.
- Parameters:
message (bool) – Report the message to the user?
- mayaAlignTool()¶
Enter Maya’s Align Tool mode
- mayaSnapTogetherTool()¶
Enter Maya’s Snap Together Tool mode
- snapPointToPoint()¶
Snap align 2 points to 2 points
- snap2PointsTo2Points()¶
Snap align point to point
- snap3PointsTo3Points()¶
Snap align 3 points to 3 points
Attributes¶
Functions related to Maya’s node attributes
Example use:
from zoo.libs.maya.cmds.objutils import attributes
attributes.shuffleAttr("eye_cntrl_L", "topLidDwn", up=True, message=True)
from zoo.libs.maya.cmds.objutils import attributes
print(attributes.listUserDefinedAttrs("eye_cntrl_L"))
Author: Andrew Silke
- createAttribute(node, attr, attributeType='float', channelBox=True, nonKeyable=False, defaultValue=0, minValue=None, maxValue=None)¶
Creates an attribute for attribute types:
“float”, “int” or “bool”
Simple one liner that handles non-keyable in the channel box more intuitively. Otherwise can use cmds.addAttr()
- Parameters:
node (str) – The object or node to add the new attribute to
attr (str) – The attribute’s name that will be created
attributeType (str) – The type of attribute to be created “float”, “int”, or “bool”
channelBox (bool) – Shows the attribute in the channel box or not
nonKeyable (bool) – Sets the attribute to be non-keyable in the channel box
defaultValue (float, bool or int) – The default value of the attribute
minValue (float, bool or int) – The minimum value of the attribute
maxValue (float, bool or int) – The maximum value of the attribute
- createEnumAttrList(node, attr, enumNames, channelBox=True, nonKeyable=False, defaultValue=False)¶
Creates a drop down attribute (enum attribute) from a list
- Parameters:
- Return driverAttr:
The driver attribute that was created ‘object.attribute’
- Rtype driverAttr:
str
- createConnectAttrs(sourceNode, sourceAttr, createTargetNode, createTargetAttr, defaultValue=0, minValue=None, maxValue=None, attributeType='float', channelBox=True, nonKeyable=False)¶
Creates an attribute on the createTargetNode and connects it
Supports “float”, “int”, or “bool”
- Parameters:
sourceNode (str) – The name of the source node
sourceAttr (str) – The name of the source attribute
createTargetNode (str) – The name of the node that the new attr will be created, must exist already
createTargetAttr (str) – The name of the attribute to be created
defaultValue (float, bool or int) – The default value of the attribute
minValue (float, bool or int) – The minimum value of the attribute, None will be ignored
maxValue (float, bool or int) – The maximum value of the attribute, None will be ignored
attributeType (str) – The type of attribute to be created “float”, “int”, or “bool”
channelBox (bool) – Shows the attribute in the channel box or not
nonKeyable (bool) – Sets the attribute to be non-keyable in the channel box
- proxyAttributes(obj)¶
Returns a list of proxy attribute names from an object or node.
- Parameters:
obj (str) – object or node name
- Return proxyAttrs:
A list of proxy attribute names
- Rtype proxyAttrs:
list(str)
- notProxyAttributes(obj)¶
TODO source from zapi directly
- setKeyIgnorePoxyAttrs(zapiNodeList)¶
TODO move into keyframe module
- setKeyIgnoreProxyAttrsSel()¶
TODO move into keyframe module
- addProxyAttribute(node, existingNode, existingAttr, proxyAttr='', channelBox=True, nonKeyable=False)¶
Creates a new proxy attribute on the given node.
If proxyAttr is left empty the function will use the existingAttr name as the proxyAttr name.
- Parameters:
node (str) – The maya object/node that the proxy attribute will be created on
existingNode (str) – The Maya obj that already exists with the attribute to be copied
existingAttr (str) – The existing attribute to be copied on the existing obj, don’t include obj
proxyAttr (str) – the name of the proxy attribute, if empty will clone the existingAttr name
channelBox (bool) – is the proxy attribute visible in the channelBox?
nonKeyable (bool) – is the proxy attribute keyable if in the channelBox?
- Return node:
The object name with the new proxy attribute
- Rtype obj:
str
- Return proxyAttr:
The attribute of the new proxy attribute
- Rtype proxyAttr:
str
- addProxyAttributeSel(driverNode, driverAttr, drivenNodeText='', drivenAttr='', channelBox=True, nonKeyable=False, message=True)¶
- addProxyAttrList(node, existingObj, existingAttrList, channelBox=True, nonKeyable=False)¶
Creates a proxy attributes from a list on the node from attributes on existingObj
If proxyAttr is empty will use the existingAttr name
- Parameters:
node (str) – The maya object the proxy attribute will be created on
existingObj (str) – The Maya obj that already exists with the attribute to be copied
existingAttrList (list[str]) – The existing attribute to be copied on the existing obj, don’t include obj
channelBox (bool) – is the proxy attribute visible in the channelBox?
nonKeyable (bool) – is the proxy attribute keyable if in the channelBox?
- lastNodeAttrFromSel(parent=False, message=True)¶
Returns the last object and its last attribute selected in the channel box.
- selObjsCommaSeparated(message=True)¶
Returns the selection as a str comma separated:
“pCube1, pCube3, pCube2”
- Parameters:
message (bool) – Report the message to the user
- Return objsString:
A single string comma separated of the selected object/s names. “pCube1, pCube3, pCube2”
- Rtype objsString:
str
- attributeDefault(node, attr, defaultValue, setValue=True)¶
Sets the attribute to a default value and changes the value to match.
- nodeShortName(nodeName)¶
- nodeShortNameList(nodeNameList)¶
- labelAttr(labelName, node, checkExists=False)¶
Adds a label attribute with the next attr named “_” the label name is the enum entry and the attr is locked.
- labelAttrSel(labelName, message=True)¶
Adds a label attribute with the next attr named “_” the label name is the enum entry and the attr is locked.
- getTransRotScaleAttrsAsList(transformNode)¶
Returns the attribute values of MAYATRANSFORMATTRS as a list, each value is a float value.
[“translateX”, “translateY”, “translateZ”, “rotateX”, “rotateY”, “rotateZ”, “scaleX”, “scaleY”, “scaleZ”]
- Parameters:
transformNode (str) – The transform or joint node name to return
- Return attrValueList:
list with all the float values
- Rtype attrValueList:
list(float)
- srtAttrsDict(transformNode, rotate=True, translate=True, scale=True)¶
Creates a dictionary with rot translate and scale attributes and their values.
Useful for copying default SRT values.
- setFloatAttrsDict(mayaNode, attrDict)¶
Sets the dictionary with attributes that are floats (or ints?)
Useful for pasting default SRT values
- setTransRotScaleAttrsAsList(transformNode, attrValueList)¶
Given an attribute value list set the rotation, translation, and scale values on a transformNode
- setAttrAutoType(node, attr, value, message=False, debugMe=False)¶
Sets a Maya attribute with auto type discovery functionality. Supports the most common attr types.
float
string
bool
enum
float3
double3
doubleLinear
double
doubleAngle
long
Ie. Will find the type of the attribute and this function adds the type flag into the cmds.setAttr command
- setAttrributesFromDict(node, attributeDict, message=False)¶
Takes an attribute dictionary and applies it to a node setting all the attributes d = {‘translateX’: (1.2, ‘diffuseColor’: (.5, .5, .5)}
- setAttCurrentDefault(obj, attr, report=True)¶
Sets an attribute’s current value to the default value
- setAllAttrsCurrentDefualts(obj, report=True)¶
Sets all the attributes current value of the given object to be the default value Will only work on user defined attributes as you’re unable to cahnge default attributes
- setSelCurValuesAsDefaults(report=True)¶
Iterates through the current object selection setting it’s current attribute values as the default values Will only work on user defined attributes as you’re unable to change default attributes
- Parameters:
report (bool) – report error messages?
- setAttrsShapeAuto(nodes, attr, value, includeTransforms=True, includeShapes=True, message=True)¶
Sets attributes on many objects with options to include shape nodes.
If the attribute is not found then the node will be ignored and not set.
Supports multiple attribute types see docs for setAttrAutoType()
- Parameters:
nodes (list(str)) – The maya node names to set
attr (str) – The attribute name to set
value (multipleTypes) – The value of the attribute multi-type (can be many types, str, float, int or list/tuple)
includeTransforms (bool) – Try to the selected nodes usually transforms but can be others.
includeShapes (bool) – Also try to set any shape nodes
message (bool) – Report a message to the user
- setAttrShapeAutoSel(attr, value, includeTransforms=True, includeShapes=True, message=True)¶
Sets attributes on the selected objects with options to include shape nodes and or transforms.
If the attribute is not found then the node will be ignored and not set.
Supports multiple attribute types see docs for setAttrAutoType()
- visibilityConnectObjs(visAttr, masterObj, objList, channelBox=True, nonKeyable=True, defaultValue=False)¶
Creates a new attribute that is a visibility switch for multiple objects.
- Parameters:
visAttr (str) – The attribute name to create that will toggle visibility
masterObj (str) – The object/control that will have the attribute
objList (list(str)) – The objects that will be affected with the visibility switch
channelBox (bool) – Show in the channelbox
nonKeyable (bool) – Make non-keyable if in the channelbox
defaultValue (bool) – The default visibility of the main attribute
- showAllAttrChannelBox(obj, translate=True, rotate=True, scale=True, visibility=True, channelBValue=True, keyable=True)¶
Shows Common (rotation, translation, scale and vis) attributes in the channel box
- Parameters:
obj (str) – Maya object name to reset
rotate (bool) – reset rotate
translate (bool) – reset translate
scale (bool) – reset scale
visibility (bool) – reset visibility
channelBValue (bool) – Display in the channel box, should be True in most cases
keyable (bool) – Make the attribute keyable, should be true in most cases
- checkAllAttrsZeroed(transformNode)¶
Checks to see if all the current pos values are zeroed, a useful check before freezing transforms. Uses a tolerance in case of micro values which is often on Maya objects.
Checks these values are zeroed:
[“translateX”, “translateY”, “translateZ”, “rotateX”, “rotateY”, “rotateZ”]
Checks these values are 1.0:
[“scaleX”, “scaleY”, “scaleZ”]
- Parameters:
transformNode (str) – The name of the Maya transform or joint node
- Return isZero:
True if zeroed, False if not
- Rtype isZero:
bool
- checkAllAttrsZeroedList(transformNodeList)¶
Checks to see if all the current pos values are zeroed on an object list, a useful check before freezing transforms. Uses a tolerance in case of micro values which is often on Maya objects.
Returns a list of True False values.
Checks these values are zeroed:
[“translateX”, “translateY”, “translateZ”, “rotateX”, “rotateY”, “rotateZ”]
Checks these values are 1.0:
[“scaleX”, “scaleY”, “scaleZ”]
- Parameters:
transformNodeList (list(str)) – A list of Maya transform or joint node names
- Return isZeroList:
A list of True or False values, True if the object is zeroed, False if not
- Rtype isZeroList:
list(bool)
- resetTransformAttributes(obj, rotate=True, translate=True, scale=True, visibility=False)¶
Resets the transforms (and potentially visibility) of a Maya object.
- srtIsZeroed(obj)¶
Returns True if the translate and rotate attributes and zeroes and the scale values are set to 1.0
- Parameters:
obj (str) – A maya transform name
- Return zeroed:
True if the translate and rotate attributes and zeroes and the scale values are set to 1.0
- Rtype zeroed:
bool
- createColorAttribute(node, attrName='color', keyable=True)¶
Creates a color attribute in maya on the node, attrName can be changed from color
- deleteNodesWithAttributeList(nodeList, attributeName)¶
deletes nodes that have an attribute with attributeName
- Parameters:
nodeList (list) – a list of maya nodes
attributeName (str) – the name of the attribute without the node
- Return deletedNodes:
list of the nodes that have been deleted
- Rtype deletedNodes:
list
- checkRemoveAttr(node, attrName)¶
Checks if the attribute exists and if it does remove/delete the attribute, deletes the parent if a vector etc
Also unlocks and disconnects before deleting.
- deleteAttributeSel(message=True)¶
Deletes selected attributes from the channel box selection. Can delete multiple on multiple objects.
- Parameters:
message (bool) – Report a message to the user?
- Return deletedAttrs:
list of strings, “node.attribute” example if successfully deleted.
- Rtype deletedAttrs:
str
- removeKeysAttr(node, attr, timeRange=(-10000, 100000))¶
Deletes all the keys on an attribute within the range
- lockAttr(node, attr, lock=True)¶
Simple function that locks/unlocks an attribute
- hideAttr(node, attr, hide=True, keyable=True)¶
- hideAttrs(node, attrs, hide=True, keyable=True)¶
- lockHideAttr(node, attr, lockHide=True, keyable=True)¶
Locks and hides an attribute.
If lockHide=False then show and unlock the attribute
- disconnectAttr(node, attr)¶
Disconnects using only one attribute, as per right click disconnect in the channel box.
- unlockDisconnectAttrs(node, attrList)¶
Unlocks/deletes keys/disconnects all attributes in a list on a single node
- unlockDisconnectSRT(node)¶
Unlocks/deletes keys/disconnects translate, rotate and scale
- Parameters:
node (str) – A maya node name
- unlockSRTV(obj, translate=True, rotate=True, scale=True, visibility=True, lock=False, keyable=True)¶
Unlocks All Common (rotation, translation, scale and vis) Attributes
- Parameters:
obj (str) – The name of the object
translate (bool) – Do you want to affect translate?
rotate (bool) – Do you want to affect rotate?
scale (bool) – Do you want to affect scale?
visibility (bool) – Do you want to affect visibility?
lock (bool) – this state will either lock or unlock, True will lock all attributes
- isSettable(obj, attr)¶
- getLockedConnectedAttrs(obj, attrList=None, keyframes=False, constraints=False)¶
Gets all the locked or connected attributes from either:
attrList=None: all keyable attributes on an object
attrList=list(attrs): the given attributes
Returns connected or locked attributes as a list, empty list if none found
- getLockedConnectedAttrsList(nodeList, attrList=None, keyframes=False, constraints=False)¶
Gets all the locked or connected attributes from a node list.
Attributes can be either:
attrList=None: all keyable attributes on an object
attrList=list(attrs): the given attributes
- Returns two lists:
lockedNodes: A list of nodes with locked or connected attributes lockedAttrList: Records the attrs locked/connected. Is a list(list) of attributes matching the lockedNodes
- Parameters:
- Return lockedNodes:
A list of nodes with locked or connected attributes, is empty if no locked or connected attrs
- Rtype lockedNodes:
list(str)
- Return lockedNodes:
Records the attrs locked/connected. Is a list(list) of attributes matching the lockedNodes
- Rtype lockedNodes:
list(list(str))
- disableNonUniformScale(obj)¶
Links the scaleX to the other two scales, so the object can’t be non-uniformly scaled.
- Parameters:
obj (str) – The transform node to disable non-uniform scale
- animatableAttrs(obj)¶
Returns a list of all the animatable attribute names on a node (channel box animatable, not locked etc.
- Parameters:
obj (str) – Name of the object or node
- Return attrs:
List of attribute names eg [u’visibility’, u’translateX’, u’translateY’, u’translateZ’, u’rotateX’]
- Rtype attrs:
list(str)
- listConnectableAttrs(obj)¶
List all the connectable attributes of a Maya node
- Parameters:
obj (str) – A Maya object or node name
- Return attributeList:
list of potentially connectable attributes on the node
- Rtype attributeList:
list(str)
- listConnectableAttrsSel(selectionIndex=0, message=True)¶
From the selection list all the connectable attributes
- removeUnsettableAttrs(obj, attrs)¶
Removes attributes that cannot be set.
- channelBoxAttrs(obj, settableOnly=True, includeProxyAttrs=True)¶
helper function to retrieve all the attributes listed in the channelbox as cmds does not support.
Extra support for returning only settable attrs and for including proxy attributes too.
- getChannelBoxAttrs(message=False)¶
Selected Chnnel box attributes. Returns the long name of the selected attribute from the channel box
Annoying function as it’s not easy to retrieve the long name. Mel has a one liner for short names.
selAttrs = mel.eval(‘selectedChannelBoxAttributes’)
- Parameters:
message (bool) – Report the message to the user
- Return attrNames:
list of long attribute names eg [“translateX”, “rotateX”]
- Rtype attrNames:
list(str)
- moveAttrBottomList(attrList, obj, indx)¶
Drops a single attribute to the bottom of the channel box. The list is updated as it’s been shuffled.
Note: Uses the Maya hack and is not undoable:
cmds.deleteAttr(attribute=attrList[indx], name=obj) cmds.undo()
- returnParentAttrs(obj, attrs, channelBoxOnly=True)¶
Filters out child attrs eg rotateX and returns only the parent
- listUserDefinedAttrs(obj, channelBoxOnly=True)¶
Returns the user defined attributes and only includes parent attributes.
Eg a vector of attributes becomes a single attr
blinkX, blinkY, blinkZ becomes blink
- shuffleAttr(obj, attr, up=True, message=True)¶
Shuffles attributes up and down in the channel box. up=True is up and up=False is down.
Note: Requires selection of the obj for the cmds.deleteAttr() weird, this function does not handle select
Note: Uses the Maya hack to drop attributes to the bottom of a list and is not undoable:
cmds.deleteAttr(attribute=attrList[indx], name=obj) cmds.undo()
- shuffleAttrChannelBoxSel(up=True, message=True)¶
From the channel box selection shuffle the attributes up or down.
Note: Uses the Maya hack and is not undoable:
cmds.deleteAttr(attribute=attrList[indx], name=obj) cmds.undo()
- openAddAttrWindow()¶
Opens Maya’s Add Attribute window
- openEditAttrWindow()¶
Opens Maya’s Add Attribute window
- openDeleteAttrWindow()¶
Opens Maya’s Add Attribute window
Cleanup¶
- nonManifold(objList=[], select=True, message=True)¶
Selects Non-Manifold Vertices on selected meshes or those given with objList
- interiorVertex(objList=[], includeBoundary=False, select=True, message=True)¶
Selects Interior-Vertex Vertices on selected meshes
- Parameters:
- Return interiorVerts:
Interior Vert selection if found otherwise an empty list
- Rtype interiorVerts:
list(str)
- findLaminaFaces(objList=[], delete=False, select=True, message=True)¶
Selects or deletes Lamina Faces on selected meshes
- Parameters:
- Return laminaFaces:
laminaFace selection if found otherwise an empty list
- Rtype laminaFaces:
list(str)
- zeroFace(objList, select=True, message=True)¶
Finds faces with zero area and selects them as vertices so they are easy to see.
- zeroFaceSelected(select=True, message=True)¶
From the selection finds faces with zero area and optionally selects them as vertices so they are easy to see.
- calcZeroFace(selObjs, select=True, message=True)¶
Finds any zero faces and returns and optionally selects them
- deleteHistory()¶
Delete History on selected objects
- freezeTransforms(message=True)¶
Maya default Freeze Transforms on selected
- unlockVertexNormalsObj(obj)¶
Unlocks vertex normals on an object.
WARNING: keepSoftHard takes a lot of time on dense meshes 20sec per 3k faces. Slow function
- Parameters:
obj (str) – A maya mesh object
- unlockVertexNormalsList(objList=[], message=True)¶
Unlocks vertex normals on the currently selected object or the given object list.
If no objectList is give works on current selection.
WARNING: keepSoftHard takes a lot of time on dense meshes 20sec per 3k faces. Slow function
- averageVertexNormals()¶
- conformNormals()¶
Maya’s Mesh Display > Conform Command, all normals conform to face the same direction
- reverseFaceNormals()¶
Maya’s Mesh Display > Reverse Command, flips normal direction
- mergeIdenticalVertices()¶
Merge Vertices with extremely low distance tolerance
- selectVerts(vertSelection, origSel)¶
Helper function for GUI while selecting vertices
- Parameters:
vertSelection (list(str)) – A maya list of vertices
origSel (list()) – A list of maya objects usually containing the faces
- selectFaces(faceSelection, origSel, selObject=True)¶
Helper function for GUI while selecting faces
- Parameters:
faceSelection (list(str)) – A maya list of faces
origSel (list()) – A list of maya objects usually containing the faces
- checkMeshSelection()¶
Checks for selected meshes, used by GUIs
- Return selMeshTransforms:
Selected mesh transforms will be an empty list if none
- Rtype selMeshTransforms:
list(str)
- checkMeshIssues(objList=[], select=True, message=True)¶
Checks meshes for issues:
Non-Manifold
Interior-Vertex
Zero-Face Area
Lamina-Faces
Returns each type as a list, lists are empty if no issues.
- Parameters:
message (bool) – Report the message to the user?
- Return selMeshTransforms:
The meshes in the selection, empty list if no issues
- Rtype selMeshTransforms:
list(str)
- Return nonManifoldVerts:
A list of vertices matching non-manifold issues, empty list if no issues
- Rtype nonManifoldVerts:
list(str)
- Return interiorVerts:
A list of vertices matching interior-vertex issues, empty list if no issues
- Rtype interiorVerts:
list(str)
- Return zeroFacesAsVerts:
A list of vertices matching zero-face issues, empty list if no issues
- Rtype zeroFacesAsVerts:
list(str)
- Return laminaFaces:
A list of lamina faces, empty list if no issues
- Rtype laminaFaces:
list(str)
- softenEdge(objComponentList)¶
Softens the selected edges or objects (all edges) as per mesh display > soften edge From the given objComponentList, a maya selection list
- Parameters:
objComponentList (list(str)) – list of edges or objects
- softenEdgeSelection()¶
Softens the selected edges or objects (all edges) as per mesh display > soften edge
- hardenEdgeSelection()¶
Hardens the selected edges or objects (all edges) as per mesh display > harden edge
- deleteIntermediateObjs()¶
Deletes all shape original nodes (intermediate objects) associated with the current selection.
- Return shapeNodeList:
A list of the shape nodes deleted
- Rtype shapeNodeList:
list(str)
- removeInstances(message=True)¶
Uninstances a the selected transform and shape nodes by duplicating and deleting the original objects. Connections are not maintained. Accepts transforms only. Newly created objects are returned.
This function is similar to the mel that works on selection:
mel.eval(‘convertInstanceToObject;’)
The mel also duplicates geo, but can badly rename new transform nodes, doesn’t return names, or support connections.
- Parameters:
message (bool) – Report messages to the user?
- Return instancedTranforms:
The new instanced transform names
- Rtype instancedTranforms:
list(str)
- checkSymmetry()¶
- loadObjPlugin()¶
Check if the plugin objExport is loaded, if not load it.
- objCleanSingle(obj, filePath, objOptions='groups=0;ptgroups=0;materials=0;smoothing=0;normals=1', keepShaders=True, keepSubDs=True, unlockNormals=True, type='obj')¶
Cleans a single object with OBJ import/export
Handles:
Shader reassignment assignment, supports any shader
Vertex normals
Naming
SubD settings
- Parameters:
obj (str) – The mesh objects transform name, must have a mesh shape node.
filePath (string) – The full file path to save (file will be immediately deleted)
objOptions (str) – Options for the save of the obj file, see Maya’s cmds.file command with options kwarg
keepShaders (bool) – Keeps current shaders by transferring the shaders onto the newly imported objects
keepSubDs (bool) – Keeps current subD settings, note issues regarding getting the state of a subD (on off)
- Return oldObj:
The old object now potentially renamed, long name
- Rtype oldObj:
str
- Return newObj:
The new object’s long name
- Rtype newObj:
str
- objClean(deleteOldObj=False, keepNormals=True, keepShaders=True, keepSubDs=True, type='obj', keepParentStructure=True, message=True)¶
Cleans an object by exporting it as an OBJ to the temp directory and importing it again. Parents the object in world coords.
Option to delete the old object.
Handles:
Shader reassignment assignment, supports any shader
Vertex normals kept
Naming
SubD settings
Keeps Parent Structure
- Parameters:
deleteOldObj (bool) – Will remove the existing object now replaced with the new.
keepNormals (bool) – Keeps the normals on the export so they import with the new model
keepShaders (bool) – Keeps current shaders by transferring the shaders onto the newly imported objects
keepSubDs (bool) – Keeps current shaders by transferring the shaders onto the newly imported objects
type (bool) – The export file type, should be “obj” in most cases.
keepParentStructure (bool) – If True re-parents the imported objects from where they once came
message (bool) – Reports the message to the user
- Return newObjectList:
A list of new objects that have been created
- Rtype newObjectList:
list(str)
- Return oldObjectList:
A list of the old objects now potentially renamed
- Rtype oldObjectList:
list(str)
- selectTris()¶
Selects Tri faces on selected objects
- selectNGons()¶
Selects NGon faces on selected objects
- triangulateNGons()¶
Selects and triangulates an nGons in the current selection
Connections¶
- getDestinationAttrs(drivenObj, message=False)¶
From a driven object return all it’s destination connected attributes as destinationObjAttrs
Seems to be difficult to retrieve the destinationObjAttrs so have created this function, could be a better way?
- Parameters:
drivenObj (str) – A maya node driven by some connections. Eg “pCube4”
- Return destinationObjAttrs:
List of maya node.connections driven by some connections Eg [“pCube4.visibility”]
- Rtype destinationObjAttrs:
list(str)
- getDestinationSourceAttrs(drivenObj, message=False)¶
From a driven object return all it’s destinationObjAttrs and sourceObAttrs
Seems to be difficult to retrieve the destinationObjAttrs, once you have those you can get the
- Parameters:
drivenObj (str) – A maya node driven by some connections. Eg “pCube4”
- Return destinationObjAttrs:
List of maya node.connections driven by some connections Eg [“pCube4.visibility”]
- Rtype destinationObjAttrs:
list(str)
- Return destinationObjAttrs:
List of maya node.connections that drive the connections Eg [“hand_control.hidePCube4”]
- Rtype destinationObjAttrs:
list(str)
- makeSafeConnectionsTwoObjs(sourceObj, sourceAttr, destinationObj, destinationAttr, breakConnections=True, message=False)¶
Safely connects to objects with cmds.connectAttr()
Checks:
Attributes exist
Attributes Match
Destination attribute is connectable
- Parameters:
sourceObj (str) – A maya node name
sourceAttr (str) – name of the source attribute (the from attribute)
destinationObj (str) – A maya node name
destinationAttr (str) – name of the destination attribute (target will be connected)
breakConnections (bool) – Break existing connections? May fail if objects are already connected
message (bool) – Report messages to the user
- Return success:
True if the attributes were connected
- Rtype success:
bool
- safeConnectList(objList, sourceAttr, destinationAttr, breakConnections=True, message=True)¶
Safely connects the first object from an object list to the remaining objects. Will ignore potential issues.
Checks:
Attributes exist
Attributes Match
Destination attribute is connectable
- Parameters:
objList (list(str)) – A list of Maya nodes
sourceAttr (str) – The source attribute (the from attribute) of the first object only
destinationAttr (str) – The destination attribute to be connected on all remaining objects (not first)
breakConnections (bool) – Break existing connections? May fail if objects are already connected
message (bool) – Report the message to the user?
- Return success:
Will report True if any (not all) connections were made successfully
- Rtype success:
bool
- safeConnectSelection(sourceAttr, destinationAttr, message=True)¶
Safely connects the first selected object to the remaining selected objects. Will ignore potential issues.
Checks:
Attributes exist
Attributes Match
Destination attribute is connectable
- Parameters:
- Return success:
Will report True if any (not all) connections were made successfully
- Rtype success:
bool
- makeConnectionAttrsOrChannelBox(driverAttr='', drivenAttr='', message=True)¶
From a GUI connect the “driver.attr” and “driven.attr” from the selection list The first selected object to the remaining selected objects. Will ignore potential issues.
If nothing is entered in the GUI then will try to use the channel box selected attribute to fill any missing data.
Must be only one attribute selected in the channel box.
- Parameters:
- Return success:
Will report True if any (not all) connections were made successfully
- Rtype success:
bool
- makeSrtConnectionsObjs(objList, translate=True, rotation=True, scale=True, matrix=False, message=True)¶
Convenience function for making SRT connections between the first obj, and all others in a list
- Parameters:
objList (list(str)) – A list of Maya node names, the first node will be the master
translate (bool) – Connect all translate values?
rotation (bool) – Connect all rotation values?
scale (bool) – Connect all scale values?
matrix (bool) – Connect .matrix to .offsetParentMatrix values?
message (bool) – Report the messages to the user?
- Return translateSuccess:
True if connected some (not necessarily all object’s) translate attributes
- Rtype translateSuccess:
bool
- Return rotateSuccess:
True if connected some (not necessarily all object’s) rotate attributes
- Rtype rotateSuccess:
bool
- Return scaleSuccess:
True if connected some (not necessarily all object’s) scale attributes
- Rtype scaleSuccess:
bool
- Return matrixSuccess:
True if connected some (not necessarily all object’s) matrix attributes
- Rtype matrixSuccess:
bool
- makeSrtConnectionsObjsSel(rotation=False, translate=False, scale=False, matrix=False, message=True)¶
Convenience function for making SRT connections between the first selected obj, and all others
- Parameters:
- Return translateSuccess:
True if connected some (not necessarily all object’s) translate attributes
- Rtype translateSuccess:
bool
- Return rotateSuccess:
True if connected some (not necessarily all object’s) rotate attributes
- Rtype rotateSuccess:
bool
- Return scaleSuccess:
True if connected some (not necessarily all object’s) scale attributes
- Rtype scaleSuccess:
bool
- breakAttr(objectAttribute)¶
Disconnects using only one attribute, as per right click disconnect in the channel box
- Parameters:
objectAttribute (str) – “objectName.objectAttribute” node name and attribute name separated by a “.”
- breakAttrList(objAttrList)¶
Disconnects using only one attribute, as per right click disconnect in the channel box on a list:
objAttrList: [“pCube1.rotateX”, “pCube1.translateY”]
- Parameters:
objAttrList (list(str)) – a list of objects with attribute names ie [“pCube1.rotateX”, “pCube1.translateY”]
- Return success:
Will be True if any (not all) attributes are disconnected
- Rtype success:
bool
- breakConnectionSourceDestination(sourceObj, sourceAttr, destinationObj, destinationAttr)¶
Breaks a connection, with checks to see if it exists. Must be in the correct order, source and destination
Can use breakConnectionsTwoObj() if you do not know the source and destination order
- breakConnectionsTwoObj(objOne, objOneAttr, objTwo, objTwoAttr)¶
Breaks a connection, with checks to see if it exists. The destination/source order does not matter, tries both.
- breakConnectionsList(objList, sourceAttr, destinationAttr, message=True)¶
Safely breaks the connection between the first object from the remaining objects.
- Parameters:
- Return success:
Will report True if any (not all) connections were broken successfully
- Rtype success:
bool
- breakConnectionsSelection(sourceAttr, destinationAttr, message=True)¶
Safely breaks the connection between the first object from the remaining objects from the selection
- Parameters:
- Return success:
Will report True if any (not all) connections were broken successfully
- Rtype success:
bool
- breakConnectionAttrsOrChannelBox(driverAttr='', drivenAttr='', message=True)¶
- breakAllDrivenOrChannelBoxSel(message=True)¶
Breaks all the connections on the selection, or if channel box has attr selections only break those selected connections
- Parameters:
message (bool) – Report messages to the user
- Return success:
True if all operations were successfully completed
- Rtype success:
bool
- breakAllConnectionsObj(obj, message=True)¶
Breaks all the driven connections from an object or node
- breakAllConnectionsObjList(objList, message=True)¶
Breaks all the driven connections from an object list
- breakAllConnectionsSel(objList, message=True)¶
Breaks all the driven connections from all selected objects
- breakSrtConnectionsObjs(objList, translate=False, rotation=False, scale=False, matrix=False, message=True)¶
Convenience function for breaking SRT connections between the first obj, and all others in a list
- Parameters:
objList (list(str)) – A list of Maya node names, the first node will be the master
translate (bool) – Disconnect all translate values?
rotation (bool) – Disconnect all rotation values?
scale (bool) – Disconnect all scale values?
matrix (bool) – Disconnect the matrix connections?
message (bool) – Report the messages to the user?
- Return translateSuccess:
True if disconnected some (not necessarily all) translate attributes
- Rtype translateSuccess:
bool
- Return rotateSuccess:
True if disconnected some (not necessarily all) rotate attributes
- Rtype rotateSuccess:
bool
- Return scaleSuccess:
True if disconnected some (not necessarily all) scale attributes
- Rtype scaleSuccess:
bool
- delSrtConnectionsObjsSel(rotation=False, translate=False, scale=False, matrix=False, message=True)¶
Convenience function for breaking SRT connections between the first selected obj, and all others
- Parameters:
- Return translateSuccess:
True if disconnected some (not necessarily all) translate attributes
- Rtype translateSuccess:
bool
- Return rotateSuccess:
True if disconnected some (not necessarily all) rotate attributes
- Rtype rotateSuccess:
bool
- Return scaleSuccess:
True if disconnected some (not necessarily all) scale attributes
- Rtype scaleSuccess:
bool
- swapDriverConnectionAttr(currentDriver, newDriver, attribute, checkDestNodeTypes=[])¶
Replaces the connection of a single attribute from one object to another, all destinations of the attr will be swapped.
- Parameters:
currentDriver (str) – The object with the connection, will be replaced.
newDriver (str) – The ne object recieving the connections
attribute (str) – The name of the attribute (driver attribute) to be swapped eg “rotateX”
checkDestNodeType (str) – Check the node of the destination, for example “skinCluster” will only replace that type
- swapDriverConnection(currentDriver, newDriver)¶
Swaps the driver object to a new object, the newDriver object will have all connections.
- swapDrivenConnection(currentDriven, newDriven)¶
Swaps the driven/target object to a new object, the newDriven object will have all connections.
- swapConnectionSelected(driver=True, message=True)¶
Swaps the first (driver/driven) object to a new unrelated object, the second object will receive/emit all connections.
Can only swap two objects if driven
driver: If True the driver (source) attributes will be swapped
- getConnectionsBetweenNodes(objA, objB, message=True)¶
Returns the connections between two objects
Will only the first direction found, nodes should not be connected in different directions (source/destination)
- Parameters:
- Return sourceAttrList:
The source connections as object.attribute eg “pCube1.rotate”
- Rtype sourceAttrList:
str
- Return destinationAttrList:
The destination connections as object.attribute eg “pCube1.rotate”
- Rtype destinationAttrList:
str
- swapConnectionDirection(objA, objB, message=True)¶
Swaps connection directions between two objects. Attributes must exist for the switch to take place.
- swapConnectionDirectionSel(message=True)¶
Swaps connection directions between two selected objects. Attributes must exist for the switch to take place.
- Parameters:
message (bool) – Report the message to the user?
- Return success:
True if the switch took place
- Rtype success:
bool
- copyDrivenConnectedAttrs(obj, message=True)¶
Copy driven attributes. Used in copy attributes GUI command
Returns:
The sources for connected attributes, from the driving object/s list(object.attribute)
All the driven attributes, ie those attributes with a connection incoming to the node list(attributeNames)
- Parameters:
- Return sourceObjAttrs:
The sources for connected attributes, from the driving object/s list(object.attribute)
- Rtype sourceObjAttrs:
list(str)
- Return destinationAttrs:
All the driven attributes, attributes with an incoming connection list(attributeNames)
- Rtype destinationAttrs:
list(str)
- copyDrivenConnectedAttrsSel(message=True)¶
Copy driven attributes for the first selected object. Used in copy attributes GUI command
Returns:
The sources for those attributes, from the driving object/s list(object.attribute)
All the driven attributes, ie those attributes with a connection incoming to the node list(attributeNames)
- Parameters:
message (bool) – Report messages to the user?
- Return sourceObjAttrs:
The sources for connected attributes, from the driving object/s list(object.attribute)
- Rtype sourceObjAttrs:
list(str)
- Return destinationAttrs:
All the driven attributes, attributes with an incoming connection list(attributeNames)
- Rtype destinationAttrs:
list(str)
- pasteDrivenConnectedAttrs(objList, sourceObjAttrs, destinationAttrs, message=True)¶
Paste connects a list of destinationAttrs onto all objects. From sourceObjAttrs
All objects must have all attributes
- Parameters:
objList (list(str)) – A list of Maya objects/nodes
sourceObjAttrs (list(str)) – The sources for connected attributes, from the driving object/s list(object.attribute)
destinationAttrs (list(str)) – All the driven attributes, attributes with an incoming connection list(attributeNames)
message (bool) – Report messages to the user?
- Return success:
True if successfully completed
- Rtype success:
bool
- pasteDrivenConnectedAttrsSel(sourceObjAttrs, destinationAttrs, message=True)¶
Paste connects a list of destinationAttrs onto all selected objects. From sourceObjAttrs
All objects must have all attributes. Used in GUI command
- Return sourceObjAttrs:
The sources for connected attributes, from the driving object/s list(object.attribute)
- Rtype sourceObjAttrs:
list(str)
- Return destinationAttrs:
All the driven attributes, attributes with an incoming connection list(attributeNames)
- Rtype destinationAttrs:
list(str)
- Parameters:
message (bool) – Report messages to the user?
Constraints¶
Constraint related code.
Example use:
from zoo.libs.maya.cmds.objutils import constraints
constraints.constrainMatchList()
Author: Andrew Silke
- MOPATH_SIDETWIST_ATTR = 'sideTwist'¶
DELETE CONSTRAINTS
- deleteConstraintsFromObjList(objList, message=True)¶
Deletes any constraints attached to any object in an object list
- deleteConstraintsFromSelObj(message=True)¶
Deletes any constraints attached to any object from the current selection
- Parameters:
message (bool) – report the message to the user?
- Return constrainList:
the constraints deleted, will be empty list if none found
- Rtype constrainList:
list(str)
- selectConstraints()¶
Selects all constraints connected to the selected objects.
- constrainObjsToSurface(surface, objs, deleteConstraint=True)¶
Constrains an object list to a surface with surface constraints.
If deleteConstraint is True acts as a snap for objects, snaps pivot points.
- Parameters:
- Return constraintList:
A list of constraint nodes if created, otherwise will be an empty list.
- Rtype constraintList:
list(str)
- constrainObjsToSurfaceSelection(surface='', deleteConstraint=True)¶
Constrains selected objects to a surface with surface constraints.
If no surface object is given the surface object will be the last in the selection list.
If deleteConstraint is True acts as a snap for objects, snaps pivot points.
- setSurfaceObj()¶
Returns the surface object for UI code. Must be a mesh or nurbsSurface object.
- Return surfaceObject:
The first selected mesh or nurbsSurface object.
- Rtype surfaceObject:
str
- constrainMatchList(prefix='SCXX', message=True)¶
Constrains one object to another with prefixing, object to be constrained is prefixed
Prefix is constrained to non prefix:
“SCXX_head” is constrained to “head”
Curves¶
- createCurveContext(degrees=3, bezier=0)¶
Enters the create curve context (user draws cvs). Uses mel. Cubic Has option for curve degrees.
More options can be added later.
- createBezierCurveContext()¶
Enters the create bezier curve context (user draws cvs).
Uses mel.
- splineIkHandleContext(spans=2)¶
Create Spline Ik Handle
- Parameters:
spans –
- Returns:
- Return type:
- reverseCurves(curveList, replaceOriginal=True)¶
Reverses multiple Maya nurbs curves direction. Uses cmds.reverseCurve()
- reverseCurvesSelection(replaceOriginal=True)¶
Reverses selected Maya nurbs curve direction. Uses cmds.reverseCurve()
- Parameters:
replaceOriginal (bool) – If True will reverse the current curve, False and will duplicate
Display¶
Various functions for displaying Maya objects
To Do Have the selected functions work with bad selections and with hierarchy option too, should be in a UI
Author: Andrew Silke
- setPrimaryVisible(objList, value=True)¶
Sets all objects to primary visibility with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setDoubleSided(objList, value=True)¶
Sets all objects to double sided with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setCastShadows(objList, value=True)¶
Sets all objects to cast shadows with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setReceiveShadows(objList, value=True)¶
Sets all objects to receive shadows with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setReflectionVisibility(objList, value=True)¶
Sets all objects reflection visibility with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setRefractionVisibility(objList, value=True)¶
Sets all objects refraction visibility with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- setPrimaryVisibleSelected(value=True)¶
Sets all selected objects to primary visibility with a value of “value”
- Parameters:
value (bool) – value of the attribute to be changed
- Return success:
The function succeeded or failed
- Rtype success:
bool
- setDoubleSidedSelected(value=True)¶
Sets all selected objects to double sided with a value of “value”
- Parameters:
value (bool) – value of the attribute to be changed
- Return success:
The function succeeded or failed
- Rtype success:
bool
- setCastShadowsSelected(value=True)¶
Sets all selected objects to cast shadows with a value of “value”
- Parameters:
value (bool) – value of the attribute to be changed
- Return success:
The function succeeded or failed
- Rtype success:
bool
- setReceiveShadowsSelected(value=True)¶
Sets all selected objects to receive shadows with a value of “value”
- Parameters:
value (bool) – value of the attribute to be changed
- Return success:
The function succeeded or failed
- Rtype success:
bool
- setHierarchyToRenderable(objList, value=True)¶
Sets the hierarchy below to be either renderable or not renderable depending on the value primary visibility, cast shadows, and receive shadows, reflections and refraction vis
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- Return meshList:
The mesh names affected
- Rtype meshList:
list
- setHierarchyToPrimaryVis(objList, value=True)¶
Sets all objects in the hierarchy to primary visibility with a value of “value”
- Parameters:
objList (list) – maya object names
value (bool) – value of the attribute to be changed
- Return meshList:
The mesh names affected
- Rtype meshList:
list
- setHierarchyToRenderableSelected(value=True)¶
Sets the selected hierarchy below to be either renderable or not renderable depending on the value primary visibility, cast shadows, and receive shadows
- Parameters:
value (bool) – value of the attribute to be changed
- Return success:
The function succeeded or failed
- Rtype success:
bool
Duplicates¶
Code for duplicating objects.
Example use:
from zoo.libs.maya.cmds.objutils import duplicates
duplicates.duplicateToComponentsSel()
Author: Andrew Silke
- duplicateWithoutChildrenList(nodeList)¶
Duplicates nodes without their children
- Parameters:
nodeList (list(str)) – a list of Maya node names
- Return duplicateList:
A list of the duplicated nodes/objects
- Rtype duplicateList:
list(str)
- duplicateWithoutChildrenSelected(message=True)¶
Duplicates selected nodes without their children
- Return duplicateList:
A list of the duplicated nodes/objects
- Rtype duplicateList:
list(str)
- duplicateToComponentCenter(objs, componentList)¶
- duplicateToComponentsSel(objs, selectObjs=True, message=True)¶
Filtertypes¶
Module for filtering by node type for example filtering shape nodes and returning their transforms
Example: .. code-block:: python
from zoo.libs.maya.cmds.objutils import filtertypes filtertypes.filterTypeReturnTransforms(objList, children=False, shapeType=”nurbsCurve”)
- filterExactTypeList(nodeList, type='transform', long=True)¶
Returns a list filtered to be only the type of node
Easy to forget this one liner, best not to use, here for reference
- filterTypeReturnTransforms(objList, children=False, shapeType='nurbsCurve')¶
From a transform list filters the objects which have shape nodes of the given type, returns a transform list.
Joints are also included as transforms and can be passed in and returned
- Parameters:
objList (list) – Maya obj list
- Return curveObjList:
list of curve transforms now filtered
- Rtype curveObjList:
list
- filterTypeReturnShapes(objList, children=False, shapeType='nurbsCurve')¶
From a transform list filters the objects which have shape nodes of the given type, returns a shape list.
Joints are also included as transforms and can be passed in
- Parameters:
objList (list) – Maya transform obj list
- Return curveObjList:
list of curve shapes now filtered
- Rtype curveObjList:
list
- shapeTypeFromTransformOrShape(nodeList, shapeType='nurbsCurve')¶
Returns a list of shapes of the given type from a node list that can include transforms and shape nodes.
Joints are also included as transforms
- filterGeoOnly(objList, nurbs=True, polygons=True)¶
Filters a node list for both shapes and transforms and returns geometry, nurbs or polygons
Note: cmds.ls(objList, geometry=True) # will only return if shapes are selected
- deformerHistoryOnObj(objTransform, ignoreTweak=True)¶
Returns all deformers on object including skinning, can ignore the tweak node.
- filterTypeObjList(objTypeList, objList=(), searchHierarchy=False, searchScene=False, dag=False)¶
Returns a list of objects/nodes in Maya that match the filter criteria, usually by node type:
Can filter by a list of nodeTypes Can limit the filter to an object list or override to search the whole scene Can search the hierarchy of the objList
- Parameters:
objTypeList (list(str)) – A list of node types, usually from a key in TYPE_FILTER_DICT. DEFORMER_TYPE_LIST for example
objList (list(str)) – A list of maya nodes/object names
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
searchScene (bool) – If True will ignore the objList and search the whole scene instead
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree? Includes children
- Return filteredNodes:
Returns a list of objects/nodes in Maya that match the filter criteria
- Rtype filteredNodes:
list(str)
- filterShapesFromList(objList, allowJoints=True, allowConstraints=True, allowDG=True)¶
If a shape node is in objList replace with it’s transform parent. Otherwise will leave the node in the list.
Options:
Can include joints as transforms Can allow DG nodes (can’t have transform node parents)
- Parameters:
objList (list(str)) – A list of maya nodes/object names
allowJoints (bool) – If True include joints in the returned list, treat them as transform nodes
allowConstraints (bool) – If True include constraints in the returned list, treat them as transform nodes
allowDG (bool) – If True allow DG nodes to be returned. DG nodes cannot have transform parents eg shaders
- Return objList:
objList now with the shape nodes replaced to be their transform nodes
- Rtype objList:
list(str)
- filterDagObjTransforms(objTypeList, searchHierarchy=False, selectionOnly=True, message=True, dag=False, transformsOnly=True)¶
Returns a list of objects/nodes in Maya that match the filter criteria, usually by node type, will filter further by returning only the transform parents of shape nodes. Also can filter based on selection
Can filter by a list of nodeTypes Can limit the filter to an object list or over ride to search the whole scene Can search the hierarchy of the objList Can limit the returned list to transforms that will replace any shape nodes Can limit the returned objects to the current selection
- Parameters:
objTypeList (list(str)) – A list of node types, usually from a key in TYPE_FILTER_DICT. DEFORMER_TYPE_LIST for example
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
selectionOnly (bool) – If True search the selected objects not the whole scene
message (bool) – Return the message to the user?
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree? Includes children
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
- Return filteredNodes:
Returns a list of objects/nodes in Maya that match the filter criteria
- Rtype filteredNodes:
list(str)
- filterAllNodeTypes(selectionOnly=True, searchHierarchy=False, dag=False, transformsOnly=False, removeMayaDefaults=True, includeConstraints=True, message=True)¶
Function used while filtering with no restrictions on node types, ie All node types.
Does not use the function filterShapesFromList()
Can limit the returned objects to the current selection, or False whole scene Can search the hierarchy of the objList Can limit the returned list to transforms that will replace any shape nodes, but leave constraints Can ignore Maya default nodes such as lambert1 and persp front cams etc
- Parameters:
selectionOnly (bool) – If True search the selected objects not the whole scene
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree? Includes children
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
includeConstraints (bool) – If True will include constraints which can be filtered out as not transforms.
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
- Return filteredNodes:
Returns a list of objects/nodes in Maya that match the filter criteria
- Rtype filteredNodes:
list(str)
- filterByGroup(selectionOnly, searchHierarchy, dag, message=True)¶
Return nodes that are “groups”. Groups are empty transform nodes with no shapes nodes
- Parameters:
selectionOnly (bool) – If True search the selected objects not the whole scene
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree? Includes children
message (bool) – Return the message to the user?
- Return filteredNodes:
Returns a list of objects/nodes in Maya that match the filter criteria
- Rtype filteredNodes:
list(str)
- filterByNiceType(niceNameType, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, includeConstraints=True, message=True)¶
Returns a list of objects/nodes in Maya that match the filter criteria, usually by node type.
This is the main function as used by GUIs:
Can filter by a list of nodeTypes Can filter by special node types such as “group” which does not have a node type name Can limit the filter to an object list or over ride to search the whole scene (selectionOnly=False) Can include the hierarchy of the objList in the search Can limit the returned list to transforms that will replace any shape nodes Can ignore Maya default nodes such as lambert1 and persp front cams etc
The nice names include types that aren’t maya object types such as “Groups” and “All Types”, some types are multiple object types, “Light” for example will find many node types.
TYPE_FILTER_LIST globals include:
ALL = “All Types” POLYGON = “Polygon” NURBS = “Nurbs” GEOMETRY = “Geometry” JOINT = “Joint” CURVE = “Curve” GROUP = “Group” LOCATOR = “Locator” LIGHT = “Light” CAMERA = “Camera” CLUSTER = “Cluster” FOLLICLE = “Follicle” DEFORMER = “Deformer” TRANSFORM = “Transform”
- Parameters:
niceNameType (str) – A single string from the list TYPE_FILTER_LIST, describes a type of node/s in Maya
selectionOnly (bool) – If True search the selected objects not the whole scene
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree? Includes children
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
includeConstraints (bool) – If True will include constraints which can be filtered out as not transforms.
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
message (bool) – Return the message to the user?
- Return filteredNodes:
Returns a list of objects/nodes in Maya that match the filter criteria
- Rtype filteredNodes:
list(str)
- filterByNiceTypeKeepOrder(niceNameType, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Same as filterByNiceType() but keeps the order of selection and hierarchy with more work
TODO: May be possible to keep the order in the original function, mostly has to do with sets losing the order.
See filterByNiceType() for documentation
Joints¶
Joint related functions.
Example use:
from zoo.libs.maya.cmds.objutils import joints
joints.getJoints(objList)
Author: Andrew Silke & David Sparrow
- selectedStartEndJoints()¶
Returns the first and last joints/nodes selected. Must have 2 joints or transforms selected.
- Returns:
Returns the first and last joints/nodes selected in a list. If none then returns empty list.
- Return type:
list(str)
- jointPropertiesSel()¶
Returns the joint properties of the first selected joint for UI
- filterChildJointList(jointList)¶
retrieves all joints under the joint list in the hierarchy, all child joints
- Parameters:
jointList (list) – a list of Maya joints
- Return allJoints:
a join list now including children
- Rtype allJoints:
list
- getJoints(objList, children=True)¶
From an object list filter out the joints, with option for children No duplicates
- Parameters:
objList (list) – maya object list of strings
children (bool) – return the child joints of all objects in the objList
- Return jntList:
list of maya joints as strings
- Rtype jntList:
list
- jointsFromIkHandle(ikHandle)¶
Gets joints from IK Handle
- Parameters:
ikHandle (
zapi.DagNode
) – The maya Ik handle- Returns:
- Return type:
- getJointsSelected(children=True)¶
from selection return all the joints and most likely all the children too
- Parameters:
children (bool) – return the child joints of all objects in the objList
- Return jntList:
list of maya joints as strings
- Rtype jntList:
list
- getJointChain(startJoint, endJoint='')¶
Returns a joint list in the order of hierarchy between the start join and the end joint.
Will check for branches if an endJoint is specified, does not check branches it only start joint is given.
If the end joint is not given it will return the entire chain.
- jointChains(jointList, ignoreConnectedJoints=True, type='joint')¶
Checks the joint list for chains and returns a list of chains, each branch being a separate chain.
Each member of the joint chains must be in the jointList.
- Parameters:
- Returns:
A list of lists of joint names, each list being a chain.
- Return type:
list(list(str))
- jointDrawNone(jntList)¶
hides joints without affecting the .visibility attr uses drawStyle to None
- Parameters:
jntList (list) – list of maya joints as strings
- jointDrawNoneSelected(children=True)¶
hides joints without affecting the .visibility attr uses drawStyle to None
- Parameters:
children (Boolean) – should child joints also be affected?
- jointDrawBone(jntList)¶
displays joints regular style via drawStyle to bone
- Parameters:
jntList (list) – list of maya joints as strings
- jointDrawJoint(jntList)¶
displays joints in the joint (floating) style ie not bone. via drawStyle to joint
Only compatible in later versions of Maya.
- Parameters:
jntList (list) – list of maya joints as strings
- jointDrawMultiBox(jntList)¶
displays joints with multiple connections as boxes ie not bone. via drawStyle to Multi-child as box
- Parameters:
jntList (list) – list of maya joints as strings
- jointDrawHide(jntList, hide=True)¶
Hide and show the draw joint state.
- Parameters:
jntList (list) – list of maya joints as strings
hide (bool) – Hide the draw state of the joints, if False show the draw state of the joints
- jointDrawBoneSelected(children=True)¶
displays joints regular style via drawStyle to bone
- Parameters:
children (Boolean) – should child joints also be affected?
- jointDrawJointSelected(children=True)¶
displays joints regular style via drawStyle to bone
- Parameters:
children (Boolean) – should child joints also be affected?
- jointDrawMultiBoxSelected(children=True)¶
displays joints regular style via drawStyle to bone
- Parameters:
children (Boolean) – should child joints also be affected?
- toggleJntDrawStyle(jntList)¶
Toggles the visibility of joints without affecting the .visibility attribute uses the attribute drawStyle Finds the first selected and toggles all joints opposite of that
- Parameters:
jntList (list) – list of maya joints as strings
- toggleJntDrawStyleSelected(children=True)¶
Toggles the visibility of joints without affecting the .visibility attribute uses the attribute drawStyle Finds the first selected and toggles all joints opposite of that Can affect children
- Parameters:
children (Boolean) – should child joints also be affected?
- jointScaleCompensate(compensate=True, children=False)¶
Turns the segment scale compensate on or off for the selected joints.
- Parameters:
children (Boolean) – should child joints also be affected?
- zeroRotAxisJointList(jointList, zeroChildren=True)¶
Zero’s the Joint Rotation Axis, as the manual rotation of the axis is bad for joints
- Parameters:
jointList (list) – The list of maya joints
zeroChildren (bool) – Do you want this to affect all children as well?
- Returns:
- Return type:
- zeroRotAxisSelected(zeroChildren=True, message=True)¶
Zero’s the Joint Rotation Axis, as the manual rotation of the axis is bad for joints Works on selection
- Parameters:
zeroChildren (bool) – Do you want this to affect all children as well?
- displayLocalRotationAxisJointList(jntList, children=True, display=True, message=True)¶
Function for showing or hiding the Local Rotation Axis on an object list, usually joints
- displayLocalRotationAxisSelected(children=True, display=True, message=True)¶
Function for showing or hiding the Local Rotation Axis on selected objects, usually joints
- toggleLocalRotationAxisSelection(children=False, message=True)¶
Toggles the Local Rotation Axis on selected objects, usually joints
- alignJoint(jointList, secondaryAxisOrient='yup', children=False, freezeJnt=True, message=False)¶
Aligns the joints given a joint list
- Parameters:
- alignJointZoo(jointList, primaryAxisVector=(1.0, 0.0, 0.0), secondaryAxisVector=(0.0, 1.0, 0.0), worldUpAxisVector=(0.0, 1.0, 0.0), orientChildren=False, ignoreConnectedJoints=True, freezeJoints=True, message=True)¶
Zoo Tools Pro align joint function, aligns the joints given a joint list. Unparents orients and reparents and gives more options than regular maya orient joint tool and cmds. - Allows vectors especially world up vector - Allows for negative axis aligns
- Parameters:
jointList (list(str)) – A list of joint names
primaryAxisVector (tuple) – The primary axis vector (aim)
secondaryAxisVector (tuple) – The secondary axis vector (up)
worldUpAxisVector (tuple) – The world up axis vector
orientChildren (bool) – Orient all child joints?
ignoreConnectedJoints (bool) – skip joints that are connected, have constraints, locked or keyframes.
freezeJoints (bool) – Freeze all joints after orienting?
message (bool) – Report the message to the user?
- alignJointZooSel(primaryAxisVector=(1.0, 0.0, 0.0), secondaryAxisVector=(0.0, 1.0, 0.0), worldUpAxisVector=(0.0, 1.0, 0.0), orientChildren=False, ignoreConnectedJoints=True, freezeJoints=True, message=True)¶
Zoo Tools Pro align joint function, aligns the selected joints. Unparents orients and reparents and gives more options than regular maya orient joint tool and cmds.
Allows vectors especially world up vector
Allows for negative axis aligns
- Parameters:
primaryAxisVector (tuple) – The primary axis vector (aim)
secondaryAxisVector (tuple) – The secondary axis vector (up)
worldUpAxisVector (tuple) – The world up axis vector
orientChildren (bool) – Orient all child joints?
ignoreConnectedJoints (bool) – skip joints that are connected, have constraints, locked or keyframes.
freezeJoints (bool) – Freeze all joints after orienting?
message (bool) – Report the message to the user?
- alignJointPlaneOrient(jointList, metaNode, orientChildren, ignoreConnectedJoints=True, freezeJoints=True, message=True)¶
Snap and orient the joints to the plane control with the orient meta node.
Auto finds joint chains and orients accordingly.
- Parameters:
jointList (list(str)) – A list of Maya joint names
metaNode (
zoo.libs.maya.meta.planeorientmeta.CoPlanarMeta
) – The zoo object - plane orient meta nodeorientChildren (bool) – Orient all child joints?
ignoreConnectedJoints (bool) – skip joints that are connected, have constraints, locked or keyframes.
freezeJoints (bool) – Freeze all joints after orienting?
message (bool) – report a message to the user
- alignJointPlaneOrientSel(metaNode, orientChildren, ignoreConnectedJoints=True, freezeJoints=True, message=True)¶
Snap and orient the selected joints to the plane control with the orient meta node.
Auto finds joint chains and orients accordingly.
- Parameters:
metaNode (
zoo.libs.maya.meta.planeorientmeta.CoPlanarMeta
) – The zoo object - plane orient meta nodeorientChildren (bool) – Orient all child joints?
ignoreConnectedJoints (bool) – skip joints that are connected, have constraints, locked or keyframes.
freezeJoints (bool) – Freeze all joints after orienting?
message (bool) – report a message to the user
- checkHasChildJoint(joint)¶
Searches for a child joint, only searches two deep
- Parameters:
joint (str) – A maya joint name
- Return hasChildJoint:
True if a child joint is found
- Rtype hasChildJoint:
bool
- alignJointSelected(secondaryAxisOrient='yup', children=False, message=True, endAlignParent=True)¶
Aligns the joints that are selected
- alignJointToParent(jnt)¶
Align Joints To Parent useful for end joints Uses orient constraint (while temp unparenting children) to reorient the joint to match it’s parent Freezes the Joint transforms bfore reparenting children
- Parameters:
jnt (str) – the joint to be aligned
- alignJointToParentList(jntList)¶
- alignJointToParentSelected(message=True)¶
Align Joints To Parent useful for end joints Uses orient constraint (while temp unparenting children) to reorient the joint to match it’s parent Freezes the Joint transforms before reparenting children
- Parameters:
message (bool) – display the success message to the user
- editComponentLRA(editLRA=True)¶
Makes the local rotation axis editable in component mode, when False will disable and exit to object mode
- Parameters:
editLRA (bool) – When True will enter the component mode with localRotationAxis editable, False exits
- rotateLRA(obj, rot)¶
Will rotate the local rotation axis of the given object usually a joint by the rotation amount.
- rotateLRAList(objList, rot)¶
Will rotate the local rotation axis of the given object list usually a joint list by the rotation amount.
- rotateLRASelection(rot, includeChildren=True)¶
Will rotate the local rotation axis of the given object list usually a joint list by the rotation amount.
- mirrorJoint(joint, axis, searchReplace=(['_L', '_R'], ['_lft', '_rgt']), mirrorBehavior=True)¶
Mirrors a joint along an axis
Finds the first search string in the list and will do the mirror based on that two entry list. ie. Will not search all lists, only the first matching string it finds.
- mirrorJointList(jointList, axis, searchReplace=(['_L', '_R'], ['_lft', '_rgt']), mirrorBehavior=True)¶
Mirrors a joint list along an axis
- mirrorJointSelected(axis, searchReplace=(['_L', '_R'], ['_lft', '_rgt']), mirrorBehavior=True, message=True)¶
Mirrors selected joints along an axis
- Parameters:
- Return jointList:
A list of joint names
- Rtype jointList:
list(str)
- setJointRadiusSelected(radius, children=False, message=True)¶
Sets the joint radius for selected joints and potentially their children.
- buildJointStraight(jntName='joint', suffixName='', jointCount=10, jointSpacing=2)¶
- buildJointTwoPoints(startPosition, endPosition, jointCount=10, worldUpVector=[0, 1, 0], suffixName='', jntName='jointStraight')¶
Builds the spine joints in a straight line, given two positions as start and end as [x,y,z] returns the joint list as names
- Parameters:
startPostition –
endPosition –
jointSpacing (float) – Distance in X between each joint
worldUpVector –
- Return jointList:
List of joint names, long fullpath names
- Rtype jointList:
list
- buildCubesOnJoints(jointList)¶
Layers¶
Module for handling layers and assignments
Example use:
from zoo.libs.maya.cmds.objutils import layers
layers.addToLayer("newLayer", ["pSphere1"], ref=False, playback=True, hierarchy=False)
Author: Andrew Silke
- addToLayerExists(layerName, objs, ref=False, playback=True)¶
Adds objects to a display layer, can be a little flaky on the update.
See addToLayer() to include hierarchy and auto create option, this assigns the current objects to existing layer.
It does not include children.
- addToLayer(layerName, objs, ref=False, playback=True, hierarchy=False, message=False)¶
Adds objects to a display layer, and if it doesn’t exist create it, can be a little flaky on the update.
Optional flags:
ref - sets reference playback - sets playback setting hierarchy - includes child transform nodes
Unfortunately cmds.editDisplayLayerMembers() includes shape nodes which is bad for shape colors as it overrides.
- Parameters:
layerName (str) – The name of the layer, will create it if it doesn’t exist
objs (list(str)) – a list of the objs to assign to the layer
ref (bool) – Reference the layer?
playback (bool) – set the layer to playback in the viewport?
hierarchy (bool) – If True will include the hierarchy of transform nodes, usually not needed
Matching¶
Code for matching objects.
Example use:
from zoo.libs.maya.cmds.objutils import matching
matching.centerOfSelection()
Author: Andrew Silke
- matchZooAlSimpErrConstrain(obj, matchObj)¶
Tries the 2017 new match function, if it fails do the old 2017 constraint version cmds.delete(cmds.parentConstraint(obj, matchObj))
- centerOfMultipleObjects(objs)¶
Finds the averaged center of all objects. Supports components and multiple object selection.
Note: Face Edge selection is not accurate, better to use matchCenterCluster() Note: object centers are not pivot point positions but seems like bounding box centers.
- Parameters:
objs (list(str)) – Objects and or flattened components (components not in groups)
- Returns:
The center of the pivot in world coords x, y, z
- Return type:
list()
- centerOfSelection()¶
Finds the averaged center of all selected objects. Supports components and multiple object selection.
Note: Face Edge selection is not accurate, better to use matchCenterCluster()
- Returns:
The center of the pivot in world coords x, y, z
- Return type:
list()
- matchCenterCluster(obj, matchToObjs, orientToComponents=True)¶
Matches the object to the center of the selection by creating a cluster and then deleting.
- matchToCenterObjsComponents(obj, matchToObjs, setObjectMode=True, orientToComponents=True, aimVector=(0.0, 1.0, 0.0), localUp=(0.0, 0.0, -1.0), worldUp=(0.0, 1.0, 0.0))¶
Takes an object and
If no match objs do nothing
If one object selected match to the rotation and translate.
If multiple objects match to the center of all dag objects (bounding boxes I think)
If component selection face/vert/edge match to center of selection via cluster method, also uses average normal (faces or verts) to orient.
else do nothing
- groupZeroObj(objName, freezeScale=True, removeSuffixName='')¶
Groups the selected object, matching the group to the object and zero’s the obj. objName can be long name.
Will freeze scale by default, the group will not be scaled
- Parameters:
- Return objName:
The name of the original object, if fullname the name will have changed, will be unique
- Rtype objName:
str
- Returns:
The name of the new group, will be a unique name
- Return type:
- groupZeroObjList(objList, freezeScale=True, removeSuffixName='')¶
Groups an object list, matching a new group to each object and zero’s the obj. objNames can be long names.
Will freeze scale by default, the groups will not be scaled
- Parameters:
- Return updatedObjList:
The names of the original objects, if fullnames the names will have changed, will be unique
- Rtype updatedObjList:
list(str)
- Returns:
The names of the new groups, will be unique names
- Return type:
list(str)
- groupZeroObjSelection(freezeScale=True, message=True, removeSuffixName='')¶
Groups selected objs, matching a new group to each object and zero’s the obj. objNames can be long names.
Will freeze scale by default, the groups will not be scaled
- Parameters:
- Returns:
First Element is the names of the original objects, if fullnames the names will have changed, will be unique. Second Element is the names of the new groups, will be unique names.
- Return type:
- grouper(it, n)¶
Uses zip py3 r izip py2 to pack a list into groups of n
- Parameters:
it (list()) – List to group
n (int) – Group via n
- Returns:
A list of groups now grouped into batches of n
- Return type:
tuple(tuple())
- averageNormals(normals)¶
Given many normals [[0.1, 0.9, 0.0], [0.0, 0.5, 0.5]] return the average, [0.5, 0.75, 0.25]
- averageVertNormals(verts)¶
Given a list of vertices return their averaged normals.
- faceNormals(faces)¶
Returns a list of face normals from a list of faces.
- averageFaceNormals(faces)¶
Given a list of faces return their averaged normals.
- createGroupFromVector(vector, aimVector=(0.0, 1.0, 0.0), localUp=(0.0, 0.0, -1.0), worldUp=(0.0, 1.0, 0.0), relativeObject='')¶
Creates a group oriented along a vector, builds and aim constraint and deletes.
If a relative object is given uses the objects world space and not local space.
- Parameters:
vector (list(float)) – A vector direction, list with three floats.
aimVector (list(float)) – The direction to aim the group
localUp (list(float)) – The direction to aim the group up
worldUp (list(float)) – The world up of the aim
relativeObject (str) – Take into consideration the relative rotation of a given object.
- Returns:
The group/transform now oriented as per the vector.
- Return type:
- createGroupOrientFromVertices(verts, aimVector=(0.0, 1.0, 0.0), localUp=(0.0, 0.0, -1.0), worldUp=(0.0, 1.0, 0.0))¶
Creates a group oriented to the average vector of the selected vertices, uses vertex normals.
- Parameters:
- Returns:
The group/transform now oriented as per the vector.
- Return type:
- createGroupOrientFromFaces(faces, aimVector=(0.0, 1.0, 0.0), localUp=(0.0, 0.0, -1.0), worldUp=(0.0, 1.0, 0.0))¶
Creates a group oriented to the average vector of the selected faces, uses face normals.
- Parameters:
- Returns:
The group/transform now oriented as per the vector.
- Return type:
- createGroupOrientFromComponents(components, aimVector=(0.0, 1.0, 0.0), localUp=(0.0, 0.0, -1.0), worldUp=(0.0, 1.0, 0.0))¶
Creates a group oriented to the average vector of the selected verts/edges/faces:
Edges are converted to verts. Verts use vertex normals. Faces use face normals.
- Parameters:
- Returns:
The group/transform now oriented as per the vector.
- Return type:
Matrix¶
cmds functions related to Offset Parent Matrix in Maya 2020 and above.
Example use:
from zoo.libs.maya.cmds.objutils import matrix
Author: Andrew Silke
- hasMatrixOffset(transform)¶
Checks to see if a transforms Offset Parent Matrix (Composition) has been modified at all.
Attribute: offsetParentMatrix
- Parameters:
transform (str) – A maya transform node
- Return hasOffset:
True if there is an offset, False if no offset
- Rtype hasOffset:
bool
- selectionMatrixCheck(message=True)¶
- zeroMatrixOffset(transform, unlockAttrs=True)¶
Resets/zeros the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr of a single object. Maintains the current position/rotation/scale.
- resetMatrixOffsetList(transformList, unlockAttrs=True)¶
Resets/zeros the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr of a list of objects. Maintains the current position/rotation/scale.
- zeroMatrixOffsetSel(unlockAttrs=True, children=False, nodeType=None, message=True)¶
Resets/zeros the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr of the selected objects. Maintains the current position/rotation/scale.
- Parameters:
unlockAttrs (str) – If True will unlock/del keys/disconnect any connected SRT attributes
children (bool) – If True will also reset the children of the selected objects
nodeType (str) – If children is True will only reset the children of the selected objects of this nodeType
message (bool) – report a message to the user?
- childrenByNodeType(objList, nodeType='transform')¶
retrieves all objs under the obj list in the hierarchy, all child joints
- Parameters:
objList (list(str)) – a list of Maya objects DAG nodes
- Return allObjs:
an obj list now including children
- Rtype allObjs:
list(str)
- srtToMatrixOffset(transform, unlockAttrs=True)¶
Sets the transforms translate, rotate to be zero and the scale to be one and passes the information into the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr For a single transform Maintains the current position/rotation/scale.
# TODO could possibly be done by simple math on the scale/rot/trans values not sure
- srtToMatrixOffsetList(transformList, unlockAttrs=True)¶
Sets the transforms translate, rotate to be zero and the scale to be one and passes the information into the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr For a list of tranforms Maintains the current position/rotation/scale.
- srtToMatrixOffsetSel(unlockAttrs=True, children=False, nodeType=None, message=True)¶
Sets the transforms translate, rotate to be zero and the scale to be one and passes the information into the Offset Parent Matrix (Composition) “.offsetParentMatrix” attr For a the selected transforms Maintains the current position/rotation/scale.
- Parameters:
unlockAttrs (str) – If True will unlock/del keys/disconnect any connected SRT attributes
children (bool) – If True will also reset the children of the selected objects
nodeType (str) – If children is True will only reset the children of the selected objects of this nodeType
message (bool) – report a message to the user?
- zeroSrtModelMatrix(transform, unlockAttrs=True)¶
Modeller Matrix Zero SRT, this will zero SRT and move offsets to the offsetParentMatrix but will freeze transforms for scale so the object can be rotated nicely.
# TODO record the scale values so the freeze can be undone?
- zeroSrtModelMatrixList(transformList, unlockAttrs=True)¶
Modeller Matrix Zero SRT, this will zero SRT and move offsets to the offsetParentMatrix but will freeze transforms for any scale so the object can be rotated nicely.
Works on a list of transforms.
- zeroSrtModelMatrixSel(unlockAttrs=True, children=False, nodeType=None, message=True)¶
Modeller Matrix Zero SRT, this will zero SRT and move offsets to the offsetParentMatrix but will freeze transforms for any scale so the object can be rotated nicely.
Works on selected transform objects.
- Parameters:
unlockAttrs (str) – If True will unlock/del keys/disconnect any connected SRT attributes
children (bool) – If True will also reset the children of the selected objects
nodeType (str) – If children is True will only reset the children of the selected objects of this nodeType
message (bool) – report a message to the user?
Mesh¶
- createPrimitiveMatch(matchObj=None, type='cube', message=True, scale=1.0)¶
Creates an primitive and tries to match it to the object given. If matchObj is None then defaults to world center.
- Parameters:
- Return newObj:
The newly created primitive
- Return type:
- createPrimitiveSelected(type='cube', message=True, scale=1.0)¶
Creates an primitive and tries to match it to the first selected object if one is selected. Otherwise defaults to world center.
- createPrimitiveFromList(matchObjList, type='cube', message=False, scale=1.0, parent=True, matchNames=True)¶
Creates new primitive objects from a list of existing objects. Matches the position and rotation, possibly scale
- Parameters:
- Return newObjList:
The newly created primitives
- Rtype newObjList:
list
Meshhandling¶
- getMeshSubDSettings(meshTransform, longName=True)¶
Returns four SubD mode attribute settings as a dict with these keys…
DISPLAYSMOOTHMESH: if the object has subd mode on (2) or hull (1) or none (0) SMOOTHLEVEL: the divisions level setting as an int USESMOOTHPREVIEWFORRENDERER: if renderer override is on (True False) RENDERSMOOTHLEVEL: the renderer override level as int
- getMeshSubDSettingsList(meshTransformList, longName=True)¶
Returns a nested dict of the 4 SubD mode settings given a meshTransformNode as a dict The nested dicts keys are meshTransform names The subD attribute dict has four keys
DISPLAYSMOOTHMESH: if the object has subd mode on (2) or hull (1) or none (0) SMOOTHLEVEL: the divisions level setting as an int USESMOOTHPREVIEWFORRENDERER: if renderer override is on (True False) RENDERSMOOTHLEVEL: the renderer override level as int
- Parameters:
meshTransformList (list) – a list of maya transform nodes with mesh shape nodes attached
longName (bool) – query as longnames
- Return subDMeshDict:
a nested dictionary meshes as keys and subD dict of attribute values
- Rtype subDMeshDict:
dict
- setMeshSubDSettings(meshTransform, subDDict, longName=True)¶
for a meshTransform apply the settings of a subDDict, with the following attributes being set…
DISPLAYSMOOTHMESH: if the object has subd mode on (2) or hull (1) or none (0) SMOOTHLEVEL: the divisions level setting as an int USESMOOTHPREVIEWFORRENDERER: if renderer override is on (True False) RENDERSMOOTHLEVEL: the renderer override level as int
- setMeshSubDSettingsList(meshTransformList, subDDict, longName=True)¶
for a meshTransformList apply the settings of a single subDDict
DISPLAYSMOOTHMESH: if the object has subd mode on (2) or hull (1) or none (0) SMOOTHLEVEL: the divisions level setting as an int USESMOOTHPREVIEWFORRENDERER: if renderer override is on (True False) RENDERSMOOTHLEVEL: the renderer override level as int
- setMeshSubDSettingsSelected(subDDict, longName=True)¶
For the selected objects apply the settings of a single subDDict
DISPLAYSMOOTHMESH: if the object has subd mode on (2) or hull (1) or none (0) SMOOTHLEVEL: the divisions level setting as an int USESMOOTHPREVIEWFORRENDERER: if renderer override is on (True False) RENDERSMOOTHLEVEL: the renderer override level as int
Moveorient¶
- getPosRotRoo(mayaObj)¶
gets the position and orientation of an object including the rotate order in world space
- Parameters:
mayaObj (str) – the object to record the pos and orient rot order
- Return PosRotRoo:
list of tuples in this order pos, rot, roo
- Rtype PosRotRoo:
list
- setPosRotRoo(mayaObj, posRotRoo)¶
sets the position and orientation give the posRotRoo which is a list in world space ((posX, posY, posz), (rotX, rotY, rotZ), xyz)
- Parameters:
mayaObj –
xformData –
- Returns:
- Return type:
Namehandling¶
Functions for handling names.
Example use:
from zoo.libs.maya.cmds.objutils import namehandling
Author: Andrew Silke
- convertStringToMayaCompatibleStr(anyNameString)¶
Converts a string to a Maya name, useful when files are imported and given Maya names that don’t support spaces.
- Parameters:
anyNameString (str) – A string with any letters “the-filename adfaf??yes”
- Return mayaCompatibleName:
the string with all non alpha numeric letters replaced with _ “the_filename_adfaf__yes”
- Rtype mayaCompatibleName:
str
- safeRename(objName, newName, uuid=None, renameShape=True, message=False, returnLongName=True)¶
Safe renames objects. Handles long names and if a uuid is supplied use the most current name instead. Checks for invalid names, numbers starting a name or locked nodes and will warn user without errors/issues
Example
objName: "|group1|Cube" replace: "|group1|aBox" or "aBox" result: "|group1|aBox"
Example with uuid
uuid: "B7EABB60-4578-A4D1-73DC-07B9A14F267F" replace: "|group1|aBox" or "aBox" result: "|group1|aBox"
If an uuid is given will use that instead of the node name, handy with re-parenting and hierarchies longname lists
- Parameters:
objName (str) – The name of the object to be renamed, can be in longname format
newName (str) – The new name of the object can be in long format
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or parenting
renameShape (bool) – also rename the shape node if a transform or joint?
message (bool) – Report the message to the user
returnLongName (bool) – If True will return a long name of the new name if successfully renamed
- Returns:
The new name of the object now potentially renamed
- Return type:
- safeRenameList(objList, renameList, uuidList=None, renameShape=True, message=False, returnLongName=True)¶
Safe renames a list of objects. Handles long names and will convert to uuids for safe renaming. Checks for invalid names, numbers starting a name or locked nodes and will warn user without errors/issues
Example of each object in the list
objName: "|group1|Cube" replace: "|group1|aBox" or "aBox" result: "|group1|aBox"
Example with uuid list:
uuid: "B7EABB60-4578-A4D1-73DC-07B9A14F267F" replace: "|group1|aBox" or "aBox" result: "|group1|aBox"
If a uuid list is given will use that instead of the node name list
- Parameters:
objList (list(str)) – The existing objectList to be renamed, can be in longname format
renameList (list(str)) – The new name list object names, can be in long format
uuidList (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or reparenting
renameShape (bool) – also rename the shape node if a transform or joint?
message (bool) – Report the message to the user
returnLongName (bool) – If True will return a long name of the new name if successfully renamed
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- renameShapeNodes(nodeName, uuid=None, returnLongName=False)¶
Renames the shape nodes of a transform or joint node. cmds.rename() doesn’t handle shape nodes well.
- Parameters:
- Returns:
The new name of the shape nodes now potentially renamed
- Return type:
list(str)
- renameShapeNodesList(nodeNames, returnLongName=False)¶
Renames the shape nodes under a transform or joint node. cmds.rename() doesn’t handle shape nodes well.
- mayaNamePartTypes(objName)¶
Breaks up a Maya node name now with the “longName prefix” and “namespace” (if exists) and “pureName”.
Example 1:
objectName: "pCube1" return longPrefix: "" return namespace: "" return pureName: "pCube1"
Example 2:
objectName: "scene4:y:group2|scene4:y:locator2|scene4:x:pCube1" return longPrefix: "scene4:y:group2|scene4:y:locator2" return namespace: "scene4:x" return pureName: "pCube1"
- mayaNamePartsJoin(longPrefix, namespace, pureName)¶
Joins names from 3 potential components, longPrefi and namespace can be None or empty strings
Example 1 (long names with namespaces):
longPrefix: "xx:group1|group2" namespace: "x:y" pureName: "pCube1" result: "xx:group1|group2|x:y:pCube1"
Example 2 (short names):
longPrefix: "" namespace: "" pureName: "pCube1" result: "pCube1"
Both longPrefix and namespace can be empty strings or None.
- Parameters:
- Return fullName:
The joined Maya name “xx:group1|group2|x:y:pCube1”
- Rtype fullName:
str
- getLongNameFromShort(objName)¶
Get the long name from a short name
- getLongNameList(objectList)¶
From a mixed longname and shortname list, return all long names
- Parameters:
objectList (list) – a list of maya objects/nodes/objectFaces etc
- Returns:
a list of maya objects/nodes/objectFaces now with longnames
- Return type:
list
- getShortName(longName)¶
Returns the short readable name of a Maya object, pure text function. Doesn’t check nonUnique or care if the obj exists
- getShortNameList(longNameList)¶
Returns the short names of a Maya object list, pure text function Doesn’t check Maya for non-unique or care if the obj exists
- Parameters:
longNameList (list) – Maya object/node list of long names
- Return shortNameList:
the short names
- Rtype shortNameList:
list
- getUniqueShortName(longName)¶
Returns the shortest unique name.
For example:
"|grp|rig|geo|mesh" May not be a Maya unique name, it is the full path or long name Instead the unique name is the shortest path to the unique name, so it could be "geo|mesh"
Also invalid are names that start with a pipe such as unless they are parented to the world:
"|geo|mesh"
For example world unique names may be valid:
"|sphere1" can be ok if sphere1 is duplicated elsewhere
This is important for mel (or mel eval) functions such as the mel:
findRelatedSkinCluster "geo|mesh"
Which cannot be passed true long names
- getUniqueShortNameList(longNameList)¶
Returns a list of objs with unique names, will try short and if non-unique then will keep the longname
- Parameters:
longNameList (list) – Maya object/node list of long names
- Returns:
the short and unique names if duplicated are still kept as long
- Return type:
list
- trailingNumber(name)¶
Returns the trailing number of a string, the name with the number removed, and the padding of the number
Examples:
"shaderName" returns "shaderName", None, 0 "shaderName2" returns "shaderName", 2, 1 "shader1_Name04" returns "shader1_Name", 4, 2 "shaderName_99" returns "shaderName_", 99, 2 "shaderName_0009" returns "shaderName_", 9, 4
- incrementName(name)¶
Increment Name
Examples:
"obj" --> "obj1" "obj2" --> "obj3" "obj_5" --> "obj_5" "obj_02" --> "obj_03"
- generateUniqueName(name, checkMax=1000)¶
Generates a unique node name in maya, if it’s already unique it will return name
- Returns:
- Return type:
- nonUniqueNameNumber(name, shortNewName=True, paddingDefault=2)¶
If a short name is not-unique in Maya return the first numbered unique name
Will detect padding automatically if the existing name already has a numbered suffix ie “objName_0001” is 4 padding Default padding is two if no number suffix exists
Examples:
"shaderName" becomes "shaderName_01" "shaderName2" becomes "shaderName3" "shader1_Name04" becomes "shader1_Name05" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
Handles infinite numbers will go up above 999 though the padding will expand
- Parameters:
- Returns:
the new name with a potential iterative number suffix newName5_01, can be long or short
- Return type:
- uniqueNameFromList(name, nameList, paddingDefault=2)¶
Finds a unique name when compared against a list, Maya is not queried
Will detect padding automatically if the existing name already has a numbered suffix ie “objName_0001” is 4 padding Default padding is two if no number suffix exists
The returned name won’t match any in the list
Examples:
"shaderName" becomes "shaderName_01" "shaderName2" becomes "shaderName3" "shader1_Name04" becomes "shader1_Name05" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
Handles infinite numbers will go up above 999 though the padding will expand
- getUniqueNamePadded(name, paddingDefault=2)¶
Returns a unique name with padding.
Example “shader1” already exists in the scene.
name: “shader1” returnedName: “shader_02”
- getUniqueNameSuffix(name, suffix, paddingDefault=2, nameAlreadySuffixed=False)¶
Returns a unique “_”join([name, suffix]) with a smart iterative number before the suffix, see examples
Will detect padding automatically if the existing name already contains a numbered suffix ie “objName0001_PXR” is 4 pad Default padding is two if no number suffix exists
Example:
"shader_PXR" becomes "shader_01_PXR" "shader_04_PXR" becomes "shader_05_PXR" "shader99_PXR" becomes "shader100_PXR" "shader_1x9_PXR" becomes "shader_1x10_PXR" "shader_002_PXR" becomes "shader_003_PXR"
Handles infinite numbers will go up above 999 though the padding will expand
- forceUniqueShortName(name, paddingDefault=2, uuid=None, ignoreShape=False, shortNewName=True)¶
Given a long name, if it is not unique then rename the Maya object to the first unique name with numbered suffix.
Existing numbers are handled smartly with padding
example:
"shaderName" becomes "shaderName_01" "shaderName_2" becomes "shaderName_3" "shaderName_04" becomes "shaderName_04" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
- Parameters:
name (str) – the name to check and possibly rename, should be a long name “group2|objName”
paddingDefault (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or reparenting
ignoreShape (str) – if on will not auto rename the shape node
shortNewName (bool) – will shorten the new name if a long name
- Returns:
the new name with a potential iterative number suffix newName5_01, can be long or short
- Return type:
- forceUniqueShortNameList(nameList, paddingDefault=2, ignoreShape=False, shortNewName=True)¶
- given a name list if a name is not unique then rename the Maya object to the first unique name
By default adds an underscore and 2 padding
example:
"shaderName" becomes "shaderName_01" "shaderName_2" becomes "shaderName_3" "shaderName_04" becomes "shaderName_04" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
Uses uuid for safety while renaming long names lists and for re-parenting
- Parameters:
- Returns:
the new name with a potential iterative number suffix newName5_01, can be long or short
- Return type:
- forceUniqueShortNameSelection(paddingDefault=2, ignoreShape=False, shortNewName=True)¶
For the selected object list if a name is not unique then rename the Maya object to the first unique name
By default, adds an underscore and 2 padding
Example:
"shaderName" becomes "shaderName_01" "shaderName_2" becomes "shaderName_3" "shaderName_04" becomes "shaderName_04" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
- forceUniqueShortNameFiltered(niceNameType, padding=2, shortNewName=True, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
From a filtered list, filtered by node type (see filterTypes.TYPE_FILTER_LIST) force unique names on the result
By default, adds an underscore and 2 padding
Example:
"shaderName" becomes "shaderName_01" "shaderName_2" becomes "shaderName_3" "shaderName_04" becomes "shaderName_04" "shaderName_99" becomes "shaderName_100" "shaderName_0009" becomes "shaderName_0010"
More documentation:
See filterTypes.filterByNiceType() for more information about filtering by type
- Parameters:
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
shortNewName (bool) – Return the new short name and not a long name?
renameShape (bool) – Rename the shape nodes automatically to match transform renames
selectionOnly (bool) – If True search the selected objects not the whole scene
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree?
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- nameIsUnique(nodeName)¶
Checks to see if a long name is unique in the scene, returns a bool
- nodeListIsUniqueName(nodeLongNameList, removeNamespaces=False)¶
Checks to see if any nodes in a node list are not unique Returns a list that of not unique names, or if None found returns an empty string
- removeNumbersObj(objName, uuid=None, trailingOnly=False, renameShape=True, killUnderscores=True)¶
Removes numbers from a name.
Can remove underscores too:
"name_001" becomes "name" "name1" becomes "name"
trailingOnly True:
"name_1_character3" becomes "name_1_character"
trailingOnly False:
"name_1_character3" becomes "name_character"
killUnderscores False:
"name_1_character_3" becomes "name__character_"
- Parameters:
objName (str) – The name of the Maya object or node
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or parenting
trailingOnly (bool) – If True only remove numbers at the end of the name, leave numbers in the middle
renameShape (bool) – Rename the shape nodes automatically to match transform renames
killUnderscores (bool) – Will remove the unwanted underscores “name_1_character_3” becomes “name_character”
- Returns:
the new name of the object or node
- Return type:
- removeNumbersList(objList, trailingOnly=False, renameShape=True, killUnderscores=True)¶
Removes numbers from an object/node list of names:
See removeNumbersObj() for full documentation and examples.
- Parameters:
objList (list) – A list of Maya object or node names
trailingOnly (bool) – If True only remove numbers at the end of the name, leave numbers in the middle
renameShape (bool) – Rename the shape nodes automatically to match transform renames
killUnderscores (bool) – Will remove the unwanted underscores “name_1_character_3” becomes “name_character”
- Returns:
the object list with new names
- Return type:
list(str)
- removeNumbersSelection(trailingOnly=False, renameShape=True, killUnderscores=True)¶
Removes numbers from a selection of objects or nodes:
See removeNumbersObj() for cull documentation and examples.
- Parameters:
- Returns:
the object list with new names
- Return type:
list(str)
- removeNumbersFilteredType(niceNameType, trailingOnly=False, killUnderscores=True, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Removes numbers from objects/nodes depending on the kwargs and nicename node type:
See removeNumbersObj() for documentation and examples about the rename. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
trailingOnly (bool) – If True only remove numbers at the end of the name, leave numbers in the middle
renameShape (bool) – Rename the shape nodes automatically to match transform renames
killUnderscores (bool) – Will remove the unwanted underscores “name_1_character_3” becomes “name_character”
selectionOnly (bool) – If True search the selected objects not the whole scene
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree?
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- renumberObjList(objList, removeTrailingNumbers=True, addUnderscore=True, padding=2, renameShape=True, message=False)¶
Renumbers from a list of objects/nodes
removeTrailingNumbers True, addUnderscore=True, padding=2:
"[pCube1, pSphere1, pCylinder1]" becomes "[pCube_01, pSphere_02, pCylinder_03]"
removeTrailingNumbers False, addUnderscore=True, padding=3:
"[pCube1, pSphere1, pCylinder1]" becomes "[pCube1_001, pSphere1_002, pCylinder1_003]"
removeTrailingNumbers True, addUnderscore=False, padding=1:
"[pCube1, pSphere1, pCylinder1]" becomes "[pCube1, pSphere2, pCylinder3]"
- Parameters:
objList (list) – A list of Maya object or node names
removeTrailingNumbers (bool) – Removes trailing numbers before doing the renumber. “pCube1” becomes “pCube_##”
addUnderscore (bool) – Adds an underscore between the name and the new number
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- renumberSelection(removeTrailingNumbers=True, addUnderscore=True, padding=2, renameShape=True, message=False)¶
Renumbers from a selection of objects or nodes:
See renumberObjList() for documentation and examples about the renumbering.
- Parameters:
removeTrailingNumbers (bool) – Removes trailing numbers before doing the renumber. “pCube1” becomes “pCube_##”
addUnderscore (bool) – Adds an underscore between the name and the new number
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Return objList:
the object list with new names
- Rtype objList:
list(str)
- renumberFilteredType(niceNameType, removeTrailingNumbers=True, padding=2, addUnderscore=True, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Renumbers objects/nodes depending on the kwargs and nicename node type:
See renumberObjList() for documentation and examples about the renumbering. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
removeTrailingNumbers (bool) – Removes trailing numbers before doing the renumber. “pCube1” becomes “pCube_##”
padding (int) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
addUnderscore (bool) – Adds an underscore between the name and the new number
renameShape (bool) – Rename the shape nodes automatically to match transform renames
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
selectionOnly (bool) – If True search the selected objects not the whole scene
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree?
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- renumberListSingleName(newName, objList, padding=2, renameShape=True, message=False)¶
Renames a list of objects with a single name and numbered padding
Returns renamed objects:
[newName_01, newName_02, newName_03]
- Parameters:
newName (str) – The new name suffix to name all objects in the list
objList (list(str)) – A list of Maya object or node names
padding (int) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- changeSuffixPadding(objName, uuid=None, padding=2, addUnderscore=True, renameShape=True, message=False)¶
Changes the suffix numerical padding of an objects or node:
addUnderscore=True, padding=2:
"pCube1" becomes "pCube_01"
addUnderscore=False, padding=3:
"pCube1" becomes "pCube001"
- Parameters:
objName (str) – The name of the Maya object or node
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
addUnderscore (bool) – Adds an underscore between the name and the new number
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Returns:
the new name of the object or node
- Return type:
- changeSuffixPaddingList(objList, padding=2, addUnderscore=True, renameShape=True, message=False)¶
Changes the suffix numerical padding from a list of objects or nodes:
See changeSuffixPadding() for documentation and examples about changing suffix padding.
- Parameters:
objList (list) – A list of Maya object or node names
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
addUnderscore (bool) – Adds an underscore between the name and the new number
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Returns:
the object list with new names
- Return type:
list(str)
- changeSuffixPaddingSelection(padding=2, addUnderscore=True, renameShape=True, message=False)¶
Changes the suffix numerical padding from a selection of objects or nodes:
See changeSuffixPadding() for documentation and examples about changing suffix padding.
- Parameters:
padding (str) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
addUnderscore (bool) – Adds an underscore between the name and the new number
renameShape (bool) – Rename the shape nodes automatically to match transform renames
message (bool) – Return the message to the user?
- Return objList:
the object list with new names
- Rtype objList:
list(str)
- changeSuffixPaddingFilter(niceNameType, padding=2, addUnderscore=True, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Changes the suffix numerical padding of objects/nodes depending on the kwargs and nicename node type:
See changeSuffixPadding() for documentation and examples about changing suffix padding. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
padding (int) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
addUnderscore (bool) – Adds an underscore between the name and the new number
renameShape (bool) – Rename the shape nodes automatically to match transform renames
searchHierarchy (bool) – Also try to search the hierarchy below the objectList? False will only filter objList
selectionOnly (bool) – If True search the selected objects not the whole scene
dag (bool) – return only dag nodes? Ie nodes that can be viewed in the outliner hierarchy tree?
removeMayaDefaults (bool) – While filtering the whole scene don’t include default nodes such as lambert1/persp etc
transformsOnly (bool) – If True will not further filter the transforms with the function filterShapesFromList()
message (bool) – Return the message to the user?
- Return objList:
the object list with new names
- Rtype objList:
list(str)
- forceRenameListSel(forceText, niceNameType, padding=2, renameShape=True, hierarchy=False, message=False)¶
Force renames the selected objects in the selection order to be:
“forceText_01” “forceText_02” “forceText_03”
- Parameters:
forceText (str) – The new name to affect all objects in the list
padding (int) – the amount of numerical padding. 2 = 01, 3 = 001, etc, only used if no number exists
renameShape (bool) – Rename the shape nodes automatically to match transform renames
hierarchy (bool) – Include the hierarchy of the selected objects?
message (bool) – Return the message to the user?
- Return objList:
the object list with new names
- Rtype objList:
list(str)
- searchReplaceName(objName, searchTxt, replaceText, uuid=None, renameShape=True, message=False)¶
For a single object search and replace on the object name.
Example:
search: “Cube” replace: “Koala” result: “pCube1” becomes “pKoala1”
If a uuid is given will use that instead of the node name, can be handy with re-parenting/hierarchies with renaming
- Parameters:
objName (str) – The name of the object to be renamed
searchTxt (str) – The text to search for, this text will be replaced
replaceText (str) – The replace text that replaces the search text
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
renameShape (bool) – also rename the shape node if a transform or joint?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- searchReplaceObjList(objList, searchTxt, replaceText, renameShape=True, message=False)¶
Renames a list of object/node names with the replaceText replacing the searchTxt:
See searchReplaceName() for documentation.
- Parameters:
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- searchReplaceSelection(searchTxt, replaceText, renameShape=True, message=True)¶
Renames the selected objects/nodes with the replaceText replacing the searchTxt:
See searchReplaceName() for documentation
- Parameters:
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- searchReplaceFilteredType(searchTxt, replaceText, niceNameType, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
From a special filter type will filter the search and replace to only rename the returned type of object:
See filterTypes.filterByNiceType() for more information about filtering by type
- Parameters:
searchTxt (str) – The text to search for, this text will be replaced
replaceText (str) – The replace text that replaces the search text
niceNameType (str) – A nice name of an object type, as found in filterTypes.TYPE_FILTER_LIST eg “Polygon”, “Locator”
renameShape (bool) – also rename the shape node if a transform or joint?
searchHierarchy (bool) – Also search the hierarchy of the selected objects?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- suffixPrefix(objName, sptype='suffix')¶
Returns the suffix or the prefix of a string name. Must be serarated by an underscore “_”
SUFFIX example:
“a_string_here” returns “here”
“aNameHere” returns “aNameHere
- checkSuffixPrefixExists(objName, suffixPrefix, sptype='suffix')¶
Checks to see if the suffix, or prefix already exists, returns True if a match, false if not found.
- Parameters:
- Return suffixPrefixFound:
True if a suffixPrefix is found, False if not found
- Rtype suffixPrefixFound:
bool
- stripSuffixExact(fullName, suffix, seperator='_')¶
Removes the suffix if given the exact letters to match and remove
Example:
“name_suffix” becomes “name”
If the suffix isn’t found returns the fullName
- addPrefixSuffix(objName, prefixSuffix, sptype='suffix', uuid=None, addUnderscore=False, renameShape=True, message=False, checkExistingSuffixPrefix=True)¶
Uses the safeName() function to rename with a prefix or suffix,
Pass in a uuid if having trouble with hierarchy naming or parenting/re-parenting and long names
Example:
objName: "|group1|Cube" prefixSuffix: "_jnt" sptype: "suffix" result: "|group1|Cube_jnt" (object renamed)
Example with uuid:
uuid: "B7EABB60-4578-A4D1-73DC-07B9A14F267F" prefixSuffix: "jnt" addUnderscore: True sptype: "prefix" result: "|group1|jnt_Cube" (object renamed)
- Parameters:
objName (str) – The name of the object to be renamed
prefixSuffix (str) – string to add at the start/finish of the name, add underscore with “addUnderscore” flag
sptype (str) – Suffix or Prefix, use SUFFIX or PREFIX
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
addUnderscore (bool) – Will add an underscore to the suffix ie “pCube1suffix” becomes pCube1_suffix”
renameShape (bool) – also rename the shape node if a transform or joint?
checkExistingSuffixPrefix (bool) – checks if the suffix/prefix exists and if so doesn’t add another
message (bool) – also rename the shape node if a transform or joint?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- addPrefixSuffixList(objList, prefixSuffix, sptype='suffix', uuid=None, addUnderscore=False, renameShape=True, checkExistingSuffixPrefix=True, message=False)¶
Uses the safeName() function to rename and object list adding a prefix or suffix.
Uses uuid’s in case of hierarchies or re-parenting long name issues:
See addPrefixSuffix() documentation for more information about how this function renames.
- Parameters:
objList (list) – Objects to be renamed as a list
prefixSuffix (str) – string to add at the start/finish of the name, add underscore with “addUnderscore” flag
uuid (str) – optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
addUnderscore (bool) – Will add an underscore to the suffix ie “pCube1suffix” becomes pCube1_suffix”
renameShape (bool) – also rename the shape node if a transform or joint?
checkExistingSuffixPrefix (bool) – checks if the suffix/prefix exists and if so doesn’t add another
message (bool) – also rename the shape node if a transform or joint?
renameShape – also rename the shape node if a transform or joint?
- Return newNameList:
The new names of all objects now potentially renamed
- Rtype newNameList:
list
- addSuffixSelection(prefixSuffix, sptype='suffix', uuid=None, addUnderscore=False, renameShape=True, message=False)¶
Uses the safeName() function to rename the current selection adding a prefix or suffix to every selected object
Uses uuid’s in case of hierarchies or re-parenting avoiding long name issues:
See addPrefixSuffix() documentation for more information about how this function renames.
- Parameters:
- Return newNameList:
The new names of all objects now potentially renamed
- Rtype newNameList:
list
- prefixSuffixFilteredType(prefixSuffix, niceNameType, sptype='suffix', renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
With a niceNameType, this function will filter and prefix or suffix by the filtered object type:
See addPrefixSuffix() documentation for more information about how this function renames. See filterTypes.filterByNiceType() for more information about filtering by niceNameType.
- Parameters:
prefixSuffix (str) – string to add at the start/finish of the name, add underscore with “addUnderscore” flag
niceNameType (str) – A nice name of an object type, as found in filterTypes.TYPE_FILTER_LIST eg “Polygon”, “Locator”
renameShape (bool) – Also rename the shape node if a transform or joint?
searchHierarchy (bool) – Also search the hierarchy of the selected objects?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- autoPrefixSuffixObj(objName, uuid=None, sptype='suffix', renameShape=True)¶
Will auto suffix or prefix a node automatically in Maya by it’s node type.
Suffix example:
“group1” becomes “group1_grp” “pCube1” becomes “pCube1_geo”
Suffix types must be defined in filterTypes.SUFFIXLIST(), later would like to add to a JSON so users can modify in a GUI.
The suffix in some cases is intelligent, for example a transform node selection will look for the first shape node to define its type. And in special cases such as groups or controls the code intelligently figures the suffix since there are no node types in Maya for controls or groups.
Suffix examples, refer to filterTypes.SUFFIXLIST() for latest:
filterTypes.GEO_SX = ‘geo’ filterTypes.JOINT_SX = ‘jnt’ filterTypes.CONTROLLER_SX = ‘ctrl’ filterTypes.GROUP_SX = ‘grp’ filterTypes.SRT_SX = ‘srt’ filterTypes.LEFT_SX = ‘L’ filterTypes.LEFT2_SX = ‘lft’ filterTypes.RIGHT_SX = ‘R’ filterTypes.RIGHT2_SX = ‘rgt’ filterTypes.CENTER_SX = ‘M’ filterTypes.CENTER2_SX = ‘cntr’ filterTypes.CENTER3_SX = ‘mid’ filterTypes.CURVE_SX = ‘crv’ filterTypes.CLUSTER_SX = ‘cstr’ filterTypes.FOLLICLE_SX = ‘foli’ filterTypes.NURBS_SX = ‘geo’ filterTypes.IMAGEPLANE_SX = ‘imgp’ filterTypes.LOCATOR_SX = ‘loc’ filterTypes.LIGHT_SX = ‘lgt’ filterTypes.SHADER_SX = ‘shdr’ filterTypes.SHADINGGROUP_SX = ‘shdg’ filterTypes.CAMERA_SX = ‘cam’
- Parameters:
objName (str) – The current name of the object or node, can be long or unique names
uuid (str) – Optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
sptype (str) – Suffix Prefix type, eg filterTypes.GROUP_SX is “grp”. “group1” becomes “group1_grp”
renameShape (bool) – Also rename the shape node if a transform or joint?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- autoPrefixSuffixList(objList, sptype='suffix', renameShape=True)¶
Will auto suffix or prefix a object/node list automatically in Maya by it’s node type:
See autoPrefixSuffixObj() for full documentation.
- Parameters:
- Return newNameList:
The new names of all objects now potentially renamed
- Rtype newNameList:
list
- autoPrefixSelection(sptype='suffix', renameShape=True)¶
Will auto suffix or prefix selected nodes/objects automatically in Maya by it’s node type:
See autoPrefixSuffixObj() for full documentation.
- autoPrefixSuffixFilteredType(niceNameType, sptype='suffix', renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Auto suffix/prefix nodes/objects automatically by node type. Uses filtering to restrict the renaming:
See autoPrefixSuffixObj() for full documentation. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
sptype (str) – Suffix Prefix type, eg filterTypes.GROUP_SX is “grp”. “group1” becomes “group1_grp”
renameShape (bool) – Also rename the shape node if a transform or joint?
searchHierarchy (bool) – Also search the hierarchy of the selected objects?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- checkIndexIntInList(nameList, index)¶
Checks to see if an index is in a nameList (the name broken up by the separator usually by underscore).
Returns exists: True or False
Example:
nameList: [“pCube1”, “grp”] 0 exists, it is “pCube1” return True 1 exists, it is “grp” return True 2 does not exist, return False -1 exists, it is “grp, return True -2 exists, it is “pCube1”, return True -3 does not exist, return False
- Parameters:
- Return exists:
The index is in the nameList True, or isn’t False
- Rtype exists:
bool
- editIndexItem(objName, index, text='', mode='insert', separator='_', renameShape=True, uuid=None, message=False)¶
Split an object/node name by it’s separator (usually underscore), edit the position based by it’s index number.
Modes:
EDIT_INDEX_INSERT: “insert”, will insert (add) a new value into that position EDIT_INDEX_REMOVE: “remove”, will delete the text by index at that position EDIT_INDEX_REPLACE: “replace”, will overwrite the text at that position
Example args/kwargs:
objName: “pCube_01_geo” (index 0 is “pCube”. 1 is “01”. 2 is “geo”. -1 is “geo” etc) index: 1 text: “variantA”
Results:
Insert result: “pCube_variantA_01_geo” Replace result: “pCube_variantA_geo” Remove result: “pCube_geo”
Optional uuid can be used in case of hierarchies or re-parenting avoiding long name issues.
- Parameters:
objName (str) – The current name of the object or node, can be long or unique names
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
text (str) – The text to “insert” or “replace”. “remove” no text is needed.
mode (str) – The three modes for this function… EDIT_INDEX_INSERT, EDIT_INDEX_REMOVE, EDIT_INDEX_REPLACE
separator (str) – The text used to split the text, usually an underscore “_”
renameShape (bool) – Also rename the shape node if a transform or joint?
uuid (str) – Optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
message (bool) – Report a message to the user?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- editIndexItemList(objList, index, text='', mode='insert', separator='_', renameShape=True, message=False)¶
Split an object/node list by it’s separator (usually underscore), edit the position based by it’s index number:
See editIndexItem() for full documentation.
- Parameters:
objList (list) – Objects to be renamed as a list
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
text (str) – The text to “insert” or “replace”. “remove” no text is needed.
mode (str) – The three modes for this function… EDIT_INDEX_INSERT, EDIT_INDEX_REMOVE, EDIT_INDEX_REPLACE
separator (str) – The text used to split the text, usually an underscore “_”
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report a message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- editIndexItemSelection(index, text='', mode='insert', separator='_', renameShape=True, message=False)¶
Split a selection by it’s separator (usually underscore), edit the position based by it’s index number:
See editIndexItem() for full documentation.
- Parameters:
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
text (str) – The text to “insert” or “replace”. “remove” no text is needed.
mode (str) – The three modes for this function… EDIT_INDEX_INSERT, EDIT_INDEX_REMOVE, EDIT_INDEX_REPLACE
separator (str) – The text used to split the text, usually an underscore “_”
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report a message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- editIndexItemFilteredType(index, niceNameType, text='', mode='insert', separator='_', renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Split object/s by their separator (usually underscore), edit the position by it’s index number, uses filtering:
See editIndexItem() for full documentation. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
text (str) – The text to “insert” or “replace”. “remove” no text is needed.
mode (str) – The three modes for this function… EDIT_INDEX_INSERT, EDIT_INDEX_REMOVE, EDIT_INDEX_REPLACE
separator (str) – The text used to split the text, usually an underscore “_”
renameShape (bool) – Also rename the shape node if a transform or joint?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- shuffleItemByIndex(objName, index, offset=1, uuid=None, renameShape=True, separator='_', message=False)¶
Shuffles the position of a text item usually split by an underscore. offset 1 is forwards, -1 is backwards.
Index is the text to move/shuffle, can be a negative number so “pCube_variant01_geo”:
0: “pCube1” 1: “pCube_variant01_geo” -1: “geo”
Example shuffle index 0 forwards:
“pCube_variant01_geo” becomes “variant01_pCube_geo”
Example shuffle index -1 backwards
“pCube_variant01_geo” becomes “pCube_geo_variant01”
This function comes with error checking so if certain tasks can’t be completed it will return early and bail no errors will be reported for the shuffle even with message on. Usually in the GUI shuffle errors aren’t critical.
Optional uuid can be used in case of hierarchies or re-parenting avoiding long name issues.
- Parameters:
objName (str) – The current name of the object or node, can be long or unique names
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
offset (int) – The of the shuffle/move, can only be 1 (forwards) or -1 (backwards)
uuid (str) – Optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
renameShape (bool) – Also rename the shape node if a transform or joint?
separator (str) – The text used to split the text, usually an underscore “_”
message (bool) – Report the message to the user?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- shuffleItemByIndexList(objList, index, offset=1, renameShape=True, separator='_', message=False)¶
Shuffles the position of a txt item usually split by an underscore in an obj/node list. 1 forwards, -1 backwards:
See shuffleItemByIndex() for full documentation.
- Parameters:
objList (list) – Objects to be renamed as a list
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
offset (int) – The of the shuffle/move, can only be 1 (forwards) or -1 (backwards)
renameShape (bool) – Also rename the shape node if a transform or joint?
separator (str) – The text used to split the text, usually an underscore “_”
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- shuffleItemByIndexSelection(index, offset=1, renameShape=True, separator='_', message=False)¶
Shuffles the position of a txt item usually split by an underscore in the selection. 1 forwards, -1 backwards:
See shuffleItemByIndex() for full documentation.
- Parameters:
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
offset (int) – The of the shuffle/move, can only be 1 (forwards) or -1 (backwards)
renameShape (bool) – Also rename the shape node if a transform or joint?
separator (str) – The text used to split the text, usually an underscore “_”
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- shuffleItemByIndexFilteredType(index, niceNameType, offset=1, separator='_', renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Shuffles the position of a txt item usually split by an underscore with filters. 1 forwards, -1 backwards:
See shuffleItemByIndex() for full documentation. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
index (int) – The index number, can be negative. [“pCube1”, “grp”] 0 is “pCube1”, 1 is “grp” -1 is “grp”
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
offset (int) – The of the shuffle/move, can only be 1 (forwards) or -1 (backwards)
separator (str) – The text used to split the text, usually an underscore “_”
renameShape (bool) – Also rename the shape node if a transform or joint?
searchHierarchy (bool) – Also search the hierarchy of the selected objects?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- namespacesInScene()¶
- nameSpace(node)¶
Returns the name space of a node if it has one. Will be “” if None.
- namespaceSelected(message=True)¶
Takes the namespace from the first selected node. If None will return “”
- bakeNamespaces(objName, returnLongName=False)¶
replaces a namespace : character with _:
“rig:polyCube1” becomes “rig_polyCube1”
- Parameters:
objName (str) – The name of the object to be renamed, can be in longname format
- Return newName:
The new long name of the object now potentially renamed
- Rtype newName:
str
- bakeNamespacesList(objList)¶
replaces a namespace : character with _ on an object list:
[“rig:polyCube1”, “rig:polyCube2”] becomes [“rig_polyCube1”, “rig_polyCube2”]
- Parameters:
objList (list(str)) – The names of the objects to be renamed, can be in longname format
- Return newNames:
The new long names of the objects now potentially renamed.
- Rtype newNames:
list(str)
- bakeNamespacesSel(message=True)¶
replaces a namespace : character with _ on an object selection:
[“rig:polyCube1”, “rig:polyCube2”] becomes [“rig_polyCube1”, “rig_polyCube2”]
- Parameters:
message (bool) – Report a message to the user?
- Return newNames:
The new long names of the objects now potentially renamed.
- Rtype newNames:
list(str)
- removeEmptyNamespaces(message=True)¶
Removes all empty namespaces in the scene
Recursive function that starts at the bottom and empties namespaces one by one until the top of the namespace hierarchy is reached.
Credit bob.w http://discourse.techart.online/t/deleting-namespace-the-python-way/5179/3
- Parameters:
message (bool) – Report the message to the user?
- Return delNamespaceList:
the list of namespace names deleted
- Rtype delNamespaceList:
list
- assignNamespace(objName, existingNamespace, removeNamespace=False, uuid=None, renameShape=True, message=False)¶
Will assign (or remove) a namespace to an object. The namespace must already exist in the scene.
Assign Example:
objName: “pCube1” existingNamespace: “chair” removeNamespace: False result: “chair:pCube1”
Remove Example:
objName: “chair:pCube1” existingNamespace: “chair” removeNamespace: False result: “pCube1”
- Parameters:
objName (str) – The current name of the object or node, can be long or unique names
existingNamespace (str) – The name of the namespace to assign, it must currently exist in the scene
removeNamespace (bool) – Remove namespaces from the name? Returned name will not have a namespace
uuid (str) – Optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report the message to the user?
- Return newName:
The new name of the object now potentially renamed
- Rtype newName:
str
- createAssignNamespaceList(objList, namespaceName, removeNamespace=False, renameShape=True, message=False)¶
Will assign (or remove) a namespace to an object list. The namespace will be created if it doesn’t exist:
See assignNamespace() for more information.
- Parameters:
objList (list) – Objects to be renamed as a list
namespaceName (str) – The new or existing namespace name to assign or remove (if removeNamespace=True)
removeNamespace (bool) – Remove namespaces from the name? Returned name will not have a namespace
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- createAssignNamespaceSelected(namespaceName, removeNamespace=False, renameShape=True, message=False)¶
Will assign (or remove) a namespace to a obj/node selection. The namespace will be created if it doesn’t exist:
See assignNamespace() for more information.
- Parameters:
namespaceName (str) – The new or existing namespace name to assign or remove (if removeNamespace=True)
removeNamespace (bool) – Remove namespaces from the name? Returned name will not have a namespace
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- createAssignNamespaceFilteredType(namespaceName, niceNameType, removeNamespace=False, renameShape=True, searchHierarchy=False, selectionOnly=True, dag=False, removeMayaDefaults=True, transformsOnly=True, message=True)¶
Will assign (or remove) a namespace to a obj/nodes based off filters. The namespace will be created if it doesn’t exist:
See assignNamespace() for more information. See filterTypes.filterByNiceType() for more information about filtering by type.
- Parameters:
namespaceName (str) – The new or existing namespace name to assign or remove (if removeNamespace=True)
niceNameType (str) – A single string from the list filterTypes.TYPE_FILTER_LIST, describes a type of node/s in Maya
removeNamespace (bool) – Remove namespaces from the name? Returned name will not have a namespace
renameShape (bool) – Also rename the shape node if a transform or joint?
searchHierarchy (bool) – Also search the hierarchy of the selected objects?
selectionOnly (bool) – Only search within the current selection
dag (bool) – filter dag (viewport hierarchy) nodes only?
removeMayaDefaults (bool) – If not searching the selection will remove default Maya objects like persp and lambert1
transformsOnly (bool) – filter out the shape nodes, usually True
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- removeNamespaceFromObj(objName, uuid=None, renameShape=True, message=True)¶
Removes the namespace from an object by renaming it. Will leave the namespace in the scene.
Remove Example:
objName: “chair:pCube1” result: “pCube1”
Multiple namespaces will also be removed
objName: “scene1:chair:pCube1” result: “pCube1”
- Parameters:
objName (str) – The current name of the object or node, can be long or unique names
uuid (str) – Optional unique hash identifier in case of long name issues while renaming hierarchies or re-parenting
renameShape (bool) – Also rename the shape node if a transform or joint?
message (bool) – Report the message to the user?
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- removeNamespaceFromObjList(objNameList, renameShape=True, message=True)¶
Safe removes the namespace from an object by renaming it with UUIDs. Will leave the namespace in the scene.
Remove Example, for each item in list:
objName: “chair:pCube1” result: “pCube1”
Multiple namespaces will also be removed, for each item in list
objName: “scene1:chair:pCube1” result: “pCube1”
- Parameters:
- Return newNameList:
The new names of the objects now potentially renamed
- Rtype newNameList:
list
- emptyAndDeleteNamespace(namespaceName, renameShape=True, message=True)¶
Given a namespace name, remove it from the scene renaming all associated objects/nodes:
Remove Example:
objName: “chair:pCube1” result: “pCube1” deletedNamespace: “chair”
Namespace may have namespace children and may not be removed in all cases
- Parameters:
- Return namespaceRemoved:
True if the namespace was successfully removed
- Rtype namespaceRemoved:
bool
- deleteSelectedNamespace(renameShape=True, message=True)¶
From the first selected object, remove the namespace from the scene. Will affect all associated objects.
Remove Example:
selectedObjs[0]: “chair:pCube1” result: “pCube1” deletedNamespace: “chair”
- deleteNamespaces(objs, renameShape=True, message=True)¶
Deletes namespaces
- getNamespacesFromList(nodeList)¶
Gets the namespaces from a node list
- Parameters:
nodeList (str) – list of maya node names, can be long or short
- Return namespaceList:
A list of Maya namespacesFound
- Rtype namespaceList:
list
- removeNamespaceFaceAssign(objFaces)¶
special case for namespaces in objectFace assigns as they may have a “:” colon:
NewNamespace1:pCube1.f[1:5] becomes pCube1.f[1:5]
- Return faceAssign:
a maya obj/face assign, no namespace removed “pCube1.f[1:5]”
- Rtype faceAssign:
- removeNamespaceShortName(nodeName, checkFaceAssign=False)¶
Removes a Maya namespace “name:” from a shortname string
NOTE: This does not remove the actual namespace in Maya only the from the string name
- removeNamespaceLongnames(nodeLongName, checkFaceAssign=False, checkShortNames=False)¶
Removes a Maya namespace “name:” from a longname string
NOTE: This does not remove the actual namespace in Maya only the from the string name
- Parameters:
- Return nodeLongName:
a maya long name with “|” in the name, now with no namespaces
- Rtype nodeLongName:
str
- removeNamespaceShortNameList(nodeShortNameList, checkFaceAssign=False)¶
Removes a Maya namespace “name:” from a shortname list
NOTE: This does not remove the actual namespace in Maya only the from the string names
- Parameters:
nodeShortNameList (list) – list of maya shortname node names
checkFaceAssign (bool) – this is True if the node is a obj/face assign eg “NewNamespace1:pCube1.f[1:5]”
- Return nodeShortNameList:
the list now with no namespaces
- Rtype nodeShortNameList:
list
- removeNamespaceLongnamesList(nodeLongNameList, checkFaceAssign=False, checkShortNames=False)¶
Removes a Maya namespace “name:” from a longname list
NOTE: This does not remove the actual namespace in Maya only the from the string names
- Parameters:
- Return nodeLongNameList:
list of Maya longname objects with “|” in the name, now with namespaces removed
- Rtype nodeLongNameList:
list
Namewildcards¶
Functions for handling wildcard matching of objects in Maya. Wildcards are usually suffix or prefix names
Used in matching controls, proxies and triggers etc Wildcard should be given without a “_” underscore
Author: Andrew Silke
- renameWithUniquePrefix(prefixName, nodeName)¶
Renames the node with a suffix and checks that the suffix is unique
- filterNonMatchingObjs(nodeList, wildcardName)¶
Given a list of nodes return the matching nodes with the wildcard name removed Also return the wildcard objects with successful matches
- Parameters:
objectList –
wildcardName –
- Returns:
- Return type:
- getWildcardObjs(wildcardName, suffix='suffix', underscoreInWildCard=False, reportMessage=False)¶
Returns objects specified by wildcardName suffix string
- Parameters:
wildcardName –
suffix (string) – Can be any of three strings “suffix”, “prefix”, “both”
reportMessage –
- Returns:
- Return type:
- renameWildcardTwoObj(objList, wildcard, reverse=False, suffix='suffix')¶
Renames the first object [0] to the name of the second [1] adding the suffix to the tail of the name if reverse then reverse the named object to be the second [1]
- Parameters:
- Return originalObject:
- Return type:
- Return newRenamedObj:
- Return type:
- renameWildcardTwoObjSelected(wildcard, reverse=False, suffix='suffix')¶
Renames the first selected object to the name of the second now adding the suffix to the tail of the name if reverse then reverse the named object to be the second
- removeWildcardNameObjsList(objList, wildcardName)¶
changes a list so that the wildcard name is taken out of every item
- Parameters:
objList (list) – list of Maya object names
wildcardName (str) – the name of the wildcard to be removed
- Return wildcardRemovedList:
A list of the given objects now with the wildcard removed from each name
- Rtype wildcardRemovedList:
list
Nodemultibase¶
Node base is used as a base class for multiple node type (usually multi-renderer) setups
Designed to be inherited by other classes.
Includes but is not restricted to:
Shaders
Lights
Textures etc
Author: Andrew Silke
- class NodeMultiBase¶
Bases:
object
Main base class that manages node multi setups usually for multi-renderer
- suffix = ''¶
- exists()¶
Tests to see if the node connected to the instance exists
- Return shaderExists:
True if the shader exists in the scene, False if not.
- Rtype shaderExists:
bool
- create(message=True)¶
Should be overridden
- delete()¶
Deletes the main node
Can be overridden if multiple nodes
- setName(newName, uniqueNumberSuffix=True)¶
Renames the node, auto handles suffixing with the shader type and unique names:
shader_01_ARN if not unique becomes shader_02_ARN
- Parameters:
newName (str) – The name to rename the current shader
uniqueNumberSuffix – shader_01_ARN if not unique becomes shader_02_ARN or next unique name
- Return newName:
The new name of the node
- Rtype newName:
str
- rename(name, uniqueNumberSuffix=True)¶
Renames the node, auto handles suffixing with the shader type and unique names:
shader_01_ARN if not unique becomes shader_02_ARN
See also self.setName()
- Parameters:
newName (str) – The name to rename the current shader
uniqueNumberSuffix – shader_01_ARN if not unique becomes shader_02_ARN or next unique name
- Return newName:
The new name of the node
- Rtype newName:
str
- name()¶
Returns the fullpath name of the node if it exists
- Return nodeName:
The name of main node
- Rtype nodeName:
str
- nodeZapi()¶
Returns the name of the main node as a zapi object.
- Returns:
Zapi node object or None if does not exist
- Return type:
zapi.DGNode
- shortName()¶
Returns the short name of the node if it exists
- Return shortName:
The shortened name if a DAG node
- Rtype shortName:
str
- shapeName()¶
Returns the shape node name (str) of the current node, will return “” if it doesn’t exist.
Is not used by DG nodes and will return None.
- Return shapeNodeName:
the name of the lights shape node, returns “” if doesn’t exist
- Rtype shapeNodeName:
str
- renderer()¶
Returns the current renderer as a string.
Should be overridden. If Unknown returns “”.
- Return renderer:
“Arnold”, “Maya” “Redshift” etc.
- Rtype renderer:
str
Objcolor¶
Various functions for setting, retrieving and offsetting object colors, usually control curves for animation/rigging
This file handles the coloring of objects in Maya, most commonly for animator NURBS Controls also the wireframes shape node or NURBS curves. Transform nodes can be colored though this script affects shape nodes as a default. Colors default to linear as per the Maya’s viewport. While using a UI or coming from a program like photoshop colors may be switched to srgb Colors are not shader related.
Colors can be two types, Index (both numbers or strings), or RGB/HSV (color values) RGB is in 0-1 range (0.5, 0.5, 0.5) defaults to linear color space HSV is in 0-360 for hue, 0-1 for values and saturation (180.0, 0.5, 0.5) defaults to linear color space
Author: Andrew Silke
- convertColorMayaStringToInt(colorString)¶
Given a color nice name as string, return the Maya index number. 0 -30 ish Names are at the top of this file as global variable MAYA_COLOR_NICENAMES (list)
- Parameters:
colorString (str) – Color as nice name
- Return colorIndex:
Maya’s color as int (number)
- convertColorMayaIntToRGB(colorIndex, linear=True)¶
Given a Maya Color Index Number return the RGB value
- convertColorMayaStringToRGB(colorString, linear=True)¶
Given a Maya Color string (nice name) return the RGB value
- getRgbColor(shape, hsv=False, linear=True, limitDecimalPlaces=False)¶
Returns the color of a shape node in rgb or hsv Nodes are usually shapes, can be transforms Can return rgb or hsv values, defaults rgb. If RGB mode isn’t on interprets the Maya Index color as RGB rgb = [.5, .5, .5] hsv = [180, .5, .5] Will return an empty list [] if .overrideRGBColors is off
- Parameters:
shape (str) – the name of the node, usually a shape node, should be long names
hsv (bool) – return the hue saturation value values rather than rgb which is the default
linear (bool) – If true return the color in linear space, matches the viewport
limitDecimalPlaces (bool) – If true limits the decimal places to max of 3 ie .098
- Return color:
a list either hsv or rgb [float, float, float]
- Return type:
list
- getHsvColor(shape, linear=True)¶
Returns the color of the node if the attribute on the Maya node .overrideRGBColors is on Nodes are usually shapes, can be transforms Returns hsv values hsv = [180, .5, .5] Will return an empty list [] if .overrideRGBColors is off
- getIndexColor(shape)¶
Returns the shape’s Index color value, blue if not enabled, None if rgb is on
- Parameters:
shape (str) – name of the shape node
- Return mayaIndexColorInt:
the color as a Maya number, if -1 the number is not applicable as is in rgb mode
- Rtype mayaIndexColorInt:
int
- setColorShapeRgb(node, rgb, linear=True)¶
Colors a shape node with rgb values Override color in RGB values from Maya 2016+ Switches override to on and to rgb colors
- setColorShapeHsv(shape, hsv, linear=True)¶
Colors a shape node with hsv values
- Parameters:
shape (str) – The name of a single shape node
hsv (list) – tuple of hsv values eg (180, .5, .5)
- setColorShapeIndex(shape, mayaColor)¶
Sets the color on a shape node in Index Maya Colors
- setColorShapeIndexToRgb(shape, mayaColor, linear=True)¶
Given the color as an index (int) or Maya nice name (str) set the color of the shape in rgb mode
- Parameters:
shape (str) – Maya node, usually shape, can be transform node.
mayaColor (str/int/float) – the color can be a string (nicename) or int/float
- setColorListRgb(nodeList, rgb, colorShapes=True, displayMessage=True, linear=True)¶
sets the color of all object list’s shape nodes to rgb color
- Parameters:
nodeList (list) – list of Maya objects
rgb (list) – Red Green Blue, tuple of three numbers, float values 0-1
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
displayMessage (bool) – display the message to the user?
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- setColorListHsv(nodeList, hsv, colorShapes=True, displayMessage=True, linear=True)¶
Sets the color for a list of objects in hsv values. 3 tuple of 0-1 floats
- Parameters:
nodeList (list) – List of Maya Objects
hsv (list) – Hue Saturation Value, tuple of floats hue is 0-360 sat and value is 0-1
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
displayMessage (bool) – Displays the success message
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- setColorListIndex(nodeList, mayaColor, colorShapes=True, displayMessage=True)¶
Sets the color of shape nodes, given an object list Color can be Maya Index (int) or Maya Nice Name (str)
- setColorSelectedRgb(rgb, colorShapes=True, displayMessage=True, linear=True)¶
Sets the selected object’s shape nodes to be a color in rgb
- Parameters:
rgb (list) – Red Green Blue, tuple of three numbers, float values 0-1
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
displayMessage (bool) – If true display the message to the user
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- setColorSelectedHsv(hsv, displayMessage=True, linear=True)¶
Sets the selected object’s shape nodes to be the rgb color
- setColorSelectedIndex(mayaColor, displayMessage=True)¶
Sets the selected object’s shape nodes to be the Maya Index (int) color, or the nice name (str) color
- convertShapeColorIndexToRGB(shape, linear=True)¶
Given a shape node, and assuming that it’s in index color mode (.overrideRGBColors = 0) find the color and set the object to that rgb color
- convertObjIndexToRGB(mayaObj, linear=True)¶
Find if any shapes of the object are in index color and convert all shape nodes to RGB Given an object, (joint/transform etc)
- convertListIndexToRGB(mayaObjList, linear=True)¶
Find if any list of objects are in index color and convert all shape nodes to RGB Given an object, (joint/transform etc)
- offsetObjHsv(mayaNode, offset, colorShapes=True, hsvType='hue', displayMessage=True, linear=True)¶
Recolors shape nodes related to a Maya object in RGB values Offsets the hue by the offset amount (0-360) Can go past 360 or less than 0 Saturation and Value range is 0-1
- Parameters:
mayaObj (str) – The Maya object
offset (float) – the offset value to offset the color, 0-1 or if hue is 0-360
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
hsvType (str) – the type to offset, “hue”, “saturation” or “value”
displayMessage (bool) – If true display the message to the user
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- offsetListHsv(nodeList, offset, colorShapes=True, hsvType='hue', displayMessage=True, linear=True)¶
Recolors the overrideRGBColors for all shape nodes in an object list Offsets the hue by the offset amount (0-360) Can go past 360 or less than 0
- Parameters:
nodeList (list) – list of obj names, usually transforms/joints
offset (float) – How much to offset the hue component, can go past 360 or less than 0. 0-360 color wheel
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
hsvType (str) – the type to offset, “hue”, “saturation” or “value”
displayMessage (bool) – If true display the message to the user
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- offsetOutlinerColorHsv(node, offset, hsvType='hue', displayMessage=True)¶
Offsets a Maya nodes affecting the outliner color by hue or, saturation, or value
Hue is 0-360, saturation and value are 0-1 ranges (srgbFloat)
- Parameters:
node (str) – A maya node
offset (float) – the offset value to offset the color, 0-1 or if hue is 0-360
hsvType (str) – the type to offset, “hue”, “saturation” or “value”
displayMessage (bool) – If true display the message to the user
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- offsetOutlinerColorListHsv(nodeList, offset, hsvType='hue', displayMessage=True)¶
Offsets a list of Maya nodes affecting the outliner colors by hue or, saturation, or value
Hue is 0-360, saturation and value are 0-1 ranges
- Parameters:
nodeList (list(str)) – A list of Maya node names
offset (float) – the offset value to offset the color, 0-1 or if hue is 0-360
hsvType (str) – the type to offset, “hue”, “saturation” or “value”
displayMessage (bool) – If true display the message to the user
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- convertHsvOffsetTuple(offsetTuple)¶
Receives a hsv offset as a tuple and converts to a single float and string Offsets the hue by the offset amount (0-360), value and saturation are 0-1
Hue is 0-360, saturation and value are 0-1 ranges
- Parameters:
offsetTuple (tuple) – The hsv offset as a tuple eg (45.1, 0.0, 0.0)
hsvType – hsv type to modify, can be “hue”, “saturation” or “value”
- Return offset:
The offset now as a single float
- Rtype offset:
float
- Rtype hsvType:
str
- offsetSelectedHsv(offset, hsvType='hue', linear=True, message=True)¶
Recolors the overrideRGBColors for shape nodes under selected objects (usually jnts/transforms) Offsets the hue by the offset amount (0-360), value and saturation are 0-1 Can go past 360 or less than 0
- Parameters:
offset (float) – How much to offset the hue component, 0-1 or neg 360-360 for hue
hsvType (str) – hsv type to modify, can be “hue”, “saturation” or “value”
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
message (bool) – report the message to the user?
- recordedObjColor(RECORDCOLORBOBJS)¶
This function is for UIs where it’s handy to keep track of objects after they’re deselected This is because it’s hard/impossible to see curves while they’re being adjusted uses the global variable RECORDCOLORBOBJS, which must be set and returned when the script is run.
- Parameters:
RECORDCOLORBOBJS (list) – global list of objects used so objects can be changes without selection
- Return RECORDCOLORBOBJS:
global list of objects used so objects can be changes without selection
- Rtype RECORDCOLORBOBJS:
list
- getColorList(objList, hsv=False, linear=False, limitDecimalPlaces=False)¶
From an object list returns each first shape node’s color as either:
hsv or rgb linear or srgb
- Parameters:
- Return colorList:
A list of colors
- Rtype colorList:
list(tuple(float))
- getColorListSelection(hsv=False, linear=False, limitDecimalPlaces=False)¶
From a selection return each first shape node’s color as either:
hsv or rgb linear or srgb
- getDictOfRGBColors(objectList, linear=True)¶
Creates a dictionary of given objects with the color of each object’s first shape node
- Parameters:
objectList (list) – list of Maya objects
linear (bool) – If true the rgb color is in linear space, matching the viewport, else convert it
- Return objRGBDict:
The obj[color] dict, colors are always in rgb
- Rtype objRGBDict:
dict
- getDictOfRGBColorsSel(fullPath=False, linear=True)¶
Creates a dictionary of selected objects with the color of each object’s first shape node
- setDictOfRGBColors(dictObjRGB, linear=True, displayMessage=False)¶
Reads a dictionary and sets colors for all shape nodes of the given Maya objects
- setDictOfRGBColorsExistCheck(dictObjRGB, linear=True, displayMessage=False)¶
Reads a dictionary and sets colors for all shape nodes of the given Maya objects This function checks if obj exists as they may not if the rig is dynamic
- resetOverrideObjColor(node)¶
Resets the color of a node to Maya default, does not reset the rgb color
- Parameters:
node (str) – Maya node name, should be a dag object
- resetOverrideObjColorList(nodeList, colorShapes=True)¶
Resets the color of a node list to Maya default, does not reset the rgb color
- resetOverrideObjColorSelection(colorShapes=True)¶
Resets the color of the current selection to Maya default, does not reset the rgb color
TODO should fiter objects as some may not be supported
- Parameters:
colorShapes (bool) – if True set the shapeNodes, otherwise set the exact list, often transforms
- compareColorsTolerance(firstColor, secondColor, tolerance)¶
Compares two colors usually rgb floats, but could be other types within a tolerance level
Colors often aren’t precise especially when converting back n forth between linear, srgb or rgb and hsv
Tolerance is the margin for error.
- objsByColor(nodeList, color, tolerance=0.05, queryShapes=True)¶
Returns objects by shape color, given a filtered list
Will match by finding the rgbColor of the first shape node of the transform, if color is a match it will return
Tolerance is the margin for error. Colors often aren’t precise especially when converting back n forth between linear, srgb or rgb and hsv
- Parameters:
nodeList (list(str)) – list of objects (transforms), usually filtered by curve, but can be other types
color (tuple(float)) – The color to match to the obj list
tolerance (float) – The range in which the colors can vary
queryShapes (bool) – Will query the first shape node for the matching color value
- Return coloredTransforms:
Transform objs where the first shape matches the color
- Rtype coloredTransforms:
list(str)
- selectObjsByColor(nodeList, color, queryShapes=True, message=True, selectObjs=True)¶
Selects objects by shape color, given a filtered list
- Parameters:
nodeList (list(str)) – list of objects (transforms), usually filtered, ready to find any color matches
color (tuple(float)) – The color to match to the obj list
queryShapes (bool) – Will query the first shape node for the matching color value
selectObjs (bool) – If False will just return the objects and not select them
message (bool) – Report the message to the user?
- setOutlinerColor(node, rgb, incomingIsLinear=False)¶
Colors the Outliner color for a node
- setOutlinerColorList(nodeList, rgb, incomingIsLinear=False)¶
Colors the outliner color for a nodeList
- setOutlinerColorSelection(rgb, incomingIsLinear=False)¶
Colors the Outliner color for the current selection
- Parameters:
rgb (set/list) – set/list of rgb values eg (0.5, 0.5, 0.5), if srgb color then set linear to be False
incomingIsLinear (bool) – Set to True if the incoming color is linear. Outliner colors are in SRCB only
- getOutlinerColors(node, returnLinear=False)¶
Gets the outliner color of a node
- Parameters:
node (str) – Maya node name, should be a dag object
- Return color:
The color in srgb float, if returnLinear is on then will be in linear float
- Rtype color:
list(float)
- resetOutlinerColor(node)¶
Resets the Outliner color of a node to Maya default
- Parameters:
node (str) – Maya node name, should be a dag object
- resetOutlinerColorList(nodeList)¶
Resets the OUtliner color of a node list to Maya default
- Parameters:
nodeList (list(str)) – Maya node names, should be dag objects
- resetOutlinerColorSelection()¶
Resets the Outliner color of the current selection to Maya default
TODO should fiter objects as some may not be supported
- selectObjsByOutlinerColor(objList, matchColor, tolerance=0.05, incomingLinear=False, selectObjs=True)¶
Matches objects by Outliner colour. Colour is in srgb float. If passing linear in use incomingLinear=True.
- Parameters:
objList (list(str)) – A Maya object list of nodes
matchColor (list(float)) – The color to match to the obj list
tolerance (float) – The range in which the colors can vary
incomingLinear (bool) – If the incoming color is in linear float color, set this to True, otherwise leave as False.
selectObjs (bool) – Mark as True if you want to select the objects
- Returns:
If the incoming matchColor is in linear space, set this to True
- Return type:
Objhandling¶
functions for handling objects in Maya.
Example use:
from zoo.libs.maya.cmds.objutils import objhandling
objhandling.uninstanceSelected()
- getAllParents(obj, long=True)¶
Returns all parents of the current obj. Long will return long names
- getRootObjectsFromList(objsLongList)¶
Returns only the bottom hierarchy objects (roots) in an object list.
Compares longNames and filters by the start of each string o get the lowest unique name.
e.g. |group1 will filter out |group1|mesh1 and |group1|mesh1|locator2.
- Parameters:
objsLongList (list) – list of maya object names, as long (full) names with “|”
- Returns:
only the bottom objects of the hierarchy, no children included.
- Return type:
list[str]
- getRootObjectsFromSelection()¶
Returns only the bottom hierarchy objects in a selection, Compares longNames and filters byt the start.
e.g. |group1 will filter out |group1|mesh1 and |group1|mesh1|locator2
- Return rootObjs:
only the bottom objects of the hierarchy, no children included
- Rtype rootObjs:
list
- getListTransforms(mayaShapeList, longName=True)¶
From a list of Maya shape nodes return their transforms
- Parameters:
mayaShapeList (list) – list of maya shape node names
- Return transformList:
list of transform names related to the node list
- Rtype transformList:
list
- getInstances()¶
Returns all instanced nodes in a scene
TODO: doesn’t support transforms only shape nodes.
- Returns:
all instance names in a scene, will be shape nodes
- Type:
list(str)
- isInstancedTransform(transformNode)¶
Returns if a transform node is instanced? Must be a transform node.
- Parameters:
transformNode – A maya transform node, will check the first shape node to see if it’s instanced.
- Return isInstanced:
Is the object an instance or not?
- Rtype isInstanced:
bool
- isInstancedShape(shape)¶
- isInstanced(obj)¶
Returns if a transform or shape node is instanced.
- rootInstance(obj)¶
Find if an object is an instance and if so, walk up the hierarchy and return the top instance object.
Returns “” if no objects are instances.
- Parameters:
obj (str) – A Maya DAG object
- Return rootInstanceObj:
The top most parent (root) object that is an instance from the given object.
- Rtype rootInstanceObj:
str
- uninstanceObj(obj)¶
Uninstances a single maya transform node (and shapes contained) by duplicating and deleting the original. Connections are maintained. Accepts transforms only and newly created objects are returned.
This function is similar to the mel that works on selection:
mel.eval(‘convertInstanceToObject;’)
The mel also duplicates geo, but badly renames new transforms, doesn’t return names, or support connections.
- Parameters:
obj (str) – A name of a transform node
- Return obj:
The newly created object
- Rtype obj:
str
- uninstanceObjs(objs)¶
Uninstances an obj list by duplicating and deleting the original objects. New names are returned. Connections are maintained. Accepts transforms only and newly created objects are returned.
This function is similar to the mel that works on selection:
mel.eval(‘convertInstanceToObject;’)
The mel also duplicates geo, but badly renames new transforms, doesn’t return names, or support connections.
- Parameters:
objs (list(str)) – A list of transform node names.
- Return objs:
A list of transform node names, now updated with the non instanced transforms.
- Rtype objs:
list(str)
- uninstanceSelected(uninstanceRoot=True, message=True)¶
Uninstances the selected transform and shape nodes by duplicating and deleting the original objects. Connections are maintained. Accepts transforms only and newly created objects are returned.
If uninstanceRoot is True then will uninstance the top parent that is instanced in the hierarchy of the selection.
This function improves on the mel:
mel.eval(‘convertInstanceToObject;’)
The mel also duplicates geo, but badly renames new transforms, doesn’t return names, or support connections.
- uninstanceAll(message=True)¶
Uninstances all objects in a scene. Works by duplicating the instance and deletes it while maintaining names.
This function is similar to the mel that works on selection:
mel.eval(‘convertInstanceToObject;’)
The mel also duplicates geo, but can badly rename new transform nodes, doesn’t return names, or support connections.
- Return parentInstanceList:
The Instanced Parents in the scene that were uninstanced
- Rtype parentInstanceList:
list
- cleanConnections(objName, keyframes=True)¶
Cleans an object of all connections, keys/connections constraints currently only works for keys
- getTypeTransformsHierarchy(objList, nodeType='mesh')¶
Returns the nodes of a certain type under the current hierarchy (maya list)
- Parameters:
objList (list) – list of maya objects
nodeType (str) – the type of node to filter
- Returns:
a list of maya node names, the nodes now filtered
- Return type:
list
- selectTypeUnderHierarchy(type='mesh')¶
Select objects of a given type as a child of the selected objects
- Parameters:
type –
- Returns:
- Return type:
- returnSelectLists(selectFlag='all', long=False)¶
Based on a selectFlag will return nodes of three types:
#. "all" : All in scene #. "selected" : only selected #. "hierarchy" : search selected hierarchy
Todo
Selected should include shape nodes
- selectHierarchyFilterType(nodeType='transform')¶
Filters the select hierarchy command by a node type, usually transform type so it doesn’t select the shape nodes
- Parameters:
nodeType (str) – type of object or nde to be filtered in the selection
- Returns:
the objs to be selected
- Return type:
list
- findParentObjList(objectList)¶
Find the parent from list world is a none type, check for it and add as None * no idea what this does anymore, leaving it as hotkeys may reference, old code
- Parameters:
objectList –
- Returns:
- Return type:
- getAllTansformsInWorld(long=True)¶
Returns all transforms in world, are not parented to anything
- Return rootTransforms:
transform node names that are in world
- Rtype rootTransforms:
list
- getTheWorldParentOfObj(objLongName)¶
Returns the bottom most object of a hierarchy given the object as a child. (assembly) Will return the same object if in world
- Parameters:
objLongName (str) – maya object dag node name, must be long name
- Return worldParent:
the
- Rtype worldParent:
- getTheWorldParentOfObjList(objLongNameList)¶
- getAllMeshTransformsInScene(longName=True)¶
Returns all meshes (poly geo) in a scene as a list
- Parameters:
longName (bool) – names will be in long format
- Return allMeshTransforms:
list of all the mesh transform names in the scene
- Rtype allMeshTransforms:
list
- getTransformListFromShapeNodes(shapeList, fullPath=True)¶
Given a lit of shapes find their parents (transforms)
- Parameters:
shapeList (list) – list of shape nodes by name
fullPath (bool) – do you want to return the fullpath name?
- Return transformList:
a list of transform names
- Rtype transformList:
list
- getParentHierarchyOfObjList(sceneRootsLongName)¶
Returns the parentHierarchy of an object list (long names) will filter out world or empty “” returns.
- Parameters:
sceneRootsLongName (list) – a list of long names in Maya [“|group1|object”, “|group1|object2”]
- Returns:
the parent hierarchy as a long name list.
- Return type:
list
- removePrefixLists(parentHierarchy, objectLongName)¶
From a single object and single parent hierarchy remove it if there’s a prefix match
- removeParentHierarchyObj(objectLongName, parentHierarchyList)¶
For an objectLongName remove possible parent hierarchies from the name in parentHierarchyList
- removeRootParentListObj(objectLongName, sceneRootsLongName)¶
For an objectLongName remove possible parent hierarchies of sceneRootsLongName list
- Parameters:
objectLongName (str) – the maya object long name
- removeRootParentListObjList(objectListLongName, sceneRootsLongName)¶
Function that is useful for exporting alembic selected which export from the selected top root node when exported recorded objects will have incorrect long names so this will fix that and remove the parent hierarchies from the longnames.
- Parameters:
- Returns:
the fixed names with roots hierarchies eliminated
- Return type:
list
- zeroFrozenTransform(obj, freeze=True, buildLocator=True, parentToWorld=True)¶
Resets a frozen object to be zero in the world, will move and rotate back to world zero, and remove the local rotate/scale pivot offset
Can build a locator to mark the original position/rotation so the object can be snapped back later.
- removeFreezeTransform(obj, message=True)¶
Removes the freeze local pivot info from an object while maintaining it’s position.
- removeFreezeTransformList(transformNodes, message=True)¶
Removes the freeze local pivot info from an object list while maintaining their positions.
- removeFreezeTransformSelected(message=True)¶
Removes the freeze local pivot info from selected transforms while maintaining their positions.
- Parameters:
message (bool) – Report the messages to the user?
- Return success:
True if the freeze was successfully removed on all objects. False if some failed.
- Rtype success:
bool
- checkSmallNumbers(number, toleranceNumber=0.001)¶
Tests if a number is smaller than the toleranceNumber. True if so.
- checkCloseToNumber(number, targetNumber, toleranceRange=0.001)¶
- checkForFrozenGeometry(obj)¶
Checks to see if the geometry has been frozen, ie it’s rotate pivot is not zeroed.
Uses a tolerance threshold.
- Parameters:
obj (str) – A maya object name
- Return frozen:
True if the object was frozen
- Rtype frozen:
bool
- checkForMatchVector(obj, targetVector, attribute='rotatePivot', toleranceRange=0.001)¶
Checks to see if an double3 attribute matches a vector (list with three entries).
Uses a tolerance threshold.
- checkFrozenTransformOffsetList(transformList, message=True)¶
Checks if an object list’s transforms have been frozen, ie the Local Rotate Pivot attribute is not zeroed.
Returns any objects that are frozen as an object list.
- checkFrozenTransformOffsetSelected(extraObjects=[], message=True)¶
Checks if an object list’s transforms have been frozen, ie the Local Rotate Pivot attribute is not zeroed.
Returns any objects that are frozen as an object list.
- Parameters:
message (bool) – Report messages to the user?
- Return frozenObjs:
A list of objects that have been frozen, ie their rotatePivot attribute is not zeroed.
- Rtype frozenObjs:
list(str)
- checkRotatePivMatchSelection(extraObjects=[], message=True)¶
This function compares the first selected rotate pivot attribute with all others.
It checks if the pivots match and returns True if they match and False if they don’t match.
- Parameters:
extraObjects –
message –
- Returns:
- Return type:
- matchPivotSpace(objChange, target, message=True)¶
This function will match an object to the other object’s rotate and scale pivot space.
Useful in replace shapes where the shape nodes must match after being frozen.
The changeObj will change pivot info but will not move in 3d space.
The change object must be able to be frozen on translate and rotate, no connections.
- matchPivotSpaceSelection()¶
This function will match the first sel object to the second sel object’s rotate and scale pivot space.
Useful in Replace Shapes where the shape nodes must match in pivot space after being frozen.
The changeObj will change pivot info but will not move in 3d space.
The change object must be able to be frozen on translate and rotate, no connections.
Randomizeobjects¶
- offsetAttrValue(obj, attr, offsetValue, min, max, current=0.0, absolute=False)¶
Offsets an attribute by the offset value which is somewhere between 0.0-1.0
Used by the scale attribute when the scale random amount needs to be uniform for all attributes
- randomizeAttr(obj, attr, min, max, current=0.0, absolute=False)¶
Randomizes an attribute in either absolute or relative mode:
min = 0.0 max = 10.0 current = 20.0 absolute = False Result is 23.556 (random between 20.0 and 30.0)
Must be float attributes
- Parameters:
obj (str) – The maya object string name
attr (str) – The name of the attribute to randomize
min (float) – The minimum range value
max (float) – The maximum range value
current (float) – The current value if absolute is False (relative mode)
absolute (bool) – If True mode is absolute, if False relative mode
- randomizeAttrList(obj, attrList, min, max, uniformScale=True, absolute=False)¶
Randomizes a list of attributes with both relative/absolute and uniform modes.
- Parameters:
obj (str) – The maya object string name
attrList (list(str)) – A list of Maya attribute names, currently must be floats.
min (float) – The minimum range value
max (float) – The maximum range value
uniformScale (bool) – If True, will scale the scale attributes by the same amount for each attribute
absolute (bool) – If True mode is absolute, if False relative mode
- randomizeRotObj(obj, randRotate=False, randTranslate=False, randScale=False, randOther=False, absolute=False, translateMinMax=((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), rotateMinMax=((0.0, 0.0, 0.0), (45.0, 45.0, 45.0)), scaleMinMax=((0.0, 0.0, 0.0), (5.0, 5.0, 5.0)), otherMinMax=(0.0, 1.0), otherAttrName='', uniformScale=True)¶
Randomizes an object with options for rotate, translate, scale and other.
min = 0.0 max = 10.0 current = 20.0 absolute = False Result is 23.556 (random between 20.0 and 30.0)
- Parameters:
obj (str) – The maya object string name
randRotate (bool) – Randomize the rotation?
randTranslate (bool) – Randomize the translation?
randScale (bool) – Randomize the scale?
randOther (bool) – Randomize a user inputed attribute?
translateMinMax (tuple(tuple)) – The min/max translate values
rotateMinMax (tuple(tuple)) – The min/max rotation values
scaleMinMax (tuple(tuple)) – The min/max scale values
otherMinMax (tuple) – The min/max other values
otherAttrName (str) – the name of the user inputed attribute if there is one
uniformScale (bool) – If True, will scale the scale attributes by the same amount for each axis
- randomizeRotObjList(objList, randRotate=False, randTranslate=False, randScale=False, randOther=False, translateMinMax=((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), rotateMinMax=((0.0, 0.0, 0.0), (45.0, 45.0, 45.0)), scaleMinMax=((0.0, 0.0, 0.0), (5.0, 5.0, 5.0)), otherMinMax=(0.0, 1.0), otherAttrName='', absolute=False, uniformScale=True, message=True)¶
Randomizes an object list with options for rotate, translate, scale and other.
min = 0.0 max = 10.0 current = 20.0 absolute = False Result is 23.556 (random between 20.0 and 30.0)
- Parameters:
objList (list(str)) – A list of Maya object string names
randRotate (bool) – Randomize the rotation?
randTranslate (bool) – Randomize the translation?
randScale (bool) – Randomize the scale?
randOther (bool) – Randomize a user inputed attribute?
translateMinMax (tuple(tuple)) – The min/max translate values
rotateMinMax (tuple(tuple)) – The min/max rotation values
scaleMinMax (tuple(tuple)) – The min/max scale values
otherMinMax (tuple) – The min/max other values
otherAttrName (str) – the name of the user inputed attribute if there is one
uniformScale (bool) – If True, will scale the scale attributes by the same amount for each axis
message (bool) – Report a message to the user?
- randomObjSelection(randRotate=False, randTranslate=False, randScale=False, randOther=False, translateMinMax=((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), rotateMinMax=((0.0, 0.0, 0.0), (45.0, 45.0, 45.0)), scaleMinMax=((0.0, 0.0, 0.0), (5.0, 5.0, 5.0)), otherMinMax=(0.0, 1.0), otherAttrName='', absolute=False, uniformScale=True, message=True)¶
Randomizes any selected objects with options for rotate, translate, scale and other.
min = 0.0 max = 10.0 current = 20.0 absolute = False Result is 23.556 (random between 20.0 and 30.0)
- Parameters:
randRotate (bool) – Randomize the rotation?
randTranslate (bool) – Randomize the translation?
randScale (bool) – Randomize the scale?
randOther (bool) – Randomize a user inputed attribute?
translateMinMax (tuple(tuple)) – The min/max translate values
rotateMinMax (tuple(tuple)) – The min/max rotation values
scaleMinMax (tuple(tuple)) – The min/max scale values
otherMinMax (tuple) – The min/max other values
otherAttrName (str) – the name of the user inputed attribute if there is one
uniformScale (bool) – If True, will scale the scale attributes by the same amount for each axis
message (bool) – Report a message to the user?
- randomAttrChannelSelection(minMax, absolute=False, uniformScale=False, message=True)¶
Scaleutils¶
from zoo.libs.maya.cmds.objutils import scaleutils scaleutils.scaleToSceneConversion(1.0, fromUnit=”cm”)
- sceneUnits()¶
Returns the current scene unit scale ie “mm”, “cm”, “m”, “in”, “ft”, “yd”
- Returns:
The current scene units of the scene ie “mm”, “cm”, “m”, “in”, “ft”, “yd”
- Return type:
- setSceneUnits(units='cm')¶
Sets the current scene unit scale ie “mm”, “cm”, “m”, “in”, “ft”, “yd”
- Parameters:
units (str) – the units as a string ie “mm”, “cm”, “m”, “in”, “ft”, “yd”
- sceneUnitsContext(units='cm')¶
Context manager for temporarily setting the scene units.
- Parameters:
units (str) – the units as a string i.e. “mm”, “cm”, “m”, “in”, “ft”, “yd”
- stringExtractNumber(s)¶
Converts 10.1cm string to 10.0 float
- scaleUnitToSceneConversion(value, fromUnit='cm')¶
Returns the scale from a unit scale to the current scene units
- scaleSceneToUnitConversion(value, toUnit='cm')¶
Returns the scale from the scene unit size to a given unit size
- scaleUnitToUnitConversion(value, fromUnit='cm', toUnit='cm')¶
Returns the scale from a unit scale to another unit scale
- getRawBoundingBox(obj, worldSpace=True)¶
Returns the raw limits in Maya units (cms) of the outer limits of the bounding box in world
- Parameters:
obj (str) – The maya object to measure
- Return objBoundingBoxRaw:
raw world limits of the bounding box Maya units (cms) [-x, -y, -z, +x, +y, +z]
- Rtype objBoundingBoxRaw:
list
- scaleBoundingBox(boundingBox, scaleXYZ)¶
Scales a bounding box by a xyz scale amount
- getBoundingBoxNoChildren(obj, worldSpace=True)¶
Measures the bounding box of a transform with no children. Measures all shape nodes, adds them up to get the total bounding box of the object.
Result is in objectSpace to the object not it’s parent
- Parameters:
obj (str) – The maya object to measure
- Return boundingBox:
raw world limits of the bounding box Maya units (cms) [-x, -y, -z, +x, +y, +z]
- Rtype boundingBox:
- getBoudingBoxNoChildrenLegacy(obj, worldSpace=True)¶
Duplicate a copy of the current object so that it can be measured in isolation, read warning below.
WARNING!! This can be bad as shape node is parented in and out of the object. Useful for controls but not polys. If the shape nodes are heavy will take time to compute.
TODO find a better way of managing this
- getLongestBbEdge(bbHWL)¶
returns the longest edge of a height width and length bounding box
- Parameters:
bbHWL (list) – height width and length of the bounding box in Maya units (cms) [x, y, z]
- Return longestEdge:
the longest edge of a height width length bounding box
- Return type:
- getLongestEdgeObj(obj, worldSpace=True, ignoreChildren=False)¶
Returns the longest edge of the selected object in maya units, will include children in the scale.
WARNING with the flag ignoreChildren!! This can be bad as shape node is parented in and out of the object. Useful for controls but not polys. If the shape nodes are heavy will take time to compute.
- Parameters:
obj (str) – The maya object to measure
- Return longestEdge:
The longest edge of the selected object in maya units
- Rtype longestEdge:
float
- getBoundingBoxHWL(rawBoundingBox)¶
Returns the the height, width and length
- Parameters:
obj (str) – The maya object to measure
- Return bbHWL:
height width and length of the bounding box in Maya units (cms) [x, y, z]
- Rtype bbHWL:
list
- getBoundingBoxMultiple(boundingBoxList)¶
Calculates the total bounding box of multiple bounding boxes.
- Parameters:
boundingBoxList (list(float)) – A bounding box list of 6 floats [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
- Return totalBoundingBox:
Total bounding box list(6 floats)
- Rtype totalBoundingBox:
list(float)
- getBoundingBoxMultipleObjs(objList)¶
Returns the total bounding box raw limits of multiple objects
- Parameters:
objList (list) – list of Maya object names
- Return totalBoundingBoxRaw:
raw world limits of the bounding box Maya units (cms) [-x, -y, -z, +x, +y, +z]
- Rtype totalBoundingBoxRaw:
list
- getRawBoundingBoxMultipleSelObjs(message=True)¶
Returns the total bounding box raw limits of multiple selected objects
- Parameters:
message (bool) – report the message to the user?
- Return totalBoundingBoxRaw:
raw world limits of the bounding box Maya units (cms) [-x, -y, -z, +x, +y, +z]
- Rtype totalBoundingBoxRaw:
list
- getBoundingBoxHWLMultipleSelObjs()¶
Returns the total length width and height for multiple selected objects in Maya
- Return totalBoundingBoxHWL:
The total bounding boxes for multiple object [WidthX HeightY LengthZ]
- Rtype totalBoundingBoxHWL:
list
- getLongestEdgeMultipleSelObjs()¶
From multiple selected objects returns the longest edge of the all object bounding box
- Return longestEdge:
The longest edge (from width X height y and length z), largest number
- Rtype longestEdge:
float
- scaleObjListPivot(transformList, gScale, scalePivot=(0, 0, 0))¶
Receives a uniquely/long named transformList will scale from a pivot by parenting to a temp grp and scaling, then reparenting back to the original parents.
Names should be unique/long
If objects can be pivot centered after scale can use scaleWorldPivotCenterPivot()
- Parameters:
transformList (list) – list of object names in Maya
gScale (float) – the scale amount as a float ie 0.9 (is 90% of the current size)
scalePivot (tuple) – tuple of floats, the scale pivot in world space
- scaleWorldPivotCenterPivot(transformList, gScale, scalePivot=(0, 0, 0))¶
Receives a uniquely/long named transformList will scale from a pivot by world space xform scale.
Note: All objects pivots will be centered after the scale. Avoids parenting, but center pivot isn’t appropriate in many situations
If pivots are an issue use scaleObjListPivot() instead
Names should be unique or long
- Parameters:
transformList (list) – list of object names in Maya
gScale (float) – the scale amount as a float ie 0.9 (is 90% of the current size)
scalePivot (tuple) – tuple of floats, the scale pivot in world space
Selection¶
selection based code
Example use:
from zoo.libs.maya.cmds.objutils import selection
from maya import cmds
selObjs = cmds.ls(selection=True)
faces = selection.numberListToComponent(selObjs[0], numberList, componentType="faces")
Author: Andrew Silke
- selWarning(warningTxt='Please make a selection', message=True, long=False)¶
Basic selection function with warning if nothing is selected
- convertGeometryFaces(nodeList, individualFaces=False)¶
From a list of node string names, return only those objects that are polys, nurbs or polyfaces
- componentByObject(componentList)¶
From a component list, return a nested list with components sorted per object:
[pCube2.e[4], pCylinder1.e[9], pCylinder1.e[2], pCSphere[9]]
Returns:
[[pCube2.e[4]], [pCylinder1.e[9], pCylinder1.e[2]], [pCSphere[9]]]
- Parameters:
componentList (list(str)) – A list of components, can be objects too
- Return componentNestedList:
a list of lists, the first list is by object name and then all components of that name
- Rtype componentNestedList:
list(list(str))
- selectObjectNoComponent(message=True)¶
If in component mode with nothing selected, return to the object mode and return those objects instead.
Returns the potentially updated selection, and if the user is in component mode or not
Used in a lot of UV functions when nothing is selected you still want to operate on the current object.
- Parameters:
message (bool) – Return the messages to the user?
- Return selObjs:
maya selection, could be components or objects.
- Rtype selObjs:
list(str)
- Return componentMode:
True if in component mode eg vertex or edge mode, False if in object mode.
- Rtype componentMode:
bool
- componentFullList(componentSelection)¶
Converts a component selection list into a full list
- Example:
[“pSphere4.e[22:24]”] becomes [“pSphere4.e[22]”, “pSphere4.e[23]”, “pSphere4.e[24]”]
- Parameters:
componentSelection (list(str)) – A selection of Maya components eg [“pSphere4.e[1438:1439]”, “pSphere4.e[23:25]”]
- componentNumberList(componentSelection)¶
Converts a component selection list into number list
Assumes only components are from a single object
- Example:
[“pSphere4.e[22:24]”] becomes [22, 23, 24]
- Parameters:
componentSelection (list(str)) – A selection of Maya components eg [“pSphere4.e[1438:1439]”, “pSphere4.e[23:25]”]
- countComponentsInSelection(componentSelection)¶
Counts the amount of components in a selection, should be filtered to only one component type ie only edges
- Parameters:
componentSelection (list(str)) – A selection of Maya components eg [“pSphere4.e[1438:1439]”, “pSphere4.e[23:25]”]
- Return componentCount:
The exact numbers of components in the selection
- Rtype componentCount:
int
- numberListToComponent(obj, numberList, componentType='uvs')¶
Takes a number list and makes it into a component selection
- Example:
“pSphere”, [22, 23, 24], “edges” becomes [“pSphere.e[22]”, “pSphere.e[23]”, “pSphere.e[24]”]
- componentsToObjectList(componentSelection)¶
From a list of components return only the objects in the selection. Handles long or short names and namespaces
- Example:
[“pSphere.e[22]”, “pSphere.e[23]”, “pCube.e[24]”] becomes [“pSphere”, “pCube”]
- Parameters:
componentSelection (list(str)) – A list of components or objects or both
- Return objectList:
A list of objects now filtered
- Rtype objectList:
list(str)
- componentSelectionFilterType(selectedComponents, selectType)¶
Pass in a selection and will return the single selection list specified by selectType:
selectType can be “faces”, “vertices”, or “edges”
- componentSelectionType(componentSelection)¶
Returns “object”, “vertices”, “edges”, “faces” or “uvs” depending on the first selection type.
Will return None if unknown
- Parameters:
componentSelection (list(str)) – a Maya selection
- Return componentType:
the type of component as the first selection, eg. “vertices”
- Rtype componentType:
str
- componentOrObject(componentSelection)¶
Returns either “object” or “component” or “uv” depending on the first selection type.
Return None if unknown
- Parameters:
componentSelection (list(str)) – a Maya selection
- Return componentType:
“component”, “object” or None
- Rtype componentType:
str
- selectComponentSelectionMode(componentType='vertices')¶
Selects a component mode “vertices”, “edges”, “faces” or “uvs”
- Parameters:
componentType (str) – The component mode to enter “vertices”, “edges”, “faces” or “uvs”
- convertSelection(type='faces')¶
Converts a selection to either edges, faces, vertices, or uvs
- selectType can be:
“faces” “vertices” “edges” “edgeLoop” “edgeRing” “edgePerimeter” “uvs” “uvShell” “uvShellBorder”
- Parameters:
type (str) – The selection to convert to “faces”, “vertices”, “edges”, “edgeRing” etc see function documentation
- invertSelection()¶
- selectHierarchy(nodeType='transform')¶
Filters the select hierarchy command by a node type, usually transform type so it doesn’t select the shape nodes
- Parameters:
nodeType (str) – type of node to be filtered in the selection, usually transform
- Returns:
objsFiltered: the objs selected
- growSelection()¶
Standard maya grow component selection “>” hotkey
- shrinkSelection()¶
Standard maya grow component selection “<” hotkey
- randomSelection(randomPercent)¶
From the current selection objs or components, select random objects given the randomAmount:
50.0 will select 50% of objects in the selection 10.0 will select 10% of the objects in the selection
- Parameters:
randomPercent (float) – A value between 0 and 1. 0.5 selects 50% of objects 0.1 selects 10%
- Return newSelection:
A list of the randomly selected objects
- Rtype newSelection:
list(str)
- selectionPairs(oddEven=False, forceEvenSelection=True, type='transform')¶
Returns selection pairs usually “transforms”
[“objA”, “objB”, “objC”, “objD”]
- oddEven True returns:
[“objA”, “objC”], [“objB”, “objD”]
- oddEven False returns:
[“objA”, “objB”], [“objC”, “objD”]
- Parameters:
- Return twoLists:
Returns two matching object lists based off the selection.
- Rtype twoLists:
tuple(list(str), list(str))
- addSelectionSet(selectSetName, objs)¶
Adds to an existing selection set, or if it doesn’t exist then create
Shapenodes¶
- getTransform(shapeNode)¶
returns the transform node from a shape node name
- Parameters:
shapeNode (str) – maya shape node name
- Return transformNode:
maya transform node name
- Rtype transformNode:
str
- getTransformList(shapeNodeList, eliminateDoubleNames=True)¶
returns a transformList from the shapeNodeList no doubled up names returned by default
- Parameters:
shapeNodeList (list) – list of maya shape node names
- Return transformList:
list of maya transform node names
- Rtype transformList:
list
- transformHasShapeOfType(node, nodeType)¶
Checks to see if the node, or shape nodes of the current node is a match to nodeType ie “nurbsCurve”
- filterShapesInList(objList, nodeTypeList=['nurbsCurve', 'locator', 'mesh', 'nurbsSurface', 'camera', 'light', 'clusterHandle', 'baseLattice', 'lattice', 'softMod', 'deformBend', 'sculpt', 'deformTwist', 'deformWave', 'deformFlare'])¶
Filters a Maya object list leaving only shapes, and those shapes in the filter nodeTypeList
- Parameters:
objList (list) – The Maya Object List
nodeTypeList (list) – Types of nodes to filter from
- Return shapesList:
The filtered shape node list
- Rtype shapesList:
list
- translateShapeCVs(nurbsShape, translateXYZ)¶
Translate a shape node by the xyz amount [float, float, float] without affecting the transform
- Parameters:
nurbsShape (str) – The shape node name
translateXYZ (list) – The scale in x y z [float, float, float]
- scaleShapeCVs(nurbsShape, scaleXYZ)¶
Scales a shape node by the xyz amount [float, float, float] without affecting the transform
- Parameters:
nurbsShape (str) – The shape node name
scaleXYZ (list) – The scale in x y z [float, float, float]
- rotateShapeCVs(nurbsShape, rotateXYZ, relative=True, objectCenterPivot=True)¶
Rotates a shape node by the xyz amount [float, float, float] without affecting the transform
- translateObjListCVs(mayaObjList, translateXYZ)¶
Translates an object list, usually transform nodes of nurbsCurves by the xyz amount [float, float, float] Doesn’t affect the transform scale, scales CVs
- Parameters:
mayaObjList (list) – List of maya object names, will filter the shape nodes from the transforms
translateXYZ (list) – The scale in x y z [float, float, float]
- scaleObjListCVs(mayaObjList, scaleXYZ)¶
Scales an object list, usually transform nodes of nurbsCurves by the xyz amount [float, float, float] Doesn’t affect the transform scale, scales CVs
- Parameters:
mayaObjList (list) – List of maya object names, will filter the shape nodes from the transforms
scaleXYZ (list) – The scale in x y z [float, float, float]
- scaleObjListCVsSelected(scaleXYZ, message=True)¶
Scales the selection (transform nodes of nurbsCurves shapes) by the xyz amount [float, float, float] Doesn’t affect the transform scale, scales CVs
- Parameters:
scaleXYZ (list) – The scale in x y z [float, float, float]
message (bool) – Report the message to the user?
- rotateObjListCVs(mayaObjList, rotateXYZ, relative=True, objectCenterPivot=True)¶
Rotates an object list, usually transform nodes of nurbsCurves by the xyz amount [float, float, float] Doesn’t affect the transform rotation, rotates CVs
- Parameters:
nurbsShape (list) – List of maya object names, will filter the shape nodes from the transforms
rotateXYZ (list) – how to rotate the cvs
relative (bool) – rotate relative to the object space, recommended
objectCenterPivot (bool) – rotate are the the objects center pivot, recommended, will be worls if False
- scaleSelectedObjCVs(scaleXYZ)¶
Scales selected Maya object lists cvs filters the nurbsCurve shapes and scales by the xyz amount [float, float, float] Doesn’t affect the transform scale, scales CVs
- Parameters:
scaleXYZ (list) – The scale in x y z [float, float, float]
- rotateSelectedObjCVs(rotateXYZ, relative=True, objectCenterPivot=True, message=True)¶
Rotates selected Maya object lists cvs filters the nurbsCurve shapes and rotates by the xyz amount [float, float, float] Doesn’t affect the transform scale, scales CVs
- shapeNodeParent(masterObj, sourceObj, replace=False, deleteMaster=True, objSpaceParent=False, renameShapes=True, delShapeType='', ogsReset=True, instance=False)¶
Shape node parents/replaces a single object to another object.
- Parameters:
masterObj (str) – The master object from which the shapes are parented
sourceObj (str) – The target object that the shapes will be parented to
replace (bool) – replace will replace the shape nodes of the sourObj with the nodes of the masterObj
deleteMaster (bool) – Will delete the masterObj, usually True as it’s an empty transform
objSpaceParent (bool) – if True parents in local/object space, if False will parent in world space
renameShapes (bool) – Will rename all existing shape nodes to match the transform name as per Maya
delShapeType (str) – If deleteOriginal True the shape type can be specified eg “nurbsCurve”. “” empty deletes all
ogsReset (bool) – runs cmds.ogs(reset=True) which is a force refresh in Maya 2022.0 as it’s buggy
- Return sourceObj:
The object now with the new shape nodes
- Rtype sourceObj:
str
- shapeNodeParentList(objectList, replace=False, message=False, renameShapes=True, delShapeType='', deleteMaster=True, objSpaceParent=False, instance=False)¶
Shape parents from an objectList, objects must be transform nodes
The parent object is the last obj in objectList and is returned, all other objects are shape parented and removed.
If deleteOriginal then the combine works more like a replace where the last object is over-ridden by the new shapes Otherwise default replace=False works as combine curves
Note 1: This function requires the parent to objects (objectList[:-1]) to have free attrs, ie not locked or connected. See shapeNodeParentLockedAttrs() for version which handles locked/connected attrs, or shapeNodeParentSafe() is useful if the locked/connected attrs are unknown.
- Parameters:
objectList (list) – The object list to be shape parented (should be checked for parent order)
replace (bool) – delete the shape nodes of the last selected object
message (bool) – report the success message to Maya
renameShapes (bool) – Will rename all existing shape nodes to match the transform name as per Maya
delShapeType (str) – If deleteOriginal True the shape type can be specified eg “nurbsCurve”. “” empty deletes all
- Return combinedObjectList:
List of combined objects
- Return type:
list(str)
- shapeNodeParentLockedAttrs(objectList, replace=False, message=False, renameShapes=True, delShapeType='', deleteMaster=True, objSpaceParent=False, instance=False)¶
Shape parents from an objectList, objects must be transform nodes
The parent object is the last obj in objectList and is returned, all other objects are shape parented and removed If deleteOriginal then the combine works more like a replace where the last object is over-ridden by the new shapes Otherwise default replace=False works as combine curves
Note 1: This function should be used if the “parent to” objs have locked attrs or connections or parent issue
Note 2: Will not delete the other objs if they have children
- Parameters:
objectList (list(str)) – A list of Maya transform node string names
replace (bool) – delete the shape nodes of the last selected object
message (bool) – report the success message to Maya
renameShapes (bool) – Will rename all existing shape nodes to match the transform name as per Maya
delShapeType (str) – If deleteOriginal True the shape type can be specified eg “nurbsCurve”. “” empty deletes all
- Return combinedObjectList:
List of combined objects
- Return type:
list(str)
- shapeNodeCombine(objectList, delShapeType='nurbsCurve', select=False, message=True)¶
Combines shape nodes into one object with multiple shape nodes, usually used for combining controls
- Parameters:
- Return combinedObj:
The transform of the combined object
- Rtype combinedObj:
str
- shapeNodeParentSafe(objectList, replace=False, message=False, selectObj=False, delShapeType='', deleteMaster=True, objSpaceParent=False, instance=False)¶
Shape parents from an objectList, objects must be transform nodes
The parent object is the last obj in objectList and is returned, all other objects are shape parented and removed If deleteOriginal then the combine works more like a replace where the last object is over-ridden by the new shapes Otherwise defa