Maya API Test

import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx

sl = OpenMaya.MSelectionList()
OpenMaya.MGlobal.getActiveSelectionList(sl)
itersl = OpenMaya.MItSelectionList(sl, OpenMaya.MFn.kDagNode)

dagPath = OpenMaya.MDagPath()
dagFn = OpenMaya.MFnDagNode()

while (not itersl.isDone()):
    itersl.getDagPath(dagPath)
    try:
        dagPath.extendToShape()  # get shaper node
    except:
        pass
    dagObject = dagPath.node()
    dagFn.setObject(dagObject)
    name = dagFn.name()
    print 'Get the Dag Node Name Is :', name

    itersl.next()

# create MFnMeshVertex
object = OpenMaya.MItMeshVertex(dagPath)
while (not object.isDone()):
    print object.position().x
    object.next()
View Code

http://ewertb.soundlinker.com/api/api.php

https://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/mayaapi.html

https://nccastaff.bournemouth.ac.uk/jmacey/RobTheBloke/www/research/maya/mfnanimcurve.htm

Python PIP升级:

python -m pip install --upgrade pip

Event in Maya Api to capture currentTime / frame change

http://download.autodesk.com/us/maya/2009help/API/class_m_event_message.html#c038e5bbbfc19b2772d1a01220b570c0

    // ...

    // Our callback Id array to 
    // store the Ids of all our callbacks
    // for later removal    
    MCallbackIdArray myCallbackIds;

    // This is where the actual adding callback happens
    // We register our callback to the "timeChanged" event
    MCallbackId callbackId = MEventMessage::addEventCallback("timeChanged",  (MMessage::MBasicFunction) MySampleCmd::userCB);

    // ...

    if(myCallbackIds.length() != 0)
        // Make sure we remove all the callbacks we added
        stat = MEventMessage::removeCallbacks(myCallbackIds);
View Code
class MySampleCmd : public MPxCommand {
public:
                MySampleCmd();
    virtual     ~MySampleCmd();

    // Our callback - implemented as a static method
    static      void userCB(void* clientData);

    MStatus     doIt( const MArgList& );
    MStatus     redoIt();
    MStatus     undoIt();   
    bool        isUndoable() const;
    static      void* creator();

public:

    // Our callback Id array to 
    // store the Ids of all our callbacks
    // for later removal
    MCallbackIdArray myCallbackIds;
};
cmd.h
    // Clearing our callback Id array
    // for housekeeping    
    myCallbackIds.clear();
}

// Destructor
MySampleCmd::~MySampleCmd() {

    // Make sure we remove all the callbacks we added
    // Failing to do so will result in fatal error    
    if(myCallbackIds.length() != 0)

        // Remove the MEventMessage callback
        MEventMessage::removeCallbacks(myCallbackIds);
}

MStatus MySampleCmd::redoIt() {

    // This is where the actual adding callback happens
    // We register our callback to the "timeChanged" event
    MCallbackId callbackId = MEventMessage::addEventCallback("timeChanged",  (MMessage::MBasicFunction) MySampleCmd::userCB);

    // Append the newly added callback's ID to our list of callback ids
    // for future removal
    myCallbackIds.append(callbackId);
    return MS::kSuccess;
}

MStatus MySampleCmd::undoIt() {
    MStatus stat;
    if(myCallbackIds.length() != 0)
        // Make sure we remove all the callbacks we added
        stat = MEventMessage::removeCallbacks(myCallbackIds);
    return stat;
}

// Our callback function
void SafeSelect::userCB(void* clientData) {
    MGlobal::displayInfo( "Callback userCB called!
" );
    return;
}
cmd.cpp

Get Points At Time

MStatus myPlugIn::GetPointsAtTime(
    const MDagPath& dagPath,
    const MTime& mayaTime,
    MPointArray& points )
{
  MStatus                               status = MS::kSuccess;

  points.clear();

  MFnMesh                               fnMesh;

  // Move Maya to current frame
  MGlobal::viewFrame( mayaTime );

  // You MUST reinitialize the function set after changing time!
  fnMesh.setObject( dagPath );

  // Get vertices at this time
  status = fnMesh.getPoints( points );

  return status;
}
View Code
MStatus myPlugIn::doIt( const MArgList& args )
{
  MStatus                               status = MS::kSuccess;

  MDagPath                              dagPath;

  // .. determing dagPath from current selection, or whatever .. //

  MPointArray                           points;

  MTime                                 currentTime, maxTime;

  // Get start- and end-frame from Maya
  currentTime = MAnimControl::minTime();
  maxTime = MAnimControl::maxTime();

  // Iterate through time
  while ( currentTime <= maxTime )
  {
    // Get vertices at this time
    status = GetPointsAtTime( dagPath, currentTime, points );

    // .. do something with the points here .. //

    // Advance by one frame
    currentTime++;
  }

  return status;
}
Use the Get points at time

M3dView Capture

(1)

#Import api modules
import maya.OpenMaya as api
import maya.OpenMayaUI as apiUI

#Grab the last active 3d viewport
view = apiUI.M3dView.active3dView()
print view

#read the color buffer from the view, and save the MImage to disk
image = api.MImage()
view.readColorBuffer(image, True)
image.writeToFile('C:/test.jpg', 'jpg')
View Code

(2)

import os
 
import maya.OpenMaya as mod_om
import maya.OpenMayaUI as mod_om_ui
import maya.cmds as mod_mc
import maya.mel as mel
 
 
view = mod_om_ui.M3dView.active3dView()
image_ = mod_om.MImage()
 
for frame in range(1,11):
        # Change the frame number
        mod_mc.currentTime(frame)
        for obj in ['headMouthScp_geo', 'pSphere1']:
               
                # Isolate the object, so that only that particular object is seen
                # Also Tried with turning off/on the visibility
                mod_mc.select(obj)
                mod_mc.isolateSelect('modelPanel4',s=1)
                mod_mc.isolateSelect( 'modelPanel4', addSelected=True )
                #mod_mc.select(obj)
                #mod_mc.isolateSelect( 'modelPanel4', addSelected=True )
                mod_mc.setAttr(obj + '.visibility', 0)
                mod_mc.setAttr(obj + '.visibility', 1)
               
                # Refresh the scene
                view.refresh()
                mod_mc.refresh()
                               
                # Read Color Buffer
                view.readColorBuffer(image_, True)
 
                # Write The Color Buffer
                image_.resize(640, 480)
                image_.writeToFile('C:/Temp/Frame_Buffer_%s_%d.bmp' % (obj, frame), 'bmp')
 
                mod_mc.select(clear=True)
                mod_mc.isolateSelect( 'modelPanel4', state=0 )
View Code

(3)cmds context

import contextlib

@contextlib.contextmanager
def solo_renderable(solo_cam):

    # Disable all cameras as renderable
    # and store the original states
    cams = cmds.ls(type='camera')
    states = {}
    for cam in cams:
        states[cam] = mc.getAttr(cam + '.rnd')
        cmds.setAttr(cam + '.rnd', 0)
        
    # Change the solo cam to renderable
    cmds.setAttr(solo_cam + '.rnd', 1)

    try:
        yield
    finally:
        # Revert to original state
        for cam, state in states.items():
            cmds.setAttr(cam + '.rnd', state)

with solo_cam('myCamShape'):
    cmds.playblast()
View Code

OGL Render in backend:

import sys
import os
import contextlib

try:
    import maya.cmds as cmds
    import maya.standalone as standalone

    standalone.initialize(name='python')
except:
    raise ImportError


def openScene(openPath):
        sceneName = os.path.basename(openPath[:-3])
        print "opening path.................
"
        cmds.file(openPath, open=True)



if __name__ == "__main__":
    openScene(r"c:/test2.ma")
    cmds.hwRenderLoad()

    for x in xrange(1,68,1):
        print cmds.ogsRender(width=1280,height=720,cam='camera1',frame = x)
View Code

(4)code snipts

<1>

import maya.cmds as cmds

cmds.ls(*cmds.listHistory (mynode), type = 'animCurve' )

<2> iter by type

import maya.OpenMaya as om
import maya.OpenMayaMPx as omp
import maya.OpenMayaAnim  as oma


# just loop the animation curve
it = om.MItDependencyNodes(om.MFn.kMesh) 

while not it.isDone():
    aobj =  it.item()
    print aobj
    #aniCur = oma.MFnAnimCurve(aobj)
    #print aniCur.name()
    
    it.next()
View Code

(5) save two matrixs into a float* array

 // MMatrix stores double values, but I want floating point values on the GPU so convert them here.
    unsigned int numFloat = 32;
    float* temp = new float[numFloat];
    unsigned int curr = 0;
    for(unsigned int row = 0; row<4; row++)
    {
        for(unsigned int column = 0; column<4; column++)
        {
            temp[curr++] = (float)omat(row, column);
        }
    }
    for(unsigned int row = 0; row<4; row++)
    {
        for(unsigned int column = 0; column<4; column++)
        {
            temp[curr++] = (float)omatinv(row, column);
        }
    }
View Code

 in opencl use pointer offset

__global const float4* matrices,                    //first matrix is offset matrix, second matrix is offset matrix inverse
__global const float4* matrixInverse = &(matrices[4]);
__global const float4* matrix = matrices;

(6) command port eval scripts:

MEL:

commandPort -stp "python" -n ":5055" ;
cmds.commandPort (n=':6328', stp='python')

other Python version:

import socket
maya = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
maya.connect(("127.0.0.1", 5055))
maya.send("""maya.cmds.polySphere( radius=4 )""")
The above code will create a new sphere in your currently running Maya. You can use any python terminal (doesn't have to be mayapy).

(If you're running python3, the last command will produce an error until you change it to:

maya.send(bytes("""maya.cmds.polySphere( radius=4 )""", 'UTF-8'))
View Code
原文地址:https://www.cnblogs.com/gearslogy/p/6900272.html