MStatus exampleCameraSetViewCmd::testResults(MPx3dModelView &view) { MObject cstObj = MObject::kNullObj; MStatus stat = view.getCameraSet(cstObj); if (stat != MS::kSuccess) return stat; cout << "fCameraList.length() = " << fCameraList.length() << endl; cout << "fCameraList = " << fCameraList << endl; MFnCameraSet cstFn(cstObj); unsigned int numLayers = cstFn.getNumLayers(); cout << "view.cameraSet.numLayers = " << numLayers << endl; cout << "Cameras:" << endl; for (unsigned int i=0; i<numLayers; i++) { MDagPath camPath; cstFn.getLayerCamera(i, camPath); camPath.extendToShape(); cout << " " << camPath.fullPathName() << endl; } return MS::kSuccess; }
MStatus polyModifierCmd::cacheMeshData() { MStatus status = MS::kSuccess; MFnDependencyNode depNodeFn; MFnDagNode dagNodeFn; MObject meshNode = fDagPath.node(); MObject dupMeshNode; MPlug dupMeshNodeOutMeshPlug; // Duplicate the mesh // dagNodeFn.setObject( meshNode ); dupMeshNode = dagNodeFn.duplicate(); MDagPath dupMeshDagPath; MDagPath::getAPathTo( dupMeshNode, dupMeshDagPath ); dupMeshDagPath.extendToShape(); depNodeFn.setObject( dupMeshDagPath.node() ); dupMeshNodeOutMeshPlug = depNodeFn.findPlug( "outMesh", &status ); MCheckStatus( status, "Could not retrieve outMesh" ); // Retrieve the meshData // status = dupMeshNodeOutMeshPlug.getValue( fMeshData ); MCheckStatus( status, "Could not retrieve meshData" ); // Delete the duplicated node // MGlobal::deleteNode( dupMeshNode ); return status; }
MStatus DDConvexHullCmd::doIt(const MArgList& args) { if (args.length() != 1) { MGlobal::displayError("Needs at least 2 args"); return MS::kFailure; } MString input = args.asString(0); MString output = args.asString(1); // Get the mObject for the input MSelectionList selList; selList.add(input); MDagPath inputMesh; selList.getDagPath(0, inputMesh); // Ensure we're looking at the shape inputMesh.extendToShape(); // Create output object MDagModifier dm; MObject outMeshNode = dm.createNode(MFn::kMesh); MFnDependencyNode outMeshDag(outMeshNode); outMeshDag.setName("poopShape#"); DDConvexHullUtils::hullOpts hullOptions; return DDConvexHullUtils::generateMayaHull(outMeshNode, inputMesh.node(), hullOptions); }
void liqIPRNodeMessage::onOtherNode(const MString &node, std::vector<MString> &updateObjectName) { MStringArray descendents; MString cmd("listRelatives -allDescendents "+node); MGlobal::executeCommand(cmd, descendents); for(int i=0; i<descendents.length(); ++i) { addUpdateObject(updateObjectName, descendents[i]);//record descendents[i] MDagPath dagPath; getDagPathByName(dagPath, descendents[i].asChar()); if( dagPath.node().hasFn(MFn::kTransform) ) { onOtherNode(descendents[i], updateObjectName);//visit descendents[i] } else if( dagPath.node().hasFn(MFn::kMesh) ) { std::vector<std::string> shaderPlugs; liquid::RendererMgr::getInstancePtr()-> getRenderer()->getValidShaderPlugsInShadingGroup(shaderPlugs); IfMErrorWarn(dagPath.extendToShape());//extend to shape std::vector<std::string> shadingGroups; getShadingGroups(dagPath.fullPathName(), shadingGroups); for(std::size_t j=0; j<shadingGroups.size(); ++j)//for each shading group { MString shadingGroup(shadingGroups[j].c_str()); for(std::size_t k=0; k<shaderPlugs.size(); ++k)//for each shader plug { MString shaderPlug(shaderPlugs[k].c_str()); int isShaderPlugExist; cmd = "attributeQuery -node \""+shadingGroup+"\" -ex \""+shaderPlug+"\""; IfMErrorMsgWarn(MGlobal::executeCommand( cmd, isShaderPlugExist), cmd); if( isShaderPlugExist ) { //get the source shade node of $shadingGroup.$shaderPlug MStringArray shaders; cmd = "listConnections -s true -d false -plugs false (\""+shadingGroup+"\" + \"."+shaderPlug+"\")"; IfMErrorMsgWarn(MGlobal::executeCommand( cmd, shaders), cmd); if( shaders.length() > 0 )//has source shader node { onShaderNode(shaders[0], updateObjectName); }//if( shaders.length() > 0 )//has source shader node }//if( isShaderPlugExist ) }//for each shader plug }//for each shading group }//kMesh }//for(int i=0; i<descendents.length(); ++i) }
MStatus polyMessageCmd::doIt( const MArgList& ) // // Takes the nodes that are on the active selection list and adds an // attriubte changed callback to each one. // { MStatus stat; MObject node; MSelectionList list; MCallbackId id; // Register node callbacks for all nodes on the active list. // MGlobal::getActiveSelectionList( list ); for ( unsigned int i=0; i<list.length(); i++ ) { list.getDependNode( i, node ); MDagPath dp; MObject shapeNode = node; if ( MS::kSuccess == MDagPath::getAPathTo( node, dp ) ) if ( MS::kSuccess == dp.extendToShape() ) shapeNode = dp.node(); bool wantIdChanges[3]; wantIdChanges[MPolyMessage::kVertexIndex] = true; wantIdChanges[MPolyMessage::kEdgeIndex] = true; wantIdChanges[MPolyMessage::kFaceIndex] = true; id = MPolyMessage::addPolyComponentIdChangedCallback( shapeNode, wantIdChanges, 3, userCB, NULL, &stat); // If the callback was successfully added then add the // callback id to our callback table so it can be removed // when the plugin is unloaded. // if ( stat ) { callbackIds.append( id ); } else { cout << "MPolyMessage.addCallback failed\n"; } } return stat; }
MStatus updateTCCData::getTCCNode( MSelectionList &selList ) { MStatus status; MItSelectionList selListIter( selList ); selListIter.setFilter( MFn::kMesh ); for( ; !selListIter.isDone(); selListIter.next() ) { MDagPath dagPath; MObject component; selListIter.getDagPath( dagPath, component ); status = dagPath.extendToShape(); if (status == MS::kSuccess) { MFnDependencyNode meshShapeFn(dagPath.node()); MObject outMeshAttr = meshShapeFn.attribute( "outMesh" ); MPlug outMeshPlug(dagPath.node(), outMeshAttr ); // worldMeshPlug = worldMeshPlug.elementByLogicalIndex( 0 ); cout<<"inMesh-connected dagnode name: "<<endl<<" > "<<outMeshPlug.info().asChar()<<endl; MPlugArray plugArray; outMeshPlug.connectedTo(plugArray, true, true); cout<<"connected attrs: "<<plugArray.length()<<endl; for (size_t k=0; k<plugArray.length(); k++) { MObject TCCnode(plugArray[k].node()); MFnDependencyNode TCCDepNode( TCCnode ); cout<<"Dependency node type: "<<TCCDepNode.typeName().asChar()<<endl; if (TCCDepNode.typeName() == "TCC") { fSrcDagPath = dagPath; fTCCnode = TCCnode; fComponent = component; return MS::kSuccess; } } } } return MS::kFailure; }
void OpenSubdivPtexShaderOverride::addTopologyChangedCallbacks( const MDagPath& dagPath, OsdPtexMeshData *data ) { MStatus status = MS::kSuccess; // Extract shape node and add callback to let us know when an attribute changes MDagPath meshDagPath = dagPath; meshDagPath.extendToShape(); MObject shapeNode = meshDagPath.node(); MCallbackId id = MNodeMessage::addAttributeChangedCallback(shapeNode, attrChangedCB, data, &status ); if ( status ) { _callbackIds.append( id ); } else { cerr << "MNodeMessage.addCallback failed" << endl; } }
void skinClusterWeights::doItQuery() { MStatus status; unsigned int i, j; MDoubleArray weights; // To allow "skinClusterWeights -q" to return empty double array setResult(weights); MSelectionList selList; for (i = 0; i < geometryArray.length(); i++) { MDagPath dagPath; MObject component; selList.clear(); selList.add(geometryArray[i]); MStatus status = selList.getDagPath(0, dagPath, component); if (status != MS::kSuccess) { continue; } if (component.isNull()) dagPath.extendToShape(); MObject skinCluster = findSkinCluster(dagPath); if (!isSkinClusterIncluded(skinCluster)) { continue; } MFnSkinCluster skinClusterFn(skinCluster, &status); if (status != MS::kSuccess) { continue; } MIntArray influenceIndexArray; populateInfluenceIndexArray(skinClusterFn, influenceIndexArray); weights.clear(); skinClusterFn.getWeights(dagPath, component, influenceIndexArray, weights); if (weights.length() > 0) { for (j = 0; j < weights.length(); j++) { appendToResult(weights[j]); } } } }
void btSPHCmd::getAABB(const MString &name, MPoint& min, MPoint &max) { _LogFunctionCall("btSPHCmd::getAABB("<< name<<")"); MStatus status = MS::kSuccess; MSelectionList sList; IfMErrorWarn(MGlobal::getSelectionListByName(name, sList)); assert(sList.length()==1); MDagPath dp; IfMErrorWarn(sList.getDagPath(0, dp)); IfMErrorWarn(dp.extendToShape());//particle shape MFnMesh meshFn( dp, &status ); IfMErrorWarn(status); MPointArray positions; IfMErrorWarn(meshFn.getPoints(positions, MSpace::kWorld)); const size_t LEN = positions.length(); for(size_t i=0; i<LEN; ++i) { const MPoint &p = positions[i]; if(p.x<min.x) min.x = p.x; if(p.y<min.y) min.y = p.y; if(p.z<min.z) min.z = p.z; if(p.x>max.x) max.x = p.x; if(p.y>max.y) max.y = p.y; if(p.z>max.z) max.z = p.z; } // MPlug plug; // getPlugValue_asDistance(min.x, meshFn, "boundingBoxMinX"); // getPlugValue_asDistance(min.y, meshFn, "boundingBoxMinY"); // getPlugValue_asDistance(min.z, meshFn, "boundingBoxMinZ"); // getPlugValue_asDistance(max.x, meshFn, "boundingBoxMaxX"); // getPlugValue_asDistance(max.y, meshFn, "boundingBoxMaxY"); // getPlugValue_asDistance(max.z, meshFn, "boundingBoxMaxZ"); }
// // Method to add in a light "prune" list. Only selected // lights will be have their shadows requested, and // be used for the scene render shader override. // MStatus viewRenderOverrideShadows::updateLightList() { mLightList.clear(); shadowPrepass* shadowOp = (shadowPrepass*)mRenderOperations[kShadowPrePass]; sceneRender* sceneOp = (sceneRender*)mRenderOperations[kMaya3dSceneRender]; if (!shadowOp || !sceneOp) return MStatus::kFailure; // Scan selection list for active lights // MSelectionList selectList; MDagPath dagPath; MObject component; MGlobal::getActiveSelectionList( selectList ); for (unsigned int i=0; i<selectList.length(); i++) { selectList.getDagPath( i, dagPath, component ); dagPath.extendToShape(); if ( dagPath.hasFn( MFn::kLight ) ) { mLightList.add( dagPath ); } } // Set light list to prune which lights to request shadows for // if (mLightList.length()) shadowOp->setLightList( &mLightList ); else shadowOp->setLightList( NULL ); // Set light list to prune which lights to bind for scene shader // if (mLightList.length()) sceneOp->setLightList( &mLightList ); else sceneOp->setLightList( NULL ); return MStatus::kSuccess; }
void vixo_hairCacheExport::getInCurveInfo(map<int,int>& plugMapVID,MString vixoHairNode,map<int,MVectorArray>& inCurveShape) { MSelectionList slist; MGlobal::getSelectionListByName(vixoHairNode,slist); MDagPath vixoHairNodeDag; slist.getDagPath(0,vixoHairNodeDag); vixoHairNodeDag.extendToShape(); MFnDagNode fnVixoHair(vixoHairNodeDag); MPlug plugInCtrlCurveData=fnVixoHair.findPlug("inCtrlCurveData"); map<int,int>::iterator iterPlugMapVID; for(iterPlugMapVID=plugMapVID.begin();iterPlugMapVID!=plugMapVID.end();iterPlugMapVID++) { MPlug inCurvePlug=plugInCtrlCurveData.elementByLogicalIndex(iterPlugMapVID->first); MFnVectorArrayData fnVector(inCurvePlug.asMObject()); MVectorArray data=fnVector.array(); MVectorArray tangent(data.length()-1); MPlugArray tempArr; inCurvePlug.connectedTo(tempArr,true,false); MFnDependencyNode fnHairSystem(tempArr[0].node()); MPlug inputHairs=fnHairSystem.findPlug("inputHair"); tempArr.clear(); inputHairs.elementByLogicalIndex(iterPlugMapVID->first).connectedTo(tempArr,true,false); MFnDependencyNode fnFolli(tempArr[0].node()); MFnMatrixData fnMatData(fnFolli.findPlug("worldMatrix[0]").asMObject()); MMatrix mat=fnMatData.matrix(); for(int i=0;i<data.length()-1;i++) { tangent[i]=data[i+1]*mat-data[i]*mat; } inCurveShape.insert(pair<int,MVectorArray>(iterPlugMapVID->second,tangent)); } }
void VertexPolyColourCommand::CreateJobListFromSelection(MSelectionList& selection) { // Go through the selection looking for relevant geometry and add them to the list of jobs MItSelectionList iter(selection); for ( ; !iter.isDone(); iter.next() ) { MDagPath dagPath; MObject component; iter.getDagPath( dagPath, component ); // check node type if (dagPath.node().hasFn(MFn::kTransform) || dagPath.node().hasFn(MFn::kPolyMesh) || dagPath.node().hasFn(MFn::kMesh)) { if (component.isNull() || m_operation == OP_UpdateLayerComposite) { dagPath.extendToShape(); AddJob(dagPath, MObject::kNullObj); } else { switch (component.apiType()) { case MFn::kMeshComponent: case MFn::kMeshEdgeComponent: case MFn::kMeshPolygonComponent: case MFn::kMeshVertComponent: case MFn::kMeshVtxFaceComponent: case MFn::kMeshMapComponent: dagPath.extendToShape(); AddJob(dagPath, component); break; default: break; } } } } for (size_t i = 0; i < m_meshes.size(); i++) { MeshData* meshData = m_meshes[i]; if (!MeshHasConstructionHistory(meshData->dagPath)) { m_isRestoreSelection = true; MString meshName = meshData->mesh->fullPathName(); //MGlobal::executeCommand(MString("select -r ") + meshName); //MGlobal::executeCommand("polySmooth -divisions 0"); MGlobal::executeCommand(MString("polySmooth -divisions 0") + meshName); meshData->BuildMesh(); } /* MPlug outMeshPlug, inMeshPlug; MObject intermediate; AddConstructionHistory(meshData->dagPath, outMeshPlug, inMeshPlug, intermediate, NULL); */ } }
HRESULT CMayaManager::PerspectiveCamera_Synchronize() { MDagPath MayaCamera; M3dView panel; for(UINT iView= 0; iView < M3dView::numberOf3dViews(); iView++) { D3DXMATRIX mCamera; M3dView::get3dView(iView, panel); panel.getCamera(MayaCamera); MayaCamera.pop(); MString perspNameStr( "persp" ); MString cameraNameStr = MayaCamera.partialPathName(); cameraNameStr = cameraNameStr.substring(0, perspNameStr.length()-1 ); const char* cameraName= cameraNameStr.asChar(); if(cameraNameStr == perspNameStr ) { MayaCamera.extendToShape(); MFloatMatrix fView(MayaCamera.inclusiveMatrix().matrix ); ConvertWorldMatrix(mCamera, fView); panel.getCamera(MayaCamera); MFnCamera fnMayaCamera(MayaCamera.node()); MVector mUp= fnMayaCamera.upDirection(); MVector mAt= fnMayaCamera.viewDirection(); MPoint mEye= fnMayaCamera.eyePoint(MSpace::kWorld); D3DXVECTOR3 dxEye( (float)mEye.x, (float)mEye.y, (float)-mEye.z ); D3DXVECTOR3 dxAt( (float)mAt.x, (float)mAt.y, (float)-mAt.z ); D3DXVECTOR3 dxUp( (float)mUp.x, (float)mUp.y, (float)-mUp.z ); D3DXVECTOR4 fEye; D3DXVECTOR4 fAt; D3DXVECTOR3 fUp; D3DXVec3Transform(&fEye, &dxEye,(D3DXMATRIX*)&mCamera); D3DXVec3Transform(&fAt, &dxAt,(D3DXMATRIX*)&mCamera); D3DXVec3TransformNormal(&fUp, &dxUp,(D3DXMATRIX*)&mCamera); D3DXMatrixLookAtLH(&PerspectiveCamera_View, (D3DXVECTOR3*)&fEye, (D3DXVECTOR3*)&fAt, &fUp); // Projection matrix float zNear = (float)fnMayaCamera.nearClippingPlane(); float zFar = (float)fnMayaCamera.farClippingPlane(); float hFOV = (float)fnMayaCamera.horizontalFieldOfView(); float f = (float) (1.0f / (float) tan( hFOV / 2.0f )); ZeroMemory( &PerspectiveCamera_Projection, sizeof(PerspectiveCamera_Projection) ); PerspectiveCamera_Projection._11 = f; PerspectiveCamera_Projection._22 = f; PerspectiveCamera_Projection._33 = (zFar+zNear) / (zFar-zNear); PerspectiveCamera_Projection._34 = 1.0f; PerspectiveCamera_Projection._43 = -2 * (zFar*zNear)/(zFar-zNear); break; } } return S_OK; }
MStatus SplitFromImage::doIt(const MArgList& args) { MSelectionList list; MGlobal::getActiveSelectionList(list); MObject node; MFnDependencyNode depFn; MStringArray types; MString name; MDagPath dag; for( MItSelectionList iter( list ); !iter.isDone(); iter.next() ) { // Print the types and function sets of all of the objects iter.getDependNode( node ); depFn.setObject( node ); name = depFn.name(); MGlobal::getFunctionSetList( node, types ); cout << "Name: " << name.asChar() << endl; cout << "Type: " << node.apiTypeStr() << endl; /*cout << "Function Sets: "; for(unsigned int i = 0; i < types.length(); i++ ) { if ( i > 0 ) cout << ", "; cout << types[i].asChar(); } cout << endl << endl;*/ // Check if object has a MDagPath if(iter.getDagPath( dag ) == MS::kSuccess) { // Get the MFnMesh from the MDagPath dag.extendToShape(); MFnMesh mesh(dag.node()); //MPointArray points; //mesh.getPoints(points); //MFloatArray uPoints; //MFloatArray vPoints; //mesh.getUVs(uPoints, vPoints); //for (unsigned int i = 0; i < uPoints.length(); i++) { // cout << "uPoints[" << i << "]: " << uPoints[i] << endl; //} //for(unsigned int i = 0; i < points.length(); i++) { // cout << "Points[" << i << "]: " << points[i] << endl; //} if (splitFromBinaryImage(mesh, args.asString(0)) == MS::kSuccess) { cout << "Splitted image!" << endl; } else { cout << "Could not split image!" << endl; } } else { cout << "Selected object has no MDagPath!" << endl << endl; } } return MS::kSuccess; }
MStatus MayaToCorona::doIt( const MArgList& args) { MStatus stat = MStatus::kSuccess; MGlobal::displayInfo("Executing mayaToCorona..."); logger.setLogLevel(Logging::Debug); MArgDatabase argData(syntax(), args); int width = -1; int height = -1; MayaScene *mayaScene = MayaTo::MayaSceneFactory().getMayaScene(); if( !mayaScene->good ) { logger.error("Problems have occurred during creation of mayaScene(). Sorry cannot proceed.\n\n"); MayaTo::MayaSceneFactory().deleteMaysScene(); return MS::kFailure; } if ( argData.isFlagSet("-width", &stat)) { argData.getFlagArgument("-width", 0, width); logger.debug(MString("width: ") + width); if( width > 0 ) mayaScene->renderGlobals->imgWidth = width; } if ( argData.isFlagSet("-height", &stat)) { argData.getFlagArgument("-height", 0, height); logger.debug(MString("height: ") + height); if( height > 0 ) mayaScene->renderGlobals->imgHeight = height; } if ( argData.isFlagSet("-stopIpr", &stat)) { logger.debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRSTOP; theRenderEventQueue()->push(e); return MS::kSuccess; } if ( argData.isFlagSet("-pauseIpr", &stat)) { logger.debug(MString("-pauseIpr")); logger.debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRPAUSE; theRenderEventQueue()->push(e); return MS::kSuccess; } if ( argData.isFlagSet("-startIpr", &stat)) { logger.debug(MString("-startIpr")); mayaScene->setRenderType(MayaScene::IPR); } if ( argData.isFlagSet("-camera", &stat)) { MDagPath camera; MSelectionList selectionList; argData.getFlagArgument("-camera", 0, selectionList); stat = selectionList.getDagPath(0, camera); camera.extendToShape(); logger.debug(MString("camera: ") + camera.fullPathName()); mayaScene->setCurrentCamera(camera); } EventQueue::Event e; e.type = EventQueue::Event::INITRENDER; theRenderEventQueue()->push(e); RenderQueueWorker::startRenderQueueWorker(); return MStatus::kSuccess; }
MStatus tm_polySplit::doIt( const MArgList& args) { #ifdef _DEBUG cout << endl << "####################################################" << endl; cout << "tm_polySplit::doIt - DEBUG version info:" << endl; #endif MStatus status; MGlobal::getActiveSelectionList( oldSelList ); MArgDatabase argData( syntax(), args); //parse flags // if(argData.isFlagSet( loop_Flag)) { cmd_flag_loop = true; argData.getFlagArgument( loop_Flag, 0, cmd_flag_loop_mode); argData.getFlagArgument( loop_Flag, 1, cmd_flag_loop_angle); // argData.getFlagArgument( loop_Flag, 2, cmd_flag_loop_maxcount); // - max count; } else if(argData.isFlagSet( sel_Flag)) { cmd_flag_loop = false; cmd_flag_sel = true; } MSelectionList selectionList; argData.getObjects( selectionList); MItSelectionList selListIter( selectionList ); selListIter.setFilter( MFn::kMesh ); // The tm_polySplit node only accepts a component list input, so we build // a component list using MFnComponentListData. // // MIntArrays could also be passed into the node to represent the edgesIds, // but are less storage efficient than component lists, since consecutive // components are bundled into a single entry in component lists. // MFnComponentListData compListFn; compListFn.create(); bool found = false; bool foundMultiple = false; MObject meshObj; for( ; !selListIter.isDone(); selListIter.next() ) { MDagPath dagPath; MObject component; selListIter.getDagPath( dagPath, component ); meshObj = dagPath.node(); // Check for selected Edges components // if( component.apiType() == MFn::kMeshEdgeComponent ) { if( !found ) { // The variable 'component' holds all selected components on the selected // object, thus only a single call to MFnComponentListData::add() is needed // to store the selected components for a given object. // compListFn.add( component ); // Copy the component list created by MFnComponentListData into our local // component list MObject member. // fComponentList = compListFn.object(); // Locally store the actual edgesIds of the selected Edges so that this command // can directly modify the mesh in the case when there is no history and // history is turned off. // MFnSingleIndexedComponent compFn( component ); compFn.getElements( fSelEdges ); // Ensure that this DAG path will point to the shape of our object. // Set the DAG path for the polyModifierCmd. // dagPath.extendToShape(); setMeshNode( dagPath ); found = true; } else { // Break once we have found a multiple object holding selected UVs, since // we are not interested in how many multiple objects there are, only // the fact that there are multiple objects. // foundMultiple = true; break; } } } #ifdef _DEBUG cout << endl << "########################## checking arguments:" << endl; cout << endl << "fSelEdges = ";for(unsigned i=0;i<fSelEdges.length();i++) cout << fSelEdges[i] << " ";cout << endl; #endif if( foundMultiple ) { displayWarning("Found more than one object with selected Edges - Only operating on first found object."); } if( !found ) { displayError( "tm_polySplit command failed: Unable to find selected edges" ); return MStatus::kFailure; } // Initialize the polyModifierCmd node type - mesh node already set // setModifierNodeType( tm_polySplitNode::id ); //################################################################## alwaysWithConstructionHistory = true; status = doModifyPoly(); if( !status){displayError( "tm_polySplit command failed!" );return status;} //################################################################## get polymodifier node name and select it getModifierNodeName(); newSelList.add( modifierNodeName); MGlobal::setActiveSelectionList( newSelList);//, MGlobal::kAddToList); //################################################################## setResult( modifierNodeName); return MStatus::kSuccess; /* cout<<endl<<"**********"<<endl;return MStatus::kSuccess; */ }
MStatus MayaToFuji::doIt( const MArgList& args) { MStatus stat = MStatus::kSuccess; MGlobal::displayInfo("Executing mayatoFuji..."); logger.setLogLevel(Logging::Debug); MArgDatabase argData(syntax(), args); int width = -1; int height = -1; if ( argData.isFlagSet("-width", &stat)) { argData.getFlagArgument("-width", 0, width); logger.debug(MString("width: ") + width); } if ( argData.isFlagSet("-height", &stat)) { argData.getFlagArgument("-height", 0, height); logger.debug(MString("height: ") + height); } if ( argData.isFlagSet("-stopIpr", &stat)) { logger.debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRSTOP; theRenderEventQueue()->push(e); return MS::kSuccess; } if ( argData.isFlagSet("-pauseIpr", &stat)) { logger.debug(MString("-pauseIpr")); return MS::kSuccess; } MayaScene::RenderType rtype = MayaScene::NORMAL; if ( argData.isFlagSet("-startIpr", &stat)) { logger.debug(MString("-startIpr")); rtype = MayaScene::IPR; } else { logger.debug(MString("normal render")); } // if we are here, we want a normal or an startIPR rendering, so initialize the scene mtfu_MayaScene *mayaScene = new mtfu_MayaScene(rtype); if( !mayaScene->good ) { logger.error("Problems have occurred during creation of mayaScene(). Sorry cannot proceed.\n\n"); return MS::kFailure; } if( !mayaScene->parseScene(MayaScene::HIERARCHYPARSE) ) { logger.error("Problems have occurred during parsing of the scene. Sorry cannot proceed.\n\n"); return MS::kFailure; } if ( argData.isFlagSet("-camera", &stat)) { MDagPath camera; MSelectionList selectionList; argData.getFlagArgument("-camera", 0, selectionList); stat = selectionList.getDagPath(0, camera); camera.extendToShape(); logger.debug(MString("camera: ") + camera.fullPathName()); mayaScene->setCurrentCamera(camera); } if( height > 0) mayaScene->renderGlobals->imgHeight = height; if( width > 0) mayaScene->renderGlobals->imgWidth = width; if(!mayaScene->renderScene()) { logger.error("Problems have occurred during rendering of the scene. Sorry cannot proceed.\n\n"); return MS::kFailure; } MGlobal::displayInfo("mayatoFuji rendering done.\n"); return MStatus::kSuccess; }
MStatus findTexturesPerPolygon::doIt( const MArgList& ) // // Description: // Find the texture files that apply to the color of each polygon of // a selected shape if the shape has its polygons organized into sets. // { // Get the selection and choose the first path on the selection list. // MStatus status; MDagPath path; MObject cmp; MSelectionList slist; MGlobal::getActiveSelectionList(slist); slist.getDagPath(0, path, cmp); // Have to make the path include the shape below it so that // we can determine if the underlying shape node is instanced. // By default, dag paths only include transform nodes. // path.extendToShape(); // If the shape is instanced then we need to determine which // instance this path refers to. // int instanceNum = 0; if (path.isInstanced()) instanceNum = path.instanceNumber(); // Get a list of all sets pertaining to the selected shape and the // members of those sets. // MFnMesh fnMesh(path); MObjectArray sets; MObjectArray comps; if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true)) cerr << "ERROR: MFnMesh::getConnectedSetsAndMembers\n"; // Loop through all the sets. If the set is a polygonal set, find the // shader attached to the and print out the texture file name for the // set along with the polygons in the set. // for ( unsigned i=0; i<sets.length(); i++ ) { MObject set = sets[i]; MObject comp = comps[i]; MFnSet fnSet( set, &status ); if (status == MS::kFailure) { cerr << "ERROR: MFnSet::MFnSet\n"; continue; } // Make sure the set is a polygonal set. If not, continue. MItMeshPolygon piter(path, comp, &status); if ((status == MS::kFailure) || comp.isNull()) continue; // Find the texture that is applied to this set. First, get the // shading node connected to the set. Then, if there is an input // attribute called "color", search upstream from it for a texture // file node. // MObject shaderNode = findShader(set); if (shaderNode == MObject::kNullObj) continue; MPlug colorPlug = MFnDependencyNode(shaderNode).findPlug("color", &status); if (status == MS::kFailure) continue; MItDependencyGraph dgIt(colorPlug, MFn::kFileTexture, MItDependencyGraph::kUpstream, MItDependencyGraph::kBreadthFirst, MItDependencyGraph::kNodeLevel, &status); if (status == MS::kFailure) continue; dgIt.disablePruningOnFilter(); // If no texture file node was found, just continue. // if (dgIt.isDone()) continue; // Print out the texture node name and texture file that it references. // MObject textureNode = dgIt.thisNode(); MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName"); MString textureName; filenamePlug.getValue(textureName); cerr << "Set: " << fnSet.name() << endl; cerr << "Texture Node Name: " << MFnDependencyNode(textureNode).name() << endl; cerr << "Texture File Name: " << textureName.asChar() << endl; // Print out the set of polygons that are contained in the current set. // for ( ; !piter.isDone(); piter.next() ) cerr << " poly component: " << piter.index() << endl; } return MS::kSuccess; }
MStatus MayaToCorona::doIt( const MArgList& args) { MStatus stat = MStatus::kSuccess; MArgDatabase argData(syntax(), args); if (argData.isFlagSet("-version", &stat)) { MStringArray res; for (auto v : getFullVersionString()) res.append(v.c_str()); setResult(res); return MS::kSuccess; } MGlobal::displayInfo("Executing mayaToCorona..."); setLogLevel(); if (argData.isFlagSet("-state", &stat)) { Logging::debug(MString("state: ???")); MayaTo::MayaToWorld::WorldRenderState rstate = MayaTo::getWorldPtr()->renderState; if (rstate == MayaTo::MayaToWorld::RSTATETRANSLATING) setResult("rstatetranslating"); if (rstate == MayaTo::MayaToWorld::RSTATERENDERING) setResult("rstaterendering"); if (rstate == MayaTo::MayaToWorld::RSTATEDONE) setResult("rstatedone"); if (rstate == MayaTo::MayaToWorld::RSTATENONE) setResult("rstatenone"); if (rstate == MayaTo::MayaToWorld::RSTATESTOPPED) setResult("rstatestopped"); return MS::kSuccess; } if (argData.isFlagSet("-canDoIPR", &stat)) { if(MayaTo::getWorldPtr()->canDoIPR()) setResult("yes"); else setResult("no"); return MS::kSuccess; } if ( argData.isFlagSet("-stopIpr", &stat)) { Logging::debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRSTOP; theRenderEventQueue()->push(e); return MS::kSuccess; } if ( argData.isFlagSet("-pauseIpr", &stat)) { Logging::debug(MString("-pauseIpr")); Logging::debug(MString("-stopIpr")); EventQueue::Event e; e.type = EventQueue::Event::IPRPAUSE; theRenderEventQueue()->push(e); return MS::kSuccess; } // I have to request useRenderRegion here because as soon the command is finished, what happens immediatly after the command is // put into the queue, the value is set back to false. std::unique_ptr<MayaTo::CmdArgs> cmdArgs(new MayaTo::CmdArgs); MObject drg = objectFromName("defaultRenderGlobals"); MFnDependencyNode drgfn(drg); cmdArgs->useRenderRegion = drgfn.findPlug("useRenderRegion").asBool(); if ( argData.isFlagSet("-startIpr", &stat)) { Logging::debug(MString("-startIpr")); cmdArgs->renderType = MayaTo::MayaToWorld::WorldRenderType::IPRRENDER; } if (argData.isFlagSet("-width", &stat)) { argData.getFlagArgument("-width", 0, cmdArgs->width); Logging::debug(MString("width: ") + cmdArgs->width); } if (argData.isFlagSet("-height", &stat)) { argData.getFlagArgument("-height", 0, cmdArgs->height); Logging::debug(MString("height: ") + cmdArgs->height); } if ( argData.isFlagSet("-camera", &stat)) { MDagPath camera; MSelectionList selectionList; argData.getFlagArgument("-camera", 0, selectionList); stat = selectionList.getDagPath(0, camera); camera.extendToShape(); Logging::debug(MString("camera: ") + camera.fullPathName()); cmdArgs->cameraDagPath = camera; } EventQueue::Event e; e.cmdArgsData = std::move(cmdArgs); e.type = EventQueue::Event::INITRENDER; theRenderEventQueue()->push(e); // if (MGlobal::mayaState() == MGlobal::kBatch) { RenderQueueWorker::startRenderQueueWorker(); } return MStatus::kSuccess; }
// // Selects objects within the user defined area, then process them // MStatus meshRemapTool::doRelease( MEvent & event ) { char buf[1024]; // Perform the base actions MStatus stat = MPxSelectionContext::doRelease(event); // Get the list of selected items MGlobal::getActiveSelectionList( fSelectionList ); // // Get the selection's details, we must have exactly one component selected // MObject component; MDagPath path; MItSelectionList selectionIt (fSelectionList, MFn::kComponent); MStringArray selections; selectionIt.getStrings( selections ); // There are valid cases where only the meshes are selected. if( selections.length() == 0 ) { // Handling the case where the user's workflow is // 1) select src mesh, select vtx1, vtx2, vtx3 (i.e. fNumSelectedPoints == 0) // 2) select dst mesh, select vtx1, vtx2, vtx3 (i.e. fNumSelectedPoints == 3) if( fNumSelectedPoints == 0 || fNumSelectedPoints == 3 ) { MItSelectionList selectionDag (fSelectionList, MFn::kDagNode); if (!selectionDag.isDone() && selectionDag.getDagPath(path) == MS::kSuccess) { path.extendToShape(); // return true there is exactly one mesh selected if (path.hasFn(MFn::kMesh)) { selectionDag.next(); if (selectionDag.isDone()) { // If this is the destination mesh, make sure that // it doesn't have history. if (fNumSelectedPoints == 3) { return checkForHistory(path); } return MS::kSuccess; } } } } // Handling the case where the user is doing the auto remap, i.e. // select src mesh, and then dst mesh when fNumSelectedPoints == 0. if( fNumSelectedPoints == 0 ) { MItSelectionList selectionDag (fSelectionList, MFn::kDagNode); if (!selectionDag.isDone() && selectionDag.getDagPath(path) == MS::kSuccess) { path.extendToShape(); // Confirm first selection is a mesh if (path.hasFn(MFn::kMesh)) { selectionDag.next(); if (!selectionDag.isDone() && selectionDag.getDagPath(path) == MS::kSuccess) { path.extendToShape(); // Confirm second selection is a mesh if (path.hasFn(MFn::kMesh)) { selectionDag.next(); // Confirm there are exactly 2 selections if (selectionDag.isDone()) { // Make sure that the destination mesh // doesn't have history. return checkForHistory(path); } } } } } } } if( selections.length() != 1 ) { MGlobal::displayError( "Must select exactly one vertex" ); return MS::kSuccess; } if (selectionIt.isDone ()) { MGlobal::displayError( "Selected item not a vertex" ); return MS::kSuccess; } if( selectionIt.getDagPath (path, component) != MStatus::kSuccess ) { MGlobal::displayError( "Must select a mesh or its vertex" ); return MS::kSuccess; } if (!path.node().hasFn(MFn::kMesh) && !(path.node().hasFn(MFn::kTransform) && path.hasFn(MFn::kMesh))) { MGlobal::displayError( "Must select a mesh or its transform" ); return MS::kSuccess; } // If this is the first vertex of the destination mesh, make sure that // it doesn't have history. if ((fNumSelectedPoints == 3) && (checkForHistory(path) != MS::kSuccess)) { return MS::kSuccess; } MItMeshVertex fIt ( path, component, &stat ); if( stat != MStatus::kSuccess ) { MGlobal::displayError( "MItMeshVertex failed"); return MStatus::kFailure; } if (fIt.count() != 1 ) { sprintf(buf, "Invalid selection '%s'. Vertices must be picked one at a time.", selections[0].asChar() ); MGlobal::displayError( buf ); return MS::kSuccess; } else { sprintf(buf, "Accepting vertex '%s'", selections[0].asChar() ); MGlobal::displayInfo( buf ); } // // Now that we know it's valid, process the selection, the first 3 items are the source, the second // 3 define the target // if( fNumSelectedPoints < 3 ) { fSelectedPathSrc.append( path ); fSelectedComponentSrc.append( component ); } else { fSelectedPathDst.append( path ); fSelectedComponentDst.append( component ); } // // When each of the source/target are defined, process them. An error/invalid selection will restart the selection for // that particular mesh. // if( fNumSelectedPoints == 2 ) { if( ( stat = meshMapUtils::validateFaceSelection( fSelectedPathSrc, fSelectedComponentSrc, &fSelectedFaceSrc, &fSelectVtxSrc ) ) != MStatus::kSuccess ) { MGlobal::displayError("Selected vertices don't define a unique face on source mesh"); reset(); return stat; } } // // Once the target is defined, invoke the command // if( fNumSelectedPoints == 5 ) { if( ( stat = meshMapUtils::validateFaceSelection( fSelectedPathDst, fSelectedComponentDst, &fSelectedFaceDst, &fSelectVtxDst ) ) != MStatus::kSuccess ) { MGlobal::displayError("Selected vertices don't define a unique face on destination mesh"); reset(); return stat; } executeCmd(); } else { // // We don't have all the details yet, just move to the next item // fNumSelectedPoints++; } helpStateHasChanged(); return stat; }
MStatus closestPointOnCurveCommand::redoIt() { // DOUBLE-CHECK TO MAKE SURE THERE'S A SPECIFIED OBJECT TO EVALUATE ON: if (sList.length() == 0) { MStatus stat; MString msg = MStringResource::getString(kNoValidObject, stat); displayError(msg); return MStatus::kFailure; } // RETRIEVE THE SPECIFIED OBJECT AS A DAGPATH: MDagPath curveDagPath; sList.getDagPath(0, curveDagPath); // CHECK FOR INVALID NODE-TYPE INPUT WHEN SPECIFIED/SELECTED NODE IS *NOT* A "CURVE" NOR "CURVE TRANSFORM": if (!curveDagPath.node().hasFn(MFn::kNurbsCurve) && !(curveDagPath.node().hasFn(MFn::kTransform) && curveDagPath.hasFn(MFn::kNurbsCurve))) { MStatus stat; MString msg; // Use format to place variable string into message MString msgFmt = MStringResource::getString(kInvalidType, stat); MStringArray selectionStrings; sList.getSelectionStrings(0, selectionStrings); msg.format(msgFmt, selectionStrings[0]); displayError(msg); return MStatus::kFailure; } // WHEN COMMAND *NOT* IN "QUERY MODE" (I.E. "CREATION MODE"), CREATE AND CONNECT A "closestPointOnCurve" NODE AND RETURN ITS NODE NAME: if (!queryFlagSet) { // CREATE THE NODE: MFnDependencyNode depNodeFn; if (closestPointOnCurveNodeName == "") depNodeFn.create("closestPointOnCurve"); else depNodeFn.create("closestPointOnCurve", closestPointOnCurveNodeName); closestPointOnCurveNodeName = depNodeFn.name(); // SET THE ".inPosition" ATTRIBUTE, IF SPECIFIED IN THE COMMAND: if (inPositionFlagSet) { MPlug inPositionXPlug = depNodeFn.findPlug("inPositionX"); inPositionXPlug.setValue(inPosition.x); MPlug inPositionYPlug = depNodeFn.findPlug("inPositionY"); inPositionYPlug.setValue(inPosition.y); MPlug inPositionZPlug = depNodeFn.findPlug("inPositionZ"); inPositionZPlug.setValue(inPosition.z); } // MAKE SOME ADJUSTMENTS WHEN THE SPECIFIED NODE IS A "TRANSFORM" OF A CURVE SHAPE: unsigned instanceNumber=0; if (curveDagPath.node().hasFn(MFn::kTransform)) { // EXTEND THE DAGPATH TO ITS CURVE "SHAPE" NODE: curveDagPath.extendToShape(); // TRANSFORMS ARE *NOT* NECESSARILY THE "FIRST" INSTANCE TRANSFORM OF A CURVE SHAPE: instanceNumber = curveDagPath.instanceNumber(); } // CONNECT THE NODES: MPlug worldCurvePlug, inCurvePlug; inCurvePlug = depNodeFn.findPlug("inCurve"); depNodeFn.setObject(curveDagPath.node()); worldCurvePlug = depNodeFn.findPlug("worldSpace"); worldCurvePlug = worldCurvePlug.elementByLogicalIndex(instanceNumber); MDGModifier dgModifier; dgModifier.connect(worldCurvePlug, inCurvePlug); dgModifier.doIt(); // SET COMMAND RESULT TO BE NEW NODE'S NAME, AND RETURN: setResult(closestPointOnCurveNodeName); return MStatus::kSuccess; } // OTHERWISE, WE'RE IN THE COMMAND'S "QUERY MODE": else { // COMPUTE THE CLOSEST POSITION, NORMAL, TANGENT, PARAMETER-U AND DISTANCE, USING THE *FIRST* INSTANCE TRANSFORM WHEN CURVE IS SPECIFIED AS A "SHAPE": MPoint position; MVector normal, tangent; double paramU, distance; closestTangentUAndDistance(curveDagPath, inPosition, position, normal, tangent, paramU, distance); // WHEN NO QUERYABLE FLAG IS SPECIFIED, INDICATE AN ERROR: if (!positionFlagSet && !normalFlagSet && !tangentFlagSet && !paramUFlagSet && !distanceFlagSet) { MStatus stat; MString msg = MStringResource::getString(kNoQueryFlag, stat); displayError(msg); return MStatus::kFailure; } // WHEN JUST THE "DISTANCE" IS QUERIED, RETURN A SINGLE "FLOAT" INSTEAD OF AN ENTIRE FLOAT ARRAY FROM THE COMMAND: else if (distanceFlagSet && !(positionFlagSet || normalFlagSet || tangentFlagSet || paramUFlagSet)) setResult(distance); // WHEN JUST THE "PARAMETER-U" IS QUERIED, RETURN A SINGLE "FLOAT" INSTEAD OF AN ENTIRE FLOAT ARRAY FROM THE COMMAND: else if (paramUFlagSet && !(positionFlagSet || normalFlagSet || tangentFlagSet || distanceFlagSet)) setResult(paramU); // OTHERWISE, SET THE RETURN VALUE OF THE COMMAND'S RESULT TO A "COMPOSITE ARRAY OF FLOATS": else { // HOLDS FLOAT ARRAY RESULT: MDoubleArray floatArrayResult; // APPEND THE RESULTS OF THE CLOSEST POSITION, NORMAL, TANGENT, PARAMETER-U AND DISTANCE VALUES TO THE FLOAT ARRAY RESULT: if (positionFlagSet) { floatArrayResult.append(position.x); floatArrayResult.append(position.y); floatArrayResult.append(position.z); } if (normalFlagSet) { floatArrayResult.append(normal.x); floatArrayResult.append(normal.y); floatArrayResult.append(normal.z); } if (tangentFlagSet) { floatArrayResult.append(tangent.x); floatArrayResult.append(tangent.y); floatArrayResult.append(tangent.z); } if (paramUFlagSet) floatArrayResult.append(paramU); if (distanceFlagSet) floatArrayResult.append(distance); // FINALLY, SET THE COMMAND'S RESULT: setResult(floatArrayResult); } return MStatus::kSuccess; } }
MStatus skinClusterWeights::redoIt() { MStatus status; unsigned int ptr = 0; MSelectionList selList; int geomLen = geometryArray.length(); fDagPathArray.setLength(geomLen); fComponentArray.setLength(geomLen); fInfluenceIndexArrayPtrArray = new MIntArray[geomLen]; fWeightsPtrArray = new MDoubleArray[geomLen]; for (int i = 0; i < geomLen; i++) { MDagPath dagPath; MObject component; selList.clear(); selList.add(geometryArray[i]); MStatus status = selList.getDagPath(0, dagPath, component); if (status != MS::kSuccess) { continue; } if (component.isNull()) dagPath.extendToShape(); MObject skinCluster = findSkinCluster(dagPath); if (!isSkinClusterIncluded(skinCluster)) { continue; } MFnSkinCluster skinClusterFn(skinCluster, &status); if (status != MS::kSuccess) { continue; } MIntArray influenceIndexArray; populateInfluenceIndexArray(skinClusterFn, influenceIndexArray); unsigned numInf = influenceIndexArray.length(); if (numInf == 0) continue; unsigned numCV = 0; if (dagPath.node().hasFn(MFn::kMesh)) { MItMeshVertex polyIter(dagPath, component, &status); if (status == MS::kSuccess) { numCV = polyIter.count(); } } else if (dagPath.node().hasFn(MFn::kNurbsSurface)) { MItSurfaceCV nurbsIter(dagPath, component, true, &status); if (status == MS::kSuccess) { while (!nurbsIter.isDone()) { numCV++; nurbsIter.next(); } } } else if (dagPath.node().hasFn(MFn::kNurbsCurve)) { MItCurveCV curveIter(dagPath, component, &status); if (status == MS::kSuccess) { while (!curveIter.isDone()) { numCV++; curveIter.next(); } } } unsigned numEntry = numCV * numInf; if (numEntry > 0) { MDoubleArray weights(numEntry); unsigned int numWeights = weightArray.length(); if (assignAllToSingle) { if (numInf <= numWeights) { for (unsigned j = 0; j < numEntry; j++) { weights[j] = weightArray[j % numInf]; } } else { MGlobal::displayError("Not enough weights specified\n"); return MS::kFailure; } } else { for (unsigned j = 0; j < numEntry; j++, ptr++) { if (ptr < numWeights) { weights[j] = weightArray[ptr]; } else { MGlobal::displayError("Not enough weights specified\n"); return MS::kFailure; } } } // support for undo fDagPathArray[i] = dagPath; fComponentArray[i] = component; fInfluenceIndexArrayPtrArray[i] = influenceIndexArray; MDoubleArray oldWeights; skinClusterFn.getWeights(dagPath, component, influenceIndexArray, oldWeights); fWeightsPtrArray[i] = oldWeights; skinClusterFn.setWeights(dagPath, component, influenceIndexArray, weights); } } return MS::kSuccess; }
MStatus vxCache::doIt( const MArgList& args ) { MStatus status = parseArgs( args ); if( status != MS::kSuccess ) return status; MArgDatabase argData(syntax(), args); MAnimControl timeControl; MTime time = timeControl.currentTime(); int frame =int(time.value()); MString proj; MGlobal::executeCommand( MString ("string $p = `workspace -q -fn`"), proj ); MSelectionList selList; MGlobal::getActiveSelectionList ( selList ); MItSelectionList iter( selList ); MString cache_path = proj + "/data/"; MString cache_name; MString scene_name = "untitled"; worldSpace = false; if (argData.isFlagSet("-p")) argData.getFlagArgument("-p", 0, cache_path); if (argData.isFlagSet("-n")) argData.getFlagArgument("-n", 0, cache_name); if (argData.isFlagSet("-w")) argData.getFlagArgument("-w", 0, worldSpace); for ( ; !iter.isDone(); iter.next() ) { MDagPath meshPath; iter.getDagPath( meshPath ); meshPath.extendToShape(); MObject meshObj = meshPath.node(); MString surface = meshPath.partialPathName(); zWorks::validateFilePath(surface); char filename[512]; cache_name = surface; if(argData.isFlagSet("-sg")) sprintf( filename, "%s/%s.mcf", cache_path.asChar(), cache_name.asChar() ); else sprintf( filename, "%s/%s.%d.mcf", cache_path.asChar(), cache_name.asChar(), frame ); MDagPath surfDag; if ( meshPath.hasFn(MFn::kMesh)) { writeMesh(filename, meshPath, meshObj); MGlobal::displayInfo ( MString("vxCache writes ") + filename); } else MGlobal::displayError ( surface + "- Cannot find mesh to write!" ); } if ( selList.length() == 0 ) { MGlobal:: displayError ( "Nothing is selected!" ); return MS::kSuccess; } return MS::kSuccess; }
MStatus meshOp::doIt( const MArgList& argList ) // // Description: // implements the MEL meshOp command. // // Arguments: // argList - the argument list that was passes to the command from MEL // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { MStatus status; bool badArgument = false; // Only one parameter is expected to be passed to this command: the mesh // operation type. Get it, validate it or stop prematurely // if (argList.length() == 1) { int operationTypeArgument = argList.asInt(0); if (operationTypeArgument < 0 || operationTypeArgument > kMeshOperationCount - 1) { badArgument = true; } else { fOperation = (MeshOperation)operationTypeArgument; } } else badArgument = true; if (badArgument) { cerr << "Expecting one parameter: the operation type." << endl; cerr << "Valid types are: " << endl; cerr << " 0 - Subdivide edge(s)." << endl; cerr << " 1 - Subdivide face(s)." << endl; cerr << " 2 - Extrude edge(s)." << endl; cerr << " 3 - Extrude face(s)." << endl; cerr << " 4 - Collapse edge(s)." << endl; cerr << " 5 - Collapse face(s)." << endl; cerr << " 6 - Duplicate face(s)." << endl; cerr << " 7 - Extract face(s)." << endl; cerr << " 8 - Split face(s)." << endl; cerr << " 8 - Chamfer vertex(s)." << endl; displayError(" Expecting one parameter: the operation type."); return MS::kFailure; } // Each mesh operation only supports one type of components // MFn::Type componentType = meshOpFty::getExpectedComponentType(fOperation); // Parse the selection list for selected components of the right type. // To simplify things, we only take the first object that we find with // selected components and operate on that object alone. // // All other objects are ignored and return warning messages indicating // this limitation. // MSelectionList selList; MGlobal::getActiveSelectionList( selList ); MItSelectionList selListIter( selList ); selListIter.setFilter( MFn::kMesh ); // The meshOperation node only accepts a component list input, so we build // a component list using MFnComponentListData. // // MIntArrays could also be passed into the node to represent the ids, // but are less storage efficient than component lists, since consecutive // components are bundled into a single entry in component lists. // MFnComponentListData compListFn; compListFn.create(); bool found = false; bool foundMultiple = false; for( ; !selListIter.isDone(); selListIter.next() ) { MDagPath dagPath; MObject component; selListIter.getDagPath( dagPath, component ); // Check for selected components of the right type // if( component.apiType() == componentType ) { if( !found ) { // The variable 'component' holds all selected components // on the selected object, thus only a single call to // MFnComponentListData::add() is needed to store the selected // components for a given object. // compListFn.add( component ); // Copy the component list created by MFnComponentListData // into our local component list MObject member. // fComponentList = compListFn.object(); // Locally store the actual ids of the selected components so // that this command can directly modify the mesh in the case // when there is no history and history is turned off. // MFnSingleIndexedComponent compFn( component ); // Ensure that this DAG path will point to the shape // of our object. Set the DAG path for the polyModifierCmd. // dagPath.extendToShape(); setMeshNode( dagPath ); found = true; } else { // Break once we have found a multiple object holding // selected components, since we are not interested in how // many multiple objects there are, only the fact that there // are multiple objects. // foundMultiple = true; break; } } } if( foundMultiple ) { displayWarning("Found more than one object with selected components."); displayWarning("Only operating on first found object."); } // Initialize the polyModifierCmd node type - mesh node already set // setModifierNodeType( meshOpNode::id ); if( found ) { // Now, pass control over to the polyModifierCmd::doModifyPoly() method // to handle the operation. // status = doModifyPoly(); if( status == MS::kSuccess ) { setResult( "meshOp command succeeded!" ); } else { displayError( "meshOp command failed!" ); } } else { displayError( "meshOp command failed: Unable to find selected components" ); status = MS::kFailure; } return status; }
MStatus vixo_hairCacheExport::doIt(const MArgList& args) { MString vixoHairNode; int startFrame,endFrame; unsigned index; index=args.flagIndex("vhn","vixoHairNode"); if(MArgList::kInvalidArgIndex!=index) { args.get(index+1,vixoHairNode); } index=args.flagIndex("sf","startFrame"); if(MArgList::kInvalidArgIndex!=index) { args.get(index+1,startFrame); } index=args.flagIndex("ef","endFrame"); if(MArgList::kInvalidArgIndex!=index) { args.get(index+1,endFrame); } //get hairCacheFileName MSelectionList slist; MGlobal::getSelectionListByName(vixoHairNode,slist); MDagPath vixoHairNodeDag; slist.getDagPath(0,vixoHairNodeDag); vixoHairNodeDag.extendToShape(); MFnDagNode fnVixoHair(vixoHairNodeDag); MPlug plugCacheFileName=fnVixoHair.findPlug("hairCacheFileName"); MString cacheFileName=plugCacheFileName.asString(); //~get hairCacheFileName //get staticMesh MPlug plugStaticMesh=fnVixoHair.findPlug("staticInMesh"); MObject staticMeshObj=MFnMeshData(plugStaticMesh.asMObject()).object(); //~get staticMesh //build out dataBase MFnMesh fnStaticMesh(staticMeshObj); map<int,set<outInVertexRelationInfo>> outVertexDataBase; map<int,vector<outVIDCtrlInfo>> outVertexControlData; for(int i=0;i<fnStaticMesh.numVertices();i++) { set<outInVertexRelationInfo> temp; temp.clear(); outVertexDataBase.insert(pair<int,set<outInVertexRelationInfo>>(i,temp)); } //build out dataBase //get inCurveVID map<int,int> plugMapVID; map<int,int> VIDMapPlug; map<int,inVertexBasicInfo> inVIDMapInVertexDataBase; MPlug plugAllInCurve=fnVixoHair.findPlug("inCtrlCurveData"); MIntArray existIndex; plugAllInCurve.getExistingArrayAttributeIndices(existIndex); for(int i=0;i<existIndex.length();i++) { MPlugArray arr; plugAllInCurve.elementByLogicalIndex(existIndex[i]).connectedTo(arr,true,false); MFnDependencyNode fnHairSystem(arr[0].node()); MPlug inputHairs=fnHairSystem.findPlug("inputHair"); arr.clear(); inputHairs.elementByLogicalIndex(existIndex[i]).connectedTo(arr,true,false); MFnDependencyNode fnFolli(arr[0].node()); int vid=fnFolli.findPlug("vertexID").asInt(); plugMapVID.insert(pair<int,int>(existIndex[i],vid)); VIDMapPlug.insert(pair<int,int>(vid,existIndex[i])); initBasicStepInfo(vid,staticMeshObj,inVIDMapInVertexDataBase); } //~get inCurveVID //build in out relation map<int,inVertexBasicInfo>::iterator inDBIter; for(inDBIter=inVIDMapInVertexDataBase.begin();inDBIter!=inVIDMapInVertexDataBase.end();inDBIter++) { buileRelationBetweenInOut(inDBIter->first,inVIDMapInVertexDataBase,outVertexDataBase); } map<int,set<outInVertexRelationInfo>>::iterator outDBIter; for(outDBIter=outVertexDataBase.begin();outDBIter!=outVertexDataBase.end();outDBIter++) { sortControlOrder(outDBIter->first,outVertexDataBase,outVertexControlData); } //~build in out relation for(int i=startFrame;i<=endFrame;i++) { MString currentTime; currentTime.set(i); MGlobal::executeCommand("currentTime "+currentTime); MGlobal::executeCommand("dgeval "+vixoHairNode+".hiddenOutput"); //get dynamic mesh MPlug plugDynamicMesh=fnVixoHair.findPlug("dynamicInMesh"); MObject dynamicMeshObj=MFnMeshData(plugDynamicMesh.asMObject()).object(); //~get dynamic mesh //export cache //faceid triid vid position normal tangent vector<forExportHairCache> exportData; exportBasicData(dynamicMeshObj,exportData); //curve tangent //get in curve infos map<int,MVectorArray> inCurveShape; getInCurveInfo(plugMapVID,vixoHairNode,inCurveShape); //~get in curve infos vector<vec3> outCurveCacheData; vec3 init; init.x=0; init.y=0; init.z=0; outCurveCacheData.resize(fnStaticMesh.numVertices()*inCurveShape.begin()->second.length(),init); buildCache(inCurveShape.begin()->second.length(),dynamicMeshObj,outCurveCacheData,inCurveShape,outVertexControlData); //~export cache //write to file MString fileName=getFileName(cacheFileName,i); fstream fout(fileName.asChar(),ios_base::out|ios_base::binary); int triNumvertexNum[3]; triNumvertexNum[0]=exportData.size(); triNumvertexNum[1]=fnStaticMesh.numVertices(); triNumvertexNum[2]=inCurveShape.begin()->second.length(); fout.write((char*)triNumvertexNum,sizeof(int)*3); fout.write((char*)&exportData[0],sizeof(forExportHairCache)*exportData.size()); fout.write((char*)&outCurveCacheData[0],sizeof(vec3)*outCurveCacheData.size()); fout.flush(); fout.close(); /* MString fileNameDebug=fileName+".dbg"; fout.open(fileNameDebug.asChar(),ios_base::out); for(int i=0;i<outCurveCacheData.size();i++) { fout<<outCurveCacheData[i].x<<" "<<outCurveCacheData[i].y<<" "<<outCurveCacheData[i].z<<endl; } fout.flush(); fout.close(); */ //~write to file } return MS::kSuccess; }
// -------------------------------------------------------------------------------------------- MStatus polyModifierCmd::undoDirectModifier() // -------------------------------------------------------------------------------------------- { MStatus status; MFnDependencyNode depNodeFn; MFnDagNode dagNodeFn; MObject meshNode = fDagPath.node(); depNodeFn.setObject( meshNode ); // For the case with tweaks, we cannot write the mesh directly back onto // the cachedInMesh, since the shape can have out of date information from the // cachedInMesh. Thus we temporarily create an duplicate mesh, place our // old mesh on the outMesh attribute of our duplicate mesh, connect the // duplicate mesh shape to the mesh shape, and force a DG evaluation. // // For the case without tweaks, we can simply write onto the outMesh, since // the shape relies solely on an outMesh when there is no history nor tweaks. // if( fHasTweaks ) { // Retrieve the inMesh and name of our mesh node (for the DG eval) // depNodeFn.setObject( meshNode ); MPlug meshNodeInMeshPlug = depNodeFn.findPlug( "inMesh", &status ); MCheckStatus( status, "Could not retrieve inMesh" ); MString meshNodeName = depNodeFn.name(); // Duplicate our current mesh // dagNodeFn.setObject( meshNode ); MObject dupMeshNode = dagNodeFn.duplicate(); // The dagNodeFn::duplicate() returns a transform, but we need a shape // so retrieve the DAG path and extend it to the shape. // MDagPath dupMeshDagPath; MDagPath::getAPathTo( dupMeshNode, dupMeshDagPath ); dupMeshDagPath.extendToShape(); // Retrieve the outMesh of the duplicate mesh and set our mesh data back // on it. // depNodeFn.setObject( dupMeshDagPath.node() ); MPlug dupMeshNodeOutMeshPlug = depNodeFn.findPlug( "outMesh", &status ); MCheckStatus( status, "Could not retrieve outMesh" ); status = dupMeshNodeOutMeshPlug.setValue( fMeshData ); // Temporarily connect the duplicate mesh node to our mesh node // MDGModifier dgModifier; dgModifier.connect( dupMeshNodeOutMeshPlug, meshNodeInMeshPlug ); status = dgModifier.doIt(); MCheckStatus( status, "Could not connect dupMeshNode -> meshNode" ); // Need to force a DG evaluation now that the input has been changed. // MString cmd("dgeval -src "); cmd += meshNodeName; cmd += ".inMesh"; status = MGlobal::executeCommand( cmd, false, false ); MCheckStatus( status, "Could not force DG eval" ); // Disconnect and delete the duplicate mesh node now // dgModifier.undoIt(); MGlobal::deleteNode( dupMeshNode ); // Restore the tweaks on the mesh // status = undoTweakProcessing(); } else { // Restore the original mesh by writing the old mesh data (fMeshData) back // onto the outMesh of our meshNode // depNodeFn.setObject( meshNode ); MPlug meshNodeOutMeshPlug = depNodeFn.findPlug( "outMesh", &status ); MCheckStatus( status, "Could not retrieve outMesh" ); status = meshNodeOutMeshPlug.setValue( fMeshData ); MCheckStatus( status, "Could not set meshData" ); } return status; }
TfToken usdWriteJob::writeVariants(const UsdPrim &usdRootPrim) { // Init parameters for filtering and setting the active variant std::string defaultModelingVariant; // Get the usdVariantRootPrimPath (optionally filter by renderLayer prefix) MayaPrimWriterPtr firstPrimWriterPtr = *mMayaPrimWriterList.begin(); std::string firstPrimWriterPathStr( firstPrimWriterPtr->getDagPath().fullPathName().asChar() ); std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), '|', '/'); std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), ':', '_'); // replace namespace ":" with "_" SdfPath usdVariantRootPrimPath(firstPrimWriterPathStr); usdVariantRootPrimPath = usdVariantRootPrimPath.GetPrefixes()[0]; // Create a new usdVariantRootPrim and reference the Base Model UsdRootPrim // This is done for reasons as described above under mArgs.usdModelRootOverridePath UsdPrim usdVariantRootPrim = mStage->DefinePrim(usdVariantRootPrimPath); TfToken defaultPrim = usdVariantRootPrim.GetName(); usdVariantRootPrim.GetReferences().AppendInternalReference(usdRootPrim.GetPath()); usdVariantRootPrim.SetActive(true); usdRootPrim.SetActive(false); // Loop over all the renderLayers for (unsigned int ir=0; ir < mRenderLayerObjs.length(); ++ir) { SdfPathTable<bool> tableOfActivePaths; MFnRenderLayer renderLayerFn( mRenderLayerObjs[ir] ); MString renderLayerName = renderLayerFn.name(); std::string variantName(renderLayerName.asChar()); // Determine default variant. Currently unsupported //MPlug renderLayerDisplayOrderPlug = renderLayerFn.findPlug("displayOrder", true); //int renderLayerDisplayOrder = renderLayerDisplayOrderPlug.asShort(); // The Maya default RenderLayer is also the default modeling variant if (mRenderLayerObjs[ir] == MFnRenderLayer::defaultRenderLayer()) { defaultModelingVariant=variantName; } // Make the renderlayer being looped the current one MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ renderLayerName, false, false); // == ModelingVariants == // Identify prims to activate // Put prims and parent prims in a SdfPathTable // Then use that membership to determine if a prim should be Active. // It has to be done this way since SetActive(false) disables access to all child prims. MObjectArray renderLayerMemberObjs; renderLayerFn.listMembers(renderLayerMemberObjs); std::vector< SdfPath > activePaths; for (unsigned int im=0; im < renderLayerMemberObjs.length(); ++im) { MFnDagNode dagFn(renderLayerMemberObjs[im]); MDagPath dagPath; dagFn.getPath(dagPath); dagPath.extendToShape(); SdfPath usdPrimPath; if (!TfMapLookup(mDagPathToUsdPathMap, dagPath, &usdPrimPath)) { continue; } usdPrimPath = usdPrimPath.ReplacePrefix(usdPrimPath.GetPrefixes()[0], usdVariantRootPrimPath); // Convert base to variant usdPrimPath tableOfActivePaths[usdPrimPath] = true; activePaths.push_back(usdPrimPath); //UsdPrim usdPrim = mStage->GetPrimAtPath(usdPrimPath); //usdPrim.SetActive(true); } if (!tableOfActivePaths.empty()) { { // == BEG: Scope for Variant EditContext // Create the variantSet and variant UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSets().AppendVariantSet("modelingVariant"); modelingVariantSet.AppendVariant(variantName); modelingVariantSet.SetVariantSelection(variantName); // Set the Edit Context UsdEditTarget editTarget = modelingVariantSet.GetVariantEditTarget(); UsdEditContext editContext(mStage, editTarget); // == Activate/Deactivate UsdPrims UsdPrimRange it = UsdPrimRange::AllPrims(mStage->GetPseudoRoot()); std::vector<UsdPrim> primsToDeactivate; for ( ; it; ++it) { UsdPrim usdPrim = *it; // For all xformable usdPrims... if (usdPrim && usdPrim.IsA<UsdGeomXformable>()) { bool isActive=false; for (size_t j=0;j<activePaths.size();j++) { //primPathD.HasPrefix(primPathA); SdfPath activePath=activePaths[j]; if (usdPrim.GetPath().HasPrefix(activePath) || activePath.HasPrefix(usdPrim.GetPath())) { isActive=true; break; } } if (isActive==false) { primsToDeactivate.push_back(usdPrim); it.PruneChildren(); } } } // Now deactivate the prims (done outside of the UsdPrimRange // so not to modify the iterator while in the loop) for ( UsdPrim const& prim : primsToDeactivate ) { prim.SetActive(false); } } // == END: Scope for Variant EditContext } } // END: RenderLayer iterations // Set the default modeling variant UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSet("modelingVariant"); if (modelingVariantSet.IsValid()) { modelingVariantSet.SetVariantSelection(defaultModelingVariant); } return defaultPrim; }
MStatus listLightLinks::doIt( const MArgList& args ) // // Description: // Implements the MEL listLightLinks command. After parsing the // information stored in Maya's light linker nodes, it examines // the first item on the selection list. If the item is an object, // then the command selects all lights that are linked to that object. // If the item is a light, then it will select all of the objects // that are linked to that light. // // Arguments: // args - The argument list that was passes to the command from MEL. // This command takes no arguments. // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { MStatus stat = MS::kSuccess; clearResult(); // Parse the links on the current scene's light linker node(s). // MLightLinks lightLink; bool parseStatus; parseStatus = lightLink.parseLinks(MObject::kNullObj); if( !parseStatus ) { setResult( "Error parsing light links\n" ); return MS::kFailure; } // Get the first object (or component) on the selection list. // MSelectionList selectList; MDagPath dagPath; MObject component; MGlobal::getActiveSelectionList( selectList ); selectList.getDagPath( 0, dagPath, component ); dagPath.extendToShape(); // Selection list to store entities linked to the selected light or // object. // MSelectionList newSelection; newSelection.clear(); // Stores the command result. // char resultString[512]; // If the object is a surface, we'll select all the lights linked to it. // If the object is a light, we'll select all the objects linked to it. // if( dagPath.hasFn( MFn::kLight ) ) { // Select objects linked to this light. // MSelectionList objects; objects.clear(); lightLink.getLinkedObjects( dagPath, objects ); newSelection.merge( objects ); sprintf( resultString, "Selecting objects linked to light %s", dagPath.fullPathName().asChar() ); } else { // Select lights linked to this object. // MDagPathArray lights; lights.clear(); lightLink.getLinkedLights( dagPath, component, lights ); for( unsigned int j = 0; j < lights.length(); j++ ) { const MDagPath& path = lights[j]; newSelection.add( path ); } sprintf( resultString, "Selecting lights linked to object %s", dagPath.fullPathName().asChar() ); } // Select the linked entities. // MGlobal::setActiveSelectionList( newSelection ); setResult( resultString ); return stat; }
MStatus tm_polySlot::doIt( const MArgList& ) // // Description: // implements the MEL tm_polySlot command. // // Arguments: // args - the argument list that was passes to the command from MEL // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { #ifdef _DEBUG cout << endl << "####################################################" << endl; cout << "tm_polySlot::doIt - DEBUG version info:" << endl; #endif MStatus status; // Parse the selection list for objects with selected UV components. // To simplify things, we only take the first object that we find with // selected UVs and operate on that object alone. // // All other objects are ignored and return warning messages indicating // this limitation. // MGlobal::getActiveSelectionList( oldSelList ); MItSelectionList selListIter( oldSelList ); selListIter.setFilter( MFn::kMesh ); // The tm_polySlot node only accepts a component list input, so we build // a component list using MFnComponentListData. // // MIntArrays could also be passed into the node to represent the edgesIds, // but are less storage efficient than component lists, since consecutive // components are bundled into a single entry in component lists. // MFnComponentListData compListFn; compListFn.create(); bool found = false; bool foundMultiple = false; for( ; !selListIter.isDone(); selListIter.next() ) { MDagPath dagPath; MObject component; selListIter.getDagPath( dagPath, component ); // Check for selected UV components // if( component.apiType() == MFn::kMeshEdgeComponent ) { if( !found ) { // The variable 'component' holds all selected components on the selected // object, thus only a single call to MFnComponentListData::add() is needed // to store the selected components for a given object. // compListFn.add( component ); // Copy the component list created by MFnComponentListData into our local // component list MObject member. // fComponentList = compListFn.object(); // Locally store the actual edgesIds of the selected Edges so that this command // can directly modify the mesh in the case when there is no history and // history is turned off. // MFnSingleIndexedComponent compFn( component ); compFn.getElements( fSelEdges ); // Ensure that this DAG path will point to the shape of our object. // Set the DAG path for the polyModifierCmd. // dagPath.extendToShape(); setMeshNode( dagPath ); found = true; } else { // Break once we have found a multiple object holding selected UVs, since // we are not interested in how many multiple objects there are, only // the fact that there are multiple objects. // foundMultiple = true; break; } } } if( foundMultiple ) { displayWarning("Found more than one object with selected Edges - Only operating on first found object."); } if( !found ) { displayError( "tm_polySlot command failed: Unable to find selected edges" ); return MStatus::kFailure; } // Initialize the polyModifierCmd node type - mesh node already set // setModifierNodeType( tm_polySlotNode::id ); //################################################################## alwaysWithConstructionHistory = true; status = doModifyPoly(); if( !status){displayError( "tm_polySlot command failed!" );return status;} //################################################################## get polymodifier node name and select it getModifierNodeName(); newSelList.add( modifierNodeName); MGlobal::setActiveSelectionList( newSelList);//, MGlobal::kAddToList); //################################################################## successResult(); return MStatus::kSuccess; }
MStatus mshUtil::doIt( const MArgList& args ) { MString objname, mcfname; MArgDatabase argData(syntax(), args); MSelectionList selList; MGlobal::getActiveSelectionList ( selList ); if ( selList.length() < 2 ) { MGlobal:: displayError ( "Not sufficient selection!" ); return MS::kSuccess; } MItSelectionList iter( selList ); iter.reset(); MDagPath meshPath; iter.getDagPath( meshPath ); meshPath.extendToShape(); MObject meshObj = meshPath.node(); MString surface = meshPath.partialPathName(); MStatus status; MFnMesh meshFn(meshPath, &status ); if(!status) { MGlobal:: displayError ( "Not sufficient selection!" ); return MS::kSuccess; } MPointArray vxa; meshFn.getPoints (vxa, MSpace::kWorld); MPoint cenfrom(0.f, 0.f, 0.f); for(unsigned i=0; i<vxa.length(); i++) cenfrom += vxa[i]; cenfrom = cenfrom/(float)vxa.length(); iter.next(); iter.getDagPath( meshPath ); meshPath.extendToShape(); MFnMesh mesh1Fn(meshPath, &status ); if(!status) { MGlobal:: displayError ( "Not sufficient selection!" ); return MS::kSuccess; } vxa.clear(); mesh1Fn.getPoints (vxa, MSpace::kWorld); MPoint cento(0.f, 0.f, 0.f); for(unsigned i=0; i<vxa.length(); i++) cento += vxa[i]; cento = cento/(float)vxa.length(); MVector diff = cento - cenfrom; MDoubleArray res; res.append(diff.x); res.append(diff.y); res.append(diff.z); setResult ( res ); /* if ( !argData.isFlagSet("-i") || !argData.isFlagSet("-o") ) { //MGlobal::displayError( "No .obj or .mcf file specified to translate! Example: mshUtil -i filename.obj -o filename.mcf" ); return MS::kSuccess; } else { argData.getFlagArgument("-i", 0, objname); argData.getFlagArgument("-o", 0, mcfname); return MS::kSuccess; } */ return MS::kSuccess; }