Пример #1
0
void FxInternal::EffectUnload()
{
	HRESULT hr= S_OK;
	MStatus status= MStatus::kSuccess; 

	MFnDependencyNode depNode(GetSite());

	DXCC_RELEASE(Effect);

	MPlug scriptPlug(GetSite(), DirectXShader::aScript);
	if(!scriptPlug.isNull())
		DXCHECK_MSTATUS(scriptPlug.setValue(""));

	MObject root = depNode.attribute(DirectXShader::RootShortName);
	if(!root.isNull())
		depNode.removeAttribute(root);


}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CVstSelectCoincidentFacesCmd::GetSpecifiedMeshes(
	MSelectionList &meshList )
{
	meshList.clear();

	MSelectionList optSelectionList;
	m_undo.ArgDatabase().getObjects( optSelectionList );

	MDagPath mDagPath;
	MObject cObj;
	for ( MItSelectionList sIt( optSelectionList ); !sIt.isDone(); sIt.next() )
	{
		if ( sIt.itemType() == MItSelectionList::kDagSelectionItem && sIt.getDagPath( mDagPath, cObj ) )
		{
			if ( mDagPath.hasFn( MFn::kMesh ) )
			{
				if ( sIt.hasComponents() || !cObj.isNull() )
				{
					meshList.add( mDagPath, cObj );
				}
				else
				{
					mDagPath.extendToShapeDirectlyBelow( 0U );
					meshList.add( mDagPath, MObject::kNullObj, true );
				}
			}
		}
	}

	if ( meshList.isEmpty() )
	{
		for ( MItDag dIt( MItDag::kDepthFirst, MFn::kMesh ); !dIt.isDone(); dIt.next() )
		{
			if ( dIt.getPath( mDagPath ) )
			{
				meshList.add( mDagPath, MObject::kNullObj, true );
			}
		}
	}
}
MStatus geometrySurfaceConstraintCommand::connectObjectAndConstraint( MDGModifier& modifier )
{
	MObject transform = transformObject();
	if ( transform.isNull() )
	{
		MGlobal::displayError("Failed to get transformObject()");
		return MS::kFailure;
	}

	MStatus status;
	MFnTransform transformFn( transform );
	MVector translate = transformFn.getTranslation(MSpace::kTransform,&status);
	if (!status) { status.perror(" transformFn.getTranslation"); return status;}

	MPlug translatePlug = transformFn.findPlug( "translate", &status );
	if (!status) { status.perror(" transformFn.findPlug"); return status;}

	if ( MPlug::kFreeToChange == translatePlug.isFreeToChange() )
	{
		MFnNumericData nd;
		MObject translateData = nd.create( MFnNumericData::k3Double, &status );
		status = nd.setData3Double( translate.x,translate.y,translate.z);
		if (!status) { status.perror("nd.setData3Double"); return status;}
		status = modifier.newPlugValue( translatePlug, translateData );
		if (!status) { status.perror("modifier.newPlugValue"); return status;}

		status = connectObjectAttribute( 
			MPxTransform::geometry, 
					geometrySurfaceConstraint::constraintGeometry, false );
		if (!status) { status.perror("connectObjectAttribute"); return status;}
	}

	status = connectObjectAttribute( 
		MPxTransform::parentInverseMatrix,
			geometrySurfaceConstraint::constraintParentInverseMatrix, true, true );
	if (!status) { status.perror("connectObjectAttribute"); return status;}

	return MS::kSuccess;
}
Пример #4
0
//
// Utility method to retrieve from a node its color space attribute.
//
const MString colorTransformDataTranslator::getInputColorSpace(const MObject& object)
{
    MString inputColorSpace;

    if(!object.isNull() && 
       ( (object.apiType()==MFn::kFileTexture) || (object.apiType()==MFn::kImagePlane) ) )
    {
        MStatus	status;
        MFnDependencyNode texNode(object, &status);
        if(status)
        {
            static const char* const colorSpaceStr = "colorSpace";

            MPlug plug = texNode.findPlug(colorSpaceStr, &status);
            if (status && !plug.isNull())
            {
                plug.getValue(inputColorSpace);
            }
        }
    }
    return inputColorSpace;
}
Пример #5
0
// Node added to model callback.
static void userNodeAddedCB(MObject& node,void *clientData)
{
	MStatus status;

	if (! node.isNull()) {
		bool doDisplay = true;

		MDagPath path;
		status = MDagPath::getAPathTo(node,path);
		if ( status.error() ) {
			doDisplay = false;
			MGlobal::displayInfo("Error: failed to get dag path to node.");
		}

		if ( doDisplay ) {
			MString s = path.fullPathName();
			MString info("DAG Model -  Node added: ");
			info+= s;

			path.transform(&status);
			if (MS::kInvalidParameter == status) {
				info += "(WORLD)";
			}

			MGlobal::displayInfo(info);	
		}
	}

	// remove the callback
	MCallbackId id = MMessage::currentCallbackId();
	MMessage::removeCallback(id);

	// listen for removal message
	/* MCallbackId id = */ MModelMessage::addNodeRemovedFromModelCallback( node, userNodeRemovedCB, 0, &status );
	if ( status.error() ) {
		MGlobal::displayError("Failed to install node removed from model callback.\n");
		return;
	}
}
Пример #6
0
MStatus cvExpand::doIt( const MArgList& args )
{

	MSelectionList list;
	MSelectionList newList;

	// Get the geometry list from what is currently selected in the 
	// model
	//
	MGlobal::getActiveSelectionList( list );

	MDagPath path;
	MObject  component;
 
	// Make expanded Selection List
	//
	for ( MItSelectionList iter( list ); !iter.isDone(); iter.next() ) {
		iter.getDagPath( path, component );
		
		if ( path.hasFn( MFn::kNurbsSurfaceGeom ) && 
			 !component.isNull() ) {
			for ( MItSurfaceCV cvIter( path, component ); 
				  !cvIter.isDone(); cvIter.next() ) {
				newList.add( path, cvIter.cv() );
			}
		} else {
			newList.add( path, component );
		}
	}

	// Return expanded selection list as an array of strings
	//
	MStringArray returnArray;
	newList.getSelectionStrings( returnArray );

	MPxCommand::setResult( returnArray );

	return MS::kSuccess;
}
    // -------------------------------------------
    bool AnimationHelper::isPhysicsAnimation ( const MObject& o )
    {
        if ( o.hasFn ( MFn::kChoice ) )
        {
            MFnDependencyNode n ( o );
            MPlug p = n.findPlug ( "input" );
            uint choiceCount = p.numElements();

            for ( uint i = 0; i < choiceCount; ++i )
            {
                MPlug child = p.elementByPhysicalIndex ( i );
                MObject connection = DagHelper::getSourceNodeConnectedTo ( child );

                if ( !connection.isNull() && connection != o )
                    if ( isPhysicsAnimation ( connection ) ) return true;
            }
        }

        else if ( o.hasFn ( MFn::kRigidSolver ) || o.hasFn ( MFn::kRigid ) ) return true;

        return false;
    }
Пример #8
0
UsdMayaAdaptor::AttributeAdaptor
UsdMayaAdaptor::SchemaAdaptor::CreateAttribute(
    const TfToken& attrName, MDGModifier& modifier)
{
    if (!*this) {
        TF_CODING_ERROR("Schema adaptor is not valid");
        return AttributeAdaptor();
    }

    SdfAttributeSpecHandle attrDef = _schemaDef->GetAttributes()[attrName];
    if (!attrDef) {
        TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'",
                attrName.GetText(), _schemaDef->GetName().c_str());
        return AttributeAdaptor();
    }

    std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrDef);
    std::string mayaNiceAttrName = attrDef->GetName();
    MFnDependencyNode node(_handle.object());

    bool newAttr = !node.hasAttribute(mayaAttrName.c_str());
    MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr(
            attrDef->GetTypeName(), attrDef->GetVariability(),
            node, mayaAttrName, mayaNiceAttrName, modifier);
    if (attrObj.isNull()) {
        return AttributeAdaptor();
    }

    MPlug plug = node.findPlug(attrObj);
    if (newAttr && attrDef->HasDefaultValue()) {
        // Set the fallback value as the initial value of the attribute, if
        // it exists. (There's not much point in setting the "default" value in
        // Maya, because it won't behave like the fallback value in USD.)
        UsdMayaReadUtil::SetMayaAttr(
                plug, attrDef->GetDefaultValue(), modifier);
    }

    return AttributeAdaptor(plug, attrDef);
}
MStatus lrutils::getJointByNum(MObject metaDataNode, unsigned int jointNum, MObject& jointObj) {
    MStatus status;

    if(!metaDataNode.isNull()) {
        MFnDependencyNode metaDataFn(metaDataNode);
        if(metaDataFn.typeId() == MDHipNode::id) {
            status = lrutils::getMetaNodeConnection(metaDataNode, jointObj, "hipJoint");
            MyCheckStatusReturn(status, "lrutils::getMetaNodeConnection() failed");
        } else if (metaDataFn.typeId() == MDSpineNode::id) {
            MPlug bindJointsPlug = metaDataFn.findPlug( "BindJoints", true, &status );
            MyCheckStatusReturn(status, "MFnDependencyNode.findPlug() failed");

            //follow the plug connection to the connected plug on the other object
            MPlugArray connectedJointPlugs;
            bindJointsPlug.connectedTo(connectedJointPlugs,false,true,&status);
            MyCheckStatusReturn(status,"MPlug.connectedTo() failed");
            if( connectedJointPlugs.length() > 0) {
                //for some reason when more than one plug is connected in an MPlugArray,
                //the first object connected is in index 1 and the second object connected is
                //in index 2. The following code simply reverses the joint number we are
                //looking for since this is the case.
                if( connectedJointPlugs.length() > 1) {
                    if(jointNum == 1) {
                        jointNum = 0;
                    } else if (jointNum == 0) {
                        jointNum = 1;
                    }
                }
                MPlug jointPlug = connectedJointPlugs[jointNum];
                //MPlug jointPlug = bindJointsPlug.connectionByPhysicalIndex(0);
                jointObj = jointPlug.node(&status);
                MyCheckStatusReturn(status, "MPlug.node() failed");
            }
        }
    }

    return status;
}
/* static */
bool
UsdMayaTranslatorMesh::_AssignConstantPrimvarToMesh(
        const UsdGeomPrimvar& primvar,
        MFnMesh& meshFn)
{
    const TfToken& interpolation = primvar.GetInterpolation();
    if (interpolation != UsdGeomTokens->constant) {
        return false;
    }

    const TfToken& name = primvar.GetBaseName();
    const SdfValueTypeName& typeName = primvar.GetTypeName();
    const SdfVariability& variability = SdfVariabilityUniform;

    MObject attrObj =
        UsdMayaReadUtil::FindOrCreateMayaAttr(
            typeName,
            variability,
            meshFn,
            name.GetText());
    if (attrObj.isNull()) {
        return false;
    }

    VtValue primvarData;
    primvar.Get(&primvarData);

    MStatus status;
    MPlug plug = meshFn.findPlug(
        name.GetText(),
        /* wantNetworkedPlug = */ true,
        &status);
    if (status != MS::kSuccess || plug.isNull()) {
        return false;
    }

    return UsdMayaReadUtil::SetMayaAttr(plug, primvarData);
}
MStatus findTexturesPerPolygon::doIt( const MArgList& )
//
//  Description:
//      Find the texture files that apply to the color of each polygon of
//      a selected shape if the shape has its polygons organized into sets.
//
{
    // Get the selection and choose the first path on the selection list.
    //
	MStatus status;
	MDagPath path;
	MObject cmp;
	MSelectionList slist;
	MGlobal::getActiveSelectionList(slist);
	slist.getDagPath(0, path, cmp);

	// Have to make the path include the shape below it so that
	// we can determine if the underlying shape node is instanced.
	// By default, dag paths only include transform nodes.
	//
	path.extendToShape();

	// If the shape is instanced then we need to determine which
	// instance this path refers to.
	//
	int instanceNum = 0;
	if (path.isInstanced())
		instanceNum = path.instanceNumber();

    // Get a list of all sets pertaining to the selected shape and the
    // members of those sets.
    //
	MFnMesh fnMesh(path);
	MObjectArray sets;
	MObjectArray comps;
	if (!fnMesh.getConnectedSetsAndMembers(instanceNum, sets, comps, true))
		cerr << "ERROR: MFnMesh::getConnectedSetsAndMembers\n";

	// Loop through all the sets.  If the set is a polygonal set, find the
    // shader attached to the and print out the texture file name for the
    // set along with the polygons in the set.
	//
	for ( unsigned i=0; i<sets.length(); i++ ) {
		MObject set = sets[i];
		MObject comp = comps[i];

		MFnSet fnSet( set, &status );
		if (status == MS::kFailure) {
            cerr << "ERROR: MFnSet::MFnSet\n";
            continue;
        }

        // Make sure the set is a polygonal set.  If not, continue.
		MItMeshPolygon piter(path, comp, &status);
		if ((status == MS::kFailure) || comp.isNull())
            continue;

		// Find the texture that is applied to this set.  First, get the
		// shading node connected to the set.  Then, if there is an input
		// attribute called "color", search upstream from it for a texture
		// file node.
        //
		MObject shaderNode = findShader(set);
		if (shaderNode == MObject::kNullObj)
			continue;

		MPlug colorPlug = MFnDependencyNode(shaderNode).findPlug("color", &status);
		if (status == MS::kFailure)
			continue;

		MItDependencyGraph dgIt(colorPlug, MFn::kFileTexture,
						   MItDependencyGraph::kUpstream, 
						   MItDependencyGraph::kBreadthFirst,
						   MItDependencyGraph::kNodeLevel, 
						   &status);

		if (status == MS::kFailure)
			continue;
		
		dgIt.disablePruningOnFilter();

        // If no texture file node was found, just continue.
        //
		if (dgIt.isDone())
			continue;
		  
        // Print out the texture node name and texture file that it references.
        //
		MObject textureNode = dgIt.thisNode();
        MPlug filenamePlug = MFnDependencyNode(textureNode).findPlug("fileTextureName");
        MString textureName;
        filenamePlug.getValue(textureName);
		cerr << "Set: " << fnSet.name() << endl;
        cerr << "Texture Node Name: " << MFnDependencyNode(textureNode).name() << endl;
		cerr << "Texture File Name: " << textureName.asChar() << endl;
        
        // Print out the set of polygons that are contained in the current set.
        //
		for ( ; !piter.isDone(); piter.next() )
			cerr << "    poly component: " << piter.index() << endl;
	}

	return MS::kSuccess;
}
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;
}
Пример #13
0
MStatus sseDeformer::compute(const MPlug& plug, MDataBlock& data)
{
    MStatus status;
    if (plug.attribute() != outputGeom) {
        printf("Ignoring requested plug\n");
        return status;
    }
    unsigned int index = plug.logicalIndex();
    MObject thisNode = this->thisMObject();

    // get input value
    MPlug inPlug(thisNode,input);
    inPlug.selectAncestorLogicalIndex(index,input);
    MDataHandle hInput = data.inputValue(inPlug, &status);
    MCheckStatus(status, "ERROR getting input mesh\n");

    // get the input geometry
    MDataHandle inputData = hInput.child(inputGeom);
    if (inputData.type() != MFnData::kMesh) {
        printf("Incorrect input geometry type\n");
        return MStatus::kFailure;
    }

    MObject iSurf = inputData.asMesh() ;
    MFnMesh inMesh;
    inMesh.setObject( iSurf ) ;

    MDataHandle outputData = data.outputValue(plug);
    outputData.copy(inputData);
    if (outputData.type() != MFnData::kMesh) {
        printf("Incorrect output mesh type\n");
        return MStatus::kFailure;
    }

    MObject oSurf = outputData.asMesh() ;
    if(oSurf.isNull()) {
        printf("Output surface is NULL\n");
        return MStatus::kFailure;
    }

    MFnMesh outMesh;
    outMesh.setObject( oSurf ) ;
    MCheckStatus(status, "ERROR setting points\n");

    // get all points at once for demo purposes. Really should get points from the current group using iterator
    MFloatPointArray pts;
    outMesh.getPoints(pts);

    int nPoints = pts.length();

    MDataHandle envData = data.inputValue(envelope, &status);
    float env = envData.asFloat();

    MDataHandle sseData = data.inputValue(sseEnabled, &status);
    bool sseEnabled = (bool) sseData.asBool();

    // NOTE: Using MTimer and possibly other classes disables
    // autovectorization with Intel <=10.1 compiler on OSX and Linux!!
    // Must compile this function with -fno-exceptions on OSX and
    // Linux to guarantee autovectorization is done. Use -fvec_report2
    // to check for vectorization status messages with Intel compiler.
    MTimer timer;
    timer.beginTimer();

    if(sseEnabled) {

        // Innter loop will autovectorize. Around 3x faster than the
        // loop below it. It would be faster if first element was
        // guaranteed to be aligned on 16 byte boundary.
        for(int i=0; i<nPoints; i++) {
            float* ptPtr = &pts[i].x;
            for(int j=0; j<4; j++) {
                ptPtr[j] = env * (cosf(ptPtr[j]) * sinf(ptPtr[j]) * tanf(ptPtr[j]));
            }
        }

    } else {

        // This inner loop will not autovectorize.
        for(int i=0; i<nPoints; i++) {
            MFloatPoint& pt = pts[i];
            for(int j=0; j<3; j++) {
                pt[j] = env * (cosf(pt[j]) * sinf(pt[j]) * tanf(pt[j]));
            }

        }
    }

    timer.endTimer();
    if(sseEnabled) {
        printf("SSE enabled, runtime %f\n", timer.elapsedTime());
    } else {
        printf("SSE disabled, runtime %f\n", timer.elapsedTime());
    }

    outMesh.setPoints(pts);

    return status;
}
Пример #14
0
bool CXRayObjectExport::initializeSetsAndLookupTables( bool exportAll )
//
// Description :
//    Creates a list of all sets in Maya, a list of mesh objects,
//    and polygon/vertex lookup tables that will be used to
//    determine which sets are referenced by the poly components.
//
{
	int i=0,j=0, length;
	MStatus stat;
	
	// Initialize class data.
	// Note: we cannot do this in the constructor as it
	// only gets called upon registry of the plug-in.
	//
	numSets = 0;
	sets = NULL;
	lastSets = NULL;
	lastMaterials = NULL;
	objectId = 0;
	objectCount = 0;
	polygonTable = NULL;
	vertexTable = NULL;
	polygonTablePtr = NULL;
	vertexTablePtr = NULL;
	objectGroupsTablePtr = NULL;
	objectNodeNamesArray.clear();
	transformNodeNameArray.clear();

	//////////////////////////////////////////////////////////////////
	//
	// Find all sets in Maya and store the ones we care about in
	// the 'sets' array. Also make note of the number of sets.
	//
	//////////////////////////////////////////////////////////////////
	
	// Get all of the sets in maya and put them into
	// a selection list
	// 
	MStringArray result;
	MGlobal::executeCommand( "ls -sets", result );
	MSelectionList * setList = new MSelectionList();
	length = result.length();
	for ( i=0; i<length; i++ )
	{	
		setList->add( result[i] );
	}
	
	// Extract each set as an MObject and add them to the
	// sets array.
	// We may be excluding groups, matierials, or ptGroups
	// in which case we can ignore those sets. 
	//
	MObject mset;
	sets = new MObjectArray();
	length = setList->length();
	for ( i=0; i<length; i++ )
	{
		setList->getDependNode( i, mset );
		
		MFnSet fnSet( mset, &stat );
		if ( stat ) {
			if ( MFnSet::kRenderableOnly == fnSet.restriction(&stat) ) {
				sets->append( mset );
			}
		}	
	}
	xr_delete(setList);
	
	numSets = sets->length();
			
	//////////////////////////////////////////////////////////////////
	//
	// Do a dag-iteration and for every mesh found, create facet and
	// vertex look-up tables. These tables will keep track of which
	// sets each component belongs to.
	//
	// If exportAll is false then iterate over the activeSelection 
	// list instead of the entire DAG.
	//
	// These arrays have a corrisponding entry in the name
	// stringArray.
	//
	//////////////////////////////////////////////////////////////////
	MIntArray vertexCounts;
	MIntArray polygonCounts;	
			
	if ( exportAll ) {
		MItDag dagIterator( MItDag::kBreadthFirst, MFn::kInvalid, &stat);

    	if ( MS::kSuccess != stat) {
    	    fprintf(stderr,"Failure in DAG iterator setup.\n");
    	    return false;
    	}
		
		objectNames = new MStringArray();
		
    	for ( ; !dagIterator.isDone(); dagIterator.next() ) 
		{
    	    MDagPath dagPath;
    	    stat = dagIterator.getPath( dagPath );

			if ( stat ) 
			{
				// skip over intermediate objects
				//
				MFnDagNode dagNode( dagPath, &stat );
				if (dagNode.isIntermediateObject()) 
				{
					continue;
				}

				if (( dagPath.hasFn(MFn::kMesh)) &&
					( dagPath.hasFn(MFn::kTransform)))
				{
					// We want only the shape, 
					// not the transform-extended-to-shape.
					continue;
				}
				else if ( dagPath.hasFn(MFn::kMesh))
				{
					// We have a mesh so create a vertex and polygon table
					// for this object.
					//
					MFnMesh fnMesh( dagPath );
					int vtxCount = fnMesh.numVertices();
					int polygonCount = fnMesh.numPolygons();
					// we do not need this call anymore, we have the shape.
					// dagPath.extendToShape();
					MString name = dagPath.fullPathName();
					objectNames->append( name );
					objectNodeNamesArray.append( fnMesh.name() );

					vertexCounts.append( vtxCount );
					polygonCounts.append( polygonCount );

					objectCount++;
				}
			}
		}	
	}else{
		MSelectionList slist;
    	MGlobal::getActiveSelectionList( slist );
    	MItSelectionList iter( slist );
		MStatus status;

		objectNames = new MStringArray();

		// We will need to interate over a selected node's heirarchy
		// in the case where shapes are grouped, and the group is selected.
		MItDag dagIterator( MItDag::kDepthFirst, MFn::kInvalid, &status);

    	for ( ; !iter.isDone(); iter.next() ){
			MDagPath objectPath;
			stat = iter.getDagPath( objectPath );

			// reset iterator's root node to be the selected node.
			status = dagIterator.reset (objectPath.node(), 
										MItDag::kDepthFirst, MFn::kInvalid );

			// DAG iteration beginning at at selected node
			for ( ; !dagIterator.isDone(); dagIterator.next() ){
				MDagPath dagPath;
				MObject  component = MObject::kNullObj;
				status = dagIterator.getPath(dagPath);

				if (!status){
					fprintf(stderr,"Failure getting DAG path.\n");
					freeLookupTables();
					return false;
				}

                // skip over intermediate objects
                //
                MFnDagNode dagNode( dagPath, &stat );
                if (dagNode.isIntermediateObject()) continue;

				if (( dagPath.hasFn(MFn::kMesh)) && ( dagPath.hasFn(MFn::kTransform))){
					// We want only the shape, 
					// not the transform-extended-to-shape.
					continue;
				}else if ( dagPath.hasFn(MFn::kMesh)){
					// We have a mesh so create a vertex and polygon table
					// for this object.
					//
					MFnMesh fnMesh( dagPath );
					int vtxCount = fnMesh.numVertices();
					int polygonCount = fnMesh.numPolygons();

					// we do not need this call anymore, we have the shape.
					// dagPath.extendToShape();
					MString name = dagPath.fullPathName();
					objectNames->append( name );
					objectNodeNamesArray.append( fnMesh.name() );
									
					vertexCounts.append( vtxCount );
					polygonCounts.append( polygonCount );

					objectCount++;	
				}
    		}
		}
	}

	// Now we know how many objects we are dealing with 
	// and we have counts of the vertices/polygons for each
	// object so create the maya group look-up table.
	//
	if( objectCount > 0 ) {
		// To export Maya groups we traverse the hierarchy starting at
		// each objectNodeNamesArray[i] going towards the root collecting transform
		// nodes as we go.
		length = objectNodeNamesArray.length();
		for( i=0; i<length; i++ ) {
			MIntArray transformNodeNameIndicesArray;
			recFindTransformDAGNodes( objectNodeNamesArray[i], transformNodeNameIndicesArray );
		}

		if( transformNodeNameArray.length() > 0 ) {
			objectGroupsTablePtr = xr_alloc<bool*>(objectCount);// (bool**) malloc( sizeof(bool*)*objectCount );
			length = transformNodeNameArray.length();
			for ( i=0; i<objectCount; i++ )
			{
//				objectGroupsTablePtr[i] = (bool*)calloc( length, sizeof(bool) );	
				objectGroupsTablePtr[i] = xr_alloc<bool>(length);
				ZeroMemory(objectGroupsTablePtr[i],length*sizeof(bool));
                // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there
				if ( objectGroupsTablePtr[i] == NULL ) {
					Log("! calloc returned NULL (objectGroupsTablePtr)");
					return false;
				}
			}
		}
//		else{
//			Log("! Can't find transform for node.");
//			return false;
//		}
	}

	// Create the vertex/polygon look-up tables.
	//
	if ( objectCount > 0 ) {
		
		vertexTablePtr = xr_alloc<bool*>(objectCount);	//(bool**) malloc( sizeof(bool*)*objectCount );
		polygonTablePtr = xr_alloc<bool*>(objectCount);	//(bool**) malloc( sizeof(bool*)*objectCount );
	
		for ( i=0; i<objectCount; i++ )
		{
//			vertexTablePtr[i] = (bool*)calloc( vertexCounts[i]*numSets, sizeof(bool) );	
			vertexTablePtr[i] = xr_alloc<bool>(vertexCounts[i]*numSets);
			ZeroMemory(vertexTablePtr[i],vertexCounts[i]*numSets*sizeof(bool));
            // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there
			if ( vertexTablePtr[i] == NULL ) {
				Log("! calloc returned NULL (vertexTable)");
				return false;
			}
	
//			polygonTablePtr[i] = (bool*)calloc( polygonCounts[i]*numSets, sizeof(bool) );
			polygonTablePtr[i] = xr_alloc<bool>(polygonCounts[i]*numSets);
			ZeroMemory(polygonTablePtr[i],polygonCounts[i]*numSets*sizeof(bool));
            // XXX nitrocaster: remove this 'cause malloc failure shouldn't be handled there
			if ( polygonTablePtr[i] == NULL ) {
				Log("! calloc returned NULL (polygonTable)");
				return false;
			}
		}	
	}

	// If we found no meshes then return
	//	
	if ( objectCount == 0 ) {
		return false;
	}
	
	//////////////////////////////////////////////////////////////////
	//
	// Go through all of the set members (flattened lists) and mark
	// in the lookup-tables, the sets that each mesh component belongs
	// to.
	//
	//
	//////////////////////////////////////////////////////////////////
	bool flattenedList = true;
	MDagPath object;
	MObject component;
	MSelectionList memberList;
	
	
	for ( i=0; i<numSets; i++ )
	{
		MFnSet fnSet( (*sets)[i] );		
		memberList.clear();
		stat = fnSet.getMembers( memberList, flattenedList );

		if (MS::kSuccess != stat) {
			fprintf(stderr,"Error in fnSet.getMembers()!\n");
		}

		int m, numMembers;
		numMembers = memberList.length();
		for ( m=0; m<numMembers; m++ )
		{
			if ( memberList.getDagPath(m,object,component) ) {

				if ( (!component.isNull()) && (object.apiType() == MFn::kMesh) )
				{
					if (component.apiType() == MFn::kMeshVertComponent) {
						MItMeshVertex viter( object, component );	
						for ( ; !viter.isDone(); viter.next() )
						{
							int compIdx = viter.index();
							MString name = object.fullPathName();
							
							// Figure out which object vertexTable
							// to get.
							//

							int o, numObjectNames;
							numObjectNames = objectNames->length();
							for ( o=0; o<numObjectNames; o++ ) {
								if ( (*objectNames)[o] == name ) {
									// Mark set i as true in the table
									//		
									vertexTable = vertexTablePtr[o];
									*(vertexTable + numSets*compIdx + i) = true;
									break;
								}
							}
						}
					}
					else if (component.apiType() == MFn::kMeshPolygonComponent) 
					{
						MItMeshPolygon piter( object, component );
						for ( ; !piter.isDone(); piter.next() )
						{
							int compIdx = piter.index();
							MString name = object.fullPathName();
							
							// Figure out which object polygonTable
							// to get.
							//							
							int o, numObjectNames;
							numObjectNames = objectNames->length();
							for ( o=0; o<numObjectNames; o++ ) {
								if ( (*objectNames)[o] == name ) {
									
									// Mark set i as true in the table
									//

									// Check for bad components in the set
									//									
									if ( compIdx >= polygonCounts[o] ) {
										Msg("! Bad polygon index '%d' found. Polygon skipped",compIdx);
										break;
									}
									
									polygonTable = polygonTablePtr[o];
									*(polygonTable + numSets*compIdx + i) = true;
									break;
								}
							}	
						}
					}										
				}
				else { 

				// There are no components, therefore we can mark
				// all polygons as members of the given set.
				//

				if (object.hasFn(MFn::kMesh)) {

					MFnMesh fnMesh( object, &stat );
					if ( MS::kSuccess != stat) {
						fprintf(stderr,"Failure in MFnMesh initialization.\n");
						return false;
					}

					// We are going to iterate over all the polygons.
					//
					MItMeshPolygon piter( object, MObject::kNullObj, &stat );
					if ( MS::kSuccess != stat) {
						fprintf(stderr,
								"Failure in MItMeshPolygon initialization.\n");
						return false;
					}
					for ( ; !piter.isDone(); piter.next() )
					{
						int compIdx = piter.index();
						MString name = object.fullPathName();

						// Figure out which object polygonTable to get.
						//
						int o, numObjectNames;
						numObjectNames = objectNames->length();
						for ( o=0; o<numObjectNames; o++ ) {
							if ( (*objectNames)[o] == name ) {
								// Check for bad components in the set
								//
								if ( compIdx >= polygonCounts[o] ) {
									Msg("! Bad polygon index '%d' found. Polygon skipped",compIdx);
									break;
								}
								// Mark set i as true in the table
								//
								polygonTable = polygonTablePtr[o];
								*(polygonTable + numSets*compIdx + i) = true;
								break;
							}
						}
					} // end of piter.next() loop
				} // end of condition if (object.hasFn(MFn::kMesh))
				} // end of else condifion if (!component.isNull()) 
			} // end of memberList.getDagPath(m,object,component)
		} // end of memberList loop
	} // end of for-loop for sets

	// Go through all of the group members and mark in the
	// lookup-table, the group that each shape belongs to.
	length = objectNodeNamesArray.length();
	if (objectGroupsTablePtr){
		for( i=0; i<length; i++ ) {
			MIntArray groupTableIndicesArray;
			bool *objectGroupTable = objectGroupsTablePtr[i];
			int length2;
			recFindTransformDAGNodes( objectNodeNamesArray[i], groupTableIndicesArray );
			length2 = groupTableIndicesArray.length();
			for( j=0; j<length2; j++ ) {
				int groupIdx = groupTableIndicesArray[j];
				objectGroupTable[groupIdx] = true;
			}
		}
	}
	return true;
}
Пример #15
0
MStatus n_tentacle::compute( const MPlug& plug, MDataBlock& data )
{
	MStatus returnStatus;

	//make sure we have the curve
	MObject curveObj = data.inputValue(curve).asNurbsCurve();

	if(!curveObj.isNull())
	{
		//get the data
		MArrayDataHandle inMatrixArrayHnd = data.inputArrayValue(matrix);

		int tangentAxisI = data.inputValue(tangentAxis).asInt();
		if(tangentAxisI > 2)
			tangentAxisI = - (tangentAxisI - 2);
		else
			tangentAxisI = tangentAxisI + 1;

		double stretchF = data.inputValue(stretch).asDouble();
		double globalScaleF = data.inputValue(globalScale).asDouble();
		double iniLengthF = data.inputValue(iniLength).asDouble();

		const MFnNurbsCurve curve(curveObj);
		MArrayDataHandle parameterArrayHnd = data.inputArrayValue(parameter);
		MArrayDataHandle blendRotArrayHnd = data.inputArrayValue(blendRot);
		MArrayDataHandle intervalArrayHnd = data.inputArrayValue(interval);
		MArrayDataHandle outTranslateArrayHnd = data.outputArrayValue(outTranslate);
		MArrayDataHandle outRotateArrayHnd = data.outputArrayValue(outRotate);

		int parameterNrPlugs = parameterArrayHnd.elementCount();
		int blendRotNrPlugs = blendRotArrayHnd.elementCount();
		int outTranslateNrPlugs = outTranslateArrayHnd.elementCount();
		int outRotateNrPlugs = outRotateArrayHnd.elementCount();

		//get the current curve length
        double currCurveLen = curve.length();

        if(this->init == false)
        {
        	if(outTranslateNrPlugs == parameterNrPlugs && outRotateNrPlugs == parameterNrPlugs && parameterNrPlugs == blendRotNrPlugs)
        	{
        		this->init = true;
        	}
        }

		if( plug == outTranslate || plug == outRotate || plug == outRotateX || plug == outRotateY || plug == outRotateZ)
		{
			if(this->init)
			{
                MArrayDataBuilder tbuilder(outTranslate, parameterNrPlugs);
                MArrayDataBuilder rbuilder(outRotate, parameterNrPlugs);

				for(int i = 0; i < parameterNrPlugs; i++)
				{
					intervalArrayHnd.jumpToArrayElement(i);
					int intervalI = intervalArrayHnd.inputValue().asInt();

					inMatrixArrayHnd.jumpToArrayElement(intervalI);
					MMatrix matrix1 = inMatrixArrayHnd.inputValue().asMatrix();
					this->removeMatrixScale(matrix1);

					inMatrixArrayHnd.jumpToArrayElement(intervalI + 1);
					MMatrix matrix2 = inMatrixArrayHnd.inputValue().asMatrix();
					this->removeMatrixScale(matrix2);

					parameterArrayHnd.jumpToArrayElement(i);
					double parameterF = parameterArrayHnd.inputValue().asDouble();

					blendRotArrayHnd.jumpToArrayElement(i);
					double blendRotF = blendRotArrayHnd.inputValue().asDouble();

					MVector outPos, outRot;

					this->computeSlerp(matrix1, matrix2, curve, parameterF, blendRotF, iniLengthF, currCurveLen, stretchF, globalScaleF, tangentAxisI, outPos, outRot);

                    MDataHandle outTranslateHnd = tbuilder.addElement(i);
                    outTranslateHnd.set3Double(outPos.x, outPos.y, outPos.z);

                    MDataHandle outRotateHnd = rbuilder.addElement(i);
                    double rotation[3];
                    outRotateHnd.set( outRot.x, outRot.y, outRot.z );

                    //this->output(outPos, outRot, i, outTranslateArrayHnd, outRotateArrayHnd);

				}

                outTranslateArrayHnd.set(tbuilder);
                outTranslateArrayHnd.setAllClean();

                outRotateArrayHnd.set(rbuilder);
                outRotateArrayHnd.setAllClean();
			}
            data.setClean(plug);

		}
		else
		{
			return MS::kUnknownParameter;
		}
	}

	return MS::kSuccess;
}
Пример #16
0
//
// Main routine
///////////////////////////////////////////////////////////////////////////////
MStatus particleSystemInfoCmd::doIt( const MArgList& args )
{
	MStatus stat = parseArgs( args );
	if( stat != MS::kSuccess ) return stat;

	if( particleNode.isNull() ) {
	        MObject parent;
		MFnParticleSystem dummy;
		particleNode = dummy.create(&stat);
		CHECKRESULT(stat,"MFnParticleSystem::create(status) failed!");

		MFnParticleSystem ps( particleNode, &stat );
		CHECKRESULT(stat,"MFnParticleSystem::MFnParticleSystem(MObject,status) failed!");

		MPointArray posArray;
		posArray.append(MPoint(-5,  5, 0));
		posArray.append(MPoint(-5, 10, 0));

		MVectorArray velArray;
		velArray.append(MPoint(1, 1, 0));
		velArray.append(MPoint(1, 1, 0));
		stat = ps.emit(posArray, velArray);
		CHECKRESULT(stat,"MFnParticleSystem::emit(posArray,velArray) failed!");

		stat = ps.emit(MPoint(5,  5, 0));
		CHECKRESULT(stat,"MFnParticleSystem::emit(pos) failed!");
		stat = ps.emit(MPoint(5, 10, 0));
		CHECKRESULT(stat,"MFnParticleSystem::emit(pos) failed!");

		stat = ps.saveInitialState();
		CHECKRESULT(stat,"MFnParticleSystem::saveInitialState() failed!");

		MVectorArray accArray;
		accArray.setLength(4);
		for( unsigned int i=0; i<accArray.length(); i++ )
		{
		        MVector& acc = accArray[i];
			acc.x = acc.y = acc.z = 3.0;
		}
		MString accName("acceleration");
		ps.setPerParticleAttribute( accName, accArray, &stat );
		CHECKRESULT(stat,"MFnParticleSystem::setPerParticleAttribute(vectorArray) failed!");
	} 

	MFnParticleSystem ps( particleNode, &stat );
	CHECKRESULT(stat,"MFnParticleSystem::MFnParticleSystem(MObject,status) failed!");

	if( ! ps.isValid() )
	{
		MGlobal::displayError( "The function set is invalid!" );
		return MS::kFailure;
	}

	const MString name = ps.particleName();
	const MFnParticleSystem::RenderType psType = ps.renderType();
	const unsigned int count = ps.count();

	const char* typeString = NULL;
	switch( psType )
	{
	case MFnParticleSystem::kCloud:
		typeString = "Cloud";
		break;
	case MFnParticleSystem::kTube:
		typeString = "Tube system";
		break;
	case MFnParticleSystem::kBlobby:
		typeString = "Blobby";
		break;
	case MFnParticleSystem::kMultiPoint:
		typeString = "MultiPoint";
		break;
	case MFnParticleSystem::kMultiStreak:
		typeString = "MultiStreak";
		break;
	case MFnParticleSystem::kNumeric:
		typeString = "Numeric";
		break;
	case MFnParticleSystem::kPoints:
		typeString = "Points";
		break;
	case MFnParticleSystem::kSpheres:
		typeString = "Spheres";
		break;
	case MFnParticleSystem::kSprites:
		typeString = "Sprites";
		break;
	case MFnParticleSystem::kStreak:
		typeString = "Streak";
		break;
	default:
		typeString = "Particle system";
		assert( false );
		break;
	}

	char buffer[256];

	sprintf( buffer, "%s \"%s\" has %u primitives.", typeString, name.asChar(), count );
	MGlobal::displayInfo( buffer );

	unsigned i;

	MIntArray ids;
	ps.particleIds( ids );

	sprintf( buffer, "count : %u ", count );
	MGlobal::displayInfo( buffer );
	sprintf( buffer, "%u ids.", ids.length() );
	MGlobal::displayInfo( buffer );

	assert( ids.length() == count );
	for( i=0; i<ids.length(); i++ )
	{
		sprintf( buffer, "id %d  ", ids[i] );
		MGlobal::displayInfo( buffer );
	}

	MVectorArray positions;
	ps.position( positions );
	assert( positions.length() == count );
	for( i=0; i<positions.length(); i++ )
	{
		MVector& p = positions[i];
		sprintf( buffer, "pos %f %f %f  ", p[0], p[1], p[2] );
		MGlobal::displayInfo( buffer );
	}

	MVectorArray vels;
	ps.velocity( vels );
	assert( vels.length() == count );
	for( i=0; i<vels.length(); i++ )
	{
		const MVector& v = vels[i];
		sprintf( buffer, "vel %f %f %f  ", v[0], v[1], v[2] );
		MGlobal::displayInfo( buffer );
	}

	MVectorArray accs;
	ps.acceleration( accs );
	assert( accs.length() == count );
	for( i=0; i<accs.length(); i++ )
	{
		const MVector& a = accs[i];
		sprintf( buffer, "acc %f %f %f  ", a[0], a[1], a[2] );
		MGlobal::displayInfo( buffer );
	}

	bool flag = ps.isDeformedParticleShape(&stat);
	CHECKRESULT(stat,"MFnParticleSystem::isDeformedParticleShape() failed!");
	if( flag ) {
	        MObject obj = ps.originalParticleShape(&stat);
		CHECKRESULT(stat,"MFnParticleSystem::originalParticleShape() failed!");
		if( obj != MObject::kNullObj ) {
		        MFnParticleSystem ps( obj );
			sprintf( buffer, "original particle shape : %s ", ps.particleName().asChar() );
			MGlobal::displayInfo( buffer );
		}
	}

	flag = ps.isDeformedParticleShape(&stat);
	CHECKRESULT(stat,"MFnParticleSystem::isDeformedParticleShape() failed!");
	if( !flag ) {
	        MObject obj = ps.deformedParticleShape(&stat);
		CHECKRESULT(stat,"MFnParticleSystem::deformedParticleShape() failed!");
		if( obj != MObject::kNullObj ) {
		        MFnParticleSystem ps( obj );
			sprintf( buffer, "deformed particle shape : %s ", ps.particleName().asChar() );
			MGlobal::displayInfo( buffer );
		}
	}

	if( ids.length() == positions.length() &&
	    ids.length() == vels.length()      &&
	    ids.length() == accs.length()       ) { 
	        setResult( int(ids.length()) );
	} else {
	        setResult( int(-1) );
	}

	return MS::kSuccess;
}
Пример #17
0
MStatus mapBlendShape::deform(MDataBlock& data, 
							  MItGeometry& itGeo, 
							  const MMatrix& localToWorldMatrix, 
							  unsigned int geomIndex)
{
    MStatus status;

	// get the blendMesh 
	MDataHandle hBlendMesh = data.inputValue( aBlendMesh, &status );
    CHECK_MSTATUS_AND_RETURN_IT( status );
    MObject oBlendMesh = hBlendMesh.asMesh();
    if (oBlendMesh.isNull())
    {
        return MS::kSuccess;
    }

	MFnMesh fnMesh( oBlendMesh, &status );
    CHECK_MSTATUS_AND_RETURN_IT( status );
    MPointArray blendPoints;
    fnMesh.getPoints( blendPoints );

	// get the dirty flags for the input and blendMap
	bool inputGeomClean = data.isClean(inputGeom, &status);
	bool blendMapClean  = data.isClean(aBlendMap, &status);

	if (!blendMapClean) {
		lumValues.reserve(itGeo.count());
	}
	
	MDoubleArray uCoords, vCoords;
	MVectorArray resultColors;
	MDoubleArray resultAlphas;

	uCoords.setLength(1);
	vCoords.setLength(1);

	bool hasTextureNode;
	bool useBlendMap = data.inputValue(aUseBlendMap).asBool();
	float blendMapMultiplier = data.inputValue(aBlendMapMultiplier).asFloat();

	if (blendMapMultiplier<=0.0) {
		useBlendMap = false;
	}

	if (useBlendMap) {
		hasTextureNode = MDynamicsUtil::hasValidDynamics2dTexture(thisMObject(), aBlendMap);
	}

	float env = data.inputValue(envelope).asFloat();
    MPoint point;
	float2 uvPoint;
    float w, lum;

    for ( ; !itGeo.isDone(); itGeo.next() )
    {
		lum = 1.0;

		if (useBlendMap) {
			if (!blendMapClean) {
				fnMesh.getUVAtPoint(blendPoints[itGeo.index()], uvPoint);

				if (hasTextureNode) {
					uCoords[0] = uvPoint[0];
					vCoords[0] = uvPoint[1];
					MDynamicsUtil::evalDynamics2dTexture(thisMObject(), aBlendMap, uCoords, vCoords, &resultColors, &resultAlphas);
					lum = float(resultColors[0][0]);
				}
				lumValues[itGeo.index()] = lum;
			} else {
				lum = lumValues[itGeo.index()];
			}
		}

        point = itGeo.position();
        w = weightValue( data, geomIndex, itGeo.index() );
        point += (blendPoints[itGeo.index()] - point) * env * w * lum * blendMapMultiplier;
        itGeo.setPosition( point );
    }

	return MS::kSuccess;
}
Пример #18
0
MStatus AlembicExportCommand::doIt(const MArgList &args)
{
  ESS_PROFILE_SCOPE("AlembicExportCommand::doIt");

  MStatus status = MS::kFailure;

  MTime currentAnimStartTime = MAnimControl::animationStartTime(),
        currentAnimEndTime = MAnimControl::animationEndTime(),
        oldCurTime = MAnimControl::currentTime(),
        curMinTime = MAnimControl::minTime(),
        curMaxTime = MAnimControl::maxTime();
  MArgParser argData(syntax(), args, &status);

  if (argData.isFlagSet("help")) {
    // TODO: implement help for this command
    // MGlobal::displayInfo(util::getHelpText());
    return MS::kSuccess;
  }

  unsigned int jobCount = argData.numberOfFlagUses("jobArg");
  MStringArray jobStrings;
  if (jobCount == 0) {
    // TODO: display dialog
    MGlobal::displayError("[ExocortexAlembic] No jobs specified.");
    MPxCommand::setResult(
        "Error caught in AlembicExportCommand::doIt: no job specified");
    return status;
  }
  else {
    // get all of the jobstrings
    for (unsigned int i = 0; i < jobCount; i++) {
      MArgList jobArgList;
      argData.getFlagArgumentList("jobArg", i, jobArgList);
      jobStrings.append(jobArgList.asString(0));
    }
  }

  // create a vector to store the jobs
  std::vector<AlembicWriteJob *> jobPtrs;
  double minFrame = 1000000.0;
  double maxFrame = -1000000.0;
  double maxSteps = 1;
  double maxSubsteps = 1;

  // init the curve accumulators
  AlembicCurveAccumulator::Initialize();

  try {
    // for each job, check the arguments
    bool failure = false;
    for (unsigned int i = 0; i < jobStrings.length(); ++i) {
      double frameIn = 1.0;
      double frameOut = 1.0;
      double frameSteps = 1.0;
      double frameSubSteps = 1.0;
      MString filename;
      bool purepointcache = false;
      bool normals = true;
      bool uvs = true;
      bool facesets = true;
      bool bindpose = true;
      bool dynamictopology = false;
      bool globalspace = false;
      bool withouthierarchy = false;
      bool transformcache = false;
      bool useInitShadGrp = false;
      bool useOgawa = false;  // Later, will need to be changed!

      MStringArray objectStrings;
      std::vector<std::string> prefixFilters;
      std::set<std::string> attributes;
      std::vector<std::string> userPrefixFilters;
      std::set<std::string> userAttributes;
      MObjectArray objects;
      std::string search_str, replace_str;

      // process all tokens of the job
      MStringArray tokens;
      jobStrings[i].split(';', tokens);
      for (unsigned int j = 0; j < tokens.length(); j++) {
        MStringArray valuePair;
        tokens[j].split('=', valuePair);
        if (valuePair.length() != 2) {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }

        const MString &lowerValue = valuePair[0].toLowerCase();
        if (lowerValue == "in") {
          frameIn = valuePair[1].asDouble();
        }
        else if (lowerValue == "out") {
          frameOut = valuePair[1].asDouble();
        }
        else if (lowerValue == "step") {
          frameSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "substep") {
          frameSubSteps = valuePair[1].asDouble();
        }
        else if (lowerValue == "normals") {
          normals = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "uvs") {
          uvs = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "facesets") {
          facesets = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "bindpose") {
          bindpose = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "purepointcache") {
          purepointcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "dynamictopology") {
          dynamictopology = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "globalspace") {
          globalspace = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "withouthierarchy") {
          withouthierarchy = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "transformcache") {
          transformcache = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "filename") {
          filename = valuePair[1];
        }
        else if (lowerValue == "objects") {
          // try to find each object
          valuePair[1].split(',', objectStrings);
        }
        else if (lowerValue == "useinitshadgrp") {
          useInitShadGrp = valuePair[1].asInt() != 0;
        }

        // search/replace
        else if (lowerValue == "search") {
          search_str = valuePair[1].asChar();
        }
        else if (lowerValue == "replace") {
          replace_str = valuePair[1].asChar();
        }
        else if (lowerValue == "ogawa") {
          useOgawa = valuePair[1].asInt() != 0;
        }
        else if (lowerValue == "attrprefixes") {
          splitListArg(valuePair[1], prefixFilters);
        }
        else if (lowerValue == "attrs") {
          splitListArg(valuePair[1], attributes);
        }
        else if (lowerValue == "userattrprefixes") {
          splitListArg(valuePair[1], userPrefixFilters);
        }
        else if (lowerValue == "userattrs") {
          splitListArg(valuePair[1], userAttributes);
        }
        else {
          MGlobal::displayWarning(
              "[ExocortexAlembic] Skipping invalid token: " + tokens[j]);
          continue;
        }
      }

      // now check the object strings
      for (unsigned int k = 0; k < objectStrings.length(); k++) {
        MSelectionList sl;
        MString objectString = objectStrings[k];
        sl.add(objectString);
        MDagPath dag;
        for (unsigned int l = 0; l < sl.length(); l++) {
          sl.getDagPath(l, dag);
          MObject objRef = dag.node();
          if (objRef.isNull()) {
            MGlobal::displayWarning("[ExocortexAlembic] Skipping object '" +
                                    objectStrings[k] + "', not found.");
            break;
          }

          // get all parents
          MObjectArray parents;

          // check if this is a camera
          bool isCamera = false;
          for (unsigned int m = 0; m < dag.childCount(); ++m) {
            MFnDagNode child(dag.child(m));
            MFn::Type ctype = child.object().apiType();
            if (ctype == MFn::kCamera) {
              isCamera = true;
              break;
            }
          }

          if (dag.node().apiType() == MFn::kTransform && !isCamera &&
              !globalspace && !withouthierarchy) {
            MDagPath ppath = dag;
            while (!ppath.node().isNull() && ppath.length() > 0 &&
                   ppath.isValid()) {
              parents.append(ppath.node());
              if (ppath.pop() != MStatus::kSuccess) {
                break;
              }
            }
          }
          else {
            parents.append(dag.node());
          }

          // push all parents in
          while (parents.length() > 0) {
            bool found = false;
            for (unsigned int m = 0; m < objects.length(); m++) {
              if (objects[m] == parents[parents.length() - 1]) {
                found = true;
                break;
              }
            }
            if (!found) {
              objects.append(parents[parents.length() - 1]);
            }
            parents.remove(parents.length() - 1);
          }

          // check all of the shapes below
          if (!transformcache) {
            sl.getDagPath(l, dag);
            for (unsigned int m = 0; m < dag.childCount(); m++) {
              MFnDagNode child(dag.child(m));
              if (child.isIntermediateObject()) {
                continue;
              }
              objects.append(child.object());
            }
          }
        }
      }

      // check if we have incompatible subframes
      if (maxSubsteps > 1.0 && frameSubSteps > 1.0) {
        const double part = (frameSubSteps > maxSubsteps)
                                ? (frameSubSteps / maxSubsteps)
                                : (maxSubsteps / frameSubSteps);
        if (abs(part - floor(part)) > 0.001) {
          MString frameSubStepsStr, maxSubstepsStr;
          frameSubStepsStr.set(frameSubSteps);
          maxSubstepsStr.set(maxSubsteps);
          MGlobal::displayError(
              "[ExocortexAlembic] You cannot combine substeps " +
              frameSubStepsStr + " and " + maxSubstepsStr +
              " in one export. Aborting.");
          return MStatus::kInvalidParameter;
        }
      }

      // remember the min and max values for the frames
      if (frameIn < minFrame) {
        minFrame = frameIn;
      }
      if (frameOut > maxFrame) {
        maxFrame = frameOut;
      }
      if (frameSteps > maxSteps) {
        maxSteps = frameSteps;
      }
      if (frameSteps > 1.0) {
        frameSubSteps = 1.0;
      }
      if (frameSubSteps > maxSubsteps) {
        maxSubsteps = frameSubSteps;
      }

      // check if we have a filename
      if (filename.length() == 0) {
        MGlobal::displayError("[ExocortexAlembic] No filename specified.");
        for (size_t k = 0; k < jobPtrs.size(); k++) {
          delete (jobPtrs[k]);
        }
        MPxCommand::setResult(
            "Error caught in AlembicExportCommand::doIt: no filename "
            "specified");
        return MStatus::kFailure;
      }

      // construct the frames
      MDoubleArray frames;
      {
        const double frameIncr = frameSteps / frameSubSteps;
        for (double frame = frameIn; frame <= frameOut; frame += frameIncr) {
          frames.append(frame);
        }
      }

      AlembicWriteJob *job =
          new AlembicWriteJob(filename, objects, frames, useOgawa,
              prefixFilters, attributes, userPrefixFilters, userAttributes);
      job->SetOption("exportNormals", normals ? "1" : "0");
      job->SetOption("exportUVs", uvs ? "1" : "0");
      job->SetOption("exportFaceSets", facesets ? "1" : "0");
      job->SetOption("exportInitShadGrp", useInitShadGrp ? "1" : "0");
      job->SetOption("exportBindPose", bindpose ? "1" : "0");
      job->SetOption("exportPurePointCache", purepointcache ? "1" : "0");
      job->SetOption("exportDynamicTopology", dynamictopology ? "1" : "0");
      job->SetOption("indexedNormals", "1");
      job->SetOption("indexedUVs", "1");
      job->SetOption("exportInGlobalSpace", globalspace ? "1" : "0");
      job->SetOption("flattenHierarchy", withouthierarchy ? "1" : "0");
      job->SetOption("transformCache", transformcache ? "1" : "0");

      // check if the search/replace strings are valid!
      if (search_str.length() ? !replace_str.length()
                              : replace_str.length())  // either search or
                                                       // replace string is
                                                       // missing or empty!
      {
        ESS_LOG_WARNING(
            "Missing search or replace parameter. No strings will be "
            "replaced.");
        job->replacer = SearchReplace::createReplacer();
      }
      else {
        job->replacer = SearchReplace::createReplacer(search_str, replace_str);
      }

      // check if the job is satifsied
      if (job->PreProcess() != MStatus::kSuccess) {
        MGlobal::displayError("[ExocortexAlembic] Job skipped. Not satisfied.");
        delete (job);
        failure = true;
        break;
      }

      // push the job to our registry
      MGlobal::displayInfo("[ExocortexAlembic] Using WriteJob:" +
                           jobStrings[i]);
      jobPtrs.push_back(job);
    }

    if (failure) {
      for (size_t k = 0; k < jobPtrs.size(); k++) {
        delete (jobPtrs[k]);
      }
      return MS::kFailure;
    }

    // compute the job count
    unsigned int jobFrameCount = 0;
    for (size_t i = 0; i < jobPtrs.size(); i++)
      jobFrameCount += (unsigned int)jobPtrs[i]->GetNbObjects() *
                       (unsigned int)jobPtrs[i]->GetFrames().size();

    // now, let's run through all frames, and process the jobs
    const double frameRate = MTime(1.0, MTime::kSeconds).as(MTime::uiUnit());
    const double incrSteps = maxSteps / maxSubsteps;
    double nextFrame = minFrame + incrSteps;

    for (double frame = minFrame; frame <= maxFrame;
         frame += incrSteps, nextFrame += incrSteps) {
      MAnimControl::setCurrentTime(MTime(frame / frameRate, MTime::kSeconds));
      MAnimControl::setAnimationEndTime(
          MTime(nextFrame / frameRate, MTime::kSeconds));
      MAnimControl::playForward();  // this way, it forces Maya to play exactly
      // one frame! and particles are updated!

      AlembicCurveAccumulator::StartRecordingFrame();
      for (size_t i = 0; i < jobPtrs.size(); i++) {
        MStatus status = jobPtrs[i]->Process(frame);
        if (status != MStatus::kSuccess) {
          MGlobal::displayError("[ExocortexAlembic] Job aborted :" +
                                jobPtrs[i]->GetFileName());
          for (size_t k = 0; k < jobPtrs.size(); k++) {
            delete (jobPtrs[k]);
          }
          restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                         curMinTime, curMaxTime);
          return status;
        }
      }
      AlembicCurveAccumulator::StopRecordingFrame();
    }
  }
  catch (...) {
    MGlobal::displayError(
        "[ExocortexAlembic] Jobs aborted, force closing all archives!");
    for (std::vector<AlembicWriteJob *>::iterator beg = jobPtrs.begin();
         beg != jobPtrs.end(); ++beg) {
      (*beg)->forceCloseArchive();
    }
    restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                   curMinTime, curMaxTime);
    MPxCommand::setResult("Error caught in AlembicExportCommand::doIt");
    status = MS::kFailure;
  }
  MAnimControl::stop();
  AlembicCurveAccumulator::Destroy();

  // restore the animation start/end time and the current time!
  restoreOldTime(currentAnimStartTime, currentAnimEndTime, oldCurTime,
                 curMinTime, curMaxTime);

  // delete all jobs
  for (size_t k = 0; k < jobPtrs.size(); k++) {
    delete (jobPtrs[k]);
  }

  // remove all known archives
  deleteAllArchives();
  return status;
}
//-----------------------------------------------------------------------------
// 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;
}
Пример #20
0
Helium::TUID Maya::GetNodeID( const MObject& node, bool create )
{
  if (node == MObject::kNullObj)
  {
    return Helium::TUID::Null;
  }

  MObject attr = MObject::kNullObj;
  MStatus status = MS::kFailure;
  MFnDependencyNode nodeFn (node);

  if ( create )
  {
    //
    // GUID->TUID legacy handling
    //

    // look for the old GUID attribute
    attr = nodeFn.attribute(MString (s_GUIDAttributeName), &status);

    // if we found it
    if ( status == MS::kSuccess && !attr.isNull() )
    {
      // get the GUID value
      MString str;
      MPlug plug (node, attr);
      status = plug.getValue(str);
      HELIUM_ASSERT( status != MS::kFailure );

      // parse it
      Helium::GUID id;
      bool parsed = id.FromString(str.asTChar());
      HELIUM_ASSERT( parsed );

      // convert it to a TUID and set the new attribute
      Helium::TUID tuid;
      tuid.FromGUID( id );
      status = SetNodeID( node, tuid );
      HELIUM_ASSERT( status != MS::kFailure );

      // check to see if we are a locked node
      bool nodeWasLocked = nodeFn.isLocked();
      if ( nodeWasLocked )
      {
        // turn off any node locking so an attribute can be added
        nodeFn.setLocked( false );
      }

      // unlock the attribute
      status = plug.setLocked( false );
      HELIUM_ASSERT( status != MS::kFailure );

      // remove the attribute
      status = nodeFn.removeAttribute( attr );
      HELIUM_ASSERT( status != MS::kFailure );

      // reset to the prior state of wasLocked
      if ( nodeWasLocked )
      {
        nodeFn.setLocked( nodeWasLocked );
      }
    }
  }

  // look for the TUID attribute
  attr = nodeFn.attribute(MString (s_TUIDAttributeName));

  // retrieve the attribute value (may be empty if we are not creating a new id)
  MString str;
  MPlug plug (node, attr);
  plug.getValue(str);

  // if we don't have an existing id and we should create one
  if ( str.length() == 0 && create )
  {
    // generate a new ID
    Helium::TUID id( Helium::TUID::Generate() );

    // set the new ID value on the node
    if( SetNodeID( node, id ) )
    {
      return id;
    }
    else
    {
      return Helium::TUID::Null;
    }
  }

  // parse the value (this may be null if we did not create the attribute)
  Helium::TUID id;
  id.FromString(str.asTChar());
  return id;
}
Пример #21
0
MStatus createClip::doIt( const MArgList& args )
{
	// parse the command arguments
	//
	MStatus stat = parseArgs(args);
	if (stat != MS::kSuccess) {
		return stat;
	}
	
	unsigned int count = 0;

	// if the character flag was used, create the clip on the specified
	// character, otherwise, create a character
	//
	MFnCharacter fnCharacter;
	if (fCharacter.isNull()) {
		MSelectionList activeList;
		MGlobal::getActiveSelectionList (activeList);
		if (0 == activeList.length()) {
			MString errMsg("No character was specified, and no objects were selected.");
			displayError(errMsg);
			return MS::kFailure;
		}
		// create a character using the selection list
		//
		fCharacter = fnCharacter.create(activeList,MFnSet::kNone,&stat);
		if (stat != MS::kSuccess) {
			MString errMsg("Failed to create character using the selection.");
			displayError(errMsg);
			return MS::kFailure;
		}
	} else {
		fnCharacter.setObject(fCharacter);
	}

	// Get the array of members of the character. We will create a clip
	// for them.
	//
	MPlugArray plugs;
	fnCharacter.getMemberPlugs(plugs);

	// Now create a animCurves to use as a clip for the character.
	// The curves will be set up between frames 0 and 10;
	//
	MTime start(0.0);
	MTime duration(10.0);
	MObjectArray clipCurves;
	
	for (count = 0; count < plugs.length(); ++count) {
		// Now create a bunch of animCurves to use as a clip for the
		// character
		//
		MFnAnimCurve fnCurve;
//		AnimCurveType plugType = fnCurve.timedAnimCurveTypeForPlug(plugs[count]);
		MObject curve = fnCurve.create(MFnAnimCurve::kAnimCurveTL); // plugType);
		fnCurve.addKeyframe(start,5.0);
		fnCurve.addKeyframe(duration,15.0);
		clipCurves.append(curve);
	}
	
	// Create a source clip node and add the animation to it
	//
	MFnClip fnClipCreate;
	MObject sourceClip = fnClipCreate.createSourceClip(start,duration,fMod,&stat);
	fnCharacter.attachSourceToCharacter(sourceClip,fMod);	
	for (count = 0; count < plugs.length(); ++count) {
		MPlug animPlug = plugs[count];
		fnCharacter.addCurveToClip(clipCurves[count],sourceClip,animPlug,fMod);
	}

	// instance the clip
	//
	MTime schedStart(15.0);
	MObject instancedClip = fnClipCreate.createInstancedClip(sourceClip,
															 schedStart,
															 fMod,
															 &stat);
	fnCharacter.attachInstanceToCharacter(instancedClip,fMod);

	// instance the clip a second time, at time 30
	//
	schedStart.setValue(30.0);
	MObject instancedClip2 = fnClipCreate.createInstancedClip(sourceClip,
															  schedStart,
															  fMod,
															  &stat);
	fnCharacter.attachInstanceToCharacter(instancedClip2,fMod);

	return stat;
}
Пример #22
0
// Set keyframes to move selected object in a spiral
MStatus spiralAnimCurve::doIt( const MArgList& )
{   
	// Get the Active Selection List
	//
	MStatus status;
	MSelectionList	sList;
	MGlobal::getActiveSelectionList( sList );

	// Create an iterator for the selection list
	//
	MItSelectionList iter( sList, MFn::kDagNode, &status );
	if ( MS::kSuccess != status ) {
		cerr << "Failure in plugin setup";
		return MS::kFailure;
	}
	
	MDagPath mObject;	
	MObject mComponent;

	for ( ; !iter.isDone(); iter.next() ) {
		status = iter.getDagPath( mObject, mComponent );

		// Check if there was an error
		//
		if ( MS::kSuccess != status ) continue;

		// We don't handle components
		//
		if ( !mComponent.isNull() ) continue;
		
		// Create the function set
		//
		MFnDagNode fnSet( mObject, &status );

		if ( MS::kSuccess != status ) {
			cerr << "Failure to create function set\n";
			continue;
		}

		// Get the plug for the X-translation channel
		//
		MString attrName( "translateX" );
		const MObject attrX = fnSet.attribute( attrName, &status );
		if ( MS::kSuccess != status ) {
			cerr << "Failure to find attribute\n";
		}
		MFnAnimCurve acFnSetX;
		acFnSetX.create( mObject.transform(), attrX, NULL, &status ); 

		if ( MS::kSuccess != status ) {
			cerr << "Failure creating MFnAnimCurve function set (translateX)\n";
			continue;
		}

		// Repeat for Y-translation
		//
		attrName.set( "translateZ" );
		const MObject attrZ = fnSet.attribute( attrName, &status );
		if ( MS::kSuccess != status ) {
			cerr << "Failure to find attribute\n";
		}
		MFnAnimCurve acFnSetZ;
		acFnSetZ.create( mObject.transform(), attrZ, NULL, &status ); 

		if ( MS::kSuccess != status ) {
			cerr << "Failure creating MFnAnimCurve function set (translateZ)\n";
			continue;
		}
		
		// Build spiral animation
		// 
		for( int i = 1; i <= NUM_FRAMES; i++ ) {
			// Build the keyframe at frame i
			//
			double x = sin( (double)i * RADIAL_VELOCITY ) * 
				            ( (double)i * OUTWARD_VELOCITY ); 
			double z = cos( (double)i * RADIAL_VELOCITY ) * 
				            ( (double)i * OUTWARD_VELOCITY );

			// cerr << "Setting keys - frame: " << i << "  x: " << x << "  z: " << z << endl;

			MTime tm( (double)i, MTime::kFilm );
			if ( ( MS::kSuccess != acFnSetX.addKeyframe( tm, x ) ) ||
				 ( MS::kSuccess != acFnSetZ.addKeyframe( tm, z ) ) ) {
				cerr << "Error setting the keyframe\n"; 
			}
		}

	}

	return status;
}
Пример #23
0
bool
atomExport::setUpCache(MSelectionList &sList, std::vector<atomCachedPlugs *> &cachedPlugs,atomAnimLayers &animLayers,
						bool sdk, bool constraint, bool layers,
						std::set<std::string> &attrStrings, atomTemplateReader &templateReader,
						MTime &startTime, MTime &endTime, MAngle::Unit angularUnit,
						MDistance::Unit	linearUnit)
{
	if(endTime<startTime)
		return false; //should never happen but just in case.
	unsigned int numObjects = sList.length();
	cachedPlugs.resize(numObjects);

	double dStart = startTime.value();
	double dEnd = endTime.value() +  (.0000001); //little nudge in case of round off errors
	MTime::Unit unit = startTime.unit();
	double tickStep = MTime(1.0,unit).value();
	unsigned int numItems = ((unsigned int)((dEnd - dStart)/tickStep)) + 1;
	bool somethingIsCached = false; //if nothing get's cached no reason to run computation loop
	for (unsigned int i = 0; i < numObjects; i++) 
	{
		atomCachedPlugs *plug = NULL;
		//make sure it's a NULL, and preset it in case we skip this node
		cachedPlugs[i] = plug;

		MDagPath path;
		MObject node;
		MString name;
		if (sList.getDagPath (i, path) == MS::kSuccess) 
		{
			node = path.node();
			name = path.partialPathName();
		}
		else if (sList.getDependNode (i, node) == MS::kSuccess) {
			
			if (!node.hasFn (MFn::kDependencyNode)) {
				continue;
			}
			MFnDependencyNode fnNode (node);
			name = fnNode.name();
		}
		if(node.isNull()==false)
		{
			if(i< animLayers.length())
			{
				MPlugArray plugs;
				animLayers.getPlugs(i,plugs);
				std::set<std::string> tempAttrStrings;
				atomTemplateReader tempTemplateReader;
				plug = new atomCachedPlugs(name,node,plugs,sdk,constraint,layers,
					tempAttrStrings,tempTemplateReader,numItems,angularUnit,
				linearUnit);
				if(plug->hasCached() ==false)
					delete plug;
				else
				{
					cachedPlugs[i] = plug;
					somethingIsCached = true;
				}
			}
			else
			{
				if(templateReader.findNode(name)== false)
				{
					continue;
				}
				MSelectionList localList;
				localList.add(node);
				MPlugArray animatablePlugs;
				MAnimUtil::findAnimatablePlugs(localList,animatablePlugs);
				plug = new atomCachedPlugs(name,node,animatablePlugs,sdk,constraint,layers,attrStrings,templateReader,numItems,angularUnit,
					linearUnit);
				if(plug->hasCached() ==false)
					delete plug;
				else
				{
					cachedPlugs[i] = plug;
					somethingIsCached = true;
				}
			}
		}
	}
	
	bool computationFinished = true; //if no interrupt happens we will finish the computation
	if(somethingIsCached)
	{
		bool hasActiveProgress = false;
		if (MProgressWindow::reserve()) {
			hasActiveProgress = true;
			MProgressWindow::setInterruptable(true);
   			MProgressWindow::startProgress();
    		MProgressWindow::setProgressRange(0, numObjects);
			MProgressWindow::setProgress(0);
			MStatus stringStat;
			MString msg = MStringResource::getString(kBakingProgress, stringStat);
			if(stringStat == MS::kSuccess)
				MProgressWindow::setTitle(msg);
		}

		unsigned int count =0;
		for(double tick = dStart; tick <= dEnd; tick += tickStep)
		{
			if(hasActiveProgress)
				MProgressWindow::setProgress(count);
			MTime time(tick,unit);
			MDGContext ctx(time);
			for(unsigned int z = 0; z< cachedPlugs.size(); ++z)
			{
				if(cachedPlugs[z])
					cachedPlugs[z]->calculateValue(ctx,count);
			}

			if  (hasActiveProgress && MProgressWindow::isCancelled())
			{
				computationFinished = false;
				break;
			}
			++count;
		}
		if(hasActiveProgress)
			MProgressWindow::endProgress();
	}
	return computationFinished;

}
void
VertexPolyColourCommand::CreateJobListFromSelection(MSelectionList& selection)
{
	// Go through the selection looking for relevant geometry and add them to the list of jobs
	MItSelectionList iter(selection);
	for ( ; !iter.isDone(); iter.next() ) 
	{
		MDagPath	dagPath;
		MObject		component;
		iter.getDagPath( dagPath, component );

		// check node type
		if (dagPath.node().hasFn(MFn::kTransform) || dagPath.node().hasFn(MFn::kPolyMesh) || dagPath.node().hasFn(MFn::kMesh))
		{
			if (component.isNull() || m_operation == OP_UpdateLayerComposite)
			{
				dagPath.extendToShape();
				AddJob(dagPath, MObject::kNullObj);
			}
			else
			{
				switch (component.apiType())
				{
				case MFn::kMeshComponent:
				case MFn::kMeshEdgeComponent:
				case MFn::kMeshPolygonComponent:
				case MFn::kMeshVertComponent:
				case MFn::kMeshVtxFaceComponent:
				case MFn::kMeshMapComponent:
					dagPath.extendToShape();
					AddJob(dagPath, component);
					break;
				default:
					break;
				}
			}
		}
	}


	for (size_t i = 0; i < m_meshes.size(); i++)
	{
		MeshData* meshData = m_meshes[i];

		if (!MeshHasConstructionHistory(meshData->dagPath))
		{
			m_isRestoreSelection = true;
			MString meshName = meshData->mesh->fullPathName();
			//MGlobal::executeCommand(MString("select -r ") + meshName);
			//MGlobal::executeCommand("polySmooth -divisions 0");
			MGlobal::executeCommand(MString("polySmooth -divisions 0") + meshName);
			meshData->BuildMesh();
		}

		/*
		MPlug outMeshPlug, inMeshPlug;
		MObject intermediate;

		AddConstructionHistory(meshData->dagPath, outMeshPlug, inMeshPlug, intermediate, NULL);
		*/
	}

}
Пример #25
0
bool 
DXMAnchor::AddAnchor(MObject& site, const MString& longAnchorName, const MString& shortAnchorName, DXMAnchor* anchor)
{
	DXCC_ASSERT( DXMAnchor::GetAnchor(site, shortAnchorName) == NULL );

	DXCC_ASSERT(anchor != NULL);
	DXCC_ASSERT(anchor->GetSite().isNull());
	DXCC_ASSERT(anchor->GetPoint().length() == 0);

	DXCC_ASSERT(longAnchorName.length() > 0);
	DXCC_ASSERT(shortAnchorName.length() > 0);
	DXCC_ASSERT(!site.isNull());

	MFnDependencyNode depNode(site);
	MString name= depNode.name();
#ifdef DEBUG
	anchor->Name= name.asChar();
#endif

	if( g_DebugBasic )
	{
		DXCC_DPFA_REPORT("%s", name.asChar());
	}

	//this attribute may exist if you had asked for this node to be duplicated or instanced :(
	if( depNode.attribute( shortAnchorName ).isNull() )
	{
		MFnNumericAttribute numeric;
		MObject anchorAttrib= numeric.create(longAnchorName, shortAnchorName, MFnNumericData::kInt, 0);
		numeric.setReadable(false);
		numeric.setWritable(false);
		numeric.setConnectable(false);
		numeric.setStorable(false);
		numeric.setCached(true);
		numeric.setArray(false);
		numeric.setKeyable(false);
		numeric.setHidden(true);
		numeric.setUsedAsColor(false);
		numeric.setIndeterminant(true);
		numeric.setRenderSource(false);
		numeric.setInternal(false);

		DXCC_ASSERT(!anchorAttrib.isNull());
		DXCHECK_MSTATUS( depNode.addAttribute(anchorAttrib) );
	}

	MPlug anchorPlug= depNode.findPlug( shortAnchorName );
	DXCC_ASSERT(!anchorPlug.isNull());

	anchorPlug.setValue( *reinterpret_cast<int*>(&anchor) );

	anchor->AnchorSite= site;
	anchor->AnchorPoint= shortAnchorName;
	
//	anchor->NodeDestroyedCID= MNodeMessage::addNodeDestroyedCallback(site, DXMAnchor::DispatchNodeDestroyed, anchor);
//	anchor->AboutToDeleteCID= MNodeMessage::addNodeAboutToDeleteCallback(site, DXMAnchor::DispatchAboutToDelete, anchor);



	anchor->OnPostAddAnchor(longAnchorName, shortAnchorName);

	return true;
}
void
VertexPolyColourCommand::PrepareMesh(VertexColourJob& job)
{
	MDGModifier* modifier = NULL;

	// If the mesh doesn't have any vertex colours yet, create some default ones
#if (MAYA_API_VERSION > 650)
	bool hasVertexColours = true;
	if (0 == job.meshData->mesh->numColorSets())
	{
		hasVertexColours = false;
	}
	else
	{
		// Check the color set isn't the VCP_MasterComp used by the layers system
		if (job.meshData->mesh->numColorSets() == 1 && job.meshData->hasLayers)
		{
			hasVertexColours = false;
		}
	}

	if (!hasVertexColours)
	{
		if (m_isUndoable)
			modifier = new MDGModifier;

		// Create a colour set
		MString colorSetName("colorSet1");
		job.meshData->mesh->createColorSet(colorSetName, modifier);
		job.meshData->mesh->setCurrentColorSetName(colorSetName, modifier);

		// Create default vertex colours
		MIntArray vertList;
		MColorArray colors;
		unsigned int numVerts = (unsigned int)job.meshData->mesh->numVertices();
		vertList.setLength(numVerts);
		colors.setLength(numVerts);
		unsigned int i = 0;
		for (i = 0; i < numVerts; i++)
			vertList[i] = i;
		for (i = 0; i < numVerts; i++)
			colors[i].set(MColor::kRGB, 0.37f, 0.37f, 0.37f, 1.0f);		// default rgb is default 0.37

		// Fill vertex colours
		job.meshData->mesh->setVertexColors(colors, vertList, modifier);

		// If the mesh has layer data, set the active layer
		if (job.meshData->hasLayers)
		{
			MString name("colorSet1");

			MFnDagNode attribNode(job.meshData->mesh->parent(0));
			MObject activeLayerObj = attribNode.attribute(MString("VCP_Layer_Active"));
			if (!activeLayerObj.isNull())
			{
				MPlug activeLayerPlug(attribNode.object(), activeLayerObj);
				activeLayerPlug.setValue(name);
			}

			MString command = "VCP_Layer_CreateDefaultLayerAttribs " + attribNode.fullPathName() + " colorSet1";
			MGlobal::executeCommand(command);
			MGlobal::executeCommand("VCP_Layers_UpdateUI();");
/*
			
			attribNode.addAttribute(attr);
			MObject layerBlendAmountObj = attribNode.attribute(MString("VCP_Layer_") + name + "_BlendAmount");
			if (!layerBlendAmountObj.isNull())
			{
				MPlug layerBlendAmountPlug(attribNode.object(), layerBlendAmountObj);
				layerBlendAmountPlug.setValue(100.0f);
			}

			MObject layerBlendModeObj = attribNode.attribute(MString("VCP_Layer_") + name + "_BlendMode");
			if (!layerBlendModeObj.isNull())
			{
				MPlug layerBlendModePlug(attribNode.object(), layerBlendModeObj);
				layerBlendModePlug.setValue("Replace");
			}

			MObject layerVisibleObj = attribNode.attribute(MString("VCP_Layer_") + name + "_Visible");
			if (!layerVisibleObj.isNull())
			{
				MPlug layerVisiblePlug(attribNode.object(), layerVisibleObj);
				layerVisiblePlug.setValue(true);
			}*/

			job.meshData->DeleteLayersData();
			GatherLayersData();
		}
	}
#endif

	if (modifier != NULL)
	{
		m_undos.push_back(modifier);
	}
}
Пример #27
0
bool
atomExport::setUpAnimLayers(MSelectionList &sList,atomAnimLayers &animLayers, std::vector<atomNodeWithAnimLayers *> &nodesWithAnimLayers,
						std::set<std::string> &attrStrings, atomTemplateReader &templateReader)
					
{
	unsigned int numObjects = sList.length();
	nodesWithAnimLayers.resize(numObjects);

	bool somethingIsAnimLayered = false; 
	for (unsigned int i = 0; i < numObjects; i++) 
	{
		atomNodeWithAnimLayers *nodeWithLayer = NULL;
		//make sure it's a NULL, and preset it in case we skip this node
		nodesWithAnimLayers[i] = nodeWithLayer;

		MDagPath path;
		MObject node;
		if (sList.getDagPath (i, path) == MS::kSuccess) 
		{
			MString name = path.partialPathName();
			//if the name is in the template, only then write it out...
			if(templateReader.findNode(name)== false)
			{
				continue;
			}
			node = path.node();
		}
		else if (sList.getDependNode (i, node) == MS::kSuccess) {
			
			if (!node.hasFn (MFn::kDependencyNode)) {
				continue;
			}
			MFnDependencyNode fnNode (node);
			MString name = fnNode.name();
			if(templateReader.findNode(name)== false)
			{
				continue;
			}
		}
		if(node.isNull()==false)
		{
			MSelectionList localList;
			localList.add(node);
			MPlugArray animatablePlugs;
			MAnimUtil::findAnimatablePlugs(localList,animatablePlugs);
			unsigned int numPlugs = animatablePlugs.length();
			MPlugArray cachedPlugs;
			for (unsigned int k = 0; k < numPlugs; k++)
			{
				MPlug plug = animatablePlugs[k];
				MObjectArray layers;
				MPlugArray	 plugs;
				if(MAnimUtil::findAnimationLayers(plug,layers,plugs) && layers.length() > 0)
				{
					bool layerAdded = animLayers.addAnimLayers(layers);
					if(layerAdded)
					{
						if(nodeWithLayer == NULL)
							nodeWithLayer = new atomNodeWithAnimLayers();
						nodeWithLayer->addPlugWithLayer(plug,layers,plugs);
					}
					somethingIsAnimLayered = somethingIsAnimLayered == false ? layerAdded : true;
				}
			}
			nodesWithAnimLayers[i] = nodeWithLayer;

		}
	}
	return somethingIsAnimLayered;
}
MStatus exportJointClusterData::doIt( const MArgList& args )
//
// Process the command	
// 1. parse the args
// 2. find the jointClusters in the scene
// 3. iterate over their members, writing their weight data out to file	
//
{
	// parse args to get the file name from the command-line
	//
	MStatus stat = parseArgs(args);
	if (stat != MS::kSuccess) {
		return stat;
	}

	// count the processed jointClusters
	//
	unsigned int jcCount = 0;

	// Iterate through graph and search for jointCluster nodes
	//
	MItDependencyNodes iter( MFn::kJointCluster);
	for ( ; !iter.isDone(); iter.next() ) {
		MObject object = iter.item();
		MFnWeightGeometryFilter jointCluster(object);

		// get the joint driving this cluster
		//
		MObject joint = jointForCluster(object);
		if (joint.isNull()) {
			displayError("Joint is not attached to cluster.");
			continue;
		}

		MObject deformSet = jointCluster.deformerSet(&stat);
		CheckError(stat,"Error getting deformer set.");
			
		MFnSet setFn(deformSet, &stat);	//need the fn to get the members
		CheckError(stat,"Error getting deformer set fn.");
		
		MSelectionList clusterSetList;

		//get all the members
		//
		stat = setFn.getMembers(clusterSetList, true);
		CheckError(stat,"Could not make member list with getMembers.");

		// print out the name of joint and the number of associated skins
		//
		MFnDependencyNode fnJoint(joint);
		fprintf(file,"%s %u\n",fnJoint.name().asChar(),
				clusterSetList.length());
		
		for (unsigned int kk = 0; kk < clusterSetList.length(); ++kk) {
			MDagPath skinpath;
			MObject components;
			MFloatArray weights;

			clusterSetList.getDagPath(kk,skinpath,components);
			jointCluster.getWeights(skinpath,components,weights);

			// print out the path name of the skin & the weight count
			//
			fprintf(file,
					"%s %u\n",skinpath.partialPathName().asChar(),
					weights.length());

			// loop through the components and print their index and weight
			//
			unsigned counter =0;
			MItGeometry gIter(skinpath,components);
			for (/* nothing */ ; !gIter.isDone() &&
								   counter < weights.length(); gIter.next()) {
				fprintf(file,"%d %f\n",gIter.index(),weights[counter]);
				counter++;
			}
		}
		jcCount++;
	}

	fclose(file);

	if (0 == jcCount) {
		displayError("No jointClusters found in this scene.");
		return MS::kFailure;
	}

	return MS::kSuccess;
}
Пример #29
0
PXR_NAMESPACE_OPEN_SCOPE



/* static */
bool 
PxrUsdMayaTranslatorMesh::Create(
        const UsdGeomMesh& mesh,
        MObject parentNode,
        const PxrUsdMayaPrimReaderArgs& args,
        PxrUsdMayaPrimReaderContext* context)
{
    if (!mesh) {
        return false;
    }

    const UsdPrim& prim = mesh.GetPrim();

    MStatus status;

    // Create node (transform)
    MObject mayaNodeTransformObj;
    if (!PxrUsdMayaTranslatorUtil::CreateTransformNode(prim,
                                                          parentNode,
                                                          args,
                                                          context,
                                                          &status,
                                                          &mayaNodeTransformObj)) {
        return false;
    }

    VtArray<GfVec3f> points;
    VtArray<GfVec3f> normals;
    VtArray<int>     faceVertexCounts;
    VtArray<int>     faceVertexIndices;
    
    UsdAttribute fvc = mesh.GetFaceVertexCountsAttr();
    if (fvc.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexCounts). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvc.Get(&faceVertexCounts, 0);
    }

    UsdAttribute fvi = mesh.GetFaceVertexIndicesAttr();
    if (fvi.ValueMightBeTimeVarying()){
        // at some point, it would be great, instead of failing, to create a usd/hydra proxy node
        // for the mesh, perhaps?  For now, better to give a more specific error
        MGlobal::displayError(
            TfStringPrintf("<%s> is a topologically varying Mesh (animated faceVertexIndices). Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false;
    } else {
        // for any non-topo-varying mesh, sampling at zero will get us the right answer
        fvi.Get(&faceVertexIndices, 0);
    }
        
    // Sanity Checks. If the vertex arrays are empty, skip this mesh
    if (faceVertexCounts.size() == 0 || faceVertexIndices.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("FaceVertex arrays are empty [Count:%zu Indices:%zu] on Mesh <%s>. Skipping...", 
                faceVertexCounts.size(), faceVertexIndices.size(), 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }

    // Gather points and normals
    // If args.GetReadAnimData() is TRUE,
    // pick the first avaiable sample or default
    UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime();
    UsdTimeCode normalsTimeSample=UsdTimeCode::EarliestTime();
    std::vector<double> pointsTimeSamples;
    size_t pointsNumTimeSamples = 0;
    if (args.GetReadAnimData()) {
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetPointsAttr(), args,
                &pointsTimeSamples);
        pointsNumTimeSamples = pointsTimeSamples.size();
        if (pointsNumTimeSamples>0) {
            pointsTimeSample = pointsTimeSamples[0];
        }
    	std::vector<double> normalsTimeSamples;
        PxrUsdMayaTranslatorUtil::GetTimeSamples(mesh.GetNormalsAttr(), args,
                &normalsTimeSamples);
        if (normalsTimeSamples.size()) {
            normalsTimeSample = normalsTimeSamples[0];
        }
    }
    mesh.GetPointsAttr().Get(&points, pointsTimeSample);
    mesh.GetNormalsAttr().Get(&normals, normalsTimeSample);
    
    if (points.size() == 0) {
        MGlobal::displayError(
            TfStringPrintf("Points arrays is empty on Mesh <%s>. Skipping...", 
                prim.GetPath().GetText()).c_str());
        return false; // invalid mesh, so exit
    }


    // == Convert data
    size_t mayaNumVertices = points.size();
    MPointArray mayaPoints(mayaNumVertices);
    for (size_t i=0; i < mayaNumVertices; i++) {
        mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
    }

    MIntArray polygonCounts( faceVertexCounts.cdata(),  faceVertexCounts.size() );
    MIntArray polygonConnects( faceVertexIndices.cdata(), faceVertexIndices.size() );

    // == Create Mesh Shape Node
    MFnMesh meshFn;
    MObject meshObj = meshFn.create(mayaPoints.length(), 
                           polygonCounts.length(), 
                           mayaPoints, 
                           polygonCounts, 
                           polygonConnects,
                           mayaNodeTransformObj,
                           &status
                           );
                           
    if (status != MS::kSuccess) {
        return false;
    }

    // Since we are "decollapsing", we will create a xform and a shape node for each USD prim
    std::string usdPrimName(prim.GetName().GetText());
    std::string shapeName(usdPrimName); shapeName += "Shape";
    // Set mesh name and register
    meshFn.setName(MString(shapeName.c_str()), false, &status);
    if (context) {
        std::string usdPrimPath(prim.GetPath().GetText());
        std::string shapePath(usdPrimPath);
        shapePath += "/";
        shapePath += shapeName;
        context->RegisterNewMayaNode( shapePath, meshObj ); // used for undo/redo
    }

    // If a material is bound, create (or reuse if already present) and assign it
    // If no binding is present, assign the mesh to the default shader    
    const TfToken& shadingMode = args.GetShadingMode();
    PxrUsdMayaTranslatorMaterial::AssignMaterial(shadingMode, mesh, meshObj,
            context);
    
    // Mesh is a shape, so read Gprim properties
    PxrUsdMayaTranslatorGprim::Read(mesh, meshObj, context);

    // Set normals if supplied
    MIntArray normalsFaceIds;
    if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {

        for (size_t i=0; i < polygonCounts.length(); i++) {
            for (int j=0; j < polygonCounts[i]; j++) {
                normalsFaceIds.append(i);
            }
        }
        if (normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {
            MVectorArray mayaNormals(normals.size());
            for (size_t i=0; i < normals.size(); i++) {
                mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
            }
            if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
            }
        }
     }

    // Determine if PolyMesh or SubdivMesh
    TfToken subdScheme = PxrUsdMayaMeshUtil::setSubdivScheme(mesh, meshFn, args.GetDefaultMeshScheme());

    // If we are dealing with polys, check if there are normals
    // If we are dealing with SubdivMesh, read additional attributes and SubdivMesh properties
    if (subdScheme == UsdGeomTokens->none) {
        if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices())) {
            PxrUsdMayaMeshUtil::setEmitNormals(mesh, meshFn, UsdGeomTokens->none);
        }
    } else {
        PxrUsdMayaMeshUtil::setSubdivInterpBoundary(mesh, meshFn, UsdGeomTokens->edgeAndCorner);
        PxrUsdMayaMeshUtil::setSubdivFVLinearInterpolation(mesh, meshFn);
        _AssignSubDivTagsToMesh(mesh, meshObj, meshFn);
    }
 
    // Set Holes
    VtArray<int> holeIndices;
    mesh.GetHoleIndicesAttr().Get(&holeIndices);   // not animatable
    if ( holeIndices.size() != 0 ) {
        MUintArray mayaHoleIndices;
        mayaHoleIndices.setLength( holeIndices.size() );
        for (size_t i=0; i < holeIndices.size(); i++) {
            mayaHoleIndices[i] = holeIndices[i];
        }
        if (meshFn.setInvisibleFaces(mayaHoleIndices) == MS::kFailure) {
            MGlobal::displayError(TfStringPrintf("Unable to set Invisible Faces on <%s>", 
                            meshFn.fullPathName().asChar()).c_str());
        }
    }

    // GETTING PRIMVARS
    std::vector<UsdGeomPrimvar> primvars = mesh.GetPrimvars();
    TF_FOR_ALL(iter, primvars) {
        const UsdGeomPrimvar& primvar = *iter;
        const TfToken& name = primvar.GetBaseName();
        const SdfValueTypeName& typeName = primvar.GetTypeName();

        // If the primvar is called either displayColor or displayOpacity check
        // if it was really authored from the user.  It may not have been
        // authored by the user, for example if it was generated by shader
        // values and not an authored colorset/entity.
        // If it was not really authored, we skip the primvar.
        if (name == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName || 
                name == PxrUsdMayaMeshColorSetTokens->DisplayOpacityColorSetName) {
            if (!PxrUsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) {
                continue;
            }
        }

        // XXX: Maya stores UVs in MFloatArrays and color set data in MColors
        // which store floats, so we currently only import primvars holding
        // float-typed arrays. Should we still consider other precisions
        // (double, half, ...) and/or numeric types (int)?
        if (typeName == SdfValueTypeNames->Float2Array) {
            // We assume that Float2Array primvars are UV sets.
            if (!_AssignUVSetPrimvarToMesh(primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for UV set <%s> on mesh <%s>", 
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        } else if (typeName == SdfValueTypeNames->FloatArray   || 
                   typeName == SdfValueTypeNames->Float3Array  || 
                   typeName == SdfValueTypeNames->Color3fArray ||
                   typeName == SdfValueTypeNames->Float4Array  || 
                   typeName == SdfValueTypeNames->Color4fArray) {
            if (!_AssignColorSetPrimvarToMesh(mesh, primvar, meshFn)) {
                MGlobal::displayWarning(
                    TfStringPrintf("Unable to retrieve and assign data for color set <%s> on mesh <%s>",
                                   name.GetText(),
                                   mesh.GetPrim().GetPath().GetText()).c_str());
            }
        }
    }

    // We only vizualize the colorset by default if it is "displayColor".  
    MStringArray colorSetNames;
    if (meshFn.getColorSetNames(colorSetNames)==MS::kSuccess) {
        for (unsigned int i=0; i < colorSetNames.length(); i++) {
            const MString colorSetName = colorSetNames[i];
            if (std::string(colorSetName.asChar()) 
                    == PxrUsdMayaMeshColorSetTokens->DisplayColorColorSetName.GetString()) {
                MFnMesh::MColorRepresentation csRep=
                    meshFn.getColorRepresentation(colorSetName);
                if (csRep==MFnMesh::kRGB || csRep==MFnMesh::kRGBA) {

                    // both of these are needed to show the colorset.
                    MPlug plg=meshFn.findPlug("displayColors");
                    if ( !plg.isNull() ) {
                        plg.setBool(true);
                    }
                    meshFn.setCurrentColorSetName(colorSetName);
                }
                break;
            }
        }
    }
    
    // == Animate points ==
    //   Use blendShapeDeformer so that all the points for a frame are contained in a single node
    //
    if (pointsNumTimeSamples > 0) {
        MPointArray mayaPoints(mayaNumVertices);
        MObject meshAnimObj;

        MFnBlendShapeDeformer blendFn;
        MObject blendObj = blendFn.create(meshObj);
        if (context) {
            context->RegisterNewMayaNode( blendFn.name().asChar(), blendObj ); // used for undo/redo
        }

        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
             mesh.GetPointsAttr().Get(&points, pointsTimeSamples[ti]);

            for (unsigned int i=0; i < mayaNumVertices; i++) {
                mayaPoints.set( i, points[i][0], points[i][1], points[i][2] );
            }

            // == Create Mesh Shape Node
            MFnMesh meshFn;
            if ( meshAnimObj.isNull() ) {
                meshAnimObj = meshFn.create(mayaPoints.length(), 
                                       polygonCounts.length(), 
                                       mayaPoints, 
                                       polygonCounts, 
                                       polygonConnects,
                                       mayaNodeTransformObj,
                                       &status
                                       );
                if (status != MS::kSuccess) {
                    continue;
                }
            }
            else {
                // Reuse the already created mesh by copying it and then setting the points
                meshAnimObj = meshFn.copy(meshAnimObj, mayaNodeTransformObj, &status);
                meshFn.setPoints(mayaPoints);
            }

            // Set normals if supplied
            //
            // NOTE: This normal information is not propagated through the blendShapes, only the controlPoints.
            //
             mesh.GetNormalsAttr().Get(&normals, pointsTimeSamples[ti]);
             if (normals.size() == static_cast<size_t>(meshFn.numFaceVertices()) &&
                normalsFaceIds.length() == static_cast<size_t>(meshFn.numFaceVertices())) {

                MVectorArray mayaNormals(normals.size());
                for (size_t i=0; i < normals.size(); i++) {
                    mayaNormals.set( MVector(normals[i][0], normals[i][1], normals[i][2]), i);
                }
                if (meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects) != MS::kSuccess) {
                }
             }

            // Add as target and set as an intermediate object
            blendFn.addTarget(meshObj, ti, meshAnimObj, 1.0);
            meshFn.setIntermediateObject(true);
            if (context) {
                context->RegisterNewMayaNode( meshFn.fullPathName().asChar(), meshAnimObj ); // used for undo/redo
            }
        }

        // Animate the weights so that mesh0 has a weight of 1 at frame 0, etc.
        MFnAnimCurve animFn;

        // Construct the time array to be used for all the keys
        MTimeArray timeArray;
        timeArray.setLength(pointsNumTimeSamples);
        for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
            timeArray.set( MTime(pointsTimeSamples[ti]), ti);
        }

        // Key/Animate the weights
        MPlug plgAry = blendFn.findPlug( "weight" );
        if ( !plgAry.isNull() && plgAry.isArray() ) {
            for (unsigned int ti=0; ti < pointsNumTimeSamples; ++ti) {
                MPlug plg = plgAry.elementByLogicalIndex(ti, &status);
                MDoubleArray valueArray(pointsNumTimeSamples, 0.0);
                valueArray[ti] = 1.0; // Set the time value where this mesh's weight should be 1.0
                MObject animObj = animFn.create(plg, NULL, &status);
                animFn.addKeys(&timeArray, &valueArray);
                if (context) {
                    context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo
                }
            }
        }
    }

    return true;
}
Пример #30
0
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;
}