不過著好象侵權了,因為ALIAS聲明不得一任何方式傳播該手冊的部分或全部_炙墨追零
Maya不為插件提供二進制兼容性。每當發布新版本時,舊插件的源代碼要重新編譯。然而,我們的目標是保持源代碼兼容性,在大多情況下,不需要修改源代碼。也許我們以后會提供支持二進制兼容性的API。
IRIX,Windows,Linux和Mac OS X上的Maya API
Maya API是提供從內部訪問Maya的C++ API,它由一系列與Maya不同功能有關的庫組成。這些庫是:
OpenMaya包含定義節點和命令的基本類
OpenMayaUI包含用于創建用戶界面元素(如manipulators, contexts, and locators)的類
OpenMayaAnim用于創建動畫的類,包括deformers和inverse kinematics
OpenMayaFX包含用于dynamics的類
OpenMayaRender包含用于執行渲染的類
載入插件
有兩種裝載和卸載插件的方法。最簡單的是用Plug-in Manager,另一種是用loadPlugin命令。二者都搜索環境變量MAYA_PLUG_IN_PATH指定的路徑。
卸載插件
用unloadPlugin命令帶上插件名卸載插件。
注釋
插件必須在重編譯前被卸載,否則Maya會崩潰。
卸載插件前必須移除場景中所有的參考和插件中定義的節點,還要清空undo隊列,因為插件的影響還可能被保留其中。
當你在插件使用中強制卸載它,就無法重載。因為現存的節點被轉換為Unknown,重載插件時這些節點不會恢復。
寫一個簡單的插件
下面演示如何寫一個簡單的Hello World插件。
#include <maya/MSimple.h>
DeclareSimpleCommand( helloWorld, "Alias", "6.0");
MStatus helloWorld::doIt( const MArgList& )
{
printf("Hello World\n");
return MS::kSuccess;
}
編譯后在命令窗口鍵入helloWorld,按數字鍵盤上的Enter執行。
重要的插件特性
以上例子展示了很多重要特性。
MSimple.h
用于簡單的command plug-in的頭文件,通過DeclareSimpleCommand宏注冊新command,但這樣你只能創建一個command。
注釋
可能經常需要創建執行許多特性的插件,例如dependency graph nodes和commands,在這種情況下MSimple.h不再可用,你要自己寫注冊代碼告知Maya插件的功能。
這個宏的主要缺陷是只能創建不能撤銷的命令。
MStatus
指明方法是否成功。API類中大部分方法返回MStatus。為防止命名空間沖突,我們用MS名字空間,如MS::kSuccess
注釋
API很少用status codes,但如果錯誤記錄被開啟,額外的錯誤細節會被寫入日志文件。
DeclareSimpleCommand
DeclareSimpleCommand宏需要三個參數:類名,作者名,命令版本號
注釋
不支持undo的命令不應該改變場景狀態,否則Maya的undo功能會失效。
寫一個與Maya交互的插件
只需要在helloWorld例子上做很少的修改。
以下程序輸出Hello后跟輸入字符。
#include <maya/MSimple.h>
DeclareSimpleCommand( hello, "Alias", "6.0");
MStatus hello::doIt( const MArgList& args )
{
printf("Hello %s\n", args.asString( 0 ).asChar() );
return MS::kSuccess;
}
MArgList
MArgList類提供和C或C++程序中argc/argv相似的作用。該類提供獲得多種類型參數(如integer,double,string,vector)的方法。
下面的例子用于創建螺旋線,有pitch和radius兩個參數。
#include <math.h>
#include <maya/MSimple.h>
#include <maya/MFnNurbsCurve.h>
#include <maya/MPointArray.h>
#include <maya/MDoubleArray.h>
#include <maya/MPoint.h>
DeclareSimpleCommand( helix, "Alias - Example", "3.0");
MStatus helix::doIt( const MArgList& args )
{
MStatus stat;
const unsigned deg = 3; // Curve Degree
const unsigned ncvs = 20; // Number of CVs
const unsigned spans = ncvs - deg; // Number of spans
const unsigned nknots = spans+2*deg-1;// Number of knots
double radius = 4.0; // Helix radius
double pitch = 0.5; // Helix pitch
unsigned i;
// Parse the arguments.
for ( i = 0; i < args.length(); i++ )
if ( MString( "-p" ) == args.asString( i, &stat )
&& MS::kSuccess == stat)
{
double tmp = args.asDouble( ++i, &stat );
if ( MS::kSuccess == stat )
pitch = tmp;
}
else if ( MString( "-r" ) == args.asString( i, &stat )
&& MS::kSuccess == stat)
{
double tmp = args.asDouble( ++i, &stat );
if ( MS::kSuccess == stat )
radius = tmp;
}
MPointArray controlVertices;
MDoubleArray knotSequences;
// Set up cvs and knots for the helix
//
for (i = 0; i < ncvs; i++)
controlVertices.append( MPoint( radius * cos( (double)i ),
pitch * (double)i, radius * sin( (double)i ) ) );
for (i = 0; i < nknots; i++)
knotSequences.append( (double)i );
// Now create the curve
//
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( controlVertices,
knotSequences, deg,
MFnNurbsCurve::kOpen,
false, false,
MObject::kNullObj,
&stat );
if ( MS::kSuccess != stat )
printf("Error creating curve.\n");
return stat;
}
提示
argc/argv和MArgList重要的不同是MArgList中的零元素是參數而不像argc/argv中是命令名。
用插件創建曲線
#include <math.h>
#include <maya/MSimple.h>
#include <maya/MPoint.h>
#include <maya/MPointArray.h>
#include <maya/MDoubleArray.h>
#include <maya/MFnNurbsCurve.h>
DeclareSimpleCommand( doHelix, "Alias - Example", "6.0");
MStatus doHelix::doIt( const MArgList& )
{
MStatus stat;
const unsigned deg = 3; // Curve Degree
const unsigned ncvs = 20; // Number of CVs
const unsigned spans = ncvs - deg; // Number of spans
const unsigned nknots = spans+2*deg-1; // Number of knots
double radius = 4.0; // Helix radius
double pitch = 0.5; // Helix pitch
unsigned i;
MPointArray controlVertices;
MDoubleArray knotSequences;
// Set up cvs and knots for the helix
//
for (i = 0; i < ncvs; i++)
controlVertices.append( MPoint( radius * cos( (double)i ),
pitch * (double)i, radius * sin( (double)i ) ) );
for (i = 0; i < nknots; i++)
knotSequences.append( (double)i );
// Now create the curve
//
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( controlVertices,
knotSequences, deg, MFnNurbsCurve::kOpen, false, false, MObject::kNullObj, &stat );
if ( MS::kSuccess != stat )
printf("Error creating curve.\n");
return stat;
}
返回頁首
LEN3D
二星視客
注冊時間: 2002-02-10
帖子: 499
視幣:643
發表于: 2005-12-31 11:03 發表主題:
--------------------------------------------------------------------------------
同Maya交互
Maya API包含四種C++對象用于和Maya交互,它們是wrappers, objects, function sets和proxies。
API中的物體所有權
object和function set的結合類似于wrapper,但區別在所有權上。API中物體所有權很重要,如果沒有很好定義,你可能會刪除一些系統需要或者已經刪除的東西。wrappers,objects,function sets解決了這類問題。
MObject
對所有Maya物體(curves, surfaces, DAG nodes, dependency graph nodes, lights, shaders, textures等)的訪問是通過句柄MObject完成的。這個句柄提供了一些簡單的方法來辨別物體類型。MObject的析構函數并不真正刪除它所參考的Maya物體,調用析構函數只會刪除句柄本身而維持所有權。
重要提示
絕對不要在插件調用外儲存指向MObject的指針。
Wrappers
wrappers為像vectors,matrices這樣的簡單對象存在。它們一般都被完整的實現,帶有公用的構造和析構函數。API方法可能會返回一個接下來由你負責的wrapper。你可以任意分配和刪除它們。前面例子中的MPointArray和MDoubleArray就是wrappers,你擁有wrappers的所有權。
Objects和Function Sets
objects和function sets總被一同使用。它們相對獨立是因為所有權問題,objects總被Maya擁有,而function sets屬于你。
Function Sets
function sets是操作對象的C++類。在前面的例子中MFnNurbsCurve就是function set,MFn前綴說明了這一點。
下面兩行創建新曲線。
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( ... );
MFnNurbsCurve curveFn;創建包含操作曲線方法的function set, create方法用來創建新曲線。
MObject curve = curveFn.create( ... );創建隨后你可以任意使用的Maya對象。
如果你再加上一行:
curve = curveFn.create( ... );
另一條曲線會被創建,名為curve的MObject現在指向新創建的這條曲線,但原先創建的曲線仍然存在,只不過不被句柄參考。
Proxies
Maya通過proxy對象創建新對象類型。proxy對象是你創建的但是被Maya占有。
一個普遍的誤解是以為可以通過繼承現存的function set來創建新對象類型,例如MFnNurbsSurface從MFnDagNode派生。但實際上這樣不行,因為function set完全被你擁有,Maya根本不使用它們,Maya只用MObject指向的物體。
無類型
分開objects和function sets帶來的一個有趣結果,API操作對象時可以不顧類型,例如:
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( ... );
MFnNurbsSurface surface( curve );
MFnNurbsSurface只操作surface對象,以上的例子是錯的,但是你可能沒有發覺。API中的錯誤檢查代碼會處理這種初始化錯誤。
function sets接受任何類型的MObjects,如果它不認識該物體,就忽略物體并返回錯誤值。
命名習慣
Maya API使用以下前綴來區別不同類型的對象。
MFn
表示function set
MIt
迭代器,功能和function set類似但用于操作單獨的對象。
MPx
表示proxy對象,你可以繼承它們來創建自己的對象類型。
M classes
大多是wrappers但也有例外。MGlobal是包含很多靜態方法的類用于全局操作,并不需要MObject。
添加參數
上面的螺旋線插件生成簡單的曲線,但每次結果都一樣。
為曲線的例子添加參數
通過一些改變可以添加如radius和pitch這樣的參數,注意下面函數參數的聲明多了一個args:
MStatus doHelix::doIt( const MArgList& args )
Add the following lines after the variable declarations:
// Parse the arguments.
for ( i = 0; i < args.length(); i++ )
if ( MString( "-p" ) == args.asString( i ) )
pitch = args.asDouble( ++i );
else if ( MString( "-r" ) == args.asString( i ) )
radius = args.asDouble( ++i );
for循環遍歷所有MArgList中的參數,兩個if語句把參數轉換成MString并與可能的值做比較。
如果匹配,后一個參數就被轉換成double并且賦給對應的值,例如:
doHelix -p 0.5 -r 5
會生成一個pitch為0.5單位長,radius為5單位長的螺旋線。
錯誤檢查
在上面的例子中還未涉及錯誤檢查問題。
大部分的方法提供一個可選參數,是一個指向MStatus的指針,用于返回值。
下面的參數解析代碼包含了錯誤檢查:
// Parse the arguments.
for ( i = 0; i < args.length(); i++ )
if ( MString( "-p" ) == args.asString( i, &stat )
&& MS::kSuccess == stat )
{
double tmp = args.asDouble( ++i, &stat );
// argument can be retrieved as a double
if ( MS::kSuccess == stat )
pitch = tmp;
}
else if ( MString( "-r" ) == args.asString( i, &stat )
&& MS::kSuccess == stat )
{
double tmp = args.asDouble( ++i, &stat );
// argument can be retrieved as a double
if ( MS::kSuccess == stat )
radius = tmp;
}
注意asString()和asDouble()增加的最后一個&stat參數,用于檢查操作是否成功。
例如args.asString(i, &stat)可能會返回MS::kFailure,索引值大于參數數量或者當不能轉換成double值時args.asDouble(++i, &stat)會失敗。
MStatus類
MStatus類用于確定方法是否成功。
Maya API既返回MStatus也給可選的MStatus參數賦值。MStatus類包含error方法并重載了bool操作符,它們都能用來檢查錯誤,例如:
MStatus stat = MGlobal::clearSelectionList;
if (!stat) {
// Do error handling
...
}
如果MStatus實例包含錯誤,你可以做以下事:
用statusCode方法獲得具體的錯誤原因。
用errorString方法獲得錯誤細節描述。
用perror打印錯誤細節描述。
用重載的相等和不相等操作符來和某個MStatusCode做比較。
用clear方法把MStatus實例設置為成功狀態。
錯誤記錄
同使用MStatus一樣,你也可以用錯誤記錄檢查錯誤。
開啟和關閉錯誤記錄:
1. 在MEL中用openMayaPref命令加上-errlog標識。
2. 在插件中調用MGlobal::startErrorLogging()和MGlobal::stopErrorLogging()方法。
一旦開啟錯誤記錄,每次插件發生錯誤都會被Maya記錄在文件中,還會包含錯誤在何處引發的描述。
默認文件名是OpenMayaErrorLog,在當前目錄下。
可以用MGlobal::setErrorLogPathName改變錯誤記錄的目錄。
提示
插件可以用MGlobal::doErrorLogEntry()向記錄文件中添加自己的記錄。
--------------------------------------------------------------------------------
用API選擇
概覽用API選擇
一個命令經常從選擇列表獲取輸入。MGlobal::getActiveSelectionList() 方法的結果包含所有當前被選擇的物體。通過MSelectionList和MItSelectionList兩個API類可以容易的檢查和修改選擇列表。
MGlobal::setActiveSelectionList()
可以通過MGlobal::setActiveSelectionList()獲得當前全局選擇列表的拷貝。
在調用MGlobal::setActiveSelectionList()前,你對返回的選擇列表的任何改變都不會真正影響到場景。
你可以創建自己的MSelectionList來與其它列表合并,列表可以用來創建對象集合。
MSelectionList
MSelectionList提供向選擇列表中添加、刪除和遍歷對象的方法。
下面的例子打印所有被選中的DAG節點的名字。
簡單的插件例子
#include <maya/MSimple.h>
#include <maya/MGlobal.h>
#include <maya/MString.h>
#include <maya/MDagPath.h>
#include <maya/MFnDagNode.h>
#include <maya/MSelectionList.h>
MStatus pickExample::doIt( const MArgList& )
{
MDagPath node;
MObject component;
MSelectionList list;
MFnDagNode nodeFn;
MGlobal::getActiveSelectionList( list );
for ( unsigned int index = 0; index < list.length(); index++ )
{
list.getDagPath( index, node, component );
nodeFn.setObject( node );
printf("%s is selected\n", nodeFn.name().asChar() );
}
return MS::kSuccess;
}
DeclareSimpleCommand( pickExample, "Alias", "1.0" );
MFnDagNode中的setObject()方法被MFnBase的所有子類繼承,用于設置該function set將要操作的對象。通常這在構造函數中完成,但如果function set已經被創建并且你想改變它要操作的對象,就使用setObject(),這比每次都重新創建和銷毀function set有效率的多。
當你選擇CVs并調用該插件時,不會得到CVs的名字,而是得到父對象(如curve,surface,mesh)的名字,并且打印名字的數量和選擇物體的數量不同。
Maya簡化像CVs這樣的對象組件的選擇,不是把每個組件都添加到選擇列表,而是添加父對象并把組件當成一個組。
例如,當nurbSphereShape1的很多CVs被選中,list.getDagPath() 會返回一個指向nurbSphereShape1 的MDagPath和一個包含了所有被選中的CVs的MObject。這里的MDagPath和MObject可以被傳遞給MItSurfaceCV迭代器來遍歷所有選中的CVs。
只要你繼續選擇一個對象的組件,選擇列表中的對象只會有一個。然而如果你選擇了一個對象中的某些組件和另一個對象中的某些組件,然后再選擇第一個對象中的某些組件,那么第一個對象會在選擇列表中出現兩次。這樣你可以決定物體被選擇的順序。所有組件也被按它們被選中的順序排列。
MItSelectionList
MltSelectionList是一個包含被選擇物體的wrapper類,它可以通過過濾讓你只看到特定類型的對象,而MSelectionList不行。
MGlobal::getActiveSelectionList( list );
for ( MItSelectionList listIter( list ); !listIter.isDone(); listIter.next() )
{
listIter.getDagPath( node, component );
nodeFn.setObject( node );
printf("%s is selected\n", nodeFn.name().asChar() );
}
上面MSelectionList的例子可以用這些代碼代替,結果完全相同。
當把MItSelectionList的構造函數改成:
MItSelectionList listIter( list, MFn::kNurbsSurface )
這時只會訪問NURBS Surface,也會忽略surface CVs。如果你只想訪問surface CVs,可以這么寫:
MItSelectionList listIter( list, MFn::kSurfaceCVComponent )
setObject()方法
限制
Mesh vertices, faces或edges并不按被選中的順序返回。
MFn::Type枚舉
到處都會用到MFn::Type枚舉來確定物件類型。
function sets類有apiType()方法用來確定MObject參考的對象類型,還有一個type()方法用來確定function set本身的類型。
MGlobal::getFunctionSetList()返回字符串數組,描述了function sets的類型。
MGlobal::selectByName()
MGlobal::selectByName()方法將所有匹配的對象添加到當前選擇列表,例如:
MGlobal::selectByName( "*Sphere*" );
選擇所有名字中包含Sphere的東西。
提示
你也可以不必創建MSelectionList而直接用MGlobal::select()往全局選擇列表添加對象。
--------------------------------------------------------------------------------
Command plug-ins
向Maya添加commands概覽
Plug-ins
API支持多種類型的插件:
Command plug-ins提供命令來擴展MEL
Tool commands獲得鼠標輸入的插件
Dependency graph plug-ins添加新的操作,如dependency graph nodes
Device plug-ins允許新的設備與Maya交互
注冊commands
你必須知道在Maya中如何正確注冊commands,MFnPlugin類用來做這件事。
MFnPlugin
下面的helloWorld用MFnPlugin注冊而不像前面那樣用宏。
#include <stdio.h>
#include <maya/MString.h>
#include <maya/MArgList.h>
#include <maya/MFnPlugin.h>
#include <maya/MPxCommand.h>
class hello : public MPxCommand
{
public:
MStatus doIt( const MArgList& args );
static void* creator();
};
MStatus hello::doIt( const MArgList& args ) {
printf("Hello %s\n", args.asString( 0 ).asChar() );
return MS::kSuccess;
}
void* hello::creator() {
return new hello;
}
MStatus initializePlugin( MObject obj ) {
MFnPlugin plugin( obj, "Alias", "1.0", "Any" );
plugin.registerCommand( "hello", hello::creator );
return MS::kSuccess;
}
MStatus uninitializePlugin( MObject obj ) {
MFnPlugin plugin( obj );
plugin.deregisterCommand( "hello" );
return MS::kSuccess;
}
注釋
所有插件都必須有initializePlugin()和uninitializePlugin(),否則不會被載入,creator是必須的,它允許Maya創建類的實例。
initializePlugin()
initializePlugin()可以被當作C或C++函數定義。你不定義它插件就不會被裝載。
它包含了注冊commands, tools, devices等的代碼,只在插件裝載時被立即調用一次。
例如commands和tools通過實例化一個操作MObject的MFnPlugin來注冊。這個MObject包含Maya私有信息如插件名字和目錄,它被傳遞給MFnPlugin的構造函數。"Any"表示Maya API的版本,是默認值。
MFnPlugin::registerCommand()用來注冊"hello"命令。如果初始化不成功,插件會被自動卸載。
uninitializePlugin()
uninitializePlugin()用來注銷initializePlugin()注冊的所有東西,只在插件被卸載時被調用一次。Maya會自己管理的對象不需要在這里銷毀。
Creator methods
插件要注冊的東西Maya事先是不知道的,所以沒辦法決定分配它需要的空間,這時creator用來幫助Maya創建這些東西的實例。
MPxCommand
從MPxCommand繼承的類至少要定義兩個函數,doIt和creator。
doIt()和redoIt()方法
doIt()方法是純虛的,而且基類中沒有定義creator,所以兩個都要定義。
簡單的command可以讓doIt做所有事,但在復雜的例子中,doIt()用來解析參數列表和選擇列表等,并用解析的結果設置內部數據,最后再調用redoIt()來做真正的工作。這樣避免了doIt()和redoIt()間的代碼重復。
校驗
下面的例子用來演示方法被調用的順序。
#include <stdio.h>
#include <maya/MString.h>
#include <maya/MArgList.h>
#include <maya/MFnPlugin.h>
#include <maya/MPxCommand.h>
class commandExample : public MPxCommand
{
public:
commandExample();
virtual ~commandExample();
MStatus doIt( const MArgList& );
MStatus redoIt();
MStatus undoIt();
bool isUndoable() const;
static void* creator();
};
commandExample::commandExample() {
printf("In commandExample::commandExample()\n");
}
commandExample::~commandExample() {
printf("In commandExample::~commandExample()\n");
}
MStatus commandExample::doIt( const MArgList& ) {
printf("In commandExample::doIt()\n");
return MS::kSuccess;
}
MStatus commandExample::redoIt() {
printf("In commandExample::redoIt()\n");
return MS::kSuccess;
}
MStatus commandExample::undoIt() {
printf("In commandExample::undoIt()\n");
return MS::kSuccess;
}
bool commandExample::isUndoable() const {
printf("In commandExample::isUndoable()\n");
return true;
}
void* commandExample::creator() {
printf("In commandExample::creator()\n");
return new commandExample();
}
MStatus initializePlugin( MObject obj )
{
MFnPlugin plugin( obj, "My plug-in", "1.0", "Any" );
plugin.registerCommand( "commandExample", commandExample::creator );
printf("In initializePlugin()\n");
return MS::kSuccess;
}
MStatus uninitializePlugin( MObject obj )
{
MFnPlugin plugin( obj );
plugin.deregisterCommand( "commandExample" );
printf("In uninitializePlugin()\n");
return MS::kSuccess;
}
第一次載入插件時"In initializePlugin()"被立即打印,在命令窗口鍵入"commandExample"會得到:
In commandExample::creator()
In commandExample::commandExample()
In commandExample::doIt()
In commandExample::isUndoable()
注意析構函數并沒有被調用,因為command還有可能被undo和redo。
這是Maya的undo機制的工作方式。Command objects負責保留undo自己需要的信息。析構函數在command掉到undo隊列的末尾或插件被卸載時才被調用。
如果你修改一下,讓isUndoable()返回false,將得到如下結果:
In commandExample::creator()
In commandExample::commandExample()
In commandExample::doIt()
In commandExample::isUndoable()
In commandExample::~commandExample()
在這種情況下析構函數立即被調用,因為不能undo了,Maya認為這樣的command不會改變場景,所以使用undo和redo時undoIt()和redoIt()不會被調用。
帶undo和redo的螺旋線例子
這個插件會把被選中的曲線變成螺旋線。
#include <stdio.h>
#include <math.h>
#include <maya/MFnPlugin.h>
#include <maya/MFnNurbsCurve.h>
#include <maya/MPointArray.h>
#include <maya/MDoubleArray.h>
#include <maya/MPoint.h>
#include <maya/MSelectionList.h>
#include <maya/MItSelectionList.h>
#include <maya/MItCurveCV.h>
#include <maya/MGlobal.h>
#include <maya/MDagPath.h>
#include <maya/MString.h>
#include <maya/MPxCommand.h>
#include <maya/MArgList.h>
class helix2 : public MPxCommand {
public:
helix2();
virtual ~helix2();
MStatus doIt( const MArgList& );
MStatus redoIt();
MStatus undoIt();
bool isUndoable() const;
static void* creator();
這邊的和前面都差不多。
private:
MDagPath fDagPath;
MPointArray fCVs;
double radius;
double pitch;
};
這個command儲存原始的曲線信息用來undo,并儲存螺旋線的描述用來redo。
非常值得注意的是它不儲存MObject,而是用一個MDagPath來指向要操作的曲線。因為命令下一次被執行時無法保證MObject繼續有效,Maya可能會核心轉儲。然而MDagPath卻能保證任何時候都指向正確的曲線。
void* helix2::creator() {
return new helix2;
}
creator簡單返回對象實例。
helix2::helix2() : radius( 4.0 ), pitch( 0.5 ) {}
初始化radius和pitch的值。
helix2::~helix2() {}
這時析構函數不需要做任何事。
注釋
不應該刪除Maya占有的數據。
MStatus helix2::doIt( const MArgList& args ) {
MStatus status;
// Parse the arguments.
for ( int i = 0; i < args.length(); i++ )
if ( MString( "-p" ) == args.asString( i, &status )
&& MS::kSuccess == status )
{
double tmp = args.asDouble( ++i, &status );
if ( MS::kSuccess == status )
pitch = tmp;
}
else if ( MString( "-r" ) == args.asString( i, &status )
&& MS::kSuccess == status )
{
double tmp = args.asDouble( ++i, &status );
if ( MS::kSuccess == status )
radius = tmp;
}
else
{
MString msg = "Invalid flag: ";
msg += args.asString( i );
displayError( msg );
return MS::kFailure;
}
在doIt()里面解析參數并且設置radius和pitch,它們將被用在redoIt()中。
從MPxCommand繼承的displayError()方法用來在命令窗口輸出消息,消息都會帶上"Error:"前綴,如果用displayWarning()就會帶上"Warning:"前綴。
// Get the first selected curve from the selection list.
MSelectionList slist;
MGlobal::getActiveSelectionList( slist );
MItSelectionList list( slist, MFn::kNurbsCurve, &status );
if (MS::kSuccess != status) {
displayError( "Could not create selection list iterator" );
return status;
}
if (list.isDone()) {
displayError( "No curve selected" );
return MS::kFailure;
}
MObject component;
list.getDagPath( fDagPath, component );
這段代碼從選擇列表中取出第一條曲線。
return redoIt();
}
最后調用redoIt()。
MStatus helix2::redoIt()
{
unsigned i, numCVs;
MStatus status;
MFnNurbsCurve curveFn( fDagPath );
numCVs = curveFn.numCVs();
status = curveFn.getCVs( fCVs );
if ( MS::kSuccess != status )
{
displayError( "Could not get curve's CVs" );
return MS::kFailure;
}
從被選中的曲線獲取CVs并儲存在command內的MPointArray中,用來在調用undoIt()時把曲線恢復為原狀。
MPointArray points(fCVs);
for (i = 0; i < numCVs; i++)
points[i] = MPoint( radius * cos( (double)i ),
pitch * (double)i, radius * sin( (double)i ) );
status = curveFn.setCVs( points );
if ( MS::kSuccess != status )
{
displayError( "Could not set new CV information" );
fCVs.clear();
return status;
}
這段代碼把曲線變為螺旋線。
updateCurve()用來通知Maya幾何已被更改,需要重繪。
return MS::kSuccess;
}
MStatus helix2::undoIt()
{
MStatus status;
MFnNurbsCurve curveFn( fDagPath );
status = curveFn.setCVs( fCVs );
if ( MS::kSuccess != status)
{
displayError( "Could not set old CV information" );
return status;
}
這里將曲線的CVs恢復了。
注釋
不需要擔心CVs數量改變或已被刪除,你可以假設command執行后的一切改變都被撤銷了,模型維持不變。
status = curveFn.updateCurve();
if ( MS::kSuccess != status )
{
displayError( "Could not update curve" );
return status;
}
fCVs.clear();
return MS::kSuccess;
}
只是為了以防萬一才調用clear。
bool helix2::isUndoable() const
{
return true;
}
指明該command是可撤銷的。
MStatus initializePlugin( MObject obj )
{
MFnPlugin plugin( obj, "Alias", "1.0", "Any");
plugin.registerCommand( "helix2", helix2::creator );
return MS::kSuccess;
}
MStatus uninitializePlugin( MObject obj )
{
MFnPlugin plugin( obj );
plugin.deregisterCommand( "helix2" );
return MS::kSuccess;
}
這里和前面差不多。
Returning results to MEL
commands也可以向MEL返回結果,這通過叫"setResult"和"appendToResult"的一系列從MPxCommand繼承的重載函數完成。例如可以這樣返回值為4的整數:
int result =4;
clearResult();
setResult( result );
也可以多次調用appendToResult來返回數組,如:
MPoint result (1.0, 2.0, 3.0);
...
clearResult();
appendToResult( result.x );
appendToResult( result.y );
appendToResult( result.z );
或者直接返回數組:
MDoubleArray result;
MPoint point (1.0, 2.0, 3.0);
result.append( point.x );
result.append( point.y );
result.append( point.z );
clearResult();
setResult( result );
Syntax objects
當你寫語法對象時需要用到MSyntax和MArgDatabase,這些類是定義和處理命令標記輸入時必需的。
MSyntax用來指定傳遞給commands的標記和參數。
MArgDatabase用于解析傳遞給commands的所有標記、參數和對象的類。它接受MSyntax對象來把命令參數解析成容易訪問的形式。
注釋
MArgParser和MArgDatabase類似但是用于context commands的而不是commands。
Flags
Syntax objects需要flags,你既要定義短flags又要定義長flags,短flags小于等于三個字母,長flags大于等于4個字母。
用#define來聲明這些flags,例如scanDagSyntax使用以下flags:
#define kBreadthFlag "-b"
#define kBreadthFlagLong "-breadthFirst"
#define kDepthFlag "-d"
#define kDepthFlagLong "-depthFirst"
創建Syntax Object
在你的command類中需要寫newSyntax方法建立你的語法。它應該是返回MSyntax的靜態函數。
在該方法中你應該為syntax object添加必要的flags并返回它。
scanDagSyntax類的newSyntax定義如下:
class scanDagSyntax: public MPxCommand
{
public:
...
static MSyntax newSyntax();
...
};
MSyntax scanDagSyntax::newSyntax()
{
MSyntax syntax;
syntax.addFlag(kBreadthFlag, kBreadthFlagLong);
syntax.addFlag(kDepthFlag, kDepthFlagLong);
...
return syntax;
}
解析參數
按習慣一般在parseArgs方法中解析參數并由doIt調用,該方法創建一個局部的用syntax object和命令參數初始化的MArgDatabase。MArgDatabase提供了決定哪些flags被設置的方便方法。
注釋
除特別情況外,所有API都用Maya內部的厘米和弧度作為單位。
MStatus scanDagSyntax::parseArgs(const MArgList &args,
MItDag::TraversalType &
traversalType,
MFn::Type &filter,
bool &quiet)
{
MArgDatabase argData(syntax(), args);
if (argData.isFlagSet(kBreadthFlag))
traversalType = MItDag::kBreadthFirst;
else if (argData.isFlagSet(kDepthFlag))
traversalType = MItDag::kDepthFirst;
...
return MS::kSuccess;
}
注冊
創建syntax object的方法同command一起在initializePlugin中被注冊。
MStatus initializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin(obj, "Alias - Example",
"2.0", "Any");
status = plugin.registerCommand("scanDagSyntax",
scanDagSyntax::creator,
scanDagSyntax::newSyntax);
return status;
}
Contexts
Maya中的contexts用于決定鼠標動作如何被解釋。context可以執行commands,改變當前選擇集,或執行繪圖操作等。context還能繪制不同的鼠標指針。在Maya中context被表述為tool。
MPxContext
MPxContext允許你創建自己的context。
在Maya中context通過一個特殊的command來創建。在這點上,context類似shape,它通過command創建和修改并具有決定其行為和外觀的狀態。當你通過繼承MPxContext來寫一個context時,你也應該為它定義一個從MPxContextCommand派生的command。
以下是選取框的例子,它會繪制一個OpenGL選取框并選擇物體。
const char helpString[] =
"Click with left button or drag with middle button to select";
class marqueeContext : public MPxContext
{
public:
marqueeContext();
virtual void toolOnSetup( MEvent & event );
virtual MStatus doPress( MEvent & event );
virtual MStatus doDrag( MEvent & event );
virtual MStatus doRelease( MEvent & event );
virtual MStatus doEnterRegion( MEvent & event );
如果虛方法沒有被重載,MPxContext將執行默認的動作,所以你只要寫必要的方法即可。
private:
short start_x, start_y;
short last_x, last_y;
MGlobal::ListAdjustment listAdjustment
M3dView view;
};
marqueeContext::marqueeContext()
{
setTitleString ( "Marquee Tool" );
}
構造函數設置了標題文字,當工具被選中時會顯示在界面上。
void marqueeContext::toolOnSetup ( MEvent & )
{
setHelpString( helpString );
}
當工具被選中該方法會被調用,在提示行顯示幫助信息。
MStatus marqueeContext::doPress( MEvent & event )
{
當工具被選中并且你按下鼠標鍵時該方法會被調用。MEvent對象包含了鼠標動作的相關信息,如單擊的坐標。
if (event.isModifierShift() || event.isModifierControl() ) {
if ( event.isModifierShift() ) {
if ( event.isModifierControl() ) {
// both shift and control pressed, merge new selections
listAdjustment = MGlobal::kAddToList;
} else {
// shift only, xor new selections with previous ones
listAdjustment = MGlobal::kXORWithList;
}
} else if ( event.isModifierControl() ) {
// control only, remove new selections from the previous list
listAdjustment = MGlobal::kRemoveFromList;
}
}
else
listAdjustment = MGlobal::kReplaceList;
這里根據鍵盤動作來決定選擇類型。
event.getPosition( start_x, start_y );
獲得開始選擇處的屏幕坐標。
view = M3dView::active3dView();
view.beginGL();
決定激活視圖并開啟OpenGL渲染。
view.beginOverlayDrawing();
return MS::kSuccess;
}
MStatus marqueeContext::doDrag( MEvent & event )
{
當你拖動鼠標時該方法會被調用。
event.getPosition( last_x, last_y );
view.clearOverlayPlane();
每次繪制新選擇框前該方法都會被調用來清空overlay planes。
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D(
0.0, (GLdouble) view.portWidth(),
0.0, (GLdouble) view.portHeight()
);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef(0.375, 0.375, 0.0);
執行視圖變換。
glLineStipple( 1, 0x5555 );
glLineWidth( 1.0 );
glEnable( GL_LINE_STIPPLE );
glIndexi( 2 );
選定直線類型。
// Draw marquee
//
glBegin( GL_LINE_LOOP );
glVertex2i( start_x, start_y );
glVertex2i( last_x, start_y );
glVertex2i( last_x, last_y );
glVertex2i( start_x, last_y );
glEnd();
繪制選擇框。
#ifndef _WIN32
glXSwapBuffers(view.display(), view.window() );
#else
SwapBuffers(view.deviceContext() );
#endif
交換雙緩沖區。
glDisable( GL_LINE_STIPPLE );
恢復繪圖模式。
return MS::kSuccess;
}
MStatus marqueeContext::doRelease( MEvent & event )
{
鼠標鍵釋放時該方法會被調用。
MSelectionList incomingList, marqueeList;
MGlobal::ListAdjustment listAdjustment;
view.clearOverlayPlane();
view.endOverlayDrawing();
view.endGL();
繪圖完成,清空overlay planes,關閉OpenGL渲染。
event.getPosition( last_x, last_y );
決定鼠標釋放處的坐標。
MGlobal::getActiveSelectionList(incomingList);
獲取并保存當前選擇列表。
if ( abs(start_x - last_x) < 2 && abs(start_y - last_y) < 2 )
MGlobal::selectFromScreen( start_x, start_y, MGlobal::kReplaceList );
如果開始和結束選擇的坐標相同,則用單擊選取代替包圍盒選取。
else
// Select all the objects or components within the marquee.
MGlobal::selectFromScreen( start_x, start_y, last_x, last_y,
MGlobal::kReplaceList );
包圍盒選取。
// Get the list of selected items
MGlobal::getActiveSelectionList(marqueeList);
獲取剛才選定的列表。
MGlobal::setActiveSelectionList(incomingList, \
MGlobal::kReplaceList);
恢復原選擇列表。
MGlobal::selectCommand(marqueeList, listAdjustment);
按指定方式修改選擇列表。
return MS::kSuccess;
}
MStatus marqueeContext::doEnterRegion( MEvent & )
{
return setHelpString( helpString );
}
當你把鼠標移到任何視圖時都會調用該方法。
class marqueeContextCmd : public MPxContextCommand
{
public:
marqueeContextCmd();
virtual MPxContext* makeObj();
static void* creator();
};
MPxContextCommand
MPxContextCommand類用來定義創建contexts的特殊command。context commands和一般的commands一樣可以用命令行調用或者寫入MEL腳本。它們擁有修改context屬性的編輯和訪問選項。它們創建一個context實例并傳給Maya。context commands不能撤銷。
創建context command
下面是用來創建前面的選擇框context的context command。
marqueeContextCmd::marqueeContextCmd() {}
MPxContext* marqueeContextCmd::makeObj()
{
return new marqueeContext();
}
用來為Maya創建context實例的方法。
void* marqueeContextCmd::creator()
{
return new marqueeContextCmd;
}
MStatus initializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin( obj, "Alias", "1.0", "Any");
status = plugin.registerContextCommand( \
"marqueeToolContext", marqueeContextCmd::creator );
用MFnPlugin::registerContextCommand()而不是MFnPlugin::registerCommand()注冊context command。
return status;
}
MStatus uninitializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin( obj );
status = plugin.deregisterContextCommand( \
"marqueeToolContext" );
用MFnPlugin::deregisterContextCommand()注銷context command。
return status;
}
創建context就是這么簡單。
把context command添加到Maya工具架
有兩種方法激活context為當前context。第一種是用setToolTo命令后跟context的名字。
第二種方法就是把context的圖表添加到Maya工具架上。Maya工具架可以儲存兩種按鈕,command按鈕和tool按鈕。
下面是用來創建context按鈕和tool按鈕的MEL命令。
marqueeToolContext marqueeToolContext1;
setParent Shelf1;
toolButton -cl toolCluster
-t marqueeToolContext1
-i1 "marqueeTool.xpm" marqueeTool1;
這些MEL代碼創建一個marqueeToolContext實例并添加到"Common"工具架。
marqueeTool.xpm是工具的圖標名,必須在XBMLANGPATH目錄下,否則就不會顯示,但工具依然可用。
這些代碼既可以手工鍵入,又可以在initializePlugin()中用MGlobal::sourceFile()調用。
Tool property sheets
Tool property sheets是用來顯示和編輯context屬性的交互式編輯器,和用來編輯dependency graph node屬性的attribute editors類似。
實現一個tool properly sheet必須寫兩個MEL文件,一個用來編輯context,一個用來訪問context。
一個文件叫<yourContextName>Properties.mel,另一個叫<yourContextName>Values.mel,<yourContextName>是context的名字,可以用getClassName()方法獲得。
<>Properties.mel用來定義編輯器外觀。
<>Values.mel用來從編輯器獲得數值。
要有效實現tool property sheet,你必須在context command中實現足夠的編輯和訪問選項,并在MPxContext實現充分的訪問方法來設置和獲得內部參數。
MPxToolCommand
MPxToolCommand是創建用來在context中執行的commands的基類。tool commands和一般的commands一樣用command flags定義可以用命令行調用。但它們要做額外的工作,因為它們不從Maya調用而是從MPxContext調用。這些工作用來讓Maya正確執行undo/redo和日志策略。
如果context想執行自己的command,必須在注冊context和context command時注冊這個command。一個context只能和一個tool command對應。
下面是綜合了螺旋線和選取框的tool command的例子。
#define NUMBER_OF_CVS 20
class helixTool : public MPxToolCommand
{
public:
helixTool();
virtual ~helixTool();
static void* creator();
MStatus doIt( const MArgList& args );
MStatus redoIt();
MStatus undoIt();
bool isUndoable() const;
MStatus finalize();
static MSyntax newSyntax();
這些方法都差不多,但是加了finalize()用來提供command用法的幫助。
void setRadius( double newRadius );
void setPitch( double newPitch );
void setNumCVs( unsigned newNumCVs );
void setUpsideDown( bool newUpsideDown );
當tool command屬性由context設置時這些方法是必要的。
private:
double radius; // Helix radius
double pitch; // Helix pitch
unsigned numCV; // Helix number of CVs
bool upDown; // Helis upsideDown
MDagPath path; // Dag path to the curve.
// Don't save the pointer!
};
void* helixTool::creator()
{
return new helixTool;
}
helixTool::~helixTool() {}
這里和前面的螺旋線例子一樣。
helixTool::helixTool()
{
numCV = NUMBER_OF_CVS;
upDown = false;
setCommandString( "helixToolCmd" );
}
構造函數保存MEL command的名字以待在finalize()中使用。
MSyntax helixTool::newSyntax()
{
MSyntax syntax;
syntax.addFlag(kPitchFlag, kPitchFlagLong,
MSyntax::kDouble);
syntax.addFlag(kRadiusFlag, kRadiusFlagLong,
MSyntax::kDouble);
syntax.addFlag(kNumberCVsFlag, kNumberCVsFlagLong,
MSyntax::kUnsigned);
syntax.addFlag(kUpsideDownFlag, kUpsideDownFlagLong,
MSyntax::kBoolean);
return syntax;
}
MStatus helixTool::doIt( const MArgList &args )
{
MStatus status;
status = parseArgs(args);
if (MS::kSuccess != status)
return status;
return redoIt();
}
MStatus helixTool::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args);
if (argData.isFlagSet(kPitchFlag)) {
double tmp;
status = argData.getFlagArgument(kPitchFlag, 0, tmp);
if (!status) {
status.perror("pitch flag parsing failed.");
return status;
}
pitch = tmp;
}
if (argData.isFlagSet(kRadiusFlag)) {
double tmp;
status = argData.getFlagArgument(kRadiusFlag, 0, tmp);
if (!status) {
status.perror("radius flag parsing failed.");
return status;
}
radius = tmp;
}
if (argData.isFlagSet(kNumberCVsFlag)) {
unsigned tmp;
status = argData.getFlagArgument(kNumberCVsFlag,
0, tmp);
if (!status) {
status.perror("numCVs flag parsing failed.");
return status;
}
numCV = tmp;
}
if (argData.isFlagSet(kUpsideDownFlag)) {
bool tmp;
status = argData.getFlagArgument(kUpsideDownFlag,
0, tmp);
if (!status) {
status.perror("upside down flag parsing failed.");
return status;
}
upDown = tmp;
}
return MS::kSuccess;
}
MStatus helixTool::redoIt()
{
MStatus stat;
const unsigned deg = 3; // Curve Degree
const unsigned ncvs = NUMBER_OF_CVS;// Number of CVs
const unsigned spans = ncvs - deg; // Number of spans
const unsigned nknots = spans+2*deg-1;// Number of knots
unsigned i;
MPointArray controlVertices;
MDoubleArray knotSequences;
int upFactor;
if (upDown) upFactor = -1;
else upFactor = 1;
// Set up cvs and knots for the helix
//
for (i = 0; i < ncvs; i++)
controlVertices.append( MPoint(
radius * cos( (double)i ),
upFactor * pitch * (double)i,
radius * sin( (double)i ) ) );
for (i = 0; i < nknots; i++)
knotSequences.append( (double)i );
// Now create the curve
//
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( controlVertices,
knotSequences, deg, MFnNurbsCurve::kOpen,
false, false, MObject::kNullObj, &stat );
if ( !stat )
{
stat.perror("Error creating curve");
return stat;
}
stat = curveFn.getPath( path );
return stat;
}
MStatus helixTool::undoIt()
{
MStatus stat;
MObject transform = path.transform();
stat = MGlobal::removeFromModel( transform );
return stat;
}
bool helixTool::isUndoable() const
{
return true;
}
這里和前面的例子類似,其實只要做很少的修改就可以把command變成tool。
MStatus helixTool::finalize()
{
MArgList command;
command.addArg( commandString() );
command.addArg( MString(kRadiusFlag) );
command.addArg( radius );
command.addArg( MString(kPitchFlag) );
command.addArg( pitch );
command.addArg( MString(kNumberCVsFlag) );
command.addArg( (int)numCV );
command.addArg( MString(kUpsideDownFlag) );
command.addArg( upDown );
return MPxToolCommand::doFinalize( command );
}
因為tool從UI調用而不是命令行,所以不能像一般command那樣輸出日志,所以需要finalize()來做這件事。
void helixTool::setRadius( double newRadius )
{
radius = newRadius;
}
void helixTool::setPitch( double newPitch )
{
pitch = newPitch;
}
void helixTool::setNumCVs( unsigned newNumCVs )
{
numCV = newNumCVs;
}
void helixTool::setUpsideDown( double newUpsideDown )
{
upDown = newUpsideDown;
}
const char helpString[] = "Click and drag to draw helix";
class helixContext : public MPxContext
{
用來執行helixTool command的context。
public:
helixContext();
virtual void toolOnSetup( MEvent & event );
virtual MStatus doPress( MEvent & event );
virtual MStatus doDrag( MEvent & event );
virtual MStatus doRelease( MEvent & event );
virtual MStatus doEnterRegion( MEvent & event );
private:
short startPos_x, startPos_y;
short endPos_x, endPos_y;
unsigned numCV;
bool upDown;
M3dView view;
GLdouble height,radius;
};
helixContext::helixContext()
{
setTitleString( "Helix Tool" );
}
void helixContext::toolOnSetup( MEvent & )
{
setHelpString( helpString );
}
MStatus helixContext::doPress( MEvent & event )
{
event.getPosition( startPos_x, startPos_y );
view = MGlobal::active3dView();
view.beginGL();
view.beginOverlayDrawing();
return MS::kSuccess;
}
和前面的例子差不多,只是在doPress()方法中不需要檢測鍵盤。
MStatus helixContext::doDrag( MEvent & event )
{
event.getPosition( endPos_x, endPos_y );
view.clearOverlayPlane();
glIndexi( 2 );
int upFactor;
if (upDown) upFactor = 1;
else upFactor = -1;
// Draw the guide cylinder
//
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glRotatef( upFactor * 90.0, 1.0f, 0.0f, 0.0f );
GLUquadricObj *qobj = gluNewQuadric();
gluQuadricDrawStyle(qobj, GLU_LINE);
GLdouble factor = (GLdouble)numCV;
radius = fabs(endPos_x - startPos_x)/factor + 0.1;
height = fabs(endPos_y - startPos_y)/factor + 0.1;
gluCylinder( qobj, radius, radius, height, 8, 1 );
glPopMatrix();
繪制表示螺旋線輪廓的圓柱。
#ifndef _WIN32
glXSwapBuffers(view.display(), view.window() );
#else
SwapBuffers(view.deviceContext() );
#endif
return MS::kSuccess;
}
MStatus helixContext::doRelease( MEvent & )
{
// Clear the overlay plane & restore from overlay drawing
//
view.clearOverlayPlane();
view.endOverlayDrawing();
view.endGL();
helixTool * cmd = (helixTool*)newToolCommand();
cmd->setPitch( height/NumCVs );
cmd->setRadius( radius );
cmd->setNumCVs( numCV );
cmd->setUpsideDown( upDown );
cmd->redoIt();
cmd->finalize();
調用helixTool::creator創建真正的command,調用redoIt() 生成數據,調用finalize()輸出日志。
return MS::kSuccess;
}
MStatus helixContext::doEnterRegion( MEvent & )
{
return setHelpString( helpString );
}
void helixContext::getClassName( MString &name ) const
{
name.set("helix");
}
下面的四個方法用于context和context command的編輯和訪問方法間的交互,會被tool property sheet調用。MToolsInfo::setDirtyFlag()告訴tool property sheet參數改變需要重繪。
void helixContext::setNumCVs( unsigned newNumCVs )
{
numCV = newNumCVs;
MToolsInfo::setDirtyFlag(*this);
}
void helixContext::setUpsideDown( bool newUpsideDown )
{
upDown = newUpsideDown;
MToolsInfo::setDirtyFlag(*this);
}
unsigned helixContext::numCVs()
{
return numCV;
}
bool helixContext::upsideDown()
{
return upDown;
}
下面的類和選取框例子相仿。
class helixContextCmd : public MPxContextCommand
{
public:
helixContextCmd();
virtual MStatus doEditFlags();
virtual MStatus doQueryFlags();
virtual MPxContext* makeObj();
virtual MStatus appendSyntax();
static void* creator();
protected:
helixContext * fHelixContext;
};
helixContextCmd::helixContextCmd() {}
MPxContext* helixContextCmd::makeObj()
{
fHelixContext = new helixContext();
return fHelixContext;
}
void* helixContextCmd::creator()
{
return new helixContextCmd;
}
下面的方法做參數解析。有兩類參數,一類修改context屬性,一類訪問context屬性。
注釋
參數解析通過MPxContextCommand::parser()方法完成,它返回的MArgParser類與MArgDatabase類相似。
MStatus helixContextCmd::doEditFlags()
{
MArgParser argData = parser();
if (argData.isFlagSet(kNumberCVsFlag)) {
unsigned numCVs;
status = argData.getFlagArgument(kNumberCVsFlag,
0, numCVs);
if (!status) {
status.perror("numCVs flag parsing failed.");
return status;
}
fHelixContext->setNumCVs(numCVs);
}
if (argData.isFlagSet(kUpsideDownFlag)) {
bool upsideDown;
status = argData.getFlagArgument(kUpsideDownFlag,
0, upsideDown);
if (!status) {
status.perror("upsideDown flag parsing failed.");
return status;
}
fHelixContext->setUpsideDown(upsideDown);
}
return MS::kSuccess;
}
MStatus helixContextCmd::doQueryFlags()
{
MArgParser argData = parser();
if (argData.isFlagSet(kNumberCVsFlag)) {
setResult((int) fHelixContext->numCVs());
}
if (argData.isFlagSet(kUpsideDownFlag)) {
setResult(fHelixContext->upsideDown());
}
return MS::kSuccess;
}
MStatus helixContextCmd::appendSyntax()
{
MStatus status;
MSyntax mySyntax = syntax();
if (MS::kSuccess != mySyntax.addFlag(kNumberCVsFlag,
kNumberCVsFlagLong, MSyntax::kUnsigned)) {
return MS::kFailure;
}
if (MS::kSuccess != mySyntax.addFlag(kUpsideDownFlag,
kUpsideDownFlagLong, MSyntax::kBoolean)) {
return MS::kFailure;
}
return MS::kSuccess;
}
MStatus initializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin( obj, "Alias", "1.0", "Any");
// Register the context creation command and the tool
// command that the helixContext will use.
//
status = plugin.registerContextCommand(
"helixToolContext", helixContextCmd::creator,
"helixToolCmd", helixTool::creator,
helixTool::newSyntax);
if (!status) {
status.perror("registerContextCommand");
return status;
}
return status;
}
initializePlugin()同時注冊command和對應的context。
MStatus uninitializePlugin( MObject obj)
{
MStatus status;
MFnPlugin plugin( obj );
// Deregister the tool command and the context
// creation command.
//
status = plugin.deregisterContextCommand(
"helixToolContext" "helixToolCmd");
if (!status) {
status.perror("deregisterContextCommand");
return status;
}
return status;
}
必須使用和選取框例子中類似的MEL代碼把helixTool添加到用戶界面。
--------------------------------------------------------------------------------
DAG層級
DAG層級概覽
在Maya中,有向無環圖(DAG)用來定義如坐標、方向、幾何體尺寸等元素。DAG包含兩種DAG節點,transforms和shapes。
Transform nodes保存變換信息(平移、旋轉、縮放等)和父子關系信息。例如,你有一個手的模型,你只想通過一次變換操作同時完成對手掌和手指的旋轉,而不是單獨操作它們,這時手掌和手指就共享一個父級transform節點。
Shape nodes參考幾何體,不提供父子關系信息和變換信息。
在最簡單的情形下,DAG描述了一個幾何體如何構成對象實例。例如,當你創建一個球體,你既創造了表示球體本身的shape node,又創造了允許你指定球體位置、大小和旋轉的transform node,shape node是transform node的子節點。
節點(Nodes)
transform nodes可擁有多個子節點,這些子節點被組合起來放在transform node之下。對節點的組合允許節點間共享變換信息,并被當作一個單元處理。
實例化
transform node和shape nodes都可以擁有多個父節點,這些節點是已被實例化的。實例化可以減少模型的幾何體儲存量。例如,當你建一棵樹的模型時,你可以創建許多獨立的葉子,但這會帶來很大的數據量,因為每片葉子都會有自己的transform nodes和shape nodes及NURBS或多邊形數據。但是你也可以只創建一片葉子并將它實例化許多次來創建一系列相同的葉子,并把它們各自正確擺放在樹枝上,這樣樹葉的shape node和NURBS或多邊形數據就被共享了。
--------------------------------------------------------------------------------
PlugInsDAGhierarchya.jpg
描述:
文件大小: 5.89 KB
看過的: 文件被下載或查看 229 次
--------------------------------------------------------------------------------
返回頁首
LEN3D
二星視客
注冊時間: 2002-02-10
帖子: 499
視幣:643
發表于: 2005-12-31 11:08 發表主題:
--------------------------------------------------------------------------------
圖示的DAG層級有三個transform nodes(Transform1, Transform2, Transform3)和一個shape node(Leaf),當Transform3和Leaf被實例化后會顯示兩片葉子。
Transforms和Shapes
DAG節點是DAG中的簡單實體。它可能擁有雙親、兄弟和孩子并掌握它們的信息,但它不必知道變換和幾何信息。Transforms和Shapes是從DAG節點派生的兩種節點。transform nodes只負責變換(平移、旋轉和縮放)而不包含幾何信息,shape nodes只負責幾何信息而不包含變換。這意味著一個幾何體需要兩個節點,一個shape node直接位于其父級,一個transform node位于shape node的父級。
例如:
MFnDagNode用來決定節點有哪些父節點。
MFnTransformNode繼承自MFnDagNode的用來操作transform nodes的function set,可以獲取并設置變換。
MFnNurbsSurface是多種操作不同類型的shape nodes的function set中的一種,也從MFnDagNode派生,有獲取和設置曲面CVs等的方法。
DAG路徑(paths)
路徑通過一系列節點指定某個節點或節點實例在DAG中的唯一位置,這一系列節點從根節點開始,直到目標節點。到同一個目標節點的不同路徑對應于一個目標節點的實例。路徑的顯示形式是從根節點開始的一系列節點的名字,用"|"符號隔開。
DAG路徑和API中世界空間的操作
因為DAG路徑表示一個shape是如何被插入場景的,所以世界空間的任何操作都要通過DAG路徑完成。如果試圖用MObject句柄獲得某個節點組件的世界空間坐標,只會導致失敗,因為沒有DAG路徑Maya無法決定對象的世界空間坐標,只有DAG路徑能唯一指定節點的某個實例。幾乎所有能返回MObject的方法都會返回MDagPath句柄用于指明路徑。所有MFn類都既可以用MObject又可以用MDagPath構造。用MObject進行世界空間操作會失敗,換作MDagPath則會成功。
添加或刪除節點
MDagPath用一個節點的堆棧來表示路徑,根節點在堆棧底部。push()和pop()方法可以用來添加或刪除節點。
注釋
這些方法不會改變真正的DAG結構,只會改變MDagPath對象本身。
包含和排除矩陣
因為DAG中的節點存在于不同的DAG層級,所以每個節點上可能有不同的變換積累。MDagPath允許把這些變換通過inclusiveMatrix()和exclusiveMatrix()兩種模式返回。
"inclusive matrix"考慮了最后一個節點對變換的影響。
"exclusive matrix"不考慮最后一個節點對變換的影響。
例如,如果一條路徑定義如下:
|RootTransform|Transform1|Transform2|Shape
inclusive matrix考慮RootTransform, Transform1和Transform2的影響,而exclusive matrix只考慮RootTransform和Transform1的影響。
為何將shape node添加到DAG路徑
在Maya中,物體級別的選擇實際上是選擇了shape node的父級transform node,當用MGlobal::getActiveSelectionList()訪問選擇集時,MDagPath只會返回transform node而不是真正的shape。extendToShape()可以方便的把shape node添加到路徑末端。
應用于某種MDagPath的function set通過路徑的最后一個node獲得。如果最后一個node是transform node,就可以獲得用來操作MDagPath實例的function set。如果最后一個node是shape node,就可以獲得用來操作shape的function set。
唯一的名字
使用DAG路徑后對象名字可以重用,只要同名的對象不在相同的父級節點下。
返回頁首
--------------------------------------------------------------------------------
Generalized instancing
Maya支持generalized instancing,意即實例化同一個節點的節點不必互為
--------------------------------------------------------------------------------
返回頁首
--------------------------------------------------------------------------------
Node 2和Node 4不是兄弟,但它們都實例化Node 3。可以創造更復雜的層級,只要不破壞DAG的無環性質即可。
帶有多Shapes的Transforms
一個transform node可以有任意數目的子transform nodes。一般上一個transform node只能有一個子shape node,當通過交互窗口查看DAG時總是可以發現這一點。然而通過API檢查DAG時你會發現transform node有多個子shape node,這在原始shape被dependency graph修改后發生。為了保持dependency graph的結果,修改后的shape會被放在和原始shape同一個transform node之下。這時,只有最終的結果會被顯示在交互窗口。
--------------------------------------------------------------------------------
|Transform1|Shape1是原始對象,而|Transform1|Shape1a是在交互窗口中真正可見的對象。|Transform1|Shape1也被稱為中間對象。這點對后面的dependency graph很重要。
警告
如果你對一個最后一個transform node包含多個子shape node的路徑使用MDagPath::extendToShape(),第一個shape node會被添加到路徑末端,如果這不是你想要的,建議你用MDagPath::child()和MDagPath::childCount() 方法代替extendToShape()方法。
The Underworld
The "underworld"指的是shape node的參數空間,例如NURBS曲面的UV空間。節點和整個子圖都可能定義在這樣的underworld空間。
例如,在NURBS曲面上定義一條曲線的transform node和shape node。曲線上的控制點位于曲面的UV空間。指定underworld中節點的路徑位于shape node之下。underworld路徑的第一個節點定義在shape的參數空間,大多屬于transform node。
underworld路徑和正常路徑的表示類似,都使用"|"符號,不同點是在shape node和underworld路徑的根節點間用"->"符號隔開。
例如NURBS曲面上一條曲線的路徑完整表示為
|SurfaceTransform|NURBSSurface->UnderworldTransform|CurvesShape。underworlds可以被遞歸定義,只要一個underworld還有參數空間,就可以有更底層的underworld。
MDagPath包括了訪問underworld不同路徑的方法。MDagPath::pathCount()返回MDagPath表示的路徑總數。在上面的曲面上的曲線的例子中,如果MDagPath表示到curve shape的路徑,那么pathCount為2。MDagPath::getPath()既返回underworld又返回3D空間的路徑。Path 0總指定3D空間,Path 1指定Path 0后的underworld路徑,Path 2指定Path 1后的underworld路徑,依此
--------------------------------------------------------------------------------
返回頁首
遍歷DAG實例
下面的scanDagSyntaxCmd例子示范了如何以深度優先或廣度優先的方式遍歷DAG,這對文件轉換器之類的要遍歷DAG的插件編寫很有幫助。
class scanDagSyntax: public MPxCommand
{
public:
scanDagSyntax() {};
virtual ~scanDagSyntax();
static void* creator();
static MSyntax newSyntax();
virtual MStatus doIt( const MArgList& );
這是一個簡單的例子,所以不提供undoIt()和redoIt()。
private:
MStatus parseArgs( const MArgList& args,
MItDag::TraversalType& traversalType,
MFn::Type& filter, bool & quiet);
MStatus doScan( const MItDag::TraversalType traversalType,
MFn::Type filter, bool quiet);
void printTransformData(const MDagPath& dagPath, bool quiet);
};
scanDagSyntax::~scanDagSyntax() {}
void* scanDagSyntax::creator()
{
return new scanDagSyntax;
}
MSyntax scanDagSyntax::newSyntax()
{
MSyntax syntax;
syntax.addFlag(kBreadthFlag, kBreadthFlagLong);
syntax.addFlag(kDepthFlag, kDepthFlagLong);
syntax.addFlag(kCameraFlag, kCameraFlagLong);
syntax.addFlag(kLightFlag, kLightFlagLong);
syntax.addFlag(kNurbsSurfaceFlag, kNurbsSurfaceFlagLong);
syntax.addFlag(kQuietFlag, kQuietFlagLong);
return syntax;
}
MStatus scanDagSyntax::doIt( const MArgList& args )
{
MItDag::TraversalType traversalType = MItDag::kDepthFirst;
MFn::Type filter = MFn::kInvalid;
MStatus status;
bool quiet = false;
DAG迭代器可以被設定為只訪問特定的類型,如果用MFn::kInvalid模式,則訪問所有DAG節點。
status = parseArgs ( args, traversalType, filter, quiet );
if (!status)
return status;
return doScan( traversalType, filter, quiet);
};
doIt()方法簡單的調用一些做真正工作的輔助方法。
MStatus scanDagSyntax::parseArgs( const MArgList& args,
MItDag::TraversalType& traversalType,
MFn::Type& filter,
bool & quiet)
{
MStatus stat;
MArgDatabase argData(syntax(), args);
MString arg;
if (argData.isFlagSet(kBreadthFlag))
traversalType = MItDag::kBreadthFirst;
else if (argData.isFlagSet(kDepthFlag))
traversalType = MItDag::kDepthFirst;
if (argData.isFlagSet(kCameraFlag))
filter = MFn::kCamera;
else if (argData.isFlagSet(kLightFlag))
filter = MFn::kLight;
else if (argData.isFlagSet(kNurbsSurfaceFlag))
filter = MFn::kNurbsSurface;
if (argData.isFlagSet(kQuietFlag))
quiet = true;
return stat;
}
DAG迭代器能以深度優先或廣度優先的方式訪問DAG。這個例子只訪問cameras, lights和NURBS surfaces,但事實上可以訪問MFn::Type中的任何類型。
MStatus scanDagSyntax::doScan( const MItDag::TraversalType traversalType,
MFn::Type filter,
bool quiet)
{
MStatus status;
MItDag dagIterator( traversalType, filter, &status);
if ( !status) {
status.perror("MItDag constructor");
return status;
}
// Scan the entire DAG and output the name and depth of each node
if (traversalType == MItDag::kBreadthFirst)
if (!quiet)
cout << endl << "Starting Breadth First scan of the Dag";
else
if (!quiet)
cout << endl << "Starting Depth First scan of the Dag";
廣度優先遍歷意思是先訪問兄弟再訪問孩子,深度優先遍歷先訪問孩子再訪問兄弟。
switch (filter) {
case MFn::kCamera:
if (!quiet)
cout << ": Filtering for Cameras\n";
break;
case MFn::kLight:
if (!quiet)
cout << ": Filtering for Lights\n";
break;
case MFn::kNurbsSurface:
if (!quiet)
cout << ": Filtering for Nurbs Surfaces\n";
break;
default:
cout << endl;
}
int objectCount = 0;
for ( ; !dagIterator.isDone(); dagIterator.next() ) {
MDagPath dagPath;
status = dagIterator.getPath(dagPath);
if ( !status ) {
status.perror("MItDag::getPath");
continue;
}
MItDag::getPath()獲取迭代器的當前對象的參考。DAG路徑可提供給function set以操作對象。不推薦用迭代器重新排列DAG。
MFnDagNode dagNode(dagPath, &status);
if ( !status ) {
status.perror("MFnDagNode constructor");
continue;
}
if (!quiet)
cout << dagNode.name() << ": " << dagNode.typeName() << endl;
if (!quiet)
cout << " dagPath: " << dagPath.fullPathName() << endl;
objectCount += 1;
if (dagPath.hasFn(MFn::kCamera)) {
這里檢查當前對象是否為攝像機,是則輸出攝像機信息。
MFnCamera camera (dagPath, &status);
if ( !status ) {
status.perror("MFnCamera constructor");
continue;
}
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
// Extract some interesting Camera data
if (!quiet)
{
cout << " eyePoint: "
<< camera.eyePoint(MSpace::kWorld) << endl;
cout << " upDirection: "
<< camera.upDirection(MSpace::kWorld) << endl;
cout << " viewDirection: "
<< camera.viewDirection(MSpace::kWorld) << endl;
cout << " aspectRatio: " << camera.aspectRatio() << endl;
cout << " horizontalFilmAperture: "
<< camera.horizontalFilmAperture() << endl;
cout << " verticalFilmAperture: "
<< camera.verticalFilmAperture() << endl;
}
} else if (dagPath.hasFn(MFn::kLight)) {
若對象為燈光,則輸出燈光信息。
MFnLight light (dagPath, &status);
if ( !status ) {
status.perror("MFnLight constructor");
continue;
}
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
// Extract some interesting Light data
MColor color;
color = light.color();
if (!quiet)
{
cout << " color: ["
<< color.r << ", "
<< color.g << ", "
<< color.b << "]\n";
}
color = light.shadowColor();
if (!quiet)
{
cout << " shadowColor: ["
<< color.r << ", "
<< color.g << ", "
<< color.b << "]\n";
cout << " intensity: " << light.intensity() << endl;
}
} else if (dagPath.hasFn(MFn::kNurbsSurface)) {
若對象為NURBS曲面,則輸出其信息。
MFnNurbsSurface surface (dagPath, &status);
if ( !status ) {
status.perror("MFnNurbsSurface constructor");
continue;
}
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
// Extract some interesting Surface data
if (!quiet)
{
cout << " numCVs: "
<< surface.numCVsInU()
<< " * "
<< surface.numCVsInV()
<< endl;
cout << " numKnots: "
<< surface.numKnotsInU()
<< " * "
<< surface.numKnotsInV()
<< endl;
cout << " numSpans: "
<< surface.numSpansInU()
<< " * "
<< surface.numSpansInV()
<< endl;
}
} else {
為其它類型,則只輸出變換信息。
// Get the translation/rotation/scale data
printTransformData(dagPath, quiet);
}
}
if (!quiet)
{
cout.flush();
}
setResult(objectCount);
return MS::kSuccess;
}
void scanDagSyntax::printTransformData(const MDagPath& dagPath, bool quiet)
{
該方法用于打印DAG節點的變換信息。
MStatus status;
MObject transformNode = dagPath.transform(&status);
// This node has no transform - i.e., it's the world node
if (!status && status.statusCode () == MStatus::kInvalidParameter)
return;
MFnDagNode transform (transformNode, &status);
if (!status) {
status.perror("MFnDagNode constructor");
return;
}
MTransformationMatrix matrix (transform.transformationMatrix());
if (!quiet)
{
cout << " translation: " << matrix.translation(MSpace::kWorld)
<< endl;
}
double threeDoubles[3];
MTransformationMatrix::RotationOrder rOrder;
matrix.getRotation (threeDoubles, rOrder, MSpace::kWorld);
if (!quiet)
{
cout << " rotation: ["
<< threeDoubles[0] << ", "
<< threeDoubles[1] << ", "
<< threeDoubles[2] << "]\n";
}
matrix.getScale (threeDoubles, MSpace::kWorld);
if (!quiet)
{
cout << " scale: ["
<< threeDoubles[0] << ", "
<< threeDoubles[1] << ", "
<< threeDoubles[2] << "]\n";
}
}
MStatus initializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin ( obj, "Alias - Example", "2.0", "Any" );
status = plugin.registerCommand( "scanDagSyntax",
scanDagSyntax::creator,
scanDagSyntax::newSyntax );
return status;
}
MStatus uninitializePlugin( MObject obj )
{
MStatus status;
MFnPlugin plugin( obj );
status = plugin.deregisterCommand( "scanDagSyntax" );
return status;
}
Dependency graph插件
Dependency graph插件概覽
Dependency graph是Maya的中心,它被用在動畫和構造記錄中。你可以為它添加新的節點來支持全新的操作。
父類描述
可以從12個父類派生新節點,這些類是:
MPxNode 允許創建新的dependency node,從最基本的DG節點派生,無繼承行為。
MPxLocatorNode 允許創建新的locator node,這是DAG對象,不能渲染,但可以繪制在3D視圖中。
MPxIkSolverNode 允許創建新類型的IK解析器。
MPxDeformerNode 允許創建新的變形器。
MPxFieldNode 允許創建新類型的動態場。
MPxEmitterNode 允許創建新類型的動態發射器。
MPxSpringNode 允許創建新類型的動態彈簧。
MPxManipContainer 允許創建新類型的操縱器。
MPxSurfaceShape 允許創建新的DAG對象,經常用來創建新類型的shape,也可以用在其它方面。
MPxObjectSet 允許創建新類型的集合。
MPxHwShaderNode 允許創建新類型的硬件著色器。
MPxTransform 允許創建新類型的變換矩陣。
基本例子
下面的例子是簡單的用戶定義的DG節點,輸入浮點數,輸出該數的正弦值。
#include <string.h>
#include <iostream.h>
#include <math.h>
#include <maya/MString.h>
#include <maya/MFnPlugin.h>
這還是一個插件所以需要MFnPlugin.h,但用不同的方法注冊節點。
#include <maya/MPxNode.h>
#include <maya/MTypeId.h>
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
大多插件DG節點都要用到這些頭文件。
#include <maya/MFnNumericAttribute.h>
有多種不同的attributes,你需要什么依賴于你的節點類型,在本例中只用到數字數據。
class sine : public MPxNode
{
從MPxNode派生用戶定義DG節點。
public:
sine();
每當該節點實例被創建時都會調用構造函數,可能發生在createNode命令被調用,或MFnDependencyNode::create()被調用等時候。
virtual ~sine();
析構函數只在節點真正被刪除時被調用。由于Maya的undo隊列,刪除節點并不真正調用析構函數,因此如果刪除被撤銷,就可以不重新創建節點而直接恢復它。一般只當undo隊列被清空時已刪除的節點的析構函數才會被調用。
virtual MStatus compute( const MPlug& plug,
MDataBlock& data );
compute()是節點的關鍵部分,用來真正通過節點的輸入產生輸出。
static void* creator();
creator()方法的職責和command中的creator一樣,它允許Maya創建節點實例。每次需要新節點實例時它都可能由createNode或MFnDependencyNode::create()方法。
static MStatus initialize();
initialize()方法由注冊機制在插件被載入時立即調用,用來定義節點的輸入和輸出(如attributes)。
public:
static MObject input;
static MObject output;
這兩個MObject是正弦節點的attributes,你可以給節點的attributes起任何名字,這里用input和output只是為了清晰。
static MTypeId id;
每個節點都需要一個唯一的標識符,用在MFnDependencyNode::create()中以指明創建哪個節點,并用于Maya文件格式。
局部測試中你可以使用任何介于0x00000000和0x0007ffff之間的標識符,但對于任何想永久使用的節點,你應該從Alias技術支持獲得唯一的id。
};
MTypeId sine::id( 0x80000 );
初始化節點標識符。
MObject sine::input;
MObject sine::output;
初始化attributes為NULL。
void* sine::creator() {
return new sine;
}
這里creator()方法簡單返回新節點實例。在更復雜的情況中可能需要相互連接很多節點,可以只定義一個creator來分配和連接所有節點。
MStatus sine::initialize() {
MFnNumericAttribute nAttr;
本例只用到數字數據所以只需要MFnNumericAttribute。
output = nAttr.create( "output", "out",
MFnNumericData::kFloat, 0.0 );
nAttr.setWritable(false);
nAttr.setStorable(false);
定義輸出attribute。定義attribute時你必須指明一個長名字(大于等于四個字符)和一個短名字(小于等于三個字符)。這些名字用在MEL腳本和UI編輯器中以區別特殊的attributes。除特殊情況外,建議attribute的長名字和其C++中的名字相同,本例中都取為"output"。
create方法還指明了attribute的類型,這里為浮點數(MFnNumericData::kFloat)并初始化為0,a? 評論這張
?
?
?
?
?
?