事实上着就是MAYA4.5完全手册插件篇的内容
不過著好象侵權(quán)了,因為ALIAS聲明不得一任何方式傳播該手冊的部分或全部_炙墨追零
Maya不為插件提供二進(jìn)制兼容性。每當(dāng)發(fā)布新版本時,舊插件的源代碼要重新編譯。然而,我們的目標(biāo)是保持源代碼兼容性,在大多情況下,不需要修改源代碼。也許我們以后會提供支持二進(jìn)制兼容性的API。
IRIX,Windows,Linux和Mac OS X上的Maya API
Maya API是提供從內(nèi)部訪問Maya的C++ API,它由一系列與Maya不同功能有關(guān)的庫組成。這些庫是:
OpenMaya包含定義節(jié)點(diǎn)和命令的基本類
OpenMayaUI包含用于創(chuàng)建用戶界面元素(如manipulators, contexts, and locators)的類
OpenMayaAnim用于創(chuàng)建動畫的類,包括deformers和inverse kinematics
OpenMayaFX包含用于dynamics的類
OpenMayaRender包含用于執(zhí)行渲染的類
載入插件
有兩種裝載和卸載插件的方法。最簡單的是用Plug-in Manager,另一種是用loadPlugin命令。二者都搜索環(huán)境變量MAYA_PLUG_IN_PATH指定的路徑。
卸載插件
用unloadPlugin命令帶上插件名卸載插件。
注釋
插件必須在重編譯前被卸載,否則Maya會崩潰。
卸載插件前必須移除場景中所有的參考和插件中定義的節(jié)點(diǎn),還要清空undo隊列,因為插件的影響還可能被保留其中。
當(dāng)你在插件使用中強(qiáng)制卸載它,就無法重載。因為現(xiàn)存的節(jié)點(diǎn)被轉(zhuǎn)換為Unknown,重載插件時這些節(jié)點(diǎn)不會恢復(fù)。
寫一個簡單的插件
下面演示如何寫一個簡單的Hello World插件。
#include <maya/MSimple.h>
DeclareSimpleCommand( helloWorld, "Alias", "6.0");
MStatus helloWorld::doIt( const MArgList& )
{
printf("Hello World\n");
return MS::kSuccess;
}
編譯后在命令窗口鍵入helloWorld,按數(shù)字鍵盤上的Enter執(zhí)行。
重要的插件特性
以上例子展示了很多重要特性。
MSimple.h
用于簡單的command plug-in的頭文件,通過DeclareSimpleCommand宏注冊新command,但這樣你只能創(chuàng)建一個command。
注釋
可能經(jīng)常需要創(chuàng)建執(zhí)行許多特性的插件,例如dependency graph nodes和commands,在這種情況下MSimple.h不再可用,你要自己寫注冊代碼告知Maya插件的功能。
這個宏的主要缺陷是只能創(chuàng)建不能撤銷的命令。
MStatus
指明方法是否成功。API類中大部分方法返回MStatus。為防止命名空間沖突,我們用MS名字空間,如MS::kSuccess
注釋
API很少用status codes,但如果錯誤記錄被開啟,額外的錯誤細(xì)節(jié)會被寫入日志文件。
DeclareSimpleCommand
DeclareSimpleCommand宏需要三個參數(shù):類名,作者名,命令版本號
注釋
不支持undo的命令不應(yīng)該改變場景狀態(tài),否則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相似的作用。該類提供獲得多種類型參數(shù)(如integer,double,string,vector)的方法。
下面的例子用于創(chuàng)建螺旋線,有pitch和radius兩個參數(shù)。
#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中的零元素是參數(shù)而不像argc/argv中是命令名。
用插件創(chuàng)建曲線
#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
發(fā)表于: 2005-12-31 11:03 發(fā)表主題:
--------------------------------------------------------------------------------
同Maya交互
Maya API包含四種C++對象用于和Maya交互,它們是wrappers, objects, function sets和proxies。
API中的物體所有權(quán)
object和function set的結(jié)合類似于wrapper,但區(qū)別在所有權(quán)上。API中物體所有權(quán)很重要,如果沒有很好定義,你可能會刪除一些系統(tǒng)需要或者已經(jīng)刪除的東西。wrappers,objects,function sets解決了這類問題。
MObject
對所有Maya物體(curves, surfaces, DAG nodes, dependency graph nodes, lights, shaders, textures等)的訪問是通過句柄MObject完成的。這個句柄提供了一些簡單的方法來辨別物體類型。MObject的析構(gòu)函數(shù)并不真正刪除它所參考的Maya物體,調(diào)用析構(gòu)函數(shù)只會刪除句柄本身而維持所有權(quán)。
重要提示
絕對不要在插件調(diào)用外儲存指向MObject的指針。
Wrappers
wrappers為像vectors,matrices這樣的簡單對象存在。它們一般都被完整的實(shí)現(xiàn),帶有公用的構(gòu)造和析構(gòu)函數(shù)。API方法可能會返回一個接下來由你負(fù)責(zé)的wrapper。你可以任意分配和刪除它們。前面例子中的MPointArray和MDoubleArray就是wrappers,你擁有wrappers的所有權(quán)。
Objects和Function Sets
objects和function sets總被一同使用。它們相對獨(dú)立是因為所有權(quán)問題,objects總被Maya擁有,而function sets屬于你。
Function Sets
function sets是操作對象的C++類。在前面的例子中MFnNurbsCurve就是function set,MFn前綴說明了這一點(diǎn)。
下面兩行創(chuàng)建新曲線。
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( ... );
MFnNurbsCurve curveFn;創(chuàng)建包含操作曲線方法的function set, create方法用來創(chuàng)建新曲線。
MObject curve = curveFn.create( ... );創(chuàng)建隨后你可以任意使用的Maya對象。
如果你再加上一行:
curve = curveFn.create( ... );
另一條曲線會被創(chuàng)建,名為curve的MObject現(xiàn)在指向新創(chuàng)建的這條曲線,但原先創(chuàng)建的曲線仍然存在,只不過不被句柄參考。
Proxies
Maya通過proxy對象創(chuàng)建新對象類型。proxy對象是你創(chuàng)建的但是被Maya占有。
一個普遍的誤解是以為可以通過繼承現(xiàn)存的function set來創(chuàng)建新對象類型,例如MFnNurbsSurface從MFnDagNode派生。但實(shí)際上這樣不行,因為function set完全被你擁有,Maya根本不使用它們,Maya只用MObject指向的物體。
無類型
分開objects和function sets帶來的一個有趣結(jié)果,API操作對象時可以不顧類型,例如:
MFnNurbsCurve curveFn;
MObject curve = curveFn.create( ... );
MFnNurbsSurface surface( curve );
MFnNurbsSurface只操作surface對象,以上的例子是錯的,但是你可能沒有發(fā)覺。API中的錯誤檢查代碼會處理這種初始化錯誤。
function sets接受任何類型的MObjects,如果它不認(rèn)識該物體,就忽略物體并返回錯誤值。
命名習(xí)慣
Maya API使用以下前綴來區(qū)別不同類型的對象。
MFn
表示function set
MIt
迭代器,功能和function set類似但用于操作單獨(dú)的對象。
MPx
表示proxy對象,你可以繼承它們來創(chuàng)建自己的對象類型。
M classes
大多是wrappers但也有例外。MGlobal是包含很多靜態(tài)方法的類用于全局操作,并不需要MObject。
添加參數(shù)
上面的螺旋線插件生成簡單的曲線,但每次結(jié)果都一樣。
為曲線的例子添加參數(shù)
通過一些改變可以添加如radius和pitch這樣的參數(shù),注意下面函數(shù)參數(shù)的聲明多了一個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循環(huán)遍歷所有MArgList中的參數(shù),兩個if語句把參數(shù)轉(zhuǎn)換成MString并與可能的值做比較。
如果匹配,后一個參數(shù)就被轉(zhuǎn)換成double并且賦給對應(yīng)的值,例如:
doHelix -p 0.5 -r 5
會生成一個pitch為0.5單位長,radius為5單位長的螺旋線。
錯誤檢查
在上面的例子中還未涉及錯誤檢查問題。
大部分的方法提供一個可選參數(shù),是一個指向MStatus的指針,用于返回值。
下面的參數(shù)解析代碼包含了錯誤檢查:
// 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參數(shù),用于檢查操作是否成功。
例如args.asString(i, &stat)可能會返回MS::kFailure,索引值大于參數(shù)數(shù)量或者當(dāng)不能轉(zhuǎn)換成double值時args.asDouble(++i, &stat)會失敗。
MStatus類
MStatus類用于確定方法是否成功。
Maya API既返回MStatus也給可選的MStatus參數(shù)賦值。MStatus類包含error方法并重載了bool操作符,它們都能用來檢查錯誤,例如:
MStatus stat = MGlobal::clearSelectionList;
if (!stat) {
// Do error handling
...
}
如果MStatus實(shí)例包含錯誤,你可以做以下事:
用statusCode方法獲得具體的錯誤原因。
用errorString方法獲得錯誤細(xì)節(jié)描述。
用perror打印錯誤細(xì)節(jié)描述。
用重載的相等和不相等操作符來和某個MStatusCode做比較。
用clear方法把MStatus實(shí)例設(shè)置為成功狀態(tài)。
錯誤記錄
同使用MStatus一樣,你也可以用錯誤記錄檢查錯誤。
開啟和關(guān)閉錯誤記錄:
1. 在MEL中用openMayaPref命令加上-errlog標(biāo)識。
2. 在插件中調(diào)用MGlobal::startErrorLogging()和MGlobal::stopErrorLogging()方法。
一旦開啟錯誤記錄,每次插件發(fā)生錯誤都會被Maya記錄在文件中,還會包含錯誤在何處引發(fā)的描述。
默認(rèn)文件名是OpenMayaErrorLog,在當(dāng)前目錄下。
可以用MGlobal::setErrorLogPathName改變錯誤記錄的目錄。
提示
插件可以用MGlobal::doErrorLogEntry()向記錄文件中添加自己的記錄。
--------------------------------------------------------------------------------
用API選擇
概覽用API選擇
一個命令經(jīng)常從選擇列表獲取輸入。MGlobal::getActiveSelectionList() 方法的結(jié)果包含所有當(dāng)前被選擇的物體。通過MSelectionList和MItSelectionList兩個API類可以容易的檢查和修改選擇列表。
MGlobal::setActiveSelectionList()
可以通過MGlobal::setActiveSelectionList()獲得當(dāng)前全局選擇列表的拷貝。
在調(diào)用MGlobal::setActiveSelectionList()前,你對返回的選擇列表的任何改變都不會真正影響到場景。
你可以創(chuàng)建自己的MSelectionList來與其它列表合并,列表可以用來創(chuàng)建對象集合。
MSelectionList
MSelectionList提供向選擇列表中添加、刪除和遍歷對象的方法。
下面的例子打印所有被選中的DAG節(jié)點(diǎn)的名字。
簡單的插件例子
#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的所有子類繼承,用于設(shè)置該function set將要操作的對象。通常這在構(gòu)造函數(shù)中完成,但如果function set已經(jīng)被創(chuàng)建并且你想改變它要操作的對象,就使用setObject(),這比每次都重新創(chuàng)建和銷毀function set有效率的多。
當(dāng)你選擇CVs并調(diào)用該插件時,不會得到CVs的名字,而是得到父對象(如curve,surface,mesh)的名字,并且打印名字的數(shù)量和選擇物體的數(shù)量不同。
Maya簡化像CVs這樣的對象組件的選擇,不是把每個組件都添加到選擇列表,而是添加父對象并把組件當(dāng)成一個組。
例如,當(dāng)nurbSphereShape1的很多CVs被選中,list.getDagPath() 會返回一個指向nurbSphereShape1 的MDagPath和一個包含了所有被選中的CVs的MObject。這里的MDagPath和MObject可以被傳遞給MItSurfaceCV迭代器來遍歷所有選中的CVs。
只要你繼續(xù)選擇一個對象的組件,選擇列表中的對象只會有一個。然而如果你選擇了一個對象中的某些組件和另一個對象中的某些組件,然后再選擇第一個對象中的某些組件,那么第一個對象會在選擇列表中出現(xiàn)兩次。這樣你可以決定物體被選擇的順序。所有組件也被按它們被選中的順序排列。
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的例子可以用這些代碼代替,結(jié)果完全相同。
當(dāng)把MItSelectionList的構(gòu)造函數(shù)改成:
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()返回字符串?dāng)?shù)組,描述了function sets的類型。
MGlobal::selectByName()
MGlobal::selectByName()方法將所有匹配的對象添加到當(dāng)前選擇列表,例如:
MGlobal::selectByName( "*Sphere*" );
選擇所有名字中包含Sphere的東西。
提示
你也可以不必創(chuàng)建MSelectionList而直接用MGlobal::select()往全局選擇列表添加對象。
--------------------------------------------------------------------------------
Command plug-ins
向Maya添加commands概覽
Plug-ins
API支持多種類型的插件:
Command plug-ins提供命令來擴(kuò)展MEL
Tool commands獲得鼠標(biāo)輸入的插件
Dependency graph plug-ins添加新的操作,如dependency graph nodes
Device plug-ins允許新的設(shè)備與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創(chuàng)建類的實(shí)例。
initializePlugin()
initializePlugin()可以被當(dāng)作C或C++函數(shù)定義。你不定義它插件就不會被裝載。
它包含了注冊commands, tools, devices等的代碼,只在插件裝載時被立即調(diào)用一次。
例如commands和tools通過實(shí)例化一個操作MObject的MFnPlugin來注冊。這個MObject包含Maya私有信息如插件名字和目錄,它被傳遞給MFnPlugin的構(gòu)造函數(shù)。"Any"表示Maya API的版本,是默認(rèn)值。
MFnPlugin::registerCommand()用來注冊"hello"命令。如果初始化不成功,插件會被自動卸載。
uninitializePlugin()
uninitializePlugin()用來注銷initializePlugin()注冊的所有東西,只在插件被卸載時被調(diào)用一次。Maya會自己管理的對象不需要在這里銷毀。
Creator methods
插件要注冊的東西Maya事先是不知道的,所以沒辦法決定分配它需要的空間,這時creator用來幫助Maya創(chuàng)建這些東西的實(shí)例。
MPxCommand
從MPxCommand繼承的類至少要定義兩個函數(shù),doIt和creator。
doIt()和redoIt()方法
doIt()方法是純虛的,而且基類中沒有定義creator,所以兩個都要定義。
簡單的command可以讓doIt做所有事,但在復(fù)雜的例子中,doIt()用來解析參數(shù)列表和選擇列表等,并用解析的結(jié)果設(shè)置內(nèi)部數(shù)據(jù),最后再調(diào)用redoIt()來做真正的工作。這樣避免了doIt()和redoIt()間的代碼重復(fù)。
校驗
下面的例子用來演示方法被調(diào)用的順序。
#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()
注意析構(gòu)函數(shù)并沒有被調(diào)用,因為command還有可能被undo和redo。
這是Maya的undo機(jī)制的工作方式。Command objects負(fù)責(zé)保留undo自己需要的信息。析構(gòu)函數(shù)在command掉到undo隊列的末尾或插件被卸載時才被調(diào)用。
如果你修改一下,讓isUndoable()返回false,將得到如下結(jié)果:
In commandExample::creator()
In commandExample::commandExample()
In commandExample::doIt()
In commandExample::isUndoable()
In commandExample::~commandExample()
在這種情況下析構(gòu)函數(shù)立即被調(diào)用,因為不能undo了,Maya認(rèn)為這樣的command不會改變場景,所以使用undo和redo時undoIt()和redoIt()不會被調(diào)用。
帶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來指向要操作的曲線。因為命令下一次被執(zhí)行時無法保證MObject繼續(xù)有效,Maya可能會核心轉(zhuǎn)儲。然而MDagPath卻能保證任何時候都指向正確的曲線。
void* helix2::creator() {
return new helix2;
}
creator簡單返回對象實(shí)例。
helix2::helix2() : radius( 4.0 ), pitch( 0.5 ) {}
初始化radius和pitch的值。
helix2::~helix2() {}
這時析構(gòu)函數(shù)不需要做任何事。
注釋
不應(yīng)該刪除Maya占有的數(shù)據(jù)。
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()里面解析參數(shù)并且設(shè)置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();
}
最后調(diào)用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內(nèi)的MPointArray中,用來在調(diào)用undoIt()時把曲線恢復(fù)為原狀。
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;
}
這段代碼把曲線變?yōu)槁菪€。
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恢復(fù)了。
注釋
不需要擔(dān)心CVs數(shù)量改變或已被刪除,你可以假設(shè)command執(zhí)行后的一切改變都被撤銷了,模型維持不變。
status = curveFn.updateCurve();
if ( MS::kSuccess != status )
{
displayError( "Could not update curve" );
return status;
}
fCVs.clear();
return MS::kSuccess;
}
只是為了以防萬一才調(diào)用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返回結(jié)果,這通過叫"setResult"和"appendToResult"的一系列從MPxCommand繼承的重載函數(shù)完成。例如可以這樣返回值為4的整數(shù):
int result =4;
clearResult();
setResult( result );
也可以多次調(diào)用appendToResult來返回數(shù)組,如:
MPoint result (1.0, 2.0, 3.0);
...
clearResult();
appendToResult( result.x );
appendToResult( result.y );
appendToResult( result.z );
或者直接返回數(shù)組:
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
當(dāng)你寫語法對象時需要用到MSyntax和MArgDatabase,這些類是定義和處理命令標(biāo)記輸入時必需的。
MSyntax用來指定傳遞給commands的標(biāo)記和參數(shù)。
MArgDatabase用于解析傳遞給commands的所有標(biāo)記、參數(shù)和對象的類。它接受MSyntax對象來把命令參數(shù)解析成容易訪問的形式。
注釋
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"
創(chuàng)建Syntax Object
在你的command類中需要寫newSyntax方法建立你的語法。它應(yīng)該是返回MSyntax的靜態(tài)函數(shù)。
在該方法中你應(yīng)該為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;
}
解析參數(shù)
按習(xí)慣一般在parseArgs方法中解析參數(shù)并由doIt調(diào)用,該方法創(chuàng)建一個局部的用syntax object和命令參數(shù)初始化的MArgDatabase。MArgDatabase提供了決定哪些flags被設(shè)置的方便方法。
注釋
除特別情況外,所有API都用Maya內(nèi)部的厘米和弧度作為單位。
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;
}
注冊
創(chuàng)建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用于決定鼠標(biāo)動作如何被解釋。context可以執(zhí)行commands,改變當(dāng)前選擇集,或執(zhí)行繪圖操作等。context還能繪制不同的鼠標(biāo)指針。在Maya中context被表述為tool。
MPxContext
MPxContext允許你創(chuàng)建自己的context。
在Maya中context通過一個特殊的command來創(chuàng)建。在這點(diǎn)上,context類似shape,它通過command創(chuàng)建和修改并具有決定其行為和外觀的狀態(tài)。當(dāng)你通過繼承MPxContext來寫一個context時,你也應(yīng)該為它定義一個從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將執(zhí)行默認(rèn)的動作,所以你只要寫必要的方法即可。
private:
short start_x, start_y;
short last_x, last_y;
MGlobal::ListAdjustment listAdjustment
M3dView view;
};
marqueeContext::marqueeContext()
{
setTitleString ( "Marquee Tool" );
}
構(gòu)造函數(shù)設(shè)置了標(biāo)題文字,當(dāng)工具被選中時會顯示在界面上。
void marqueeContext::toolOnSetup ( MEvent & )
{
setHelpString( helpString );
}
當(dāng)工具被選中該方法會被調(diào)用,在提示行顯示幫助信息。
MStatus marqueeContext::doPress( MEvent & event )
{
當(dāng)工具被選中并且你按下鼠標(biāo)鍵時該方法會被調(diào)用。MEvent對象包含了鼠標(biāo)動作的相關(guān)信息,如單擊的坐標(biāo)。
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;
這里根據(jù)鍵盤動作來決定選擇類型。
event.getPosition( start_x, start_y );
獲得開始選擇處的屏幕坐標(biāo)。
view = M3dView::active3dView();
view.beginGL();
決定激活視圖并開啟OpenGL渲染。
view.beginOverlayDrawing();
return MS::kSuccess;
}
MStatus marqueeContext::doDrag( MEvent & event )
{
當(dāng)你拖動鼠標(biāo)時該方法會被調(diào)用。
event.getPosition( last_x, last_y );
view.clearOverlayPlane();
每次繪制新選擇框前該方法都會被調(diào)用來清空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);
執(zhí)行視圖變換。
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
交換雙緩沖區(qū)。
glDisable( GL_LINE_STIPPLE );
恢復(fù)繪圖模式。
return MS::kSuccess;
}
MStatus marqueeContext::doRelease( MEvent & event )
{
鼠標(biāo)鍵釋放時該方法會被調(diào)用。
MSelectionList incomingList, marqueeList;
MGlobal::ListAdjustment listAdjustment;
view.clearOverlayPlane();
view.endOverlayDrawing();
view.endGL();
繪圖完成,清空overlay planes,關(guān)閉OpenGL渲染。
event.getPosition( last_x, last_y );
決定鼠標(biāo)釋放處的坐標(biāo)。
MGlobal::getActiveSelectionList(incomingList);
獲取并保存當(dāng)前選擇列表。
if ( abs(start_x - last_x) < 2 && abs(start_y - last_y) < 2 )
MGlobal::selectFromScreen( start_x, start_y, MGlobal::kReplaceList );
如果開始和結(jié)束選擇的坐標(biāo)相同,則用單擊選取代替包圍盒選取。
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);
恢復(fù)原選擇列表。
MGlobal::selectCommand(marqueeList, listAdjustment);
按指定方式修改選擇列表。
return MS::kSuccess;
}
MStatus marqueeContext::doEnterRegion( MEvent & )
{
return setHelpString( helpString );
}
當(dāng)你把鼠標(biāo)移到任何視圖時都會調(diào)用該方法。
class marqueeContextCmd : public MPxContextCommand
{
public:
marqueeContextCmd();
virtual MPxContext* makeObj();
static void* creator();
};
MPxContextCommand
MPxContextCommand類用來定義創(chuàng)建contexts的特殊command。context commands和一般的commands一樣可以用命令行調(diào)用或者寫入MEL腳本。它們擁有修改context屬性的編輯和訪問選項。它們創(chuàng)建一個context實(shí)例并傳給Maya。context commands不能撤銷。
創(chuàng)建context command
下面是用來創(chuàng)建前面的選擇框context的context command。
marqueeContextCmd::marqueeContextCmd() {}
MPxContext* marqueeContextCmd::makeObj()
{
return new marqueeContext();
}
用來為Maya創(chuàng)建context實(shí)例的方法。
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;
}
創(chuàng)建context就是這么簡單。
把context command添加到Maya工具架
有兩種方法激活context為當(dāng)前context。第一種是用setToolTo命令后跟context的名字。
第二種方法就是把context的圖表添加到Maya工具架上。Maya工具架可以儲存兩種按鈕,command按鈕和tool按鈕。
下面是用來創(chuàng)建context按鈕和tool按鈕的MEL命令。
marqueeToolContext marqueeToolContext1;
setParent Shelf1;
toolButton -cl toolCluster
-t marqueeToolContext1
-i1 "marqueeTool.xpm" marqueeTool1;
這些MEL代碼創(chuàng)建一個marqueeToolContext實(shí)例并添加到"Common"工具架。
marqueeTool.xpm是工具的圖標(biāo)名,必須在XBMLANGPATH目錄下,否則就不會顯示,但工具依然可用。
這些代碼既可以手工鍵入,又可以在initializePlugin()中用MGlobal::sourceFile()調(diào)用。
Tool property sheets
Tool property sheets是用來顯示和編輯context屬性的交互式編輯器,和用來編輯dependency graph node屬性的attribute editors類似。
實(shí)現(xiàn)一個tool properly sheet必須寫兩個MEL文件,一個用來編輯context,一個用來訪問context。
一個文件叫<yourContextName>Properties.mel,另一個叫<yourContextName>Values.mel,<yourContextName>是context的名字,可以用getClassName()方法獲得。
<>Properties.mel用來定義編輯器外觀。
<>Values.mel用來從編輯器獲得數(shù)值。
要有效實(shí)現(xiàn)tool property sheet,你必須在context command中實(shí)現(xiàn)足夠的編輯和訪問選項,并在MPxContext實(shí)現(xiàn)充分的訪問方法來設(shè)置和獲得內(nèi)部參數(shù)。
MPxToolCommand
MPxToolCommand是創(chuàng)建用來在context中執(zhí)行的commands的基類。tool commands和一般的commands一樣用command flags定義可以用命令行調(diào)用。但它們要做額外的工作,因為它們不從Maya調(diào)用而是從MPxContext調(diào)用。這些工作用來讓Maya正確執(zhí)行undo/redo和日志策略。
如果context想執(zhí)行自己的command,必須在注冊context和context command時注冊這個command。一個context只能和一個tool command對應(yīng)。
下面是綜合了螺旋線和選取框的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 );
當(dāng)tool command屬性由context設(shè)置時這些方法是必要的。
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" );
}
構(gòu)造函數(shù)保存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;
}
這里和前面的例子類似,其實(shí)只要做很少的修改就可以把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調(diào)用而不是命令行,所以不能像一般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
{
用來執(zhí)行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();
調(diào)用helixTool::creator創(chuàng)建真正的command,調(diào)用redoIt() 生成數(shù)據(jù),調(diào)用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調(diào)用。MToolsInfo::setDirtyFlag()告訴tool property sheet參數(shù)改變需要重繪。
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;
}
下面的方法做參數(shù)解析。有兩類參數(shù),一類修改context屬性,一類訪問context屬性。
注釋
參數(shù)解析通過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和對應(yīng)的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中,有向無環(huán)圖(DAG)用來定義如坐標(biāo)、方向、幾何體尺寸等元素。DAG包含兩種DAG節(jié)點(diǎn),transforms和shapes。
Transform nodes保存變換信息(平移、旋轉(zhuǎn)、縮放等)和父子關(guān)系信息。例如,你有一個手的模型,你只想通過一次變換操作同時完成對手掌和手指的旋轉(zhuǎn),而不是單獨(dú)操作它們,這時手掌和手指就共享一個父級transform節(jié)點(diǎn)。
Shape nodes參考幾何體,不提供父子關(guān)系信息和變換信息。
在最簡單的情形下,DAG描述了一個幾何體如何構(gòu)成對象實(shí)例。例如,當(dāng)你創(chuàng)建一個球體,你既創(chuàng)造了表示球體本身的shape node,又創(chuàng)造了允許你指定球體位置、大小和旋轉(zhuǎn)的transform node,shape node是transform node的子節(jié)點(diǎn)。
節(jié)點(diǎn)(Nodes)
transform nodes可擁有多個子節(jié)點(diǎn),這些子節(jié)點(diǎn)被組合起來放在transform node之下。對節(jié)點(diǎn)的組合允許節(jié)點(diǎn)間共享變換信息,并被當(dāng)作一個單元處理。
實(shí)例化
transform node和shape nodes都可以擁有多個父節(jié)點(diǎn),這些節(jié)點(diǎn)是已被實(shí)例化的。實(shí)例化可以減少模型的幾何體儲存量。例如,當(dāng)你建一棵樹的模型時,你可以創(chuàng)建許多獨(dú)立的葉子,但這會帶來很大的數(shù)據(jù)量,因為每片葉子都會有自己的transform nodes和shape nodes及NURBS或多邊形數(shù)據(jù)。但是你也可以只創(chuàng)建一片葉子并將它實(shí)例化許多次來創(chuàng)建一系列相同的葉子,并把它們各自正確擺放在樹枝上,這樣樹葉的shape node和NURBS或多邊形數(shù)據(jù)就被共享了。
--------------------------------------------------------------------------------
PlugInsDAGhierarchya.jpg
描述:
文件大小: 5.89 KB
看過的: 文件被下載或查看 229 次
--------------------------------------------------------------------------------
返回頁首
LEN3D
二星視客
注冊時間: 2002-02-10
帖子: 499
視幣:643
發(fā)表于: 2005-12-31 11:08 發(fā)表主題:
--------------------------------------------------------------------------------
圖示的DAG層級有三個transform nodes(Transform1, Transform2, Transform3)和一個shape node(Leaf),當(dāng)Transform3和Leaf被實(shí)例化后會顯示兩片葉子。
Transforms和Shapes
DAG節(jié)點(diǎn)是DAG中的簡單實(shí)體。它可能擁有雙親、兄弟和孩子并掌握它們的信息,但它不必知道變換和幾何信息。Transforms和Shapes是從DAG節(jié)點(diǎn)派生的兩種節(jié)點(diǎn)。transform nodes只負(fù)責(zé)變換(平移、旋轉(zhuǎn)和縮放)而不包含幾何信息,shape nodes只負(fù)責(zé)幾何信息而不包含變換。這意味著一個幾何體需要兩個節(jié)點(diǎn),一個shape node直接位于其父級,一個transform node位于shape node的父級。
例如:
MFnDagNode用來決定節(jié)點(diǎn)有哪些父節(jié)點(diǎn)。
MFnTransformNode繼承自MFnDagNode的用來操作transform nodes的function set,可以獲取并設(shè)置變換。
MFnNurbsSurface是多種操作不同類型的shape nodes的function set中的一種,也從MFnDagNode派生,有獲取和設(shè)置曲面CVs等的方法。
DAG路徑(paths)
路徑通過一系列節(jié)點(diǎn)指定某個節(jié)點(diǎn)或節(jié)點(diǎn)實(shí)例在DAG中的唯一位置,這一系列節(jié)點(diǎn)從根節(jié)點(diǎn)開始,直到目標(biāo)節(jié)點(diǎn)。到同一個目標(biāo)節(jié)點(diǎn)的不同路徑對應(yīng)于一個目標(biāo)節(jié)點(diǎn)的實(shí)例。路徑的顯示形式是從根節(jié)點(diǎn)開始的一系列節(jié)點(diǎn)的名字,用"|"符號隔開。
DAG路徑和API中世界空間的操作
因為DAG路徑表示一個shape是如何被插入場景的,所以世界空間的任何操作都要通過DAG路徑完成。如果試圖用MObject句柄獲得某個節(jié)點(diǎn)組件的世界空間坐標(biāo),只會導(dǎo)致失敗,因為沒有DAG路徑Maya無法決定對象的世界空間坐標(biāo),只有DAG路徑能唯一指定節(jié)點(diǎn)的某個實(shí)例。幾乎所有能返回MObject的方法都會返回MDagPath句柄用于指明路徑。所有MFn類都既可以用MObject又可以用MDagPath構(gòu)造。用MObject進(jìn)行世界空間操作會失敗,換作MDagPath則會成功。
添加或刪除節(jié)點(diǎn)
MDagPath用一個節(jié)點(diǎn)的堆棧來表示路徑,根節(jié)點(diǎn)在堆棧底部。push()和pop()方法可以用來添加或刪除節(jié)點(diǎn)。
注釋
這些方法不會改變真正的DAG結(jié)構(gòu),只會改變MDagPath對象本身。
包含和排除矩陣
因為DAG中的節(jié)點(diǎn)存在于不同的DAG層級,所以每個節(jié)點(diǎn)上可能有不同的變換積累。MDagPath允許把這些變換通過inclusiveMatrix()和exclusiveMatrix()兩種模式返回。
"inclusive matrix"考慮了最后一個節(jié)點(diǎn)對變換的影響。
"exclusive matrix"不考慮最后一個節(jié)點(diǎn)對變換的影響。
例如,如果一條路徑定義如下:
|RootTransform|Transform1|Transform2|Shape
inclusive matrix考慮RootTransform, Transform1和Transform2的影響,而exclusive matrix只考慮RootTransform和Transform1的影響。
為何將shape node添加到DAG路徑
在Maya中,物體級別的選擇實(shí)際上是選擇了shape node的父級transform node,當(dāng)用MGlobal::getActiveSelectionList()訪問選擇集時,MDagPath只會返回transform node而不是真正的shape。extendToShape()可以方便的把shape node添加到路徑末端。
應(yīng)用于某種MDagPath的function set通過路徑的最后一個node獲得。如果最后一個node是transform node,就可以獲得用來操作MDagPath實(shí)例的function set。如果最后一個node是shape node,就可以獲得用來操作shape的function set。
唯一的名字
使用DAG路徑后對象名字可以重用,只要同名的對象不在相同的父級節(jié)點(diǎn)下。
返回頁首
--------------------------------------------------------------------------------
Generalized instancing
Maya支持generalized instancing,意即實(shí)例化同一個節(jié)點(diǎn)的節(jié)點(diǎn)不必互為
--------------------------------------------------------------------------------
返回頁首
--------------------------------------------------------------------------------
Node 2和Node 4不是兄弟,但它們都實(shí)例化Node 3。可以創(chuàng)造更復(fù)雜的層級,只要不破壞DAG的無環(huán)性質(zhì)即可。
帶有多Shapes的Transforms
一個transform node可以有任意數(shù)目的子transform nodes。一般上一個transform node只能有一個子shape node,當(dāng)通過交互窗口查看DAG時總是可以發(fā)現(xiàn)這一點(diǎn)。然而通過API檢查DAG時你會發(fā)現(xiàn)transform node有多個子shape node,這在原始shape被dependency graph修改后發(fā)生。為了保持dependency graph的結(jié)果,修改后的shape會被放在和原始shape同一個transform node之下。這時,只有最終的結(jié)果會被顯示在交互窗口。
--------------------------------------------------------------------------------
|Transform1|Shape1是原始對象,而|Transform1|Shape1a是在交互窗口中真正可見的對象。|Transform1|Shape1也被稱為中間對象。這點(diǎn)對后面的dependency graph很重要。
警告
如果你對一個最后一個transform node包含多個子shape node的路徑使用MDagPath::extendToShape(),第一個shape node會被添加到路徑末端,如果這不是你想要的,建議你用MDagPath::child()和MDagPath::childCount() 方法代替extendToShape()方法。
The Underworld
The "underworld"指的是shape node的參數(shù)空間,例如NURBS曲面的UV空間。節(jié)點(diǎn)和整個子圖都可能定義在這樣的underworld空間。
例如,在NURBS曲面上定義一條曲線的transform node和shape node。曲線上的控制點(diǎn)位于曲面的UV空間。指定underworld中節(jié)點(diǎn)的路徑位于shape node之下。underworld路徑的第一個節(jié)點(diǎn)定義在shape的參數(shù)空間,大多屬于transform node。
underworld路徑和正常路徑的表示類似,都使用"|"符號,不同點(diǎn)是在shape node和underworld路徑的根節(jié)點(diǎn)間用"->"符號隔開。
例如NURBS曲面上一條曲線的路徑完整表示為
|SurfaceTransform|NURBSSurface->UnderworldTransform|CurvesShape。underworlds可以被遞歸定義,只要一個underworld還有參數(shù)空間,就可以有更底層的underworld。
MDagPath包括了訪問underworld不同路徑的方法。MDagPath::pathCount()返回MDagPath表示的路徑總數(shù)。在上面的曲面上的曲線的例子中,如果MDagPath表示到curve shape的路徑,那么pathCount為2。MDagPath::getPath()既返回underworld又返回3D空間的路徑。Path 0總指定3D空間,Path 1指定Path 0后的underworld路徑,Path 2指定Path 1后的underworld路徑,依此
--------------------------------------------------------------------------------
返回頁首
遍歷DAG實(shí)例
下面的scanDagSyntaxCmd例子示范了如何以深度優(yōu)先或廣度優(yōu)先的方式遍歷DAG,這對文件轉(zhuǎn)換器之類的要遍歷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迭代器可以被設(shè)定為只訪問特定的類型,如果用MFn::kInvalid模式,則訪問所有DAG節(jié)點(diǎn)。
status = parseArgs ( args, traversalType, filter, quiet );
if (!status)
return status;
return doScan( traversalType, filter, quiet);
};
doIt()方法簡單的調(diào)用一些做真正工作的輔助方法。
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迭代器能以深度優(yōu)先或廣度優(yōu)先的方式訪問DAG。這個例子只訪問cameras, lights和NURBS surfaces,但事實(shí)上可以訪問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";
廣度優(yōu)先遍歷意思是先訪問兄弟再訪問孩子,深度優(yōu)先遍歷先訪問孩子再訪問兄弟。
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()獲取迭代器的當(dāng)前對象的參考。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)) {
這里檢查當(dāng)前對象是否為攝像機(jī),是則輸出攝像機(jī)信息。
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節(jié)點(diǎn)的變換信息。
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的中心,它被用在動畫和構(gòu)造記錄中。你可以為它添加新的節(jié)點(diǎn)來支持全新的操作。
父類描述
可以從12個父類派生新節(jié)點(diǎn),這些類是:
MPxNode 允許創(chuàng)建新的dependency node,從最基本的DG節(jié)點(diǎn)派生,無繼承行為。
MPxLocatorNode 允許創(chuàng)建新的locator node,這是DAG對象,不能渲染,但可以繪制在3D視圖中。
MPxIkSolverNode 允許創(chuàng)建新類型的IK解析器。
MPxDeformerNode 允許創(chuàng)建新的變形器。
MPxFieldNode 允許創(chuàng)建新類型的動態(tài)場。
MPxEmitterNode 允許創(chuàng)建新類型的動態(tài)發(fā)射器。
MPxSpringNode 允許創(chuàng)建新類型的動態(tài)彈簧。
MPxManipContainer 允許創(chuàng)建新類型的操縱器。
MPxSurfaceShape 允許創(chuàng)建新的DAG對象,經(jīng)常用來創(chuàng)建新類型的shape,也可以用在其它方面。
MPxObjectSet 允許創(chuàng)建新類型的集合。
MPxHwShaderNode 允許創(chuàng)建新類型的硬件著色器。
MPxTransform 允許創(chuàng)建新類型的變換矩陣。
基本例子
下面的例子是簡單的用戶定義的DG節(jié)點(diǎn),輸入浮點(diǎn)數(shù),輸出該數(shù)的正弦值。
#include <string.h>
#include <iostream.h>
#include <math.h>
#include <maya/MString.h>
#include <maya/MFnPlugin.h>
這還是一個插件所以需要MFnPlugin.h,但用不同的方法注冊節(jié)點(diǎn)。
#include <maya/MPxNode.h>
#include <maya/MTypeId.h>
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
大多插件DG節(jié)點(diǎn)都要用到這些頭文件。
#include <maya/MFnNumericAttribute.h>
有多種不同的attributes,你需要什么依賴于你的節(jié)點(diǎn)類型,在本例中只用到數(shù)字?jǐn)?shù)據(jù)。
class sine : public MPxNode
{
從MPxNode派生用戶定義DG節(jié)點(diǎn)。
public:
sine();
每當(dāng)該節(jié)點(diǎn)實(shí)例被創(chuàng)建時都會調(diào)用構(gòu)造函數(shù),可能發(fā)生在createNode命令被調(diào)用,或MFnDependencyNode::create()被調(diào)用等時候。
virtual ~sine();
析構(gòu)函數(shù)只在節(jié)點(diǎn)真正被刪除時被調(diào)用。由于Maya的undo隊列,刪除節(jié)點(diǎn)并不真正調(diào)用析構(gòu)函數(shù),因此如果刪除被撤銷,就可以不重新創(chuàng)建節(jié)點(diǎn)而直接恢復(fù)它。一般只當(dāng)undo隊列被清空時已刪除的節(jié)點(diǎn)的析構(gòu)函數(shù)才會被調(diào)用。
virtual MStatus compute( const MPlug& plug,
MDataBlock& data );
compute()是節(jié)點(diǎn)的關(guān)鍵部分,用來真正通過節(jié)點(diǎn)的輸入產(chǎn)生輸出。
static void* creator();
creator()方法的職責(zé)和command中的creator一樣,它允許Maya創(chuàng)建節(jié)點(diǎn)實(shí)例。每次需要新節(jié)點(diǎn)實(shí)例時它都可能由createNode或MFnDependencyNode::create()方法。
static MStatus initialize();
initialize()方法由注冊機(jī)制在插件被載入時立即調(diào)用,用來定義節(jié)點(diǎn)的輸入和輸出(如attributes)。
public:
static MObject input;
static MObject output;
這兩個MObject是正弦節(jié)點(diǎn)的attributes,你可以給節(jié)點(diǎn)的attributes起任何名字,這里用input和output只是為了清晰。
static MTypeId id;
每個節(jié)點(diǎn)都需要一個唯一的標(biāo)識符,用在MFnDependencyNode::create()中以指明創(chuàng)建哪個節(jié)點(diǎn),并用于Maya文件格式。
局部測試中你可以使用任何介于0x00000000和0x0007ffff之間的標(biāo)識符,但對于任何想永久使用的節(jié)點(diǎn),你應(yīng)該從Alias技術(shù)支持獲得唯一的id。
};
MTypeId sine::id( 0x80000 );
初始化節(jié)點(diǎn)標(biāo)識符。
MObject sine::input;
MObject sine::output;
初始化attributes為NULL。
void* sine::creator() {
return new sine;
}
這里creator()方法簡單返回新節(jié)點(diǎn)實(shí)例。在更復(fù)雜的情況中可能需要相互連接很多節(jié)點(diǎn),可以只定義一個creator來分配和連接所有節(jié)點(diǎn)。
MStatus sine::initialize() {
MFnNumericAttribute nAttr;
本例只用到數(shù)字?jǐn)?shù)據(jù)所以只需要MFnNumericAttribute。
output = nAttr.create( "output", "out",
MFnNumericData::kFloat, 0.0 );
nAttr.setWritable(false);
nAttr.setStorable(false);
定義輸出attribute。定義attribute時你必須指明一個長名字(大于等于四個字符)和一個短名字(小于等于三個字符)。這些名字用在MEL腳本和UI編輯器中以區(qū)別特殊的attributes。除特殊情況外,建議attribute的長名字和其C++中的名字相同,本例中都取為"output"。
create方法還指明了attribute的類型,這里為浮點(diǎn)數(shù)(MFnNumericData::kFloat)并初始化為0,a? 評論這張
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的事实上着就是MAYA4.5完全手册插件篇的内容的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。