コード例 #1
0
void lrutils::createFKCtlFromLocation(MVectorArray location, MObject joint, MString prefix, unsigned int num, MString icon, MString color, MObject parent, MObject& fkCtlObj, MObject& fkCtlGroupObj, MString layerName, MObject metaDataNode) {
    MStatus status;
    MDGModifier dgMod;
    //used for holding results from executed commands
    MStringArray result;
    MFnDependencyNode depMetaDataNodeFn(metaDataNode);
    //used for creating metaParent attributes for objects
    MFnMessageAttribute mAttr;
    MFnTransform jointFn(joint);
    
    //create the control object and set its color
    status = MGlobal::executeCommand( "python(\"control = rig101().rig101WCGetByName('" + icon + "')\");" );
    status = MGlobal::executeCommand( "python(\"Utils.setControllerColor(control, '" + color + "')\");" );
    status = MGlobal::executeCommand( MString("python(\"control.fullPath()\");"), result );
    //get the MObject for the controller
    status = lrutils::getObjFromName(result[0], fkCtlObj);
    MyCheckStatus(status, "lrutils::getObjFromName() failed");
    MFnTransform fkCtlFn( fkCtlObj );
    lrutils::setLocation(fkCtlObj, location, MFnTransform::MFnTransform(), false, false, true);
    //set controller name
    MString fkCtlName = prefix + "_FK_"+num+"_CTL";
    dgMod.renameNode(fkCtlObj, fkCtlName);
    //add the metaParent attribute to the controller
    MObject controlAttr = mAttr.create("metaParent", "metaParent");
    fkCtlFn.addAttribute(controlAttr);
    //connect the controller's metaParent to the MDSpine node
    status = dgMod.connect( depMetaDataNodeFn.findPlug("FKControllers"), fkCtlFn.findPlug("metaParent") );
    dgMod.doIt();
    
    //create the fk control null
    lrutils::makeHomeNull(fkCtlObj, MFnTransform(), fkCtlGroupObj);
    lrutils::setLocation(fkCtlGroupObj, location, MFnTransform::MFnTransform(), true, true, false);
    MFnTransform fkCtlGroupFn( fkCtlGroupObj );
    if(!parent.isNull()) {
        MFnTransform parentFn(parent);
        MGlobal::executeCommand("parent " + fkCtlGroupFn.fullPathName() + " " + parentFn.fullPathName() + ";");
    }
    //add the metaParent attribute to the controller group
    fkCtlGroupFn.addAttribute(mAttr.create("metaParent", "metaParent"));
    //connect the controller group's metaParent to the MDGlobal node
    status = dgMod.connect( depMetaDataNodeFn.findPlug("FKControllerGroups"), fkCtlGroupFn.findPlug("metaParent") );
    MyCheckStatus(status, "connect failed"); 
    dgMod.doIt();

    MGlobal::executeCommand("parentConstraint -mo " + fkCtlFn.fullPathName() + " " + jointFn.fullPathName() + ";",result);
    MObject jointParentConstraintObj;
    status = lrutils::getObjFromName(result[0], jointParentConstraintObj);
    MyCheckStatus(status, "lrutils::getObjFromName() failed");
    MFnTransform jointParentConstraintFn(jointParentConstraintObj);
    jointParentConstraintFn.addAttribute(mAttr.create("metaParent", "metaParent"));
    status = dgMod.connect( depMetaDataNodeFn.findPlug("FKJointParentConstraints"), jointParentConstraintFn.findPlug("metaParent"));
    dgMod.doIt();

    //set the display layers for the controller and controller group
    MGlobal::executeCommand("editDisplayLayerMembers -noRecurse "+ layerName+" "+ fkCtlFn.fullPathName()+";");
    MGlobal::executeCommand("editDisplayLayerMembers -noRecurse "+ layerName+" "+ fkCtlGroupFn.fullPathName()+";");
    MGlobal::executeCommand("select -cl;");
}
コード例 #2
0
sgBLocator_fromGeo::sgBLocator_fromGeo()
{
	m_pointArr.setLength(6);

 	m_pointArr[0] = MFloatPoint(  1,  0, 0 );
	m_pointArr[1] = MFloatPoint( -1,  0, 0 );
	m_pointArr[2] = MFloatPoint(  0, -1, 0 );
	m_pointArr[3] = MFloatPoint(  0,  1, 0 );
	m_pointArr[4] = MFloatPoint(  0,  0, 1 );
	m_pointArr[5] = MFloatPoint(  0,  0, -1 );

	m_boundingBox.clear();
    m_boundingBox.expand( MVector( 1.0, 1.0, 1.0 ) );
    m_boundingBox.expand( MVector( -1.0, -1.0, -1.0 ) );

	m_colorActive =  MColor( 1.0f, 1.0f, 1.0f );
	m_colorLead   =	 MColor( .26f, 1.0f, .64f );
	m_colorDefault = MColor( 1.0f, 1.0f, 0.0f );

	m_lineWidth = 1;

	MFnDependencyNode fnNode( thisMObject() );
	MPlug plugOutput = fnNode.findPlug( aOutputValue );
	MPlug plugVis    =fnNode.findPlug( "v" );

	MDGModifier dgModifier;
	dgModifier.connect( plugOutput, plugVis );
}
コード例 #3
0
    //---------------------------------------------------
    bool DagHelper::connectToList ( const MPlug& source, const MObject& destination, const MString& destinationAttribute, int* _index )
    {
        MStatus status;
        MFnDependencyNode destFn ( destination );
        MPlug dest = destFn.findPlug ( destinationAttribute, &status );

        if ( status != MStatus::kSuccess ) return false;

        if ( !dest.isArray() ) return false;

        int index = ( _index != NULL ) ? *_index : -1;

        if ( index < 0 )
        {
            index = getNextAvailableIndex ( dest, ( int ) dest.evaluateNumElements() );

            if ( _index != NULL ) *_index = index;
        }

        MPlug d = dest.elementByLogicalIndex ( index );

        MDGModifier modifier;
        modifier.connect ( source, d );
        status = modifier.doIt();
        return status == MStatus::kSuccess;
    }
コード例 #4
0
    //---------------------------------------------------
    bool DagHelper::connect ( const MPlug& source, const MPlug& destination )
    {
        MDGModifier modifier;
        modifier.connect ( source, destination );
        MStatus status = modifier.doIt();

        return status == MStatus::kSuccess;
    }
コード例 #5
0
void NifTextureConnector::ConnectTexture( MDagPath mesh_path ) {
	MDGModifier dgModifier;
	MFnDependencyNode chooserFn;
	chooserFn.create( "uvChooser", "uvChooser" );

	//Connection between the mesh and the uvChooser
	MFnMesh meshFn;
	meshFn.setObject(mesh_path);
	dgModifier.connect( meshFn.findPlug("uvSet")[uvSet].child(0), chooserFn.findPlug("uvSets").elementByLogicalIndex(0) );

	//Connections between the uvChooser and the place2dTexture
	dgModifier.connect( chooserFn.findPlug("outUv"), texturePlacement.findPlug("uvCoord") );
	dgModifier.connect( chooserFn.findPlug("outVertexCameraOne"), texturePlacement.findPlug("vertexCameraOne") );
	dgModifier.connect( chooserFn.findPlug("outVertexUvOne"), texturePlacement.findPlug("vertexUvOne") );
	dgModifier.connect( chooserFn.findPlug("outVertexUvTwo"), texturePlacement.findPlug("vertexUvTwo") );
	dgModifier.connect( chooserFn.findPlug("outVertexUvThree"), texturePlacement.findPlug("vertexUvThree") );
	dgModifier.doIt();
}
コード例 #6
0
std::vector<MObject> lrutils::buildSkeletonFromGuide(std::vector<MVectorArray> locations, MString prefix, MPlug metaDataPlug, MObject metaParentJoint, MString layerName) {
    MDGModifier dgMod;
    MStatus status;
    std::vector<MObject> joints;
    MFnMessageAttribute mAttr;

    MObject parentJoint;
    unsigned int jointNum = 0;

    for (std::vector<MVectorArray>::iterator it = locations.begin(); it != locations.end(); ++it) {
        MVectorArray location = *it;
        MObject joint = createJointFromLocation(location, prefix, jointNum, parentJoint);
        joints.push_back(joint);

        MFnTransform jointFn( joint );
        //add metaParent attributes to joint
        if(!metaDataPlug.isNull()) {
            MObject jointAttr = mAttr.create("metaParent", "metaParent");
            jointFn.addAttribute(jointAttr);
            //connect the metaparent attribute to the MDSpine node
            status = dgMod.connect( metaDataPlug, jointFn.findPlug("metaParent") );
            MyCheckStatus(status, "connect failed");
            dgMod.doIt();
        }

        //if layer name is provided, add the joint to that display layer
        if(layerName != "") {
            MGlobal::executeCommand("editDisplayLayerMembers -noRecurse "+ layerName+" "+ jointFn.name()+";");
        }

        parentJoint = joint;
        jointNum++;
    }
    //orient the joint chain
    MFnTransform topJointFn(joints.at(0));
    MGlobal::executeCommand("joint -e -zso -oj \"xyz\" -sao \"yup\" -ch " + topJointFn.fullPathName() + ";");

    //if meta parent joint is not null, parent first joint to it
    if(!metaParentJoint.isNull()) {
        MFnTransform firstJointFn(joints.at(0));

        MFnTransform metaParentJointFn(metaParentJoint);
        MGlobal::executeCommand("parent " + firstJointFn.fullPathName() + " " + metaParentJointFn.fullPathName() + ";");
        //orient the parent joint
        MGlobal::executeCommand("joint -e -zso -oj \"xyz\" -sao \"yup\" -ch " + metaParentJointFn.fullPathName() + ";");
    }

    return joints;
}
コード例 #7
0
    //---------------------------------------------------
    bool DagHelper::connect ( const MObject& source, const MString& sourceAttribute, const MPlug& destination )
    {
        MStatus status;
        MFnDependencyNode srcFn ( source );

        MPlug src = srcFn.findPlug ( sourceAttribute, &status );

        if ( status != MStatus::kSuccess ) return false;

        MDGModifier modifier;

        modifier.connect ( src, destination );

        status = modifier.doIt();

        return status == MStatus::kSuccess;
    }
コード例 #8
0
ファイル: inSpecularMaterial.cpp プロジェクト: MassW/OpenMaya
// the postConstructor() function is called immediately after the objects
// constructor. It is not safe to call MPxNode member functions from the
// constructor, instead they should be called here.
//
void inSpecular::postConstructor( )
{
	MStatus stat;
    // setMPSafe indicates that this shader can be used for multiprocessor
    // rendering. For a shading node to be MP safe, it cannot access any
    // shared global data and should only use attributes in the datablock
    // to get input data and store output data.
    //
    setMPSafe( true );

	MDGModifier modifier;

	MPlug sourcePlug = MPlug(this->thisMObject(), emission);
	MPlug destPlug = MPlug(this->thisMObject(), aIncandescence);
	if( !destPlug.isConnected() )
		stat = modifier.connect(sourcePlug, destPlug);

	stat = modifier.doIt();
}
コード例 #9
0
    //---------------------------------------------------
    bool DagHelper::connect ( const MPlug& source, const MObject& destination, const MString& destinationAttribute )
    {
        MStatus status;
        MFnDependencyNode destFn ( destination );

        MPlug dst = destFn.findPlug ( destinationAttribute, &status );

        if ( status != MStatus::kSuccess ) return false;

        MDGModifier modifier;

        status = modifier.connect ( source, dst );

        if ( status != MStatus::kSuccess ) return false;

        status = modifier.doIt();

        return status == MStatus::kSuccess;
    }
void
VertexPolyColourCommand::CreateNodeOnMesh(MDagPath& dagPath, MObject& ourNode)
{
	MStatus status;

	MFnDependencyNode fnDependNode( dagPath.node() );
	MPlug plug_outMesh = fnDependNode.findPlug("outMesh");

	MDGModifier* modifier = new MDGModifier;

	// Create the node
	ourNode=modifier->createNode("RH_VCP_PolyColourNode", &status);
	if (status != MStatus::kSuccess)
		MGlobal::doErrorLogEntry("error");

	// Connect it
	MFnDependencyNode dn(ourNode, &status);
	if (status != MStatus::kSuccess)
		MGlobal::doErrorLogEntry("error");
	MString dnname = dn.name();
	MPlug plug_inMesh=dn.findPlug(PolyColourNode::m_inMesh,&status);
	MString plugName = plug_inMesh.name();
	if (status != MStatus::kSuccess)
		MGlobal::doErrorLogEntry("error");
	status=modifier->connect(plug_outMesh,plug_inMesh);
	if (status != MStatus::kSuccess)
		MGlobal::doErrorLogEntry("error");

	status=modifier->doIt();
	if (status != MStatus::kSuccess)
		MGlobal::doErrorLogEntry("error");

	if (m_isUndoable)
		m_undos.push_back(modifier);
	else
		delete modifier;
}
コード例 #11
0
void EntityNode::AddImportNode( const MObject& object )
{
    MStatus stat;
    MObjectHandle handle( object );
    if( !handle.isValid() )
    {
        return;
    }

    MFnDependencyNode nodeFn( object, &stat );
    MCheckNoErr( stat, "Unable to create depenency node fn set" );
    nodeFn.setDoNotWrite( true );

    //MItDependencyGraph childrenIt (MItDependencyGraph::kUpstream);
    //for ( childrenIt.reset( nodeFn.object() ); !childrenIt.isDone(); childrenIt.next() )
    //{
    //  MFnDependencyNode( childrenIt.item() ).setDoNotWrite( true );
    //}

    MString name = nodeFn.name( &stat );
    MCheckNoErr( stat, "Unable to get node name" );

    if( name == "" )
    {
        return;
    }

    // don't connect dag nodes to the ImportNodes attributeb array
    if( object.hasFn( MFn::kDagNode ) )
    {
        return;
    }

#ifdef _DEBUG
    std::cout << "Adding: " << name.asTChar() << std::endl;
#endif

    //create ImportMessage attrib on the imported object if necessary
    if( !nodeFn.hasAttribute( "ImportMessage", &stat ) )
    {
        MFnMessageAttribute mAttr;
        MObject importMessage = mAttr.create( "ImportMessage", "imp", &stat );
        MCheckNoErr(stat, "Unable to create attr: ImportMessage");

        stat = nodeFn.addAttribute( importMessage );
        MCheckNoErr(stat, "Unable to add attr: ImportNodes"); 
    }

    MPlug importMsg = nodeFn.findPlug( "ImportMessage", &stat );
    MCheckNoErr(stat, "Unable to find attr: ImportMessage");

    MPlug importPlug( thisMObject(), m_ImportNodes );
    u32 currentIdx = importPlug.numConnectedElements();
    MPlug importElement = importPlug.elementByLogicalIndex( currentIdx );

    MDGModifier mod;

    //if it's currently connected, disconnect it
    if( importMsg.isConnected() )
    {
        MPlugArray plugs;
        importMsg.connectedTo( plugs, true, false );
        if( plugs.length() == 1 )
        {
            mod.disconnect( importMsg, plugs[0] );
        }
    }
    stat = mod.connect( importMsg, importElement );
    mod.doIt();
}
コード例 #12
0
bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
    MStatus s;

    IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from );
    assert( skinningData );

    const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable();
    const std::vector<Imath::M44f> &influencePoseData  = skinningData->influencePose()->readable();
    const std::vector<int> &pointIndexOffsets  = skinningData->pointIndexOffsets()->readable();
    const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable();
    const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable();
    const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable();

    MFnDependencyNode fnSkinClusterNode( to, &s );
    MFnSkinCluster fnSkinCluster( to, &s );
    if ( s != MS::kSuccess )
    {
        /// \todo: optional parameter to allow custom node types and checks for the necessary attributes
        /// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one
        throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() );
    }

    const unsigned origNumInfluences = influenceNames.size();
    unsigned numInfluences = origNumInfluences;
    std::vector<bool> ignoreInfluence( origNumInfluences, false );
    std::vector<int> indexMap( origNumInfluences, -1 );
    const bool ignoreMissingInfluences = m_ignoreMissingInfluencesParameter->getTypedValue();
    const bool ignoreBindPose = m_ignoreBindPoseParameter->getTypedValue();

    // gather the influence objects
    MObject mObj;
    MDagPath path;
    MSelectionList influenceList;
    MDagPathArray influencePaths;
    for ( unsigned i=0, index=0; i < origNumInfluences; i++ )
    {
        MString influenceName( influenceNames[i].c_str() );
        s = influenceList.add( influenceName );
        if ( !s )
        {
            if ( ignoreMissingInfluences )
            {
                ignoreInfluence[i] = true;
                MGlobal::displayWarning( MString( "ToMayaSkinClusterConverter: \"" + influenceName + "\" is not a valid influence" ) );
                continue;
            }

            throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid influence" ) % influenceName ).str() );
        }

        influenceList.getDependNode( index, mObj );
        MFnIkJoint fnInfluence( mObj, &s );
        if ( !s )
        {
            if ( ignoreMissingInfluences )
            {
                ignoreInfluence[i] = true;
                influenceList.remove( index );
                MGlobal::displayWarning( MString( "ToMayaSkinClusterConverter: \"" + influenceName + "\" is not a valid influence" ) );
                continue;
            }

            throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid influence" ) % influenceName ).str() );
        }

        fnInfluence.getPath( path );
        influencePaths.append( path );
        indexMap[i] = index;
        index++;
    }

    MPlugArray connectedPlugs;

    bool existingBindPose = true;
    MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s );
    if ( !bindPlug.connectedTo( connectedPlugs, true, false ) )
    {
        existingBindPose = false;
        if ( !ignoreBindPose )
        {
            throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" does not have a valid bindPose" ) % fnSkinClusterNode.name() ).str() );
        }
    }

    MPlug bindPoseMatrixArrayPlug;
    MPlug bindPoseMemberArrayPlug;
    if ( existingBindPose )
    {
        MFnDependencyNode fnBindPose( connectedPlugs[0].node() );
        if ( fnBindPose.typeName() != "dagPose" )
        {
            throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid bindPose" ) % fnBindPose.name() ).str() );
        }

        bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s );
        bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s );
    }

    /// \todo: optional parameter to reset the skinCluster's geomMatrix plug

    // break existing influence connections to the skinCluster
    MDGModifier dgModifier;
    MMatrixArray ignoredPreMatrices;
    MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s );
    MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s );
    for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ )
    {
        MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s );
        matrixPlug.connectedTo( connectedPlugs, true, false );
        if ( !connectedPlugs.length() )
        {
            continue;
        }

        MFnIkJoint fnInfluence( connectedPlugs[0].node() );
        fnInfluence.getPath( path );
        if ( ignoreMissingInfluences && !influenceList.hasItem( path ) )
        {
            MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i );
            preMatrixPlug.getValue( mObj );
            MFnMatrixData matFn( mObj );
            ignoredPreMatrices.append( matFn.matrix() );
            ignoreInfluence.push_back( false );
            indexMap.push_back( influenceList.length() );
            influenceList.add( connectedPlugs[0].node() );
            numInfluences++;
        }
        dgModifier.disconnect( connectedPlugs[0], matrixPlug );
    }
    MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s );
    for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ )
    {
        MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s );
        lockPlug.connectedTo( connectedPlugs, true, false );
        if ( connectedPlugs.length() )
        {
            dgModifier.disconnect( connectedPlugs[0], lockPlug );
        }
    }
    MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s );
    paintPlug.connectedTo( connectedPlugs, true, false );
    if ( connectedPlugs.length() )
    {
        dgModifier.disconnect( connectedPlugs[0], paintPlug );
    }

    // break existing influence connections to the bind pose
    if ( existingBindPose )
    {
        for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ )
        {
            MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s );
            matrixPlug.connectedTo( connectedPlugs, true, false );
            if ( connectedPlugs.length() )
            {
                dgModifier.disconnect( connectedPlugs[0], matrixPlug );
            }
        }
        for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ )
        {
            MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s );
            memberPlug.connectedTo( connectedPlugs, true, false );
            if ( connectedPlugs.length() )
            {
                dgModifier.disconnect( connectedPlugs[0], memberPlug );
            }
        }
    }

    if ( !dgModifier.doIt() )
    {
        dgModifier.undoIt();
        throw IECore::Exception( "ToMayaSkinClusterConverter: Unable to break the influence connections" );
    }

    // make connections from influences to skinCluster and bindPose
    for ( unsigned i=0; i < numInfluences; i++ )
    {
        if ( ignoreInfluence[i] )
        {
            continue;
        }

        int index = indexMap[i];
        s = influenceList.getDependNode( index, mObj );
        MFnIkJoint fnInfluence( mObj, &s );
        MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s );
        MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
        MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s );
        MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
        if ( !s )
        {
            // add the lockInfluenceWeights attribute if it doesn't exist
            MFnNumericAttribute nAttr;
            MObject attribute = nAttr.create( "lockInfluenceWeights", "liw", MFnNumericData::kBoolean, false );
            fnInfluence.addAttribute( attribute );
            influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
        }

        // connect influence to the skinCluster
        MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( index );
        MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( index );
        dgModifier.connect( influenceMatrixPlug, matrixPlug );
        dgModifier.connect( influenceLockPlug, lockPlug );

        // connect influence to the bindPose
        if ( !ignoreBindPose )
        {
            MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( index );
            MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( index );
            dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug );
            dgModifier.connect( influenceBindPosePlug, memberPlug );
        }
    }
    unsigned firstIndex = find( ignoreInfluence.begin(), ignoreInfluence.end(), false ) - ignoreInfluence.begin();
    influenceList.getDependNode( firstIndex, mObj );
    MFnDependencyNode fnInfluence( mObj );
    MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
    dgModifier.connect( influenceMessagePlug, paintPlug );
    if ( !dgModifier.doIt() )
    {
        dgModifier.undoIt();
        throw IECore::Exception( "ToMayaSkinClusterConverter: Unable to create the influence connections" );
    }

    // use influencePoseData as bindPreMatrix
    for ( unsigned i=0; i < numInfluences; i++ )
    {
        if ( ignoreInfluence[i] )
        {
            continue;
        }

        MMatrix preMatrix = ( i < origNumInfluences ) ? IECore::convert<MMatrix>( influencePoseData[i] ) : ignoredPreMatrices[i-origNumInfluences];
        MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( indexMap[i], &s );
        s = preMatrixPlug.getValue( mObj );
        if ( s )
        {
            MFnMatrixData matFn( mObj );
            matFn.set( preMatrix );
            mObj = matFn.object();
        }
        else
        {
            MFnMatrixData matFn;
            mObj = matFn.create( preMatrix );
        }

        preMatrixPlug.setValue( mObj );
    }

    // remove unneeded bindPreMatrix children
    unsigned existingElements = bindPreMatrixArrayPlug.numElements();
    for ( unsigned i=influenceList.length(); i < existingElements; i++ )
    {
        MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s );
        /// \todo: surely there is a way to accomplish this in c++...
        MGlobal::executeCommand( ( boost::format( "removeMultiInstance %s" ) % preMatrixPlug.name() ).str().c_str() );
    }

    // get the geometry
    MObjectArray outputGeoObjs;
    if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) )
    {
        throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() );
    }
    MFnDagNode dagFn( outputGeoObjs[0] );
    MDagPath geoPath;
    dagFn.getPath( geoPath );

    // loop through all the points of the geometry and set the weights
    MItGeometry geoIt( outputGeoObjs[0] );
    MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s );
    for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ )
    {
        MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 );

        // remove existing influence weight plugs
        MIntArray existingInfluenceIndices;
        pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices );
        for( unsigned i=0; i < existingInfluenceIndices.length(); i++ )
        {
            MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s );
            MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() );
        }

        // add new influence weight plugs
        int firstIndex = pointIndexOffsets[pIndex];
        for( int i=0; i < pointInfluenceCounts[pIndex]; i++ )
        {
            int influenceIndex = pointInfluenceIndices[ firstIndex + i ];
            if ( ignoreInfluence[ influenceIndex ] )
            {
                continue;
            }

            int skinClusterInfluenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ indexMap[ influenceIndex ] ] );
            MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( skinClusterInfluenceIndex, &s );
            influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] );
        }
    }

    return true;
}
コード例 #13
0
ファイル: HesperisCmd.cpp プロジェクト: spinos/aphid
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;
}
コード例 #14
0
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;

   }

}
コード例 #15
0
ファイル: polyModifierCmd.cpp プロジェクト: Byron/bsuite
// --------------------------------------------------------------------------------------------
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;
}
コード例 #16
0
ファイル: polyModifierCmd.cpp プロジェクト: Byron/bsuite
// --------------------------------------------------------------------------------------------
MStatus polyModifierCmd::processUpstreamNode( modifyPolyData& data )
// --------------------------------------------------------------------------------------------
{
	MStatus status = MS::kSuccess;

	// Declare our function sets - Although dagNodeFn derives from depNodeFn, we need
	//							   both since dagNodeFn can only refer to DAG objects.
	//							   We will use depNodeFn for all times other when dealing
	//							   with the DAG.
	//
	MFnDependencyNode	depNodeFn;
	MFnDagNode			dagNodeFn;

	// Use the selected node's plug connections to find the upstream plug.
	// Since we are looking at the selected node's inMesh attribute, it will
	// always have only one connection coming in if it has history, and none
	// otherwise.
	//
	// If there is no history, copy the selected node and place it ahead of the
	// modifierNode as the new upstream node so that the modifierNode has an
	// input mesh to operate on.
	//

	//save the meshDagPath for later use
	MDagPath::getAPathTo(data.meshNodeShape,myMeshPath);

	MPlugArray tempPlugArray;

 	if( fHasHistory )
	{
		// Since we have history, look for what connections exist on the
		// meshNode "inMesh" plug. "inMesh" plugs should only ever have one
		// connection.
		//
		data.meshNodeDestPlug.connectedTo( tempPlugArray, true, false);
		

		// ASSERT: Only one connection should exist on meshNodeShape.inMesh!
		//
		MStatusAssert( (tempPlugArray.length() == 1),
					   "tempPlugArray.length() == 1 -- 0 or >1 connections on meshNodeShape.inMesh" );
		data.upstreamNodeSrcPlug = tempPlugArray[0];

		
		// Construction history only deals with shapes, so we can grab the
		// upstreamNodeShape off of the source plug.
		//
		// Dieser Bereich muss bleiben, weil diese Attribute noch bentigt werden
		data.upstreamNodeShape = data.upstreamNodeSrcPlug.node();
		depNodeFn.setObject( data.upstreamNodeShape );
		data.upstreamNodeSrcAttr = data.upstreamNodeSrcPlug.attribute();
		

		// Disconnect the upstream node and the selected node, so we can
		// replace them with our own connections below.
		//
		MPlug	nodePlug(data.meshNodeShape,data.meshNodeDestAttr ) ;
		INVIS(cout<<data.upstreamNodeSrcPlug.name().asChar()<<" --|-- "<<nodePlug.name().asChar()<<endl);
		status =	fDGModifier.disconnect( data.upstreamNodeSrcPlug,
											nodePlug );
											
		
		MCheckStatus( status, "Disconnect Upstream mit meshNode" );


	}
	else	// No History (!fHasHistory)
	{
		// Use the DAG node function set to duplicate the shape of the meshNode.
		// The duplicate method will return an MObject handle to the transform
		// of the duplicated shape, so traverse the dag to locate the shape. Store
		// this duplicate shape as our "upstream" node to drive the input for the 
		// modifierNode.
		//
		depNodeFn.setObject( data.meshNodeShape );
		data.upstreamNodeTransform = createDuplicate.createNode("mesh");
		createDuplicate.doIt();

		dagNodeFn.setObject( data.upstreamNodeTransform );
		

		// Ensure that our upstreamNode is pointing to a shape.
		//
		MStatusAssert( (0 < dagNodeFn.childCount()),
					   "0 < dagNodeFn.childCount() -- Duplicate meshNode transform has no shape." );
		data.upstreamNodeShape = dagNodeFn.child(0);

		MPlug outMeshPlug = depNodeFn.findPlug("outMesh");
		depNodeFn.setObject(data.upstreamNodeShape);

		//jetzt inMesh upstreamNodeShape mit outMesh meshShape füllen
		MDGModifier tempMod;
		tempMod.connect(outMeshPlug,depNodeFn.findPlug("inMesh"));
		tempMod.doIt();

		//force DGEVAL
		MString cmd = "dgeval -src ";
		cmd += depNodeFn.name();
		cmd += ".outMesh";
		MGlobal::executeCommand(cmd,false,false);

		tempMod.undoIt();

		
		// Re-parent the upstreamNodeShape under our original transform
		//
		reparentDuplicate.reparentNode( data.upstreamNodeShape, data.meshNodeTransform );
		reparentDuplicate.doIt();


		deleteDuplicate.deleteNode( data.upstreamNodeTransform );
		deleteDuplicate.doIt();
		/*
		status = fDagModifier.reparentNode( data.upstreamNodeShape, data.meshNodeTransform );
		MCheckStatus( status, "reparentNode" );

		// Perform the DAG re-parenting
		// 
		// Note: This reparent must be performed before the deleteNode() is called.
		//		 See polyModifierCmd.h (see definition of fDagModifier) for more details.
		//
		status = fDagModifier.doIt();
		MCheckStatus( status, "fDagModifier.doIt()" );
		*/
		// Mark the upstreamNodeShape (the original shape) as an intermediate object
		// (making it invisible to the user)
		//
		dagNodeFn.setObject( data.upstreamNodeShape );
		dagNodeFn.setIntermediateObject( true );

		// Get the upstream node source attribute
		//
		data.upstreamNodeSrcAttr = dagNodeFn.attribute( "outMesh" );
		data.upstreamNodeSrcPlug = MPlug(data.upstreamNodeShape, data.upstreamNodeSrcAttr);

		/*
		// Remove the duplicated transform node (clean up)
		//
		status = fDagModifier.deleteNode( data.upstreamNodeTransform );
		MCheckStatus( status, "deleteNode" );

		// Perform the DAG delete node
		//
		// Note: This deleteNode must be performed after the reparentNode() method is
		//		 completed. See polyModifierCmd.h (see definition of fDagModifier) for
		//		 details.
		//
		status = fDagModifier.doIt();
		MCheckStatus( status, "fDagModifier.doIt()" );
		*/

		// Cache the DAG path to the duplicate shape
		//
		dagNodeFn.getPath( fDuplicateDagPath );

		//finally delete the tweaks to avoid double transformation
		deleteTweaks();
	}

	return status;
}
コード例 #17
0
ファイル: polyModifierCmd.cpp プロジェクト: Byron/bsuite
// --------------------------------------------------------------------------------------------
MStatus polyModifierCmd::undoCachedMesh()
// --------------------------------------------------------------------------------------------
{
	MStatus status;

	// Only need to restore the cached mesh if there was no history. Also
	// check to make sure that we are in the record history state.
	//
	MStatusAssert( (fHasRecordHistory), "fHasRecordHistory == true" );

	if( !fHasHistory )
	{
		MFnDependencyNode depNodeFn;

		MString meshNodeName;
		MObject meshNodeShape;
		MPlug	meshNodeDestPlug;
		MPlug	meshNodeOutMeshPlug;
		MObject dupMeshNodeShape;
		MPlug	dupMeshNodeSrcPlug;

		meshNodeShape = fDagPath.node();
		dupMeshNodeShape = fDuplicateDagPath.node();

		depNodeFn.setObject( meshNodeShape );
		meshNodeName = depNodeFn.name();
		meshNodeDestPlug = depNodeFn.findPlug( "inMesh", &status );
		MCheckStatus( status, "Could not retrieve inMesh" );
		meshNodeOutMeshPlug = depNodeFn.findPlug( "outMesh", &status );
		MCheckStatus( status, "Could not retrieve outMesh" );

		depNodeFn.setObject( dupMeshNodeShape );
		dupMeshNodeSrcPlug = depNodeFn.findPlug( "outMesh", &status );
		MCheckStatus( status, "Could not retrieve outMesh" );

		// 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 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 )
		{
			MDGModifier dgModifier;
			dgModifier.connect( dupMeshNodeSrcPlug, meshNodeDestPlug );
			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 += ".outMesh";	//outMesh statt inMesh, damit undo (ohne history) funzt
			status = MGlobal::executeCommand( cmd, false, false );
			MCheckStatus( status, "Could not force DG eval" );

			// Disconnect the duplicate meshNode now
			//
			dgModifier.undoIt();

			
		}
		else
		{
			MObject meshData;
			status = dupMeshNodeSrcPlug.getValue( meshData );
			MCheckStatus( status, "Could not retrieve meshData" );

			status = meshNodeOutMeshPlug.setValue( meshData );
			MCheckStatus( status, "Could not set outMesh" );

			
		}
	}

	return status;
}
コード例 #18
0
MObject GlobalComponent::loadComponent(MDGModifier & dgMod) {
    MStatus status = MS::kFailure;
    this->m_metaDataNode = dgMod.createNode( "MDGlobalNode", &status );
    MyCheckStatus(status, "createNode failed");

    MString metaNodeName = "MGN_";
    metaNodeName += this->m_rigName + "_";
    metaNodeName += this->m_pCompGuide->getName();
    dgMod.renameNode(this->m_metaDataNode, metaNodeName);

    MFnDependencyNode depMetaDataNodeFn(this->m_metaDataNode);
    status = dgMod.newPlugValueFloat( depMetaDataNodeFn.findPlug("version"), this->m_pCompGuide->getVersion() );
    MyCheckStatus(status, "newPlugValueFloat() failed");
    status = dgMod.newPlugValueString( depMetaDataNodeFn.findPlug("rigId"), this->m_pCompGuide->getRigId() );
    MyCheckStatus(status, "newPlugValueInt() failed");

    GlobalComponentGuidePtr globalGuide = boost::dynamic_pointer_cast<GlobalComponentGuide>(this->m_pCompGuide);
    MString ctlColor = globalGuide->getColor();
    MString ctlIcon = globalGuide->getIcon();

    status = MGlobal::executeCommand( "python(\"control = rig101().rig101WCGetByName('" + ctlIcon + "')\");" );
    status = MGlobal::executeCommand( "python(\"Utils.setControllerColor(control, '" + ctlColor + "')\");" );
    MCommandResult res;
    status = MGlobal::executeCommand( MString("python(\"control.fullPath()\");"), res );
    int resType = res.resultType();
    if( resType == MCommandResult::kString ) {
        MString sResult;
        res.getResult(sResult);
        MObject ctlObj;
        status = lrutils::getObjFromName(sResult, ctlObj);
        MyCheckStatus(status, "lrutils::getObjFromName() failed");

        MVectorArray ctlLocation = this->m_pCompGuide->getLocation(0);
        MFnTransform transformFn( ctlObj );
        lrutils::setLocation(ctlObj, ctlLocation, MFnTransform::MFnTransform(), false, false, true);

        MString ctlName = this->m_rigName + "_" + this->m_pCompGuide->getName() + "_CTL";
        dgMod.renameNode(ctlObj, ctlName);
        dgMod.doIt();

        //add the metaParent attribute to the controller
        MFnMessageAttribute mAttr;
        MObject transformAttr = mAttr.create("metaParent", "metaParent");
        transformFn.addAttribute(transformAttr);
        //connect the controller's metaParent to the MDGlobal node
        status = dgMod.connect( depMetaDataNodeFn.findPlug("controller"), transformFn.findPlug("metaParent") );

        MObject ctlGroupObj;
        lrutils::makeHomeNull(ctlObj, MFnTransform(), ctlGroupObj);
        lrutils::setLocation(ctlGroupObj, ctlLocation, MFnTransform::MFnTransform(), true, true, false);
        MFnTransform ctlGroupFn( ctlGroupObj );
        //add the metaParent attribute to the controller group
        ctlGroupFn.addAttribute(mAttr.create("metaParent", "metaParent"));
        //connect the controller group's metaParent to the MDGlobal node
        status = dgMod.connect( depMetaDataNodeFn.findPlug("controllerGroup"), ctlGroupFn.findPlug("metaParent") );
        MyCheckStatus(status, "connect failed"); 
        MObject metaRootObj;
        status = lrutils::getMetaRootByName(metaRootObj, this->m_rigName);
        MyCheckStatus(status, "lrutils::getMetaRootByName() failed");
        MObject rigCtlGroupObj;
        status = lrutils::getMetaNodeConnection(metaRootObj, rigCtlGroupObj, "ctlGroup");
        MyCheckStatus(status, "lrutils::getMetaNodeConnection() failed");
        MFnTransform rigCtlGroupFn( rigCtlGroupObj );
        rigCtlGroupFn.addChild( ctlGroupObj );

        //add controller to controller display layer
        MObject controlLayerObj;
        status = lrutils::getMetaNodeConnection(metaRootObj, controlLayerObj, "ctlLayer");
        MyCheckStatus(status, "lrutils::getMetaNodeConnection() failed");
        MFnDependencyNode controlLayerFn(controlLayerObj);
        MString controlLayerName = controlLayerFn.name();
        MGlobal::executeCommand("editDisplayLayerMembers -noRecurse "+controlLayerName+" "+rigCtlGroupFn.name()+";");
        //create parent constraints from the global controller to the rig group
        MObject rigRigGroupObj;
        status = lrutils::getMetaNodeConnection(metaRootObj, rigRigGroupObj, "rigGroup");
        MFnTransform rigRigGroupFn( rigRigGroupObj );
        MGlobal::executeCommand("parentConstraint -mo "+transformFn.name()+" "+rigRigGroupFn.name()+";", res);
        //connect the parent constraint object to the component's metadata node
        MStringArray sResults;
        res.getResult(sResults);
        status = lrutils::getObjFromName(sResults[0], this->m_rigParentConstraint);
        MyCheckStatus(status, "lrutils::getObjFromName() failed");
        MFnTransform rigParentConstraintFn( this->m_rigParentConstraint);
        rigParentConstraintFn.addAttribute(mAttr.create("metaParent", "metaParent"));
        status = dgMod.connect( depMetaDataNodeFn.findPlug("rigParentConstraint"), rigParentConstraintFn.findPlug("metaParent"));
        //create the scale constraint from the global controller to the rig group
        MGlobal::executeCommand("scaleConstraint -mo "+transformFn.name()+" "+rigRigGroupFn.name()+";", res);
        //connect the scale constraint object to the component's metadata node
        res.getResult(sResults);
        status = lrutils::getObjFromName(sResults[0], this->m_rigScaleConstraint);
        MyCheckStatus(status, "lrutils::getObjFromName() failed");
        MFnTransform rigScaleConstraintFn( this->m_rigScaleConstraint );
        rigScaleConstraintFn.addAttribute(mAttr.create("metaParent", "metaParent"));
        status = dgMod.connect( depMetaDataNodeFn.findPlug("rigScaleConstraint"), rigScaleConstraintFn.findPlug("metaParent"));
        //create scale constraint from the global controller to the noTransform group
        MObject rigNoTransformGroupObj;
        status = lrutils::getMetaNodeConnection(metaRootObj, rigNoTransformGroupObj, "noTransformGroup");
        MFnTransform rigNoTransformGroupFn( rigNoTransformGroupObj );
        MGlobal::executeCommand("scaleConstraint -mo "+transformFn.name()+" "+rigNoTransformGroupFn.name()+";", res);
        //connect the scale constraint object to the component's metadata node
        res.getResult(sResults);
        status = lrutils::getObjFromName(sResults[0], this->m_noTransformScaleConstraint);
        MyCheckStatus(status, "lrutils::getObjFromName() failed");
        MFnTransform noTransformScaleConstraintFn( this->m_noTransformScaleConstraint);
        noTransformScaleConstraintFn.addAttribute(mAttr.create("metaParent", "metaParent"));
        status = dgMod.connect( depMetaDataNodeFn.findPlug("noTransformScaleConstraint"), noTransformScaleConstraintFn.findPlug("metaParent"));
    }

    return this->m_metaDataNode;
}
コード例 #19
0
MStatus testGlassCmd::doIt(const MArgList &args)
{
	MStatus stat=MStatus::kSuccess;

	MSelectionList list;
	MFnDependencyNode meshDependFn;
	MFnDependencyNode materialDependFn;
	MDGModifier dgMod;

	//create a new material node, here is the test glass node
	MObject testGNode=dgMod.createNode(testGlassNode::id);
	materialDependFn.setObject(testGNode);
	MString testName=materialDependFn.name();
	MGlobal::displayInfo(testName+" god, please give me the node first time");


	//find the mesh node(s) from selected object(s)
	//create a new "yafaray material" attribute if the mesh node(s) dont have
	//then conect the material node to the mesh node(s)
	MGlobal::getActiveSelectionList( list );
	MItSelectionList iter( list, MFn::kMesh );
	for( ; !iter.isDone(); iter.next())
	{
		MObject meshDependNode;
		MFnNumericAttribute numAttr;
		

		iter.getDependNode( meshDependNode );
		meshDependFn.setObject( meshDependNode );
		//MString dependName=dependFn.name();
		//MGlobal::displayInfo(dependName+" is here\n");

		if( !meshDependFn.hasAttribute("YafarayMaterial") )
		{
			MObject attrYafarayMaterial=numAttr.create("YafarayMaterial","yama",MFnNumericData::kBoolean);
			numAttr.setDefault( true );
			numAttr.setStorable( true );
			meshDependFn.addAttribute(attrYafarayMaterial,MFnDependencyNode::kLocalDynamicAttr);
		}

        //find the source plug and the result plug, then connect them
		//if the result plug as  already had a sourse plug connected to it, disconnect first
		MPlug glassPlug=materialDependFn.findPlug("OutGlass");
		MPlug meshPlug=meshDependFn.findPlug("YafarayMaterial");

		MPlugArray srcMeshPlug;		
		if(meshPlug.connectedTo(srcMeshPlug, true, false))
		{
			MPlug srcPlug;
			//if(srcMeshPlug.length!=0) 
			//{
				srcPlug=srcMeshPlug[0];
			//}

			dgMod.disconnect(srcPlug, meshPlug);
		}

		dgMod.connect(glassPlug,meshPlug);

	}



	dgMod.doIt();
	//why still cant got the name here?
	MGlobal::displayInfo(testName+" god, please give me the node second time");
	
	return stat;
}
コード例 #20
0
ファイル: polyExtract.cpp プロジェクト: AlbertR/cgru170
bool tm_polyExtract::extractFaces_Func( MSelectionList &selectionList, MStringArray &node_names)
{
	MStatus status;
	MObject meshObj;
	status = selectionList.getDependNode( 0, meshObj);
	if(!status){MGlobal::displayError("tm_polyExtract::extractFaces_Func:   Can't find object !");return false;}
	MFnMesh meshFn( meshObj, &status);
	if(!status){MGlobal::displayError("tm_polyExtract::extractFaces_Func:   Non mesh object founded !");return false;}

	MDagPath meshDagPath_first, meshDagPath;
	selectionList.getDagPath( 0, meshDagPath_first);
	MObject multiFaceComponent;
	MIntArray inputFacesArray;
	inputFacesArray.clear();
	inputFacesArray.setSizeIncrement( 4096);
	MFnComponentListData compListFn;
	compListFn.create();
	for (MItSelectionList faceComponentIter(selectionList, MFn::kMeshPolygonComponent); !faceComponentIter.isDone(); faceComponentIter.next())
	{
		faceComponentIter.getDagPath(meshDagPath, multiFaceComponent);
		if(!(meshDagPath_first == meshDagPath))
		{
			MGlobal::displayError("tm_polyExtract::extractFaces_Func:   Different meshes faces founded !");
			return false;
		}
		if (!multiFaceComponent.isNull())
		{
			for (MItMeshPolygon faceIter(meshDagPath, multiFaceComponent); !faceIter.isDone(); faceIter.next())
			{
				int faceIndex = faceIter.index();
#ifdef _DEBUG
				infoMStr += faceIndex;
				infoMStr += " ";
#endif
				inputFacesArray.append( faceIndex);
				compListFn.add( multiFaceComponent );
			}
		}
	}
	if( inputFacesArray.length() == 0)
	{
		MGlobal::displayError("tm_polyExtract::extractFaces_Func:   No faces founded !");
		return false;
	}
#ifdef _DEBUG
	MGlobal::displayInfo( infoMStr);
#endif

	meshFn.setObject( meshDagPath_first);
	meshObj = meshFn.object();

//	MDagModifier dagModifier;
	MFnDagNode meshDagNodeFn;
	MFnDependencyNode depNodeFn;
	meshDagNodeFn.setObject( meshDagPath_first);
	MString meshName = meshDagNodeFn.name();
	MObject outMesh_attrObject = meshDagNodeFn.attribute( "outMesh");

// ----------------------------------- duplicate shape

	MObject duplicated_meshObjectA;
	MObject duplicated_meshObjectB;
	MObject inMesh_attrObjectA;
	MObject inMesh_attrObjectB;
/*
	MStringArray commandResult;
	MSelectionList selList;

	MGlobal::executeCommand( "duplicate " + meshDagNodeFn.name(), commandResult, 1, 1);
	selList.add( commandResult[0]);
	selList.getDependNode( 0, duplicated_meshObjectA);
	meshDagNodeFn.setObject( duplicated_meshObjectA);
	meshDagNodeFn.setName( meshName + "_tA");
	duplicated_meshObjectA = meshDagNodeFn.child(0);
	meshDagNodeFn.setObject( duplicated_meshObjectA);
	meshDagNodeFn.setName( meshName + "_sA");
	inMesh_attrObjectA = meshDagNodeFn.attribute( "inMesh");

	meshDagNodeFn.setObject( meshDagPath_first);
	selList.clear();

	MGlobal::executeCommand( "duplicate " + meshDagNodeFn.name(), commandResult, 1, 1);
	selList.add( commandResult[0]);
	selList.getDependNode( 0, duplicated_meshObjectB);
	meshDagNodeFn.setObject( duplicated_meshObjectB);
	meshDagNodeFn.setName( meshName + "_tB");
	duplicated_meshObjectB = meshDagNodeFn.child(0);
	meshDagNodeFn.setObject( duplicated_meshObjectB);
	meshDagNodeFn.setName( meshName + "_sB");
	inMesh_attrObjectB = meshDagNodeFn.attribute( "inMesh");
*/
	duplicated_meshObjectA = meshDagNodeFn.duplicate();
	meshDagNodeFn.setObject( duplicated_meshObjectA);
	meshDagNodeFn.setName( meshName + "_tA");
	duplicated_meshObjectA = meshDagNodeFn.child(0);
	meshDagNodeFn.setObject( duplicated_meshObjectA);
	meshDagNodeFn.setName( meshName + "_sA");
	inMesh_attrObjectA = meshDagNodeFn.attribute( "inMesh");

	meshDagNodeFn.setObject( meshDagPath_first);

	duplicated_meshObjectB = meshDagNodeFn.duplicate();
	meshDagNodeFn.setObject( duplicated_meshObjectB);
	meshDagNodeFn.setName( meshName + "_tB");
	duplicated_meshObjectB = meshDagNodeFn.child(0);
	meshDagNodeFn.setObject( duplicated_meshObjectB);
	meshDagNodeFn.setName( meshName + "_sB");
	inMesh_attrObjectB = meshDagNodeFn.attribute( "inMesh");

// ----------------------------------- create node deleteComponent

	MDGModifier dgModifier;

	MObject deleteComponent_nodeObjectA = dgModifier.createNode( MString("deleteComponent"));
	depNodeFn.setObject( deleteComponent_nodeObjectA );
	MObject deleteComponent_attrObjectA( depNodeFn.attribute( "deleteComponents" ));
	MObject inputGeometry_attrObjectA( depNodeFn.attribute( "inputGeometry" ));
	MObject outputGeometry_attrObjectA( depNodeFn.attribute( "outputGeometry" ));
	dgModifier.doIt();
	depNodeFn.setName( "dfA_" + meshName);
	node_names.append( depNodeFn.name());

	MObject deleteComponent_nodeObjectB = dgModifier.createNode( MString("deleteComponent"));
	depNodeFn.setObject( deleteComponent_nodeObjectB );
	MObject deleteComponent_attrObjectB( depNodeFn.attribute( "deleteComponents" ));
	MObject inputGeometry_attrObjectB( depNodeFn.attribute( "inputGeometry" ));
	MObject outputGeometry_attrObjectB( depNodeFn.attribute( "outputGeometry" ));
	dgModifier.doIt();
	depNodeFn.setName( "dfB_" + meshName);
	node_names.append( depNodeFn.name());

// ----------------------------------- set attribute deleteComponent.deleteComponents

	MObject componentList_object = compListFn.object();

	MPlug deleteComponents_plugA( deleteComponent_nodeObjectA, deleteComponent_attrObjectA );
	status = deleteComponents_plugA.setValue( componentList_object );

	MIntArray invertedFaces;
	int numPolygons = meshFn.numPolygons();
	invertedFaces.setLength( numPolygons - inputFacesArray.length());
	int selFace = 0;
	int invFace = 0;
	for( int f = 0; f < numPolygons; f++)
	{
		if( f == inputFacesArray[selFace])
			selFace++;
		else
			invertedFaces[invFace++] = f;
	}
	MFnSingleIndexedComponent singleIndexedComponentFn( meshObj);
	singleIndexedComponentFn.create( MFn::kMeshPolygonComponent);
	singleIndexedComponentFn.addElements( invertedFaces);
	compListFn.clear();
	compListFn.create();
   componentList_object = singleIndexedComponentFn.object();
	compListFn.add( componentList_object);
	componentList_object = compListFn.object();
	MPlug deleteComponents_plugB( deleteComponent_nodeObjectB, deleteComponent_attrObjectB );
	status = deleteComponents_plugB.setValue( componentList_object );

// ------------------------------------- connecting plugs
/**/
	dgModifier.connect(
			meshObj, outMesh_attrObject,
			deleteComponent_nodeObjectA, inputGeometry_attrObjectA
		);
	dgModifier.connect(
			deleteComponent_nodeObjectA, outputGeometry_attrObjectA,
			duplicated_meshObjectA, inMesh_attrObjectA
		);

	dgModifier.connect(
			meshObj, outMesh_attrObject,
			deleteComponent_nodeObjectB, inputGeometry_attrObjectB
		);
	dgModifier.connect(
			deleteComponent_nodeObjectB, outputGeometry_attrObjectB,
			duplicated_meshObjectB, inMesh_attrObjectB
		);

	dgModifier.doIt();

// ---------------------------------- assigning shading group
/**/
	meshDagNodeFn.setObject( meshDagPath_first);
	MObject instObjGroups_attrObject = meshDagNodeFn.attribute( "instObjGroups");
	MPlug instObjGroups_plug( meshObj, instObjGroups_attrObject);
	instObjGroups_plug = instObjGroups_plug.elementByPhysicalIndex(0);
	MPlugArray instObjGroups_plug_connectionsArray;
	instObjGroups_plug.connectedTo( instObjGroups_plug_connectionsArray, false, true);
	if( instObjGroups_plug_connectionsArray.length() > 0)
	{
		MPlug dagSetMembers_plug = instObjGroups_plug_connectionsArray[0];
		MObject shadingSetNode_object = dagSetMembers_plug.node();
		MFnSet setFn( shadingSetNode_object);
		setFn.addMember( duplicated_meshObjectA);
		setFn.addMember( duplicated_meshObjectB);
//depNodeFn.setObject(shadingSetNode_object);
//MGlobal::displayInfo( depNodeFn.name());
	}

// ------------------------------------------------------------
	return true;
}
コード例 #21
0
ファイル: main.cpp プロジェクト: amadlover/setupRGBShaders
MStatus setupRGBShaders::redoIt()
{
    int numLayers = meshObjs.length() / 3;

    if( numLayers == 0 && meshObjs.length() > 0 )
        numLayers++;

    if( meshObjs.length() % 3 > 0 && meshObjs.length() > 3 )
        numLayers++;

    for( int l = 0; l < numLayers; l++ ) {
        MStatus stat;

        MFnDependencyNode mrUserBufferFn( dgMod.createNode( "mentalrayUserBuffer", &stat ));
        dgDoIt();
        //MGlobal::executeCommand( MString( "connectAttr -f " ) + mrUserBufferFn.name() + ".message miDefaultOptions.frameBufferList[" + l + "]" );
        dgMod.commandToExecute( MString( "connectAttr -f " ) + mrUserBufferFn.name() + ".message miDefaultOptions.frameBufferList[" + l + "]" );
        dgDoIt();
        mrUserBufferFn.findPlug( "dataType" ).setValue( 5 );

        for( int i = 0; i < 3; i++ ) {
            if(( l * 3 + i ) > (int)meshObjs.length() - 1 ) break;

            MFnDependencyNode nkPassFn( dgMod.createNode( "nkPass" ));
            dgDoIt();
            MFnDependencyNode meshFn( meshObjs[ l * 3 + i ]);

            dgMod.commandToExecute( MString( "sets -renderable true -noSurfaceShader true -empty -name " ) + nkPassFn.name() + "SG" );
            dgDoIt();
            dgMod.commandToExecute( MString( "connectAttr -f " ) + nkPassFn.name() + ".outValue " + nkPassFn.name() + "SG.miMaterialShader" );
            dgDoIt();
            dgMod.commandToExecute( MString( "sets -e -forceElement ") + nkPassFn.name() + "SG " + meshFn.name());
            dgDoIt();

            /*MGlobal::executeCommand( MString( "sets -renderable true -noSurfaceShader true -empty -name " ) + nkPassFn.name() + "SG" );
            MGlobal::executeCommand( MString( "connectAttr -f " ) + nkPassFn.name() + ".outValue " + nkPassFn.name() + "SG.miMaterialShader" );
            MGlobal::executeCommand( MString( "sets -e -forceElement ") + nkPassFn.name() + "SG " + meshFn.name());*/

            nkPassFn.findPlug( "layerNumber" ).setValue( l );

            if( i == 0 )
                dgMod.commandToExecute( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 1 0 0" );
            //MGlobal::executeCommand( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 1 0 0" );

            if( i == 1 )
                dgMod.commandToExecute( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 0 1 0" );
            //MGlobal::executeCommand( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 0 1 0" );

            if( i == 2 )
                dgMod.commandToExecute( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 0 0 1" );
            //MGlobal::executeCommand( MString( "setAttr " ) + nkPassFn.name() + ".color -type double3 0 0 1" );

            dgDoIt();
        }
    }

    for( unsigned int c = 0; c < camObjs.length(); c++ ) {
        MFnDependencyNode mrOutputPass( dgMod.createNode( "mentalrayOutputPass" ));
        dgDoIt();
        MFnDependencyNode nkSaver( dgMod.createNode( "nkSaver" ));
        dgDoIt();
        dgMod.connect( nkSaver.findPlug( "outValue" ), mrOutputPass.findPlug( "outputShader" ));
        dgDoIt();

        MFnDependencyNode camFn( camObjs[c] );

        //MGlobal::executeCommand( MString( "connectAttr -f " ) + mrOutputPass.name() + ".message " + camFn.name() + ".miOutputShaderList[0]" );
        dgMod.commandToExecute( MString( "connectAttr -f " ) + mrOutputPass.name() + ".message " + camFn.name() + ".miOutputShaderList[0]" );
        dgDoIt();

        nkSaver.findPlug( "numLayers" ).setValue( numLayers );
        nkSaver.findPlug( "camName" ).setValue( camFn.name() );
        nkSaver.findPlug( "fileName" ).setValue( fileName );
        nkSaver.findPlug( "folderPath" ).setValue( folderPath );
        mrOutputPass.findPlug( "datatype" ).setValue( 5 );
    }

    setResult( "Shaders setup to Render" );

    return MS::kSuccess;
}
コード例 #22
0
MStatus ParameterisedHolder<B>::createOrUpdateAttribute( IECore::ParameterPtr parameter, const MString &attributeName, bool callRestore )
{
	MObject node =  B::thisMObject();
	MFnDependencyNode fnDN( node );

	MPlugArray connectionsFromMe, connectionsToMe;

	// try to reuse an old plug if we can
	MPlug plug = fnDN.findPlug( attributeName, false /* no networked plugs please */ );
	if( !plug.isNull() )
	{
		MStatus s = MS::kSuccess;
		if( callRestore )
		{
			ParameterHandler::restore( plug, parameter );
		}
	
		if( s )
		{
			s = IECoreMaya::ParameterHandler::update( parameter, plug );
			if( s )
			{
				return MS::kSuccess;
			}
		}
		
		// failed to restore and/or update (parameter type probably changed).
		// remove the current attribute and fall through to the create
		// code

		// remember connections so we can remake them for the new
		// attribute. we have to be careful to only store non-networked plugs as
		// networked plugs are invalidated by the removal of the attribute.
		nonNetworkedConnections( plug, connectionsFromMe, connectionsToMe );
		
		fnDN.removeAttribute( plug.attribute() );
	}

	// reuse failed - create a new attribute
	/// \todo: update ParameterisedHolder to accept null plugs when the todo in ParameterHandler::create is addressed
	plug = IECoreMaya::ParameterHandler::create( parameter, attributeName, node );
	if( plug.isNull() )
	{
		msg( Msg::Error, "ParameterisedHolder::createOrUpdateAttribute", boost::format( "Failed to create attribute to represent parameter \"%s\" of type \"%s\"" ) % parameter->name() % parameter->typeName() );
		return MS::kFailure;
	}

	// restore any existing connections
	if( connectionsFromMe.length() || connectionsToMe.length() )
	{
		MDGModifier dgMod;
		for (unsigned i = 0; i < connectionsFromMe.length(); i++)
		{
			dgMod.connect( plug, connectionsFromMe[i] );
		}
		for (unsigned i = 0; i < connectionsToMe.length(); i++)
		{
			dgMod.connect( connectionsToMe[i], plug );
		}

		dgMod.doIt();
	}

	/// and set the value of the attribute, in case it differs from the default
	return IECoreMaya::ParameterHandler::setValue( parameter, plug );
}
コード例 #23
0
ファイル: pointOnMeshCmd.cpp プロジェクト: vasilenkomike/xray
MStatus pointOnMeshCommand::redoIt()

{

    // WHEN NO MESH IS SPECIFIED IN THE COMMAND, GET THE FIRST SELECTED MESH FROM THE SELECTION LIST:

    MSelectionList sList;

    if (meshNodeName=="")

    {

        MGlobal::getActiveSelectionList(sList);

        if (sList.length()==0)

        {

            displayError("No mesh or mesh transform specified!");

            return MS::kFailure;

        }

    }

    // OTHERWISE, USE THE NODE NAME SPECIFIED IN THE LAST ARGUMENT OF THE COMMAND:

    else if (sList.add(meshNodeName) == MS::kInvalidParameter)

    {

        displayError("Specified mesh does not exist!");

        return MS::kFailure;

    }



    // RETRIEVE THE FIRST ITEM FROM THE SELECTION LIST:

    MDagPath meshDagPath;

    sList.getDagPath(0, meshDagPath);



    // CREATE AND CONNECT A "pointOnMeshInfo" NODE, OR GET THE POINT AND NORMAL ACCORDING TO

    // WHETHER THE "-position/-p" AND/OR "-normal/-nr" FLAGS WERE SPECIFIED, AND WHETHER THE MESH

    // "SHAPE" OR ITS "TRANSFORM" WAS SPECIFIED/SELECTED:

    MPoint point;

    MVector normal;

    // WHEN THE SPECIFIED NODE IS THE MESH "SHAPE":

    if (meshDagPath.node().hasFn(MFn::kMesh))

    {

        // WHEN NEITHER "-position/-p" NOR "-normal/-nr" ARE SPECIFIED, CREATE AND CONNECT A "pointOnMeshInfo" NODE AND RETURN ITS NODE NAME:

        if (!positionSpecified && !normalSpecified)

        {

            // CREATE THE NODE:

            nodeCreated = true;

            MFnDependencyNode depNodeFn;

            if (pointOnMeshInfoName == "")

                depNodeFn.create("pointOnMeshInfo");

            else

                depNodeFn.create("pointOnMeshInfo", pointOnMeshInfoName);

            pointOnMeshInfoName = depNodeFn.name();



            // SET THE ".faceIndex" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (faceIndexSpecified)

            {

                MPlug faceIndexPlug = depNodeFn.findPlug("faceIndex");

                faceIndexPlug.setValue(faceIndex);

            }



            // SET THE ".relative" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (relativeSpecified)

            {

                MPlug relativePlug = depNodeFn.findPlug("relative");

                relativePlug.setValue(relative);

            }



            // SET THE ".parameterU" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (parameterUSpecified)

            {

                MPlug parameterUPlug = depNodeFn.findPlug("parameterU");

                parameterUPlug.setValue(parameterU);

            }



            // SET THE ".parameterV" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (parameterVSpecified)

            {

                MPlug parameterVPlug = depNodeFn.findPlug("parameterV");

                parameterVPlug.setValue(parameterV);

            }



            // CONNECT THE NODES:

            MPlug worldMeshPlug, inMeshPlug;

            inMeshPlug = depNodeFn.findPlug("inMesh");

            depNodeFn.setObject(meshDagPath.node());

            worldMeshPlug = depNodeFn.findPlug("worldMesh");

            worldMeshPlug = worldMeshPlug.elementByLogicalIndex(0);  // ASSUME THE *FIRST* INSTANCE OF THE MESH IS REQUESTED FOR MESH SHAPES.

            MDGModifier dgModifier;

            dgModifier.connect(worldMeshPlug, inMeshPlug);

            dgModifier.doIt();



            // SET COMMAND RESULT AND RETURN:

            setResult(pointOnMeshInfoName);

            return MStatus::kSuccess;

        }

        // OTHERWISE, COMPUTE THE POINT-POSITION AND NORMAL, USING THE *FIRST* INSTANCE'S TRANSFORM:

        else

            getPointAndNormal(meshDagPath, faceIndex, relative, parameterU, parameterV, point, normal);

    }

    // WHEN THE SPECIFIED NODE IS A "TRANSFORM" OF A MESH SHAPE:

    else if (meshDagPath.node().hasFn(MFn::kTransform) && meshDagPath.hasFn(MFn::kMesh))

    {

        // WHEN NEITHER "-position/-p" NOR "-normal/-nr" ARE SPECIFIED, CREATE AND CONNECT A "pointOnMeshInfo" NODE AND RETURN ITS NODE NAME:

        if (!positionSpecified && !normalSpecified)

        {

            // CREATE THE NODE:

            nodeCreated = true;

            meshDagPath.extendToShape();

            MFnDependencyNode depNodeFn;

            if (pointOnMeshInfoName == "")

                depNodeFn.create("pointOnMeshInfo");

            else

                depNodeFn.create("pointOnMeshInfo", pointOnMeshInfoName);

            pointOnMeshInfoName = depNodeFn.name();



            // SET THE ".faceIndex" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (faceIndexSpecified)

            {

                MPlug faceIndexPlug = depNodeFn.findPlug("faceIndex");

                faceIndexPlug.setValue(faceIndex);

            }



            // SET THE ".relative" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (relativeSpecified)

            {

                MPlug relativePlug = depNodeFn.findPlug("relative");

                relativePlug.setValue(relative);

            }



            // SET THE ".parameterU" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (parameterUSpecified)

            {

                MPlug parameterUPlug = depNodeFn.findPlug("parameterU");

                parameterUPlug.setValue(parameterU);

            }



            // SET THE ".parameterV" ATTRIBUTE, IF SPECIFIED IN THE COMMAND:

            if (parameterVSpecified)

            {

                MPlug parameterVPlug = depNodeFn.findPlug("parameterV");

                parameterVPlug.setValue(parameterV);

            }



            // CONNECT THE NODES:

            MPlug worldMeshPlug, inMeshPlug;

            inMeshPlug = depNodeFn.findPlug("inMesh");

            depNodeFn.setObject(meshDagPath.node());

            worldMeshPlug = depNodeFn.findPlug("worldMesh");

            worldMeshPlug = worldMeshPlug.elementByLogicalIndex(meshDagPath.instanceNumber());

            MDGModifier dgModifier;

            dgModifier.connect(worldMeshPlug, inMeshPlug);

            dgModifier.doIt();



            // SET COMMAND RESULT AND RETURN:

            setResult(pointOnMeshInfoName);

            return MStatus::kSuccess;

        }

        // OTHERWISE, COMPUTE THE POINT-POSITION AND NORMAL:

        else

            getPointAndNormal(meshDagPath, faceIndex, relative, parameterU, parameterV, point, normal);

    }

    // INVALID INPUT WHEN SPECIFIED/SELECTED NODE IS NOT A MESH NOR TRANSFORM:

    else

    {

        displayError("Invalid type!  Only a mesh or its transform can be specified!");

        return MStatus::kFailure;

    }



    // SET THE RETURN VALUES OF THE COMMAND'S RESULT TO BE AN ARRAY OF FLOATS OUTPUTTING THE POSITION AND/OR NORMAL:

    MDoubleArray result;

    if (positionSpecified)

    {

        result.append(point.x);

        result.append(point.y);

        result.append(point.z);

    }

    if (normalSpecified)

    {

        result.append(normal.x);

        result.append(normal.y);

        result.append(normal.z);

    }

    setResult(result);



    return MStatus::kSuccess;

}