MObject lrutils::createJointFromLocation(MVectorArray location, MString prefix, unsigned int num, MObject parent) { MStatus status = MS::kFailure; MObject jointObj; //make joint object MDagModifier dagMod; jointObj = dagMod.createNode( "joint", MObject::kNullObj, &status ); MyCheckStatus(status, "MDagModifier.createNode() failed"); dagMod.doIt(); //set position lrutils::setLocation(jointObj, location, MFnTransform::MFnTransform(), true, false, false); //set name MString jointName = prefix + "_Skel" + boost::lexical_cast<string>(num).c_str() + "_JNT"; dagMod.renameNode(jointObj, jointName); dagMod.doIt(); MFnTransform jointFn(jointObj); //parent the joint to its parent, if not null if(parent != MObject::kNullObj) { MFnTransform parentFn(parent); MGlobal::executeCommand("parent " + jointFn.fullPathName() + " " + parentFn.fullPathName() + ";"); } return jointObj; }
//----------------------------------------------------------------------------- // Adds a color set to the input history of the passed mesh //----------------------------------------------------------------------------- MObject ValveMaya::AddColorSetToMesh( const MString &colorSetName, const MDagPath &mDagPath, MDagModifier &mDagModifier ) { if ( !mDagPath.hasFn( MFn::kMesh ) ) return MObject::kNullObj; MFnMesh meshFn( mDagPath ); MString uniqueColorSetName; { MStringArray colorSetNames; meshFn.getColorSetNames( colorSetNames ); const uint nColorSets( colorSetNames.length() ); for ( int i( 0 ); uniqueColorSetName.length() == 0; ++i ) { uniqueColorSetName = colorSetName; if ( i > 0 ) { uniqueColorSetName += i; } for ( uint j( 0U ); j != nColorSets; ++j ) { if ( uniqueColorSetName == colorSetNames[ j ] ) { uniqueColorSetName.clear(); break; } } } } // Create a 'createColorSet' node MObject ccsObj( mDagModifier.MDGModifier::createNode( "createColorSet" ) ); mDagModifier.doIt(); const MFnDependencyNode ccsFn( ccsObj ); MPlug csnP( ccsFn.findPlug( "colorSetName" ) ); csnP.setValue( uniqueColorSetName ); // Insert it in the history of the mesh MPlug inMeshP( meshFn.findPlug( "inMesh" ) ); MPlugArray mPlugArray; if ( inMeshP.connectedTo( mPlugArray, true, false ) && mPlugArray.length() ) { mDagModifier.disconnect( mPlugArray[ 0 ], inMeshP ); mDagModifier.connect( mPlugArray[ 0 ], ccsFn.findPlug( "inputGeometry" ) ); } mDagModifier.connect( ccsFn.findPlug( "outputGeometry" ), inMeshP ); mDagModifier.doIt(); return ccsObj; }
/* static */ bool PxrUsdMayaTranslatorUtil::CreateNode( const MString& nodeName, const MString& nodeTypeName, MObject& parentNode, MStatus* status, MObject* mayaNodeObj) { // XXX: // Using MFnDagNode::create() results in nodes that are not properly // registered with parent scene assemblies. For now, just massaging the // transform code accordingly so that child scene assemblies properly post // their edits to their parents-- if this is indeed the best pattern for // this, all Maya*Reader node creation needs to be adjusted accordingly (for // much less trivial cases like MFnMesh). MDagModifier dagMod; *mayaNodeObj = dagMod.createNode(nodeTypeName, parentNode, status); CHECK_MSTATUS_AND_RETURN(*status, false); *status = dagMod.renameNode(*mayaNodeObj, nodeName); CHECK_MSTATUS_AND_RETURN(*status, false); *status = dagMod.doIt(); CHECK_MSTATUS_AND_RETURN(*status, false); return TF_VERIFY(not mayaNodeObj->isNull()); }
MStatus lrutils::makeHomeNull(MObject obj, MFnTransform& transformFn, MObject& groupObj) { MStatus status = MS::kFailure; status = transformFn.setObject(obj); MyCheckStatusReturn(status, "invalid MObject provided for MFnTransform.setObject()"); if( status == MS::kSuccess ) { MDagModifier dagMod; groupObj = dagMod.createNode( "transform", MObject::kNullObj, &status ); MyCheckStatusReturn(status, "MDagModifier.createNode() failed"); dagMod.doIt(); MFnTransform groupFn; groupFn.setObject(groupObj); groupFn.set(transformFn.transformation()); groupFn.addChild(obj); MString groupName = transformFn.name(); groupName = groupName.substring(0, groupName.numChars() - 4); groupName += "GRP"; groupFn.setName(groupName); } return status; }
// Break connections to this blendshape void BlendShape::breakConnections() { MStatus stat; MDagModifier dagModifier; // Clear the stored connections m_weightConnections.clear(); // Save node connections and break them MPlug weightsPlug = m_pBlendShapeFn->findPlug("weight",true); for (int i=0; i<weightsPlug.evaluateNumElements(); i++) { MPlug wPlug = weightsPlug.elementByPhysicalIndex(i); MPlugArray srcConnections; MPlugArray dstConnections; wPlug.connectedTo(srcConnections,false,true); wPlug.connectedTo(dstConnections,true,false); weightConnections wcon; for (int j=0; j<srcConnections.length(); j++) { wcon.srcConnections.append(srcConnections[j]); dagModifier.disconnect(wPlug,srcConnections[j]); dagModifier.doIt(); } for (int j=0; j<dstConnections.length(); j++) { wcon.dstConnections.append(dstConnections[j]); stat = dagModifier.disconnect(dstConnections[j],wPlug); if (MS::kSuccess != stat) { std::cout << "Error trying to disconnect plug " << wPlug.name().asChar() << " and plug " << dstConnections[j].name().asChar() << "\n"; std::cout << stat.errorString().asChar() << "\n"; std::cout.flush(); } stat = dagModifier.doIt(); if (MS::kSuccess != stat) { std::cout << "Error trying to disconnect plug " << wPlug.name().asChar() << " and plug " << dstConnections[j].name().asChar() << "\n"; std::cout << stat.errorString().asChar() << "\n"; std::cout.flush(); } } m_weightConnections.push_back(wcon); } }
// Restore connections on this blendshape void BlendShape::restoreConnections() { MDagModifier dagModifier; // Recreate stored connections on the weight attributes MPlug weightsPlug = m_pBlendShapeFn->findPlug("weight",true); for (int i=0; i<weightsPlug.evaluateNumElements(); i++) { MPlug wPlug = weightsPlug.elementByPhysicalIndex(i); weightConnections& wcon = m_weightConnections[i]; for (int j=0; j<wcon.srcConnections.length(); j++) { dagModifier.connect(wPlug,wcon.srcConnections[j]); dagModifier.doIt(); } for (int j=0; j<wcon.dstConnections.length(); j++) { dagModifier.connect(wcon.dstConnections[j],wPlug); dagModifier.doIt(); } } }
/* static */ bool UsdMayaTranslatorCamera::Read( const UsdGeomCamera& usdCamera, MObject parentNode, const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext* context) { if (!usdCamera) { return false; } const UsdPrim& prim = usdCamera.GetPrim(); const SdfPath primPath = prim.GetPath(); MStatus status; // Create the transform node for the camera. MObject transformObj; if (!UsdMayaTranslatorUtil::CreateTransformNode(prim, parentNode, args, context, &status, &transformObj)) { return false; } // Create the camera shape node. MDagModifier dagMod; MObject cameraObj = dagMod.createNode(_tokens->MayaCameraTypeName.GetText(), transformObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dagMod.doIt(); CHECK_MSTATUS_AND_RETURN(status, false); TF_VERIFY(!cameraObj.isNull()); MFnCamera cameraFn(cameraObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); const std::string cameraShapeName = prim.GetName().GetString() + _tokens->MayaCameraShapeNameSuffix.GetString(); cameraFn.setName(cameraShapeName.c_str(), &status); CHECK_MSTATUS_AND_RETURN(status, false); if (context) { const SdfPath shapePrimPath = primPath.AppendChild(TfToken(cameraShapeName)); context->RegisterNewMayaNode(shapePrimPath.GetString(), cameraObj); } return _ReadToCamera(usdCamera, cameraFn, args, context); }
MStatus lrutils::makeGroup(MObject & obj, MString name) { MStatus status = MS::kFailure; MDagModifier dagMod; MObject groupObj = dagMod.createNode( "transform", MObject::kNullObj, &status ); MyCheckStatusReturn(status, "MDagModifier.createNode() failed"); dagMod.doIt(); MFnTransform groupFn; groupFn.setObject(groupObj); MString groupName = name; groupName += "_GRP"; groupFn.setName(groupName); obj = groupObj; return status; }
void MVGMesh::setIsActive(const bool isActive) const { MStatus status; // Check is flag exists MFnMesh fn(_dagpath); MPlug mvgPlug = fn.findPlug(_MVG, false, &status); if(!status && !isActive) return; if(!status && isActive) { // Create MayaMVG attribute MDagModifier dagModifier; MFnNumericAttribute nAttr; MObject mvgAttr = nAttr.create(_MVG, "mvg", MFnNumericData::kBoolean); status = dagModifier.addAttribute(_object, mvgAttr); CHECK(status) dagModifier.doIt(); mvgPlug = fn.findPlug(_MVG, false, &status); } status = mvgPlug.setValue(isActive); CHECK(status) if(isActive) { status = MGlobal::executePythonCommand("from mayaMVG import scale"); CHECK(status) MString cmd; // Retrieve transform node cmd.format("scale.getParent(\"^1s\")", _dagpath.fullPathName()); MString transform; status = MGlobal::executePythonCommand(cmd, transform); // Freeze transform mesh cmd.format("makeIdentity -apply true \"^1s\"", transform); status = MGlobal::executeCommand(cmd); CHECK(status) // Lock node cmd.format("scale.lockNode(\"^1s\", True)", transform); status = MGlobal::executePythonCommand(cmd); CHECK(status) } else {
void MeshGitCmd::connectNodes(MString nodeName, MString locatorName){ MGlobal::displayInfo("Connecting " + nodeName + " and " + locatorName); MStatus status; //Get Node Object MSelectionList nodeList; status = nodeList.add(nodeName); MObject nodeObject; status = nodeList.getDependNode(0, nodeObject); reportError(status); //Get Viz Object MSelectionList vizList; status = vizList.add(locatorName); MObject vizObject; status = vizList.getDependNode(0, vizObject); reportError(status); //Create Node Fn MeshGitFn mgFn; status = mgFn.setObject(nodeObject); reportError(status); //Create viz fn MFnDependencyNode vizFn(vizObject, &status); //Get the node plug MPlug nodePlug = mgFn.findPlug("message", true, &status); reportError(status); //Get the viz plug MPlug vizPlug = vizFn.findPlug(MeshGitLocatorNode::meshGitNodeConnection, true, &status); //Connect the plugs MDagModifier modifier; status = modifier.connect(nodePlug,vizPlug); reportError(status); status = modifier.doIt(); }
//------------------------------------------------------------------------------ // bool CacheRepresentation::activate() { AssemblyDefinition* const assembly = dynamic_cast< AssemblyDefinition* >( getAssembly() ); if ( assembly == 0 ) { return false; } // Create a gpuCache node, and parent it to our container. MDagModifier dagMod; MStatus status; MObject cacheObj = dagMod.createNode( MString("gpuCache"), assembly->thisMObject(), &status); if (status != MStatus::kSuccess) { int isLoaded = false; // Validate that the gpuCache plugin is loaded. MGlobal::executeCommand( "pluginInfo -query -loaded gpuCache", isLoaded ); if(!isLoaded){ MString errorString = MStringResource::getString(rCreateGPUCacheNodeError, status); MGlobal::displayError(errorString); } return false; } status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } // Set the cache attribute to point to our Alembic file. MFnDependencyNode cache(cacheObj); MPlug fileName = cache.findPlug(MString("cacheFileName"), true, &status); if (status != MStatus::kSuccess) { return false; } fileName.setValue(assembly->getRepData(getName())); return status == MStatus::kSuccess; }
//----------------------------------------------------------------------------- // Creates a vstAttachment Locator //----------------------------------------------------------------------------- MStatus CVstAttachmentCmd::DoCreate() { MDagModifier *mDagModifier( new MDagModifier ); if ( !mDagModifier ) { merr << "Can't create new MDagModifier" << std::endl; return MS::kFailure; } MString optName( "vstAttachment" ); if ( m_mArgDatabase->isFlagSet( kOptName ) ) { m_mArgDatabase->getFlagArgument( kOptName, 0, optName ); } // Create the helper bone locator's transform MObject xObj = mDagModifier->createNode( "transform" ); mDagModifier->doIt(); if ( xObj.isNull() ) { merr << "Can't create new transform node" << std::endl; return MS::kFailure; } // name the shape & the transform the same thing mDagModifier->renameNode( xObj, optName ); mDagModifier->doIt(); MObject vstAttachmentObj = mDagModifier->createNode( "vstAttachment", xObj ); if ( vstAttachmentObj.isNull() ) { merr << "Can't create new vstAttachment node" << std::endl; mDagModifier->undoIt(); return MS::kFailure; } // name the shape & the transform the same thing mDagModifier->renameNode( vstAttachmentObj, MFnDependencyNode( xObj ).name() ); mDagModifier->doIt(); m_undoable = true; m_mDagModifier = mDagModifier; if ( m_mArgDatabase->isFlagSet( kOptParent ) ) { MSelectionList mSelectionList; m_mArgDatabase->getObjects( mSelectionList ); for ( MItSelectionList sIt( mSelectionList, MFn::kDagNode ); !sIt.isDone(); sIt.next() ) { MDagPath mDagPath; if ( sIt.getDagPath( mDagPath ) ) { m_mDagModifier->reparentNode( xObj, mDagPath.node() ); m_mDagModifier->doIt(); break; } } } // Save the current selection just in case we want to undo stuff MGlobal::getActiveSelectionList( m_mSelectionList ); MDagPath xDagPath; MDagPath::getAPathTo( xObj, xDagPath ); MGlobal::select( xDagPath, MObject::kNullObj, MGlobal::kReplaceList ); setResult( xDagPath.partialPathName() ); return MS::kSuccess; }
MStatus CVstAimCmd::redoIt() { MStatus mStatus; if ( !mStatus ) { setResult( MString( "Cannot parse command line" ) + mStatus.errorString() ); return MS::kFailure; } if ( m_mArgDatabase->isFlagSet( kHelp ) ) { PrintHelp(); } else { // See if there are two object specified MDagPath mDagPath; MSelectionList optSelectionList; // Validate specified items to whole dag nodes { MSelectionList tmpSelectionList; m_mArgDatabase->getObjects( tmpSelectionList ); for ( MItSelectionList sIt( tmpSelectionList, MFn::kDagNode ); !sIt.isDone(); sIt.next() ) { if ( sIt.getDagPath( mDagPath ) ) { optSelectionList.add( mDagPath, MObject::kNullObj, true ); } } } if ( m_mArgDatabase->isFlagSet( "create" ) || optSelectionList.length() >= 2 && m_mArgDatabase->numberOfFlagsUsed() == 0 ) { // Error if there aren't at least two if ( optSelectionList.length() < 2 ) { displayError( GetName() + " needs at least two objects specified or selected when -create is used" ); return MS::kFailure; } // Get name command line arg MString optName; if ( m_mArgDatabase->isFlagSet( "name" ) ) { m_mArgDatabase->getFlagArgument( "name", 0, optName ); } m_undoable = true; m_mDagModifier = new MDagModifier; MObject vstAimObj( m_mDagModifier->MDGModifier::createNode( GetName() ) ); if ( m_mDagModifier->doIt() != MS::kSuccess ) { displayError( MString( "Couldn't create " ) + GetName() + " node" ); m_mDagModifier->undoIt(); delete m_mDagModifier; m_mDagModifier = NULL; m_undoable = false; return MS::kFailure; } m_mDagModifier->renameNode( vstAimObj, optName.length() ? optName : GetName() ); if ( m_mDagModifier->doIt() != MS::kSuccess ) { if ( optName.length() ) { displayWarning( MString( "Couldn't rename newly created vstNode \"" ) + optName + "\"" ); } } // Set options on the newly create vstAim node MFnDependencyNode vstAimFn( vstAimObj ); MPlug sP; MPlug dP; if ( m_mArgDatabase->isFlagSet( kAim ) ) { MVector aim; m_mArgDatabase->getFlagArgument( kAim, 0, aim.x ); m_mArgDatabase->getFlagArgument( kAim, 1, aim.y ); m_mArgDatabase->getFlagArgument( kAim, 2, aim.z ); sP = vstAimFn.findPlug( "aimX" ); sP.setValue( aim.x ); sP = vstAimFn.findPlug( "aimY" ); sP.setValue( aim.y ); sP = vstAimFn.findPlug( "aimZ" ); sP.setValue( aim.z ); } if ( m_mArgDatabase->isFlagSet( kUp ) ) { MVector up; m_mArgDatabase->getFlagArgument( kUp, 0, up.x ); m_mArgDatabase->getFlagArgument( kUp, 1, up.y ); m_mArgDatabase->getFlagArgument( kUp, 2, up.z ); sP = vstAimFn.findPlug( "upX" ); sP.setValue( up.x ); sP = vstAimFn.findPlug( "upY" ); sP.setValue( up.y ); sP = vstAimFn.findPlug( "upZ" ); sP.setValue( up.z ); } // Now connect up the newly created vstAim node MDagPath toAim; optSelectionList.getDagPath( 1, toAim ); const MFnDagNode toAimFn( toAim ); if ( toAim.hasFn( MFn::kJoint ) ) { MPlug joP( toAimFn.findPlug( "jointOrient" ) ); if ( !joP.isNull() ) { MAngle jox, joy, joz; joP.child( 0 ).getValue( jox ); joP.child( 1 ).getValue( joy ); joP.child( 2 ).getValue( joz ); if ( abs( jox.value() ) > FLT_EPSILON || abs( joy.value() ) > FLT_EPSILON || abs( joz.value() ) > FLT_EPSILON ) { mwarn << "Joint orient on node being constrained is non-zero ( " << jox.asDegrees() << " " << joy.asDegrees() << " " << joz.asDegrees() << " ), setting to 0" << std::endl; joP.child( 0 ).setValue( MAngle( 0.0 ) ); joP.child( 1 ).setValue( MAngle( 0.0 ) ); joP.child( 2 ).setValue( MAngle( 0.0 ) ); } } } if ( toAim.hasFn( MFn::kTransform ) ) { MPlug mP( toAimFn.findPlug( "rotateAxis" ) ); if ( !mP.isNull() ) { MAngle rx, ry, rz; mP.child( 0 ).getValue( rx ); mP.child( 1 ).getValue( ry ); mP.child( 2 ).getValue( rz ); if ( abs( rx.value() ) > FLT_EPSILON || abs( ry.value() ) > FLT_EPSILON || abs( rz.value() ) > FLT_EPSILON ) { mwarn << "Rotate Axis on node being constrained is non-zero ( " << rx.asDegrees() << " " << ry.asDegrees() << " " << rz.asDegrees() << " ), setting to 0" << std::endl; mP.child( 0 ).setValue( MAngle( 0.0 ) ); mP.child( 1 ).setValue( MAngle( 0.0 ) ); mP.child( 2 ).setValue( MAngle( 0.0 ) ); } } } MDagPath aimAt; optSelectionList.getDagPath( 0, aimAt ); const MFnDagNode aimAtFn( aimAt ); // toAim.rotateOrder -> vstAim.rotateOrder sP = toAimFn.findPlug( "rotateOrder" ); dP = vstAimFn.findPlug( "rotateOrder" ); m_mDagModifier->connect( sP, dP ); // toAim.translate -> vstAim.translate sP = toAimFn.findPlug( "translate" ); dP = vstAimFn.findPlug( "translate" ); m_mDagModifier->connect( sP, dP ); // toAim.parentMatrix[ instance ] -> vstAim.parentSpace sP = toAimFn.findPlug( "parentMatrix" ); sP = sP.elementByLogicalIndex( toAim.instanceNumber() ); dP = vstAimFn.findPlug( "parentSpace" ); m_mDagModifier->connect( sP, dP ); // aimAt.worldMatrix[ instance ] -> vstAim.aimSpace sP = aimAtFn.findPlug( "worldMatrix" ); sP = sP.elementByLogicalIndex( aimAt.instanceNumber() ); dP = vstAimFn.findPlug( "aimSpace" ); m_mDagModifier->connect( sP, dP ); // vstAim.rotation -> toAim.rotation // These have to be connected individually because Maya plays stupid tricks // with rotateOrder if they aren't sP = vstAimFn.findPlug( "rotateX" ); dP = toAimFn.findPlug( "rotateX" ); m_mDagModifier->connect( sP, dP ); sP = vstAimFn.findPlug( "rotateY" ); dP = toAimFn.findPlug( "rotateY" ); m_mDagModifier->connect( sP, dP ); sP = vstAimFn.findPlug( "rotateZ" ); dP = toAimFn.findPlug( "rotateZ" ); m_mDagModifier->connect( sP, dP ); if ( m_mDagModifier->doIt() != MS::kSuccess ) { displayWarning( MString( GetName() ) + ": Couldn't connect everything when creating" ); } // Save the current selection just in case we want to undo stuff MGlobal::getActiveSelectionList( m_mSelectionList ); MGlobal::select( vstAimObj, MGlobal::kReplaceList ); setResult( vstAimFn.name() ); } else if ( m_mArgDatabase->isFlagSet( "select" ) ) { MSelectionList mSelectionList; MDagPath mDagPath; for ( MItDag dagIt; !dagIt.isDone(); dagIt.next() ) { if ( MFnDependencyNode( dagIt.item() ).typeName() == GetName() ) { dagIt.getPath( mDagPath ); mSelectionList.add( mDagPath, MObject::kNullObj, true ); } } if ( mSelectionList.length() ) { m_undoable = true; // Save the current selection just in case we want to undo stuff MGlobal::getActiveSelectionList( m_mSelectionList ); MGlobal::setActiveSelectionList( mSelectionList, MGlobal::kReplaceList ); } } else { displayError( GetName() + ": No valid operation specified via command line arguments\n" ); } } return MS::kSuccess; }
//------------------------------------------------------------------------------ // bool LocatorRepresentation::activate() { MPxAssembly* const assembly = getAssembly(); // Create a locator node, and parent it to our container. MDagModifier dagMod; MStatus status; dagMod.createNode(MString("locator"), assembly->thisMObject(), &status); if (status != MStatus::kSuccess) { return false; } status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } // If we have annotation text, create an annotation shape, and a // transform for it. Parent the annotation transform to the assembly. if (fAnnotation.numChars() > 0) { MObject transformObj = dagMod.createNode( MString("transform"), assembly->thisMObject(), &status); if (status != MStatus::kSuccess) { return false; } MString annotationName = "annotation"; // the + "#" forces Maya to rename using integers for unique names MString transformName = annotationName + "#"; dagMod.renameNode(transformObj, transformName); status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } MObject annotationObj = dagMod.createNode( MString("annotationShape"), transformObj, &status); if (status != MStatus::kSuccess) { return false; } status = dagMod.doIt(); if (status != MStatus::kSuccess) { return false; } // Set the annotation text. MFnDependencyNode annotation(annotationObj); MPlug text = annotation.findPlug(MString("text"), true, &status); if (status != MStatus::kSuccess) { return false; } text.setValue(fAnnotation); // Get rid of the arrow: our annotation doesn't need to be // offset from the locator for readability, since the locator // has no volume. Therefore, we don't need an arrow to point // from the annotation back to the object. MPlug displayArrow = annotation.findPlug(MString("displayArrow"), true, &status); if (status != MStatus::kSuccess) { return false; } displayArrow.setValue(false); } return status == MStatus::kSuccess; }
MStatus Molecule3Cmd::redoIt() { MStatus stat; MDagPath dagPath; MFnMesh meshFn; // Create a ball int nBallPolys; MPointArray ballVerts; MIntArray ballPolyCounts; MIntArray ballPolyConnects; MFloatArray ballUCoords; MFloatArray ballVCoords; MIntArray ballFvUVIDs; genBall( MPoint::origin, ballRodRatio * radius.value(), segs, nBallPolys, ballVerts, ballPolyCounts, ballPolyConnects, true, ballUCoords, ballVCoords, ballFvUVIDs ); unsigned int i, j, vertOffset; MPointArray meshVerts; MPoint p0, p1; MObject objTransform; // Setup for rods int nRodPolys; MPointArray rodVerts; MIntArray rodPolyCounts; MIntArray rodPolyConnects; MFloatArray rodUCoords; MFloatArray rodVCoords; MIntArray rodFvUVIDs; // Setup for newMesh int nNewPolys; MPointArray newVerts; MIntArray newPolyCounts; MIntArray newPolyConnects; MFloatArray newUCoords; MFloatArray newVCoords; MIntArray newFvUVIDs; int uvOffset; MDagModifier dagMod; MFnDagNode dagFn; objTransforms.clear(); // Iterate over the meshes unsigned int mi; for( mi=0; mi < selMeshes.length(); mi++ ) { dagPath = selMeshes[mi]; meshFn.setObject( dagPath ); uvOffset = 0; nNewPolys = 0; newVerts.clear(); newPolyCounts.clear(); newPolyConnects.clear(); newUCoords.clear(); newVCoords.clear(); newFvUVIDs.clear(); // Generate balls meshFn.getPoints( meshVerts, MSpace::kWorld ); for( i=0; i < meshVerts.length(); i++ ) { vertOffset = newVerts.length(); // Add the ball to the new mesh nNewPolys += nBallPolys; // Move the ball vertices to the mesh vertex. Add it to the newMesh for( j=0; j < ballVerts.length(); j++ ) newVerts.append( meshVerts[i] + ballVerts[j] ); for( j=0; j < ballPolyCounts.length(); j++ ) newPolyCounts.append( ballPolyCounts[j] ); for( j=0; j < ballPolyConnects.length(); j++ ) newPolyConnects.append( vertOffset + ballPolyConnects[j] ); // Only add the uv coordinates once, since they are shared // by all balls if( i == 0 ) { for( j=0; j < ballUCoords.length(); j++ ) { newUCoords.append( ballUCoords[j] ); newVCoords.append( ballVCoords[j] ); } } for( j=0; j < ballFvUVIDs.length(); j++ ) { newFvUVIDs.append( uvOffset + ballFvUVIDs[j] ); } } uvOffset = newUCoords.length(); // Generate rods int nRods = 0; MItMeshEdge edgeIter( dagPath ); for( ; !edgeIter.isDone(); edgeIter.next(), nRods++ ) { p0 = edgeIter.point( 0, MSpace::kWorld ); p1 = edgeIter.point( 1, MSpace::kWorld ); // N.B. Generate the uv coordinates only once since they // are referenced by all rods genRod( p0, p1, radius.value(), segs, nRodPolys, rodVerts, rodPolyCounts, rodPolyConnects, nRods == 0, rodUCoords, rodVCoords, rodFvUVIDs ); vertOffset = newVerts.length(); // Add the rod to the mesh nNewPolys += nRodPolys; for( i=0; i < rodVerts.length(); i++ ) newVerts.append( rodVerts[i] ); for( i=0; i < rodPolyCounts.length(); i++ ) newPolyCounts.append( rodPolyCounts[i] ); for( i=0; i < rodPolyConnects.length(); i++ ) newPolyConnects.append( vertOffset + rodPolyConnects[i] ); // First rod if( nRods == 0 ) { // Add rod's uv coordinates to the list for( i=0; i < rodUCoords.length(); i++ ) { newUCoords.append( rodUCoords[i] ); newVCoords.append( rodVCoords[i] ); } } // Set the face-vertex-uvIDs for( i=0; i < rodFvUVIDs.length(); i++ ) { newFvUVIDs.append( uvOffset + rodFvUVIDs[i] ); } } objTransform = meshFn.create( newVerts.length(), nNewPolys, newVerts, newPolyCounts, newPolyConnects, newUCoords, newVCoords, MObject::kNullObj, &stat ); if( !stat ) { MGlobal::displayError( MString( "Unable to create mesh: " ) + stat.errorString() ); return stat; } objTransforms.append( objTransform ); meshFn.assignUVs( newPolyCounts, newFvUVIDs ); meshFn.updateSurface(); // Rename transform node dagFn.setObject( objTransform ); dagFn.setName( "molecule" ); // Put mesh into the initial shading group dagMod.commandToExecute( MString( "sets -e -fe initialShadingGroup " ) + meshFn.name() ); } // Select all the newly created molecule meshes MString cmd( "select -r" ); for( i=0; i < objTransforms.length(); i++ ) { dagFn.setObject( objTransforms[i] ); cmd += " " + dagFn.name(); } dagMod.commandToExecute( cmd ); return dagMod.doIt(); }
void EntityNode::LoadArt() { MStatus stat; bool callbackRemoved = false; if( s_EditNodeAddedCBId != -1 ) { MDGMessage::removeCallback( s_EditNodeAddedCBId ); s_EditNodeAddedCBId = -1; callbackRemoved = true; } UnloadArt(); MString artFilePath; GetArtFilePath( artFilePath ); std::cout << "Importing from: " << artFilePath.asTChar() << "..." << std::endl; // add the callback to catch all the imported objects MObjectArray objectArrays[NodeArrays::Count]; s_ImportNodeAddedCBId = MDGMessage::addNodeAddedCallback( ImportNodeAddedCallback, kDefaultNodeType, &objectArrays ); // import stuff MFileIO::import( artFilePath, NULL, false ); // remove the callback MDGMessage::removeCallback( s_ImportNodeAddedCBId ); // add all imported stuff under this guy's transform MFnDagNode nodeFn( thisMObject() ); for( u32 i=0; i<objectArrays[NodeArrays::KeepNodes].length(); ++i ) { if( objectArrays[NodeArrays::KeepNodes][i].isNull() ) { continue; } MObjectHandle handle( objectArrays[NodeArrays::KeepNodes][i] ); if ( !handle.isValid() ) { continue; } // We should be getting only MFnDagNode in here, but just in case MFnDagNode dagFn( objectArrays[NodeArrays::KeepNodes][i], &stat ); if ( stat == MStatus::kSuccess ) { stat = dagFn.setDoNotWrite( true ); } else { MFnDependencyNode depNodeFn( objectArrays[NodeArrays::KeepNodes][i], &stat ); stat = depNodeFn.setDoNotWrite( true ); } #ifdef _DEBUG MString name = dagFn.name(); MString type = dagFn.typeName(); std::string nodeTypeStr( objectArrays[NodeArrays::KeepNodes][i].apiTypeStr() ); if ( name.length() ) { std::cout << " - Importing Child: " << name.asTChar() << " " << type.asTChar() << "(" << nodeTypeStr << ")" << std::endl; } #endif AddImportNode( objectArrays[NodeArrays::KeepNodes][i] ); nodeFn.addChild( objectArrays[NodeArrays::KeepNodes][i] ); } for( u32 i=0; i<objectArrays[NodeArrays::DeleteNodes].length(); ++i ) { MGlobal::deleteNode( objectArrays[NodeArrays::DeleteNodes][i] ); } MFnDagNode otherFn; for( u32 i=0 ; i<nodeFn.childCount(); ++i ) { MObject child = nodeFn.child( i ); if( !child.hasFn( MFn::kDagNode ) ) { continue; } otherFn.setObject( child ); if( otherFn.typeId() == EntityNode::s_TypeID ) { MDagModifier mod; u32 numChild = otherFn.childCount(); for( u32 j = 0; j < numChild; ++j ) { stat = mod.reparentNode( otherFn.child( j ), thisMObject() ); } mod.doIt(); MGlobal::deleteNode( child ); break; } } std::cout << "Done" << std::endl; }
MStatus HesperisCmd::attachSelected(const Vector3F & offsetV) { MGlobal::displayInfo(MString(" attach to grow mesh ") + m_growMeshName); MSelectionList selList; MGlobal::getActiveSelectionList(selList); MItSelectionList iter( selList ); MDagPath apath; iter.getDagPath( apath ); MObject otrans = apath.node(); if(!otrans.hasFn(MFn::kTransform)) { MGlobal::displayWarning("must select a transform/group to attach to grow mesh"); return MS::kFailure; } ASearchHelper searcher; MDagPath meshGrp; if(!searcher.dagByFullName(m_growMeshName.asChar(), meshGrp)) { MGlobal::displayWarning(MString("cannot find grow mesh by name ")+m_growMeshName); return MS::kFailure; } MObject ogrow = meshGrp.node(); if(!ogrow.hasFn(MFn::kTransform)) { MGlobal::displayWarning("-gm must be a transform/group"); return MS::kFailure; } MStatus stat; MDGModifier modif; MDagModifier dmodif; MObject hestranslate = modif.createNode("hesperisTranslateNode", &stat); modif.doIt(); if(hestranslate.isNull()) { MGlobal::displayWarning("cannot create hes translate node"); return MS::kFailure; } MFnDependencyNode fhest(hestranslate); MFnDependencyNode fgrow(ogrow); modif.connect(fgrow.findPlug("boundingBoxMinX", true), fhest.findPlug("bBoxMinX", true)); modif.connect(fgrow.findPlug("boundingBoxMinY", true), fhest.findPlug("bBoxMinY", true)); modif.connect(fgrow.findPlug("boundingBoxMinZ", true), fhest.findPlug("bBoxMinZ", true)); modif.connect(fgrow.findPlug("boundingBoxMaxX", true), fhest.findPlug("bBoxMaxX", true)); modif.connect(fgrow.findPlug("boundingBoxMaxY", true), fhest.findPlug("bBoxMaxY", true)); modif.connect(fgrow.findPlug("boundingBoxMaxZ", true), fhest.findPlug("bBoxMaxZ", true)); MPlug psrcwpmat = fgrow.findPlug("parentMatrix", true, &stat); if(!stat) MGlobal::displayInfo("cannot find plug worldParentMatrix"); modif.connect(psrcwpmat, fhest.findPlug("inParentMatrix", true)); modif.doIt(); MFnDependencyNode ftrans(otrans); dmodif.connect(fhest.findPlug("outTranslateX", true), ftrans.findPlug("translateX", true)); dmodif.connect(fhest.findPlug("outTranslateY", true), ftrans.findPlug("translateY", true)); dmodif.connect(fhest.findPlug("outTranslateZ", true), ftrans.findPlug("translateZ", true)); stat = dmodif.doIt(); if(!stat) MGlobal::displayInfo(MString("cannot make some connections to ")+ftrans.name()); fhest.findPlug("offsetX").setValue((double)-offsetV.x); fhest.findPlug("offsetY").setValue((double)-offsetV.y); fhest.findPlug("offsetZ").setValue((double)-offsetV.z); return MS::kSuccess; }
MStatus HelixBase_RemoveAllAimConstraints(MObject & helixBase, const char *type) { MStatus status; MFnDagNode this_dagNode(helixBase, &status); if (!status) { status.perror("MFnDagNode::#ctor"); return status; } unsigned int this_childCount = this_dagNode.childCount(&status); bool foundAimConstraint = false; MDagModifier dagModifier; if (!status) { status.perror("MFnDagNode::childCount"); return status; } for(unsigned int i = 0; i < this_childCount; ++i) { MObject child_object = this_dagNode.child(i, &status); if (!status) { if (status == MStatus::kInvalidParameter) { /* * There seems to be a bug in Maya when opening an already existing file that nodes are reported to have children but the MFnDagNode::child will fail */ return MStatus::kSuccess; } status.perror("MFnDagNode::child"); return status; } MFnDagNode child_dagNode(child_object, &status); if (!status) { status.perror("MFnDagNode::#ctor"); return status; } if (child_dagNode.typeName() == "aimConstraint") { foundAimConstraint = true; //std::cerr << "Found an old aimconstraint to delete named: " << child_dagNode.name().asChar() << std::endl; // DEBUG: /*if (child_object.isNull()) { std::cerr << "The object is null! terminating!" << std::endl; return MStatus::kSuccess; }*/ // This is the operation that crashes Maya when creating a "New scene" if (!(status = dagModifier.deleteNode(child_object))) { status.perror("MDagModifier::deleteNode"); return status; } } } // Execute deletion and reset transformation into translation only if (foundAimConstraint) { if (!(status = dagModifier.doIt())) { status.perror("MDagModifier::doIt"); return status; } MFnTransform this_transform(helixBase, &status); if (!status) { status.perror("MFnTransform::#ctor"); return status; } double rotation[] = { 0.0, 0.0, 0.0 }; if (!(status = this_transform.setRotation(rotation, MTransformationMatrix::kXYZ))) { status.perror("MFnTransform::setRotation"); return status; } } return MStatus::kSuccess; }
bool ToMayaLocatorConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const { ConstCoordinateSystemPtr coordSys = IECore::runTimeCast<const CoordinateSystem>( from ); if ( !coordSys ) { IECore::msg( IECore::Msg::Warning, "ToMayaLocatorConverter::doConversion", "The source object is not an IECore::CoordinateSystem." ); return false; } // check if incoming object is a locator itself MObject locatorObj; if ( to.hasFn( MFn::kLocator ) ) { locatorObj = to; } // check if incoming object is a parent of an existing locator if ( locatorObj.isNull() ) { MFnDagNode fnTo( to ); for ( unsigned i=0; i < fnTo.childCount(); ++i ) { MObject child = fnTo.child( i ); if ( child.hasFn( MFn::kLocator ) ) { locatorObj = child; break; } } } // make a new locator and parent it to the incoming object if ( locatorObj.isNull() ) { if ( !MFnTransform().hasObj( to ) ) { IECore::msg( IECore::Msg::Warning, "ToMayaLocatorConverter::doConversion", "Unable to create a locator as a child of the input object." ); return false; } MDagModifier dagMod; locatorObj = dagMod.createNode( "locator", to ); dagMod.renameNode( locatorObj, coordSys->getName().c_str() ); if ( !dagMod.doIt() ) { IECore::msg( IECore::Msg::Warning, "ToMayaLocatorConverter::doConversion", "Unable to modify the DAG correctly." ); dagMod.undoIt(); return false; } } if ( locatorObj.isNull() ) { IECore::msg( IECore::Msg::Warning, "ToMayaLocatorConverter::doConversion", "Unable to find or create a locator from the input object." ); return false; } MFnDagNode fnLocator( locatorObj ); Imath::M44f m = coordSys->getTransform()->transform(); Imath::V3f s,h,r,t; Imath::extractSHRT(m, s, h, r, t); /// obtain local position and scale from locator MStatus st; MPlug positionPlug = fnLocator.findPlug( "localPositionX", &st ); if ( !st ) return false; positionPlug.setValue(t[0]); positionPlug = fnLocator.findPlug( "localPositionY", &st ); if ( !st ) return false; positionPlug.setValue(t[1]); positionPlug = fnLocator.findPlug( "localPositionZ", &st ); if ( !st ) return false; positionPlug.setValue(t[2]); MPlug scalePlug = fnLocator.findPlug( "localScaleX", &st ); if ( !st ) return false; scalePlug.setValue(s[0]); scalePlug = fnLocator.findPlug( "localScaleY", &st ); if ( !st ) return false; scalePlug.setValue(s[1]); scalePlug = fnLocator.findPlug( "localScaleZ", &st ); if ( !st ) return false; scalePlug.setValue(s[2]); return true; }
MObject create(Alembic::AbcGeom::ICamera & iNode, MObject & iParent) { Alembic::AbcGeom::ICameraSchema schema = iNode.getSchema(); MString name(iNode.getName().c_str()); MFnCamera fnCamera; MObject obj = fnCamera.create(iParent); fnCamera.setName(name); // we need to read this to determine the film fit Alembic::AbcGeom::CameraSample samp; iNode.getSchema().get(samp); std::size_t numOps = samp.getNumOps(); if (numOps > 0) { std::string hint = samp[0].getHint(); if (hint == "filmFitFill") { fnCamera.setFilmFit(MFnCamera::kFillFilmFit); } else if (hint == "filmFitHorz") { fnCamera.setFilmFit(MFnCamera::kHorizontalFilmFit); } else if (hint == "filmFitVert") { fnCamera.setFilmFit(MFnCamera::kVerticalFilmFit); } else if (hint == "filmFitOver") { fnCamera.setFilmFit(MFnCamera::kOverscanFilmFit); } } if (schema.isConstant()) { // no center of interest fnCamera.setFocalLength(samp.getFocalLength()); fnCamera.setLensSqueezeRatio(samp.getLensSqueezeRatio()); // camera scale might be in the 3x3 // weirdo attrs that are in inches fnCamera.setHorizontalFilmAperture(samp.getHorizontalAperture()/2.54); fnCamera.setVerticalFilmAperture(samp.getVerticalAperture()/2.54); fnCamera.setHorizontalFilmOffset(samp.getHorizontalFilmOffset()/2.54); fnCamera.setVerticalFilmOffset(samp.getVerticalFilmOffset()/2.54); // film fit offset might be in the 3x3 if (samp.getOverScanLeft() == samp.getOverScanRight() && samp.getOverScanTop() == samp.getOverScanBottom() && samp.getOverScanLeft() == samp.getOverScanTop()) { fnCamera.setOverscan(samp.getOverScanLeft() + 1.0); } else { MString warn = iNode.getName().c_str(); warn += " has unsupported overscan values."; MGlobal::displayWarning(warn); } fnCamera.setNearClippingPlane(samp.getNearClippingPlane()); fnCamera.setFarClippingPlane(samp.getFarClippingPlane()); // prescale, film translate H, V, roll pivot H,V, film roll value // post scale might be in the 3x3 fnCamera.setFStop(samp.getFStop()); fnCamera.setFocusDistance(samp.getFocusDistance()); MTime sec(1.0, MTime::kSeconds); fnCamera.setShutterAngle(Alembic::AbcGeom::DegreesToRadians( 360.0 * (samp.getShutterClose()-samp.getShutterOpen()) * sec.as(MTime::uiUnit()) )); for (std::size_t i = 0; i < numOps; ++i) { Alembic::AbcGeom::FilmBackXformOp & op = samp[i]; if (op.getHint() == "filmFitOffs") { double val = op.getChannelValue(0) * samp.getHorizontalAperture() / 5.08; if (val != 0.0) { fnCamera.setFilmFitOffset(val); } else { fnCamera.setFilmFitOffset(op.getChannelValue(1) * samp.getHorizontalAperture() / 5.08); } } else if (op.getHint() == "preScale") { fnCamera.setPreScale(1.0/op.getChannelValue(0)); } else if (op.getHint() == "filmTranslate") { fnCamera.setFilmTranslateH(op.getChannelValue(0)); fnCamera.setFilmTranslateV(op.getChannelValue(1)); } else if (op.getHint() == "postScale") { fnCamera.setPostScale(1.0/op.getChannelValue(0)); } else if (op.getHint() == "cameraScale") { fnCamera.setCameraScale(op.getChannelValue(0)); } } } // extra transform node is unfortuneatly automatically created above the // camera, let's do some reparenting and delete that extra transform MDagPath path; fnCamera.getPath(path); MObject camObj = path.node(); MDagModifier dagMod; dagMod.reparentNode(camObj, iParent); dagMod.doIt(); dagMod.deleteNode(obj); dagMod.doIt(); return camObj; }