Пример #1
0
void colorTransformDataTranslator::writeColorSpaceForNodes(fstream& f)
{
	MItDependencyNodes	nodeIter;

    f << "====================== Nodes with color space attribute =======================\n";

	for (; !nodeIter.isDone(); nodeIter.next())
	{
		MObject				node = nodeIter.item();

        if(!node.isNull() && 
           ( (node.apiType()==MFn::kFileTexture) || (node.apiType()==MFn::kImagePlane) ) )
        {
          MString inputColorSpace = getInputColorSpace(node);

          MString transformId;
          
          f << "Found node with colorspace " << inputColorSpace.asUTF8();
          if(MColorManagementUtilities::getColorTransformCacheIdForInputSpace(
                 inputColorSpace, transformId))
          {
              f << ", its corresponding transform id: " << transformId.asUTF8() << std::endl;
          }
          else
          {
              f << ", no corresponding transform id found.\n";
          }
        }

    }
}
    //---------------------------------------------------
    // Retrieve the bind pose for a controller/joint std::pair
    //
    MMatrix DagHelper::getBindPoseInverse ( const MObject& controller, const MObject& influence )
    {
        MStatus status;
        if ( controller.apiType() == MFn::kSkinClusterFilter )
        {
            MFnSkinCluster controllerFn ( controller );

            // Find the correct index for the pre-bind matrix
            uint index = controllerFn.indexForInfluenceObject ( MDagPath::getAPathTo ( influence ), &status );
            if ( status != MStatus::kSuccess ) return MMatrix::identity;

            MPlug preBindMatrixPlug = controllerFn.findPlug ( "bindPreMatrix", &status );
            preBindMatrixPlug = preBindMatrixPlug.elementByLogicalIndex ( index, &status );
            if ( status != MStatus::kSuccess ) return MMatrix::identity;

            // Get the plug's matrix
            MMatrix ret;
            if ( !DagHelper::getPlugValue ( preBindMatrixPlug, ret ) ) return MMatrix::identity;

            return ret;
        }

        else if ( controller.apiType() == MFn::kJointCluster )
        {
            MMatrix ret;
            DagHelper::getPlugValue ( influence, "bindPose", ret );
            return ret.inverse();
        }

        else return MMatrix::identity;
    }
	bool AttributeParser::IsNumericCompoundAttribute(const MObject& attr, MFnNumericData::Type& type)
	{
		MFn::Type apiType = attr.apiType();
		switch (apiType)
		{
		case MFn::kAttribute2Double:
			type = MFnNumericData::k2Double;
			return true;
		case MFn::kAttribute2Float:
			type = MFnNumericData::k2Float;
			return true;
		case MFn::kAttribute2Int:
			type = MFnNumericData::k2Int;
			return true;
		case MFn::kAttribute2Short:
			type = MFnNumericData::k2Short;
			return true;
		case MFn::kAttribute3Double:
			type = MFnNumericData::k3Double;
			return true;
		case MFn::kAttribute3Float:
			type = MFnNumericData::k3Float;
			return true;
		case MFn::kAttribute3Int:
			type = MFnNumericData::k3Int;
			return true;
		case MFn::kAttribute3Short:
			type = MFnNumericData::k3Short;
			return true;
		case MFn::kAttribute4Double:
			type = MFnNumericData::k4Double;
			return true;
		}
		return false;
	}
Пример #4
0
MStatus createClip::parseArgs( const MArgList& args )
//
// No arguments to parse.
//
{
	MStatus     	stat = MS::kSuccess;
	MString     	arg;
	MSelectionList	list;
	bool			charNameUsed = 0;
	MString			charName;
	const MString	charFlag			("-c");
	const MString	charFlagLong		("-char");

	// Parse the arguments.
	for ( unsigned int i = 0; i < args.length(); i++ ) {
		arg = args.asString( i, &stat );
		if (!stat)              
			continue;
				
		if ( arg == charFlag || arg == charFlagLong ) {
			// get the char name
			//
			if (i == args.length()-1) {
				arg += ": must specify a character name";
				displayError(arg);
				return MS::kFailure;
			}
			i++;
			args.get(i, charName);
			list.add(charName);
			charNameUsed = 1;
		}
		else {
			arg += ": unknown argument";
			displayError(arg);
			return MS::kFailure;
		}
	}

	if (charNameUsed) {
		// get the character corresponding to the node name
		//
		MItSelectionList iter (list);
		for ( /* nothing */ ; !iter.isDone(); iter.next() ) {
			MObject node;
			iter.getDependNode(node);
			if (node.apiType() == MFn::kCharacter) {
				fCharacter = node;
				break;
			}
		}
		if (fCharacter.isNull()) {
			MString errMsg("Character flag must specify a character node.");
			displayError(errMsg);
			return MS::kFailure;
		}
	}
	
	return stat;
}
//-----------------------------------------------------------------------------
// Returns the vsSkinner node if the passed node is connected to a vsSkinner node
//-----------------------------------------------------------------------------
MStatus CVsSkinnerCmd::ConnectedToMesh(
	const MDagPath &iDagPath,
	MDagPath &oDagPath )
{
	MPlugArray pA;
	MPlugArray pA1;

	if ( MFnDagNode( iDagPath ).getConnections( pA ) && pA.length() )
	{
		MObject mObj;

		const uint np( pA.length() );
		for ( uint i( 0U ); i != np; ++i )
		{
			if ( pA[ i ].connectedTo( pA1, true, true ) && pA1.length() )
			{
				const uint np1( pA1.length() );
				for ( uint j( 0U ); j != np1; ++j )
				{
					mObj = pA1[ j ].node();

					if ( mObj.apiType() == MFn::kMesh )
					{
						MDagPath::getAPathTo( mObj, oDagPath );
						return MS::kSuccess;
					}
				}
			}
		}
	}

	return MS::kFailure;
}
Пример #6
0
ATTR_TYPE getPlugAttrType(const char *plugName, MFnDependencyNode& dn)
{
	MDGContext ctx = MDGContext::fsNormal;
	MStatus stat = MS::kSuccess;
	MPlug plug = dn.findPlug(plugName, &stat);
	if( !stat )
		return ATTR_TYPE::ATTR_TYPE_NONE;

	MObject attObj = plug.attribute(&stat);
	MFnAttribute att(attObj);
	if( !stat )
		return ATTR_TYPE::ATTR_TYPE_NONE;

	if(att.isUsedAsColor())
		return ATTR_TYPE::ATTR_TYPE_COLOR;
	if( attObj.apiType() == MFn::kNumericAttribute)
	{
		MFnNumericAttribute na(attObj, &stat);
		if( !stat )
			return ATTR_TYPE::ATTR_TYPE_NONE;
		if( na.unitType() == MFnNumericData::Type::kFloat )
			return ATTR_TYPE::ATTR_TYPE_FLOAT;
	}
	return ATTR_TYPE::ATTR_TYPE_NONE;
}
    // ------------------------------------------------------------
    void SceneGraph::addForcedNodes ( const MDagPath& dagPath )
    {
        MFnMesh meshFn ( dagPath );

        // Iterate upstream finding all the nodes which affect the mesh.
        MStatus stat;
        MPlug plug = meshFn.findPlug ( ATTR_IN_MESH );
        if ( plug.isConnected() )
        {
            MItDependencyGraph dependGraphIter ( plug,
                                                 MFn::kInvalid,
                                                 MItDependencyGraph::kUpstream,
                                                 MItDependencyGraph::kDepthFirst,
                                                 MItDependencyGraph::kPlugLevel,
                                                 &stat );

            if ( stat == MS::kSuccess )
            {
                dependGraphIter.disablePruningOnFilter();
                for ( ; ! dependGraphIter.isDone(); dependGraphIter.next() )
                {
                    MObject thisNode = dependGraphIter.thisNode();
                    MFn::Type type = thisNode.apiType();

                    if ( thisNode.apiType() == MFn::kSkinClusterFilter )
                    {
                        MFnSkinCluster clusterFn ( thisNode );
                        MDagPathArray jointPaths;
                        clusterFn.influenceObjects ( jointPaths, &stat );
                        if ( stat == MS::kSuccess )
                        {
                            uint count = jointPaths.length();
                            for ( uint i = 0; i < count; ++i ) appendForcedNodeToList ( jointPaths[i] );
                        }
                    }
                    else if ( thisNode.apiType() == MFn::kJointCluster )
                    {
                        MObject joint = DagHelper::getNodeConnectedTo ( thisNode, ATTR_MATRIX );
                        MDagPath jointPath = MDagPath::getAPathTo ( joint );
                        appendForcedNodeToList ( jointPath );
                    }
                }
            }
        }
    }
Пример #8
0
bool atomImport::replaceNameAndFindPlug(const MString& origName,
										atomNodeNameReplacer& replacer,
										MPlug& replacedPlug)
{
	bool rtn = false;
	
	// get the node name
	//
	MStringArray nameParts;
	origName.split('.', nameParts);

	// Perform any necessary replacement
	//
	MString tmpName(nameParts[0]);
	// TODO: type & hierarchy info -- does the replacer store enough info
	// to help us find that out since in the case of export edits we don't
	// have that info for sources
	//
	if (replacer.findNode(atomNodeNameReplacer::eDag,tmpName,0,0)) {
		MString newName(tmpName);
		newName += (".");

		// add the attribute name(s) back on again
		//
		unsigned int ii;
		MString attrName;
		for (ii = 1; ii < nameParts.length(); ++ii) {
			if (ii > 1) {
				attrName += (".");
			}
			attrName += nameParts[ii];
		}
		newName += attrName;

		MSelectionList tmpList;
		if (MS::kSuccess == tmpList.add(newName)) {
			tmpList.getPlug(0,replacedPlug);
			rtn = !replacedPlug.isNull();
			if (!rtn) {
				// test for the special case of the pivot component
				//
				MDagPath path;
				MObject component;
				if (MS::kSuccess == tmpList.getDagPath(0,path,component) &&
					component.apiType() == MFn::kPivotComponent)
				{
					MObject node;
					tmpList.getDependNode(0,node);
					MFnDependencyNode fnNode(node);
					replacedPlug = fnNode.findPlug(attrName,false);
					rtn = !replacedPlug.isNull();
				}
			}
		}
	}
	return rtn;
}
Пример #9
0
void liqRibData::parseVectorAttributes( MFnDependencyNode & nodeFn, MStringArray & strArray, ParameterType pType )
{
  int i;
  MStatus status;
  if ( strArray.length() > 0 ) {
    for ( i = 0; i < strArray.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = strArray[i].substring(5, strArray[i].length());
      MPlug vPlug = nodeFn.findPlug( strArray[i] );
      MObject plugObj;
      status = vPlug.getValue( plugObj );
      if ( plugObj.apiType() == MFn::kVectorArrayData ) {
        MFnVectorArrayData  fnVectorArrayData( plugObj );
        MVectorArray vectorArrayData = fnVectorArrayData.array( &status );
        tokenPointerPair.set(   cutString.asChar(),
                                pType,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                true,
                                false,
                                vectorArrayData.length() );
        for ( int kk = 0; kk < vectorArrayData.length(); kk++ ) {
          tokenPointerPair.setTokenFloat( kk, vectorArrayData[kk].x, vectorArrayData[kk].y, vectorArrayData[kk].z );
        }

        // should it be per vertex or face-varying
        if ( ( ( type() == MRT_Mesh ) || ( type() == MRT_Subdivision ) ) && ( vectorArrayData.length() == faceVaryingCount ) ) {
          tokenPointerPair.setDetailType( rFaceVarying);
        } else {
          tokenPointerPair.setDetailType( rVertex );
        }

        // store it all
        tokenPointerArray.push_back( tokenPointerPair );

      } else {
        // Hmmmm float ? double ?
        float x, y, z;
          tokenPointerPair.set( cutString.asChar(),
                                pType,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                false,
                                false,
                                0 );
        vPlug.child(0).getValue( x );
        vPlug.child(1).getValue( y );
        vPlug.child(2).getValue( z );
        tokenPointerPair.setTokenFloat( 0, x, y, z );
        tokenPointerPair.setDetailType( rConstant );
        tokenPointerArray.push_back( tokenPointerPair );
      }
    }
  }
}
Пример #10
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;
}
Пример #11
0
//*********************************************************
// Name: isEnumDataType
// Desc: 
//*********************************************************
bool BreakdownCommand::isEnumDataType(const MPlug &connection)
{
    MObject attrObj;

    bool isEnum = false;

    attrObj = connection.attribute( &status );
    if( attrObj.apiType() == MFn::kEnumAttribute ) {
        isEnum = true;
    }

    return isEnum;
}
Пример #12
0
//*********************************************************
// Name: isBooleanDataType
// Desc: 
//*********************************************************
bool BreakdownCommand::isBooleanDataType( const MPlug &connection )
{
    MFnNumericAttribute fnNumAttr;
    MObject attrObj;

    bool isBool = false;

    attrObj = connection.attribute( &status );
    if( attrObj.apiType() == MFn::kNumericAttribute ) {

        status = fnNumAttr.setObject( attrObj );
        if( fnNumAttr.unitType() == MFnNumericData::kBoolean )
            isBool = true;
    }

    return isBool;
}
    // --------------------------------------
    void ReferenceManager::getRootObjects(
        const MObject& referenceNode, 
        MDagPathArray& rootPaths, 
        MObjectArray& subReferences)
    {
        rootPaths.clear();
        subReferences.clear();

        MFnDependencyNode referenceNodeFn(referenceNode);

        // Get the paths of all the dag nodes included in this reference
        MStringArray nodeNames;
        MString command = MString("reference -rfn \"") + referenceNodeFn.name() + "\" -q -node -dp;";
        MGlobal::executeCommand(command, nodeNames);

        uint nodeNameCount = nodeNames.length();
        MDagPathArray nodePaths;
        for (uint j = 0; j < nodeNameCount; ++j)
        {
            MObject o = DagHelper::getNode(nodeNames[j]);
            MDagPath p = DagHelper::getShortestDagPath(o);
            if (p.length() > 0)
            {
                nodePaths.append(p);
            }
            else
            {
                if (o != MObject::kNullObj && o.apiType() == MFn::kReference
                    && strstr(nodeNames[j].asChar(), "_UNKNOWN_REF_NODE") == NULL)
                {
                    subReferences.append(o);
                }
            }
        }

        // Keep only the root transform for the reference in our path arrays
        uint nodePathCount = nodePaths.length();
        for (uint j = 0; j < nodePathCount; ++j)
        {
            const MDagPath& p = nodePaths[j];
            if ( !isRootTransform ( nodePaths, p ) ) continue;
            rootPaths.append(p);
        }
    }
Пример #14
0
UsdMayaProxyShape*
UsdMayaProxyDrawOverride::getShape(const MDagPath& objPath)
{
    MObject obj = objPath.node();
    MFnDependencyNode dnNode(obj);
    if (obj.apiType() != MFn::kPluginShape) {
        MGlobal::displayError("Failed apiType test (apiTypeStr=" +
                              MString(obj.apiTypeStr()) + ")");
        return NULL;
    }

    UsdMayaProxyShape* pShape = static_cast<UsdMayaProxyShape*>(dnNode.userNode());
    if (!pShape) {
        MGlobal::displayError("Failed getting userNode");
        return NULL;
    }

    return pShape;
}
Пример #15
0
MStatus	liqGetAttr::doIt( const MArgList& args )
{
	CM_TRACE_FUNC("liqGetAttr::doIt(args)");

	MStatus					status;
	unsigned				i;
	MString					nodeName, attrName;
	MSelectionList				nodeList;

	for ( i = 0; i < args.length(); i++ ) 
  {
		if ( MString( "-debug" ) == args.asString( i, &status) ) 
    {
		} 
    else if ( MString( "-node" ) == args.asString( i, &status) ) 
    {
			i++;
			nodeName = args.asString( i, &status ) ;
		} 
    else if ( MString( "-attr" ) == args.asString( i, &status) ) 
    {
			i++;
			attrName = args.asString( i, &status );
		}
	}
	nodeList.add( nodeName );
	MObject depNodeObj;
	nodeList.getDependNode(0, depNodeObj);
	MFnDependencyNode depNode( depNodeObj );
	MPlug attrPlug = depNode.findPlug( attrName );
	MObject plugObj;
	attrPlug.getValue( plugObj );
	if( plugObj.apiType() == MFn::kDoubleArrayData ) 
  {
	  MFnDoubleArrayData fnDoubleArrayData( plugObj );
	  const MDoubleArray& doubleArrayData( fnDoubleArrayData.array( &status ) );
	  for ( i = 0; i < doubleArrayData.length(); i++ ) 
		  appendToResult( doubleArrayData[i] );
	}
	return MS::kSuccess;
};
Пример #16
0
MStatus dagPoseInfo::doIt( const MArgList& args )
{
    // parse args to get the file name from the command-line
    //
    MStatus stat = parseArgs(args);
    if (stat != MS::kSuccess) {
        return stat;
    }

    unsigned int count = 0;

    // Get the selected joints/transforms, and for each of them print
    // out the dagPose info
    //
    MSelectionList slist;
    MGlobal::getActiveSelectionList( slist );
    MItSelectionList itr( slist );

    for (; !itr.isDone(); itr.next() )
    {
        MObject depNode;
        itr.getDependNode(depNode);
        if (depNode.apiType() == MFn::kJoint) {
            if (findDagPose(depNode)) {
                count++;
            }
        }
    }

    fclose(file);
    if (0 == count) {
        displayError("No poses were found on the selected joints.");
        return MS::kFailure;
    }

    return MS::kSuccess;
}
Пример #17
0
bool GDExporter::GetSelectedMeshTransformPath(MDagPath &transformPath)
{
	MSelectionList currSelection;
	MGlobal::getActiveSelectionList(currSelection);

	unsigned int selectionCount = currSelection.length();
	
	MFnMesh* exportingMesh = 0;

	for(unsigned int selectionIndex = 0; selectionIndex < selectionCount; ++selectionIndex )
	{
		MDagPath currPath;
		currSelection.getDagPath(selectionIndex, currPath);

		if( currPath.apiType() != MFn::kTransform )
			continue;

		MFnTransform currTransform(currPath);
		unsigned int childCount = currTransform.childCount();
		for(unsigned int childIndex = 0; childIndex < childCount; ++childIndex)
		{
			MObject childObject = currTransform.child(childIndex);
			if( childObject.apiType() == MFn::kMesh )
			{
				MFnMesh childMesh(childObject);
				if( childMesh.isIntermediateObject() )
					continue;

				currTransform.getPath(transformPath);
				return true;
			}
		}
	}

	return false;
}
Пример #18
0
// returns 0 if static, 1 if sampled, and 2 if a curve
int util::getSampledType(const MPlug& iPlug)
{
    MPlugArray conns;

    iPlug.connectedTo(conns, true, false);

    // it's possible that only some element of an array plug or
    // some component of a compound plus is connected
    if (conns.length() == 0)
    {
        if (iPlug.isArray())
        {
            unsigned int numConnectedElements = iPlug.numConnectedElements();
            for (unsigned int e = 0; e < numConnectedElements; e++)
            {
                int retVal = getSampledType(iPlug.connectionByPhysicalIndex(e));
                if (retVal > 0)
                    return retVal;
            }
        }
        else if (iPlug.isCompound() && iPlug.numConnectedChildren() > 0)
        {
            unsigned int numChildren = iPlug.numChildren();
            for (unsigned int c = 0; c < numChildren; c++)
            {
                int retVal = getSampledType(iPlug.child(c));
                if (retVal > 0)
                    return retVal;
            }
        }
        return 0;
    }

    MObject ob;
    MFnDependencyNode nodeFn;
    for (unsigned i = 0; i < conns.length(); i++)
    {
        ob = conns[i].node();
        MFn::Type type = ob.apiType();

        switch (type)
        {
            case MFn::kAnimCurveTimeToAngular:
            case MFn::kAnimCurveTimeToDistance:
            case MFn::kAnimCurveTimeToTime:
            case MFn::kAnimCurveTimeToUnitless:
            {
                nodeFn.setObject(ob);
                MPlug incoming = nodeFn.findPlug("i", true);

                // sampled
                if (incoming.isConnected())
                    return 1;

                // curve
                else
                    return 2;
            }
            break;

            case MFn::kMute:
            {
                nodeFn.setObject(ob);
                MPlug mutePlug = nodeFn.findPlug("mute", true);

                // static
                if (mutePlug.asBool())
                    return 0;
                // curve
                else
                   return 2;
            }
            break;

            default:
            break;
        }
    }

    return 1;
}
Пример #19
0
MStatus tm_polySlot::doIt( const MArgList& )
//
//	Description:
//		implements the MEL tm_polySlot command.
//
//	Arguments:
//		args - the argument list that was passes to the command from MEL
//
//	Return Value:
//		MS::kSuccess - command succeeded
//		MS::kFailure - command failed (returning this value will cause the 
//                     MEL script that is being run to terminate unless the
//                     error is caught using a "catch" statement.
//
{
#ifdef _DEBUG
cout << endl << "####################################################" << endl;
cout << "tm_polySlot::doIt - DEBUG version info:" << endl;
#endif
	MStatus status;

	// Parse the selection list for objects with selected UV components.
	// To simplify things, we only take the first object that we find with
	// selected UVs and operate on that object alone.
	//
	// All other objects are ignored and return warning messages indicating
	// this limitation.
	//
	MGlobal::getActiveSelectionList( oldSelList );
	MItSelectionList selListIter( oldSelList );
	selListIter.setFilter( MFn::kMesh );

	// The tm_polySlot node only accepts a component list input, so we build
	// a component list using MFnComponentListData.
	//
	// MIntArrays could also be passed into the node to represent the edgesIds,
	// but are less storage efficient than component lists, since consecutive 
	// components are bundled into a single entry in component lists.
	//
	MFnComponentListData compListFn;
	compListFn.create();
	bool found = false;
	bool foundMultiple = false;

	for( ; !selListIter.isDone(); selListIter.next() )
	{
		MDagPath dagPath;
		MObject component;
		selListIter.getDagPath( dagPath, component );

		// Check for selected UV components
		//
		if( component.apiType() == MFn::kMeshEdgeComponent )
		{
			if( !found )
			{
				// The variable 'component' holds all selected components on the selected
				// object, thus only a single call to MFnComponentListData::add() is needed
				// to store the selected components for a given object.
				//
				compListFn.add( component );

				// Copy the component list created by MFnComponentListData into our local
				// component list MObject member.
				//
				fComponentList = compListFn.object();

				// Locally store the actual edgesIds of the selected Edges so that this command
				// can directly modify the mesh in the case when there is no history and
				// history is turned off.
				//
				MFnSingleIndexedComponent compFn( component );
				compFn.getElements( fSelEdges );

				// Ensure that this DAG path will point to the shape of our object.
				// Set the DAG path for the polyModifierCmd.
				//
				dagPath.extendToShape();
				setMeshNode( dagPath );
				found = true;
			}
			else
			{
				// Break once we have found a multiple object holding selected UVs, since
				// we are not interested in how many multiple objects there are, only
				// the fact that there are multiple objects.
				//
				foundMultiple = true;
				break;
			}
		}
	}
	if( foundMultiple )
	{
		displayWarning("Found more than one object with selected Edges - Only operating on first found object.");
	}
	if( !found )
	{
		displayError( "tm_polySlot command failed: Unable to find selected edges" );
		return MStatus::kFailure;
	}
	// Initialize the polyModifierCmd node type - mesh node already set
	//
	setModifierNodeType( tm_polySlotNode::id );
//##################################################################
	alwaysWithConstructionHistory = true;
	status = doModifyPoly();
	if( !status){displayError( "tm_polySlot command failed!" );return status;}
//################################################################## get polymodifier node name and select it
	getModifierNodeName();
	newSelList.add( modifierNodeName);
	MGlobal::setActiveSelectionList( newSelList);//, MGlobal::kAddToList);
//##################################################################
	successResult();

	return MStatus::kSuccess;
}
bool ToMayaMeshConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
	MStatus s;

	IECore::ConstMeshPrimitivePtr mesh = IECore::runTimeCast<const IECore::MeshPrimitive>( from );
	assert( mesh );

	if ( !mesh->arePrimitiveVariablesValid() )
	{
		return false;
	}

	MFloatPointArray vertexArray;
	MIntArray polygonCounts;
	MIntArray polygonConnects;

	MFnMesh fnMesh;

	int numVertices = 0;
	IECore::PrimitiveVariableMap::const_iterator it = mesh->variables.find("P");
	if ( it != mesh->variables.end() )
	{
		/// \todo Employ some M*Array converters to simplify this
		IECore::ConstV3fVectorDataPtr p = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
		if (p)
		{
			numVertices = p->readable().size();

			vertexArray.setLength( numVertices );
			for (int i = 0; i < numVertices; i++)
			{
				vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3f>( p->readable()[i] );
			}
		}
		else
		{
			IECore::ConstV3dVectorDataPtr p = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
			if (p)
			{
				numVertices = p->readable().size();

				vertexArray.setLength( numVertices );
				for (int i = 0; i < numVertices; i++)
				{
					vertexArray[i] = IECore::convert<MFloatPoint, Imath::V3d>( p->readable()[i] );
				}
			}
			else
			{
				// "P" is not convertible to an array of "points"
				return false;
			}
		}
	}


	IECore::ConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();
	assert( verticesPerFace );
	int numPolygons = verticesPerFace->readable().size();

	polygonCounts.setLength( numPolygons );
	for (int i = 0; i < numPolygons; i++)
	{
		polygonCounts[i] = verticesPerFace->readable()[i];
	}

	IECore::ConstIntVectorDataPtr vertexIds = mesh->vertexIds();
	assert( vertexIds );
	int numPolygonConnects = vertexIds->readable().size();
	polygonConnects.setLength( numPolygonConnects );
	for (int i = 0; i < numPolygonConnects; i++)
	{
		polygonConnects[i] = vertexIds->readable()[i];
	}

	MObject mObj = fnMesh.create( numVertices, numPolygons, vertexArray, polygonCounts, polygonConnects, to, &s );

	if (!s)
	{
		return false;
	}

	it = mesh->variables.find("N");
	if ( it != mesh->variables.end() )
	{
		if (it->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
		{
			/// \todo Employ some M*Array converters to simplify this
			MVectorArray vertexNormalsArray;
			IECore::ConstV3fVectorDataPtr n = IECore::runTimeCast<const IECore::V3fVectorData>(it->second.data);
			if (n)
			{
				int numVertexNormals = n->readable().size();

				vertexNormalsArray.setLength( numVertexNormals );
				for (int i = 0; i < numVertexNormals; i++)
				{
					vertexNormalsArray[i] = IECore::convert<MVector, Imath::V3f>( n->readable()[i] );
				}
			}
			else
			{
				IECore::ConstV3dVectorDataPtr n = IECore::runTimeCast<const IECore::V3dVectorData>(it->second.data);
				if (n)
				{
					int numVertexNormals = n->readable().size();

					vertexNormalsArray.setLength( numVertexNormals );
					for (int i = 0; i < numVertexNormals; i++)
					{
						vertexNormalsArray[i] = IECore::convert<MVector, Imath::V3d>( n->readable()[i] );
					}
				}
				else
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", boost::format( "PrimitiveVariable \"N\" has unsupported type \"%s\"." ) % it->second.data->typeName() );
				}
			}
			
			if ( vertexNormalsArray.length() )
			{
				MStatus status;
				MItMeshPolygon itPolygon( mObj, &status );
				if( status != MS::kSuccess )
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Failed to create mesh iterator" );
				}

				unsigned v = 0;
				MIntArray vertexIds;
				MIntArray faceIds;
				
				for ( ; !itPolygon.isDone(); itPolygon.next() )
				{
					for ( v=0; v < itPolygon.polygonVertexCount(); ++v )
					{
						faceIds.append( itPolygon.index() );
						vertexIds.append( itPolygon.vertexIndex( v ) );
					}
				}

				if( !fnMesh.setFaceVertexNormals( vertexNormalsArray, faceIds, vertexIds ) )
				{
					IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "Setting normals failed" );
				}
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToMayaMeshConverter::doConversion", "PrimitiveVariable \"N\" has unsupported interpolation (expected FaceVarying)." );
		}
	}

	bool haveDefaultUVs = false;
	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
	IECore::RefCountedPtr sDataRef = ( sIt == mesh->variables.end() ) ? 0 : static_cast<IECore::RefCountedPtr>( sIt->second.data );

	/// Add named UV sets
	std::set< std::string > uvSets;
	for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
	{
		const std::string &sName = it->first;

		size_t suffixOffset = sName.rfind( "_s" );

		if ( ( suffixOffset != std::string::npos) && ( suffixOffset == sName.length() - 2 ) )
		{
			std::string uvSetNameStr = sName.substr( 0, suffixOffset );

			if ( uvSetNameStr.size() )
			{
				MString uvSetName = uvSetNameStr.c_str();
				std::string tName = uvSetNameStr + "_t";
				std::string stIdName = uvSetNameStr + "Indices";

				addUVSet( fnMesh, polygonCounts, mesh, sName, tName, stIdName, &uvSetName );

				uvSets.insert( uvSetNameStr );
				
				if ( sDataRef == static_cast<IECore::RefCountedPtr>( it->second.data ) )
				{
					haveDefaultUVs = true;
				}
			}
		}
	}

	/// Add default UV set if it isn't just a reference to a named set
	if ( !haveDefaultUVs )
	{
		addUVSet( fnMesh, polygonCounts, mesh, "s", "t", "stIndices" );
	}

	// We do the search again, but looking for primvars ending "_t", so we can catch cases where either "UVSETNAME_s" or "UVSETNAME_t" is present, but not both, taking care
	// not to attempt adding any duplicate sets
	for ( it = mesh->variables.begin(); it != mesh->variables.end(); ++it )
	{
		const std::string &tName = it->first;

		size_t suffixOffset = tName.rfind( "_t" );

		if ( ( suffixOffset != std::string::npos) && ( suffixOffset == tName.length() - 2 ) )
		{
			std::string uvSetNameStr = tName.substr( 0, suffixOffset );

			if ( uvSetNameStr.size() && uvSets.find( uvSetNameStr ) == uvSets.end() )
			{
				MString uvSetName = uvSetNameStr.c_str();
				std::string sName = uvSetNameStr + "_s";
				std::string stIdName = uvSetNameStr + "Indices";
				
				addUVSet( fnMesh, polygonCounts, mesh, sName, tName, stIdName, &uvSetName );
				uvSets.insert( uvSetNameStr );
			}
		}
	}

	/// If we're making a mesh node (rather than a mesh data) then make sure it belongs
	/// to the default shading group and add the ieMeshInterpolation attribute.
	MObject oMesh = fnMesh.object();
	if( oMesh.apiType()==MFn::kMesh )
	{
		assignDefaultShadingGroup( oMesh );
		setMeshInterpolationAttribute( oMesh, mesh->interpolation() );
	}

	/// \todo Other primvars, e.g. vertex color ("Cs")

	return true;
}
    // ------------------------------------
    bool LightExporter::exportLight ( const MDagPath& dagPath )
    {
        if ( !ExportOptions::exportLights() ) return false;

        MObject lightNode = dagPath.node();

        // Retrieve the Maya light object
        MStatus status;
        MFnLight lightFn(lightNode, &status); CHECK_STAT(status);
        if (status != MStatus::kSuccess) return false;

        // Get the maya light id.
        String mayaLightId = mDocumentExporter->dagPathToColladaId ( dagPath );

        // Generate a COLLADA id for the new object
        String colladaLightId;
        
        // Check if there is an extra attribute "colladaId" and use this as export id.
        MString attributeValue;
        DagHelper::getPlugValue ( lightNode, COLLADA_ID_ATTRIBUTE_NAME, attributeValue );
        if ( attributeValue != EMPTY_CSTRING )
        {
            // Generate a valid collada name, if necessary.
            colladaLightId = mDocumentExporter->mayaNameToColladaName ( attributeValue, false );
        }
        else
        {
            // Generate a COLLADA id for the new object
            colladaLightId = mDocumentExporter->dagPathToColladaId ( dagPath );
        }
        // Make the id unique and store it in a map.
        colladaLightId = mLightIdList.addId ( colladaLightId );
        mMayaIdColladaIdMap [ mayaLightId ] = colladaLightId;

        // Get a pointer to the stream writer.
        COLLADASW::StreamWriter* streamWriter = mDocumentExporter->getStreamWriter();

        // The light name
        String lightName = mDocumentExporter->dagPathToColladaName ( dagPath );

        // Figure out the type of light and create it
        COLLADASW::Light* light = NULL;
        MFn::Type type = lightNode.apiType();
        switch (type)
        {
        case MFn::kAmbientLight: 
            light = new COLLADASW::AmbientLight( streamWriter, colladaLightId, lightName ); 
            break; 
        case MFn::kDirectionalLight: 
            light = new COLLADASW::DirectionalLight( streamWriter, colladaLightId, lightName ); 
            break;
        case MFn::kSpotLight: 
            light = new COLLADASW::SpotLight( streamWriter, colladaLightId, lightName ); 
            break;
        case MFn::kPointLight: // Intentional pass-through
        default: 
            light = new COLLADASW::PointLight( streamWriter, colladaLightId, lightName ); 
            break;
        }

        // Export the original maya name.
        light->addExtraTechniqueParameter ( PROFILE_MAYA, PARAMETER_MAYA_ID, mayaLightId );

        // Get a pointer to the animation exporter.
        AnimationExporter* anim = mDocumentExporter->getAnimationExporter();
        bool animated = false;
        
        // Color/Intensity are the common attributes of all lights
        MColor mayaColor = lightFn.color ( &status ); CHECK_STAT(status);
        COLLADASW::Color lightColor ( mayaColor.r, mayaColor.g, mayaColor.b, mayaColor.a );
        animated = anim->addNodeAnimation ( lightNode, ATTR_COLOR, kColour, RGBA_PARAMETERS );
        light->setColor( lightColor, animated );

        float intensity = lightFn.intensity ( &status ); CHECK_STAT(status);
        animated = anim->addNodeAnimation ( lightNode, ATTR_INTENSITY, kSingle );
        light->setIntensity( intensity, animated );
		
		// Export light intensity
		light->addExtraTechniqueParameter(PROFILE_MAYA, ATTR_INTENSITY, intensity);


        // Add the type specific attributes
        if (lightNode.hasFn(MFn::kNonAmbientLight))
        {
            // Needed Point and Spot light types parameters: Attenuation and Attenuation_Scale
            // Attenuation in COLLADA is equal to Decay in Maya.
            MFnNonAmbientLight naLightFn(lightNode);
            int decayRate = naLightFn.decayRate(&status); CHECK_STAT(status);
            decayRate = std::min ( decayRate, 2 ); 
            decayRate = std::max ( decayRate, 0 );

            light->setConstantAttenuation ( ( decayRate == 0 ) ? 1.0f : 0.0f);
            light->setLinearAttenuation ( ( decayRate == 1 ) ? 1.0f : 0.0f);
            light->setQuadraticAttenuation ( ( decayRate == 2 ) ? 1.0f : 0.0f);
        }
        else if (lightNode.hasFn(MFn::kAmbientLight))
        {
            MFnAmbientLight ambientLightFn ( lightNode );
            float ambientShade = ambientLightFn.ambientShade();
            String paramSid = EMPTY_STRING;
            animated = anim->addNodeAnimation ( lightNode, ATTR_AMBIENT_SHADE, kSingle );
            if ( animated ) paramSid = ATTR_AMBIENT_SHADE;
            light->addExtraTechniqueParameter ( PROFILE_MAYA, MAYA_AMBIENTSHADE_LIGHT_PARAMETER, ambientShade, paramSid );
        }

        if (lightNode.hasFn(MFn::kSpotLight))
        {
            // Put in the needed spot light type attributes : Falloff, Falloff_Scale and Angle
            MFnSpotLight spotFn(lightNode);

            float fallOffAngle = COLLADABU::Math::Utils::radToDegF ( (float)spotFn.coneAngle( &status ) ); CHECK_STAT(status);
            animated = anim->addNodeAnimation ( lightNode, ATTR_CONE_ANGLE, ( SampleType ) ( kSingle | kAngle ) );
            light->setFallOffAngle ( fallOffAngle, animated );

            light->setFallOffExponent ( 1.0f );

            float penumbraValue = COLLADABU::Math::Utils::radToDegF ( (float)spotFn.penumbraAngle( &status ) ); CHECK_STAT(status);
            animated = anim->addNodeAnimation ( lightNode, ATTR_PENUMBRA_ANGLE, ( SampleType ) ( kSingle | kAngle ) );


			// Export spot setting
			float dropOff = (float)spotFn.dropOff(&status); CHECK_STAT(status);
			light->addExtraTechniqueParameter(PROFILE_MAYA, MAYA_PENUMBRA_LIGHT_PARAMETER, penumbraValue);
			light->addExtraTechniqueParameter(PROFILE_MAYA, MAYA_DROPOFF_LIGHT_PARAMETER, dropOff);


			// TODO
//            FCDLightTools::LoadPenumbra(light, penumbraValue, colladaLight->GetOuterAngle().GetAnimated());

            // TODO
//             animated = anim->addNodeAnimation ( lightNode, ATTR_DROP_OFF, kSingle );
//             light->setDropOff ( (float) spotFn.dropOff ( &status ), animated ); CHECK_MSTATUS(status);
        }
        
        SceneElement* sceneElement = NULL;
        SceneGraph* sceneGraph = mDocumentExporter->getSceneGraph();
        sceneElement = sceneGraph->findElement(dagPath);
        exportExtraAttributes(sceneElement, light);

        addLight ( *light );
        delete light;

        return true;
    }
// Get shading engine
//
void CScriptedShapeTranslator::GetShapeInstanceShader(MDagPath& dagPath, MFnDependencyNode &shadingEngineNode)
{
   // Get instance shadingEngine
   shadingEngineNode.setObject(MObject::kNullObj);
   
   // First try the usual way
   MPlug shadingGroupPlug = GetNodeShadingGroup(dagPath.node(), (dagPath.isInstanced() ? dagPath.instanceNumber() : 0));
   if (!shadingGroupPlug.isNull())
   {
      shadingEngineNode.setObject(shadingGroupPlug.node());
      return;
   }
   
   char buffer[64];
   
   // Check connection from any shadingEngine on shape
   MStringArray connections;
   MGlobal::executeCommand("listConnections -s 1 -d 0 -c 1 -type shadingEngine "+dagPath.fullPathName(), connections);
   
   MSelectionList sl;
   
   if (connections.length() == 0)
   {
      // Check for direct surface shader connection
      MGlobal::executeCommand("listConnections -s 1 -d 0 -c 1 "+dagPath.fullPathName(), connections);
      
      for (unsigned int cidx=0; cidx<connections.length(); cidx+=2)
      {
         MString srcNode = connections[cidx+1];
         // Get node classification, if can find arnold/shader/surface -> got it
         MStringArray rv;
         MGlobal::executeCommand("getClassification `nodeType "+srcNode+"`", rv);
         if (rv.length() > 0 && rv[0].indexW("arnold/shader/surface") != -1)
         {
            connections.clear();
            
            MGlobal::executeCommand("listConnections -s 0 -d 1 -c 1 -type shadingEngine "+srcNode, connections);
            
            if (connections.length() == 2)
            {
               sl.add(connections[1]);
            }
            
            break;
         }
      }
   }
   else if (connections.length() == 2)
   {
      // Single connection, use same shader for all instances
      sl.add(connections[1]);
   }
   else if (connections.length() > 2)
   {
      // Many connections, expects the destination plug in shape to be an array
      // Use instance number as logical index, if this fails, use first shadingEngine in list
      
      bool found = false;
      
      sprintf(buffer, "[%d]", dagPath.instanceNumber());
      MString iidx = buffer;
      
      for (unsigned int cidx = 0; cidx < connections.length(); cidx += 2)
      {
         MString conn = connections[cidx];
         
         if (conn.length() < iidx.length())
         {
            continue;
         }
         
         if (conn.substring(conn.length() - iidx.length(), conn.length() - 1) != iidx)
         {
            continue;
         }
         
         sl.add(connections[cidx+1]);
         
         found = true;
         
         break;
      }
      
      if (!found)
      {
         MGlobal::displayWarning("[mtoaScriptedTranslators] Instance shader plug not found, use first found shadingEngine \"" + connections[1] + "\"");
         sl.add(connections[1]);
      }
   }
   
   if (sl.length() == 1)
   {
      MObject shadingEngineObj;
      
      if (sl.getDependNode(0, shadingEngineObj) == MS::kSuccess && shadingEngineObj.apiType() == MFn::kShadingEngine)
      {
         shadingEngineNode.setObject(shadingEngineObj);
      }
      else
      {
         if (shadingEngineObj != MObject::kNullObj)
         {
            MFnDependencyNode dn(shadingEngineObj);
            MGlobal::displayWarning("[mtoaScriptedTranslators] Not a shading engine \"" + dn.name() + "\"");
         }
      }
   }
}
Пример #23
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;
}
void Exporter::extractLight(MObject& mObj)
{
	//different space variables
	MSpace::Space world_space = MSpace::kPostTransform;
	MSpace::Space object_space = MSpace::kLast;
	MSpace::Space transform_space = MSpace::kPreTransform;

	//temp storage for light
	pointLightStruct tempPointLights;
	ambientLightStruct tempAmbiLights;
	spotLightStruct tempSpotLights;
	directionalLightStruct tempDirLights;
	areaLightStruct tempAreaLights;

	//binder en ljusfunktion till objektet
	MFnLight func(mObj);

	//dess parent
	MFnDagNode functionParent(func.parent(0));

	//ljusets f�rg
	MColor col(0.0f, 0.0f, 0.0f);
	//possible fault: func maybe fnlight????
	col = func.color();


	//Get Transform experimentation
	MFnTransform fs(func.parent(0));
	//MMatrix matrix = fs.transformation().asMatrix();
	//std::cout << "\nTransform Matrix: " << matrix << std::endl;

	MVector lightTranslation = fs.translation(transform_space);


	//output light
	std::cout << "parent " << functionParent.name().asChar()
		<< "\ntype " << mObj.apiTypeStr()
		<< "\nLight color " << col.r << " " << col.g << " " << col.b
		<< "\nLight intensity " << func.intensity()
		<< "\nLight direction " << func.lightDirection(0, world_space, 0) << "\n" << std::endl;

	std::cout << "translation: " << lightTranslation << "\n" << std::endl;

	//f�r specifika attribut till specifika ljustyper:
	switch (mObj.apiType())
	{
		//pointlight-only attributes:
	case MFn::kPointLight:
	{
		MFnPointLight fnPointLight(mObj);
		tempPointLights.color.x = col.r;
		tempPointLights.color.y = col.g;
		tempPointLights.color.z = col.b;
		tempPointLights.intensity = func.intensity();
		tempPointLights.pos = lightTranslation;

		//push back in the light temp storage
		scene_.lights.pointLights.push_back(tempPointLights);

	}
	break;
	//ambientlight-only
	case MFn::kAmbientLight:
	{
		MFnAmbientLight fnAmbientLight(mObj);
		tempAmbiLights.color.x = col.r;
		tempAmbiLights.color.y = col.g;
		tempAmbiLights.color.z = col.b;
		tempAmbiLights.intensity = func.intensity();
		tempAmbiLights.pos = lightTranslation;

		//push back in the light temp storage
		scene_.lights.ambientLights.push_back(tempAmbiLights);

	}
	break;
	//spotlight-only
	case MFn::kSpotLight:
	{
		MFnSpotLight fnSpotLight(mObj);
		//cone angle represents the angle that the spotlight cone makes with the spotlight direction vector
		//penumbra angle is the outer edge of the light 
		//dropoff represents the degree to which the light intensity decreases with the angular distance from the light direction vector.
		std::cout << "Cone angle " << fnSpotLight.coneAngle() << "\nPenumbra angle " << fnSpotLight.penumbraAngle()
			<< "\nDropoff " << fnSpotLight.dropOff() << "\n" << std::endl;

		tempSpotLights.color.x = col.r;
		tempSpotLights.color.y = col.g;
		tempSpotLights.color.z = col.b;
		tempSpotLights.intensity = func.intensity();
		tempSpotLights.coneAngle = fnSpotLight.coneAngle();
		tempSpotLights.penumbraAngle = fnSpotLight.penumbraAngle();
		tempSpotLights.dropoff = fnSpotLight.dropOff();
		tempSpotLights.dir = func.lightDirection(0, MSpace::kWorld, 0);
		tempSpotLights.pos = lightTranslation;

		//push back in the light temp storage
		scene_.lights.spotLights.push_back(tempSpotLights);

	}
	break;
	//directional light-only
	case MFn::kDirectionalLight:
	{
		MFnDirectionalLight fnDirLight(mObj);

		tempDirLights.color.x = col.r;
		tempDirLights.color.y = col.g;
		tempDirLights.color.z = col.b;
		tempDirLights.intensity = func.intensity();
		tempDirLights.dir = func.lightDirection(0, MSpace::kWorld, 0);
		tempDirLights.pos = lightTranslation;

		//push back in the light temp storage
		scene_.lights.dirLights.push_back(tempDirLights);

	}
	break;
	//arealight-only
	case MFn::kAreaLight:
	{
		MFnAreaLight fnAreaLight(mObj);

		tempAreaLights.color.x = col.r;
		tempAreaLights.color.y = col.g;
		tempAreaLights.color.z = col.b;
		tempAreaLights.intensity = func.intensity();
		tempAreaLights.pos = lightTranslation;

		//push back in the light temp storage
		scene_.lights.areaLights.push_back(tempAreaLights);

	}
	break;

	default:
		break;

		//scene_.lights.push_back(TempLightStorage);

	}

}
Пример #25
0
MStatus tm_polySplit::doIt( const MArgList& args)
{
#ifdef _DEBUG
cout << endl << "####################################################" << endl;
cout << "tm_polySplit::doIt - DEBUG version info:" << endl;
#endif
	MStatus status;

	MGlobal::getActiveSelectionList( oldSelList );

	MArgDatabase argData( syntax(), args);

	//parse flags
	//
	if(argData.isFlagSet( loop_Flag))
	{
		cmd_flag_loop = true;
		argData.getFlagArgument( loop_Flag, 0, cmd_flag_loop_mode);
		argData.getFlagArgument( loop_Flag, 1, cmd_flag_loop_angle);
//		argData.getFlagArgument( loop_Flag, 2, cmd_flag_loop_maxcount); // - max count;
	}
	else if(argData.isFlagSet( sel_Flag))
	{
		cmd_flag_loop = false;
		cmd_flag_sel = true;
	}


	MSelectionList selectionList;
	argData.getObjects( selectionList);
	MItSelectionList selListIter( selectionList );
	selListIter.setFilter( MFn::kMesh );

	// The tm_polySplit node only accepts a component list input, so we build
	// a component list using MFnComponentListData.
	//
	// MIntArrays could also be passed into the node to represent the edgesIds,
	// but are less storage efficient than component lists, since consecutive 
	// components are bundled into a single entry in component lists.
	//
	MFnComponentListData compListFn;
	compListFn.create();
	bool found = false;
	bool foundMultiple = false;
	MObject meshObj;

	for( ; !selListIter.isDone(); selListIter.next() )
	{
		MDagPath dagPath;
		MObject component;
		selListIter.getDagPath( dagPath, component );
		meshObj = dagPath.node();

		// Check for selected Edges components
		//
		if( component.apiType() == MFn::kMeshEdgeComponent )
		{
			if( !found )
			{
				// The variable 'component' holds all selected components on the selected
				// object, thus only a single call to MFnComponentListData::add() is needed
				// to store the selected components for a given object.
				//
				compListFn.add( component );

				// Copy the component list created by MFnComponentListData into our local
				// component list MObject member.
				//
				fComponentList = compListFn.object();

				// Locally store the actual edgesIds of the selected Edges so that this command
				// can directly modify the mesh in the case when there is no history and
				// history is turned off.
				//
				MFnSingleIndexedComponent compFn( component );
				compFn.getElements( fSelEdges );

				// Ensure that this DAG path will point to the shape of our object.
				// Set the DAG path for the polyModifierCmd.
				//
				dagPath.extendToShape();
				setMeshNode( dagPath );
				found = true;
			}
			else
			{
				// Break once we have found a multiple object holding selected UVs, since
				// we are not interested in how many multiple objects there are, only
				// the fact that there are multiple objects.
				//
				foundMultiple = true;
				break;
			}
		}
	}
#ifdef _DEBUG
cout << endl << "########################## checking arguments:" << endl;
cout << endl << "fSelEdges = ";for(unsigned i=0;i<fSelEdges.length();i++) cout << fSelEdges[i] << " ";cout << endl;
#endif
	if( foundMultiple )
	{
		displayWarning("Found more than one object with selected Edges - Only operating on first found object.");
	}
	if( !found )
	{
		displayError( "tm_polySplit command failed: Unable to find selected edges" );
		return MStatus::kFailure;
	}
	// Initialize the polyModifierCmd node type - mesh node already set
	//
	setModifierNodeType( tm_polySplitNode::id );
//##################################################################
	alwaysWithConstructionHistory = true;
	status = doModifyPoly();
	if( !status){displayError( "tm_polySplit command failed!" );return status;}
//################################################################## get polymodifier node name and select it
	getModifierNodeName();
	newSelList.add( modifierNodeName);
	MGlobal::setActiveSelectionList( newSelList);//, MGlobal::kAddToList);
//##################################################################
	setResult( modifierNodeName);

	return MStatus::kSuccess;
/*
cout<<endl<<"**********"<<endl;return MStatus::kSuccess;
*/
}
Пример #26
0
MStatus simulateBoids::doIt( const MArgList& args )
{
	
	//	Description: implements the MEL boids command
	//	Arguments: args - the argument list that was passes to the command from MEL

	MStatus status = MS::kSuccess;

	
    /****************************************
	*	building thread/dll data structure  *
	****************************************/

	InfoCache infoCache;
	SimulationParameters simParams;
	RulesParameters *applyingRules;
	double progressBar=0;
	double aov=pi/3;
	int i,numberOfDesires=0;
	
	// params retrievement
	MSelectionList sel;
	MObject node;
	MFnDependencyNode nodeFn;
	MFnTransform locatorFn;
	MPlug plug;

	// simulation params
	int simulationLengthValue;		// [int] in seconds
	int framesPerSecondValue;		// [int]
	int startFrameValue;			// [int]
	int boidsNumberValue;			// [int]
	// export params
	MString logFilePathValue;		// [char *]
	MString logFileNameValue;		// [char *]
	int logFileTypeValue;			// 0 = nCache; 1 = log file; 2 = XML; 
	// locomotion params
	int locomotionModeValue;		// [int]
	double maxSpeedValue;			// [double]
	double maxForceValue;			// [double]

	// double mass=1;				// [double]

	MTime currentTime, maxTime;
	MPlug plugX, plugY, plugZ;
	double tx, ty, tz;
	int frameLength ;
	Vector * leader = NULL;

	MStatus leaderFound=MStatus::kFailure;

	MGlobal::getActiveSelectionList(sel);
	for ( MItSelectionList listIter(sel); !listIter.isDone(); listIter.next() )
	{
		listIter.getDependNode(node);
		switch(node.apiType())
		{
			case MFn::kTransform:
				// get locator transform to follow
				leaderFound=locatorFn.setObject(node);
				cout << locatorFn.name().asChar() << " is selected as locator" << endl;
				break;
			case MFn::kPluginDependNode:
				nodeFn.setObject(node);
				cout << nodeFn.name().asChar() << " is selected as brain" << endl;
				break;
			default:
				break;
		}
		cout<< node.apiTypeStr()<<endl;
	}

	// rules params
	setRuleVariables(alignment);
	setRuleVariables(cohesion);
	setRuleVariables(separation);
	setRuleVariables(follow);

	getPlugValue(simulationLength);
	getPlugValue(framesPerSecond);
	getPlugValue(startFrame);
	getPlugValue(boidsNumber);
	getPlugValue(logFileType);
	getRulePlugValue(alignment);
	getRulePlugValue(cohesion);
	getRulePlugValue(separation);
	getRulePlugValue(follow);
	getPlugValue(locomotionMode);
	getPlugValue(maxSpeed);
	getPlugValue(maxForce);
	getTypePlugValue(logFilePath);
	getTypePlugValue(logFileName);
		// counting active rules number
	if(alignmentActiveValue)
		numberOfDesires++;
	if(cohesionActiveValue)
		numberOfDesires++;
	if(separationActiveValue)
		numberOfDesires++;
	if(followActiveValue)
		numberOfDesires++;


	currentTime = MTime((double)startFrameValue);														// MAnimControl::minTime();
	maxTime = MTime((double)(startFrameValue + (simulationLengthValue * framesPerSecondValue)));		// MAnimControl::maxTime();
	cout << "time unit enum (6 is 24 fps): " << currentTime.unit() << endl;	
	plugX = locatorFn.findPlug( MString( "translateX" ), &status );
	plugY = locatorFn.findPlug( MString( "translateY" ), &status );
	plugZ = locatorFn.findPlug( MString( "translateZ" ), &status );
	frameLength = simulationLengthValue * framesPerSecondValue;
	
	if(leaderFound==MS::kSuccess)
	{
		leader = new Vector[frameLength];	
		while ( currentTime < maxTime )
		{
			{
				int index = (int)currentTime.value() - startFrameValue;
				/*
				MGlobal::viewFrame(currentTime);
				pos = locatorFn.getTranslation(MSpace::kWorld);
				cout << "pos: " << pos.x << " " << pos.y << " " << pos.z << endl;
				*/
				status = plugX.getValue( tx, MDGContext(currentTime) );
				status = plugY.getValue( ty, MDGContext(currentTime) );
				status = plugZ.getValue( tz, MDGContext(currentTime) );

				leader[index].x = tx;
				leader[index].y = ty;
				leader[index].z = tz;
				//cout << "pos at time " << currentTime.value() << " has x: " << tx << " y: " << ty << " z: " << tz << endl;
				currentTime++;
			}	
		}
	}

	simParams.fps=framesPerSecondValue;
	simParams.lenght=simulationLengthValue;
	simParams.numberOfBoids=boidsNumberValue;
	simParams.maxAcceleration=maxForceValue;
	simParams.maxVelocity=maxSpeedValue;
	simParams.simplifiedLocomotion=TRUE;


	
	
	applyingRules=new RulesParameters[numberOfDesires];
	

	// cache settings
	MString saveString;
	saveString = logFilePathValue+"/"+logFileNameValue;
	infoCache.fileName=new char[saveString.length()+1];
	memcpy(infoCache.fileName,saveString.asChar(),sizeof(char)*(saveString.length()+1));
	infoCache.cacheFormat=ONEFILE;
	infoCache.fps=framesPerSecondValue;
	infoCache.start=startFrameValue/framesPerSecondValue;
	infoCache.end=simulationLengthValue+infoCache.start;	
	infoCache.loging=FALSE;
	infoCache.option=POSITIONVELOCITY;
	infoCache.particleSysName="BoidsNParticles";
	infoCache.saveMethod=MAYANCACHE;

	for(i=0;i<numberOfDesires;i++)
	{
		applyingRules[i].enabled=TRUE;
		applyingRules[i].precedence=1;
		applyingRules[i].aov=aov;
		applyingRules[i].visibilityOption=FALSE;
	}	

	if(cohesionActiveValue==0)
		applyingRules[COHESIONRULE].enabled=FALSE;
	else
	{
		applyingRules[COHESIONRULE].ruleName=COHESIONRULE;
		applyingRules[COHESIONRULE].ruleFactor=cohesionFactorValue;
		applyingRules[COHESIONRULE].ruleRadius=cohesionRadiusValue;
		applyingRules[COHESIONRULE].ruleWeight=cohesionWeightValue;
	}

	if(separationActiveValue==0)
		applyingRules[SEPARATIONRULE].enabled=FALSE;
	else
	{
		applyingRules[SEPARATIONRULE].ruleName=SEPARATIONRULE;
		applyingRules[SEPARATIONRULE].ruleFactor=separationFactorValue;
		applyingRules[SEPARATIONRULE].ruleRadius=separationRadiusValue;
		applyingRules[SEPARATIONRULE].ruleWeight=separationWeightValue;
	}

	if(alignmentActiveValue==0)
		applyingRules[ALIGNMENTRULE].enabled=FALSE;
	else
	{
		applyingRules[ALIGNMENTRULE].ruleName=ALIGNMENTRULE;
		applyingRules[ALIGNMENTRULE].ruleFactor=alignmentFactorValue;
		applyingRules[ALIGNMENTRULE].ruleRadius=alignmentRadiusValue;
		applyingRules[ALIGNMENTRULE].ruleWeight=alignmentWeightValue;
	}
	
	if(followActiveValue==0)
		applyingRules[FOLLOWRULE].enabled=FALSE;
	else
	{
		applyingRules[FOLLOWRULE].ruleName=FOLLOWRULE;
		applyingRules[FOLLOWRULE].ruleRadius=followRadiusValue;
		applyingRules[FOLLOWRULE].ruleFactor=followFactorValue;
		applyingRules[FOLLOWRULE].ruleWeight=followWeightValue;
	}
	

	// initializing simulation parameters
	boidInit(numberOfDesires, applyingRules, simParams , infoCache, leader);

	DLLData datadll;
	// preparing threads pool
	status = MThreadPool::init();
	
	if (status==MStatus::kSuccess)
	{
		MThreadPool::newParallelRegion(ThreadsCreator, &datadll);
		setResult( "Command executed!\n" );
		CHECK_MSTATUS(MProgressWindow::endProgress());
		MThreadPool::release();
	}

	switch(datadll.result)
	{
	case 0:
		status=MS::kSuccess;
		break;

	default:
		status=MS::kFailure;
	}

	MThreadPool::release();
	return status;
}
Пример #27
0
void liqRibData::addAdditionalSurfaceParameters( MObject node )
{
  LIQDEBUGPRINTF("-> scanning for additional rman surface attributes \n");
  MStatus status = MS::kSuccess;
  unsigned i;

  // work out how many elements there would be in a facevarying array if a mesh or subD
  // faceVaryingCount is a private data member
  if ( ( type() == MRT_Mesh ) || ( type() == MRT_Subdivision ) ) {
    faceVaryingCount = 0;
    MFnMesh fnMesh( node );
    for ( uint pOn = 0; pOn < fnMesh.numPolygons(); pOn++ ) {
      faceVaryingCount += fnMesh.polygonVertexCount( pOn );
    }
  }

  // find how many additional
  MFnDependencyNode nodeFn( node );

  // find the attributes
  MStringArray floatAttributesFound  = findAttributesByPrefix( "rmanF", nodeFn );
  MStringArray pointAttributesFound  = findAttributesByPrefix( "rmanP", nodeFn );
  MStringArray vectorAttributesFound = findAttributesByPrefix( "rmanV", nodeFn );
  MStringArray normalAttributesFound = findAttributesByPrefix( "rmanN", nodeFn );
  MStringArray colorAttributesFound  = findAttributesByPrefix( "rmanC", nodeFn );
  MStringArray stringAttributesFound = findAttributesByPrefix( "rmanS", nodeFn );


  if ( floatAttributesFound.length() > 0 ) {
    for ( i = 0; i < floatAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = floatAttributesFound[i].substring(5, floatAttributesFound[i].length());
      MPlug fPlug = nodeFn.findPlug( floatAttributesFound[i] );
      MObject plugObj;
      status = fPlug.getValue( plugObj );
      if ( plugObj.apiType() == MFn::kDoubleArrayData ) {
        MFnDoubleArrayData  fnDoubleArrayData( plugObj );
        MDoubleArray doubleArrayData = fnDoubleArrayData.array( &status );
        tokenPointerPair.set( cutString.asChar(),
                              rFloat,
                              ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                              true,
                              false,
                              doubleArrayData.length() );
        for( unsigned int kk = 0; kk < doubleArrayData.length(); kk++ ) {
          tokenPointerPair.setTokenFloat( kk, doubleArrayData[kk] );
        }
        if ( ( type() == MRT_NuCurve ) && ( cutString == MString( "width" ) ) ) {
          tokenPointerPair.setDetailType( rVarying);
        } else if ( ( ( type() == MRT_Mesh ) || ( type() == MRT_Subdivision ) ) && ( doubleArrayData.length() == faceVaryingCount ) ) {
          tokenPointerPair.setDetailType( rFaceVarying);
        } else {
          tokenPointerPair.setDetailType( rVertex );
        }
      } else {

        if( fPlug.isArray() ) {

          int nbElts = fPlug.evaluateNumElements();
          float floatValue;
          tokenPointerPair.set( cutString.asChar(),
                                rFloat,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                false,
                                true, // philippe :passed as uArray, otherwise it will think it is a single float
                                nbElts );
          MPlug elementPlug;
          for( unsigned int kk = 0; kk < nbElts; kk++ ) {
            elementPlug = fPlug.elementByPhysicalIndex(kk);
            elementPlug.getValue( floatValue );
            tokenPointerPair.setTokenFloat( kk, floatValue );
          }
          tokenPointerPair.setDetailType( rConstant );

        } else {

          float floatValue;
          tokenPointerPair.set( cutString.asChar(),
                                rFloat,
                                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                                false,
                                false,
                                0 );
          fPlug.getValue( floatValue );
          tokenPointerPair.setTokenFloat( 0, floatValue );
          tokenPointerPair.setDetailType( rConstant );

        }

      }
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }

  if ( pointAttributesFound.length() > 0 ) {
    for ( i = 0; i < pointAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = pointAttributesFound[i].substring(5, pointAttributesFound[i].length());
      MPlug pPlug = nodeFn.findPlug( pointAttributesFound[i] );
      MObject plugObj;
      status = pPlug.getValue( plugObj );
      if ( plugObj.apiType() == MFn::kPointArrayData ) {
        MFnPointArrayData  fnPointArrayData( plugObj );
        MPointArray pointArrayData = fnPointArrayData.array( &status );
        tokenPointerPair.set( cutString.asChar(),
                              rPoint,
                              ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                              true,
                              false,
                              pointArrayData.length() );
        if ( type() == MRT_Nurbs || type() == MRT_NuCurve ) {
          for ( int kk = 0; kk < pointArrayData.length(); kk++ ) {
            tokenPointerPair.setTokenFloat( kk, pointArrayData[kk].x, pointArrayData[kk].y, pointArrayData[kk].z, pointArrayData[kk].w );
          }
        } else {
          for ( int kk = 0; kk < pointArrayData.length(); kk++ ) {
            tokenPointerPair.setTokenFloat( kk, pointArrayData[kk].x, pointArrayData[kk].y, pointArrayData[kk].z );
          }
        }
        tokenPointerPair.setDetailType( rVertex );
      } else {
        // Hmmmm float ? double ?
        float x, y, z;
        tokenPointerPair.set(
                cutString.asChar(),
                rPoint,
                ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
                false,
                false,
                0 );
        // Hmmm should check as for arrays if we are in nurbs mode : 4 values
        pPlug.child(0).getValue( x );
        pPlug.child(1).getValue( y );
        pPlug.child(2).getValue( z );
        tokenPointerPair.setTokenFloat( 0, x, y, z );
        tokenPointerPair.setDetailType( rConstant );
      }
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }
  parseVectorAttributes( nodeFn, vectorAttributesFound, rVector );
  parseVectorAttributes( nodeFn, normalAttributesFound, rNormal );
  parseVectorAttributes( nodeFn, colorAttributesFound,  rColor  );

  if ( stringAttributesFound.length() > 0 ) {
    for ( i = 0; i < stringAttributesFound.length(); i++ ) {
      liqTokenPointer tokenPointerPair;
      MString cutString = stringAttributesFound[i].substring(5, stringAttributesFound[i].length());
      MPlug sPlug = nodeFn.findPlug( stringAttributesFound[i] );
      MObject plugObj;
      status = sPlug.getValue( plugObj );
      tokenPointerPair.set(
        cutString.asChar(),
        rString,
        ( type() == MRT_Nurbs || type() == MRT_NuCurve ) ? true : false,
        false,
        false,
        0 );
      MString stringVal;
      sPlug.getValue( stringVal );
      tokenPointerPair.setTokenString( 0, stringVal.asChar(), stringVal.length() );
      tokenPointerPair.setDetailType( rConstant );
      tokenPointerArray.push_back( tokenPointerPair );
    }
  }
}
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);
		*/
	}

}
    //---------------------------------------------------------------
    void EffectTextureExporter::exportTexture (
        COLLADASW::Texture* colladaTexture,
        String channelSemantic,
        const MObject& texture,
        int blendMode,
        const String& targetPath )
    {
        mAnimationTargetPath = targetPath;

        // Set the image name
        String colladaImageId = exportImage ( texture );
        colladaTexture->setImageId ( colladaImageId );
        colladaTexture->setTexcoord ( channelSemantic );

        // Get the current stream writer
        COLLADASW::StreamWriter* streamWriter = mDocumentExporter->getStreamWriter();

        // Create the sampler
        String samplerSid = colladaImageId + COLLADASW::Sampler::SAMPLER_SID_SUFFIX;
        String surfaceSid = colladaImageId + COLLADASW::Sampler::SURFACE_SID_SUFFIX;

        COLLADASW::Sampler sampler ( COLLADASW::Sampler::SAMPLER_TYPE_2D, samplerSid, surfaceSid );
        sampler.setFormat ( FORMAT );
        sampler.setImageId ( colladaImageId );

        colladaTexture->setSampler ( sampler );

        // Add 2D placement parameters
        add2DPlacement ( colladaTexture, texture );

        // Check for 3D projection node
        MObject colorReceiver = DagHelper::getSourceNodeConnectedTo ( texture, ATTR_OUT_COLOR );
        if ( colorReceiver != MObject::kNullObj && colorReceiver.apiType() == MFn::kProjection )
        {
            add3DProjection ( colladaTexture, colorReceiver );
        }

        // Add blend mode information
        String blendModeString = getBlendMode ( blendMode );
        colladaTexture->addExtraTechniqueParameter ( PROFILE_MAYA, MAYA_TEXTURE_BLENDMODE_PARAMETER, blendModeString );

        // Wrap elements
        switch ( colladaTexture->getSampler().getSamplerType() )
        {

        case COLLADASW::Sampler::SAMPLER_TYPE_1D:
            sampler.setWrapS ( COLLADASW::Sampler::WRAP_MODE_WRAP );
            break;

        case COLLADASW::Sampler::SAMPLER_TYPE_2D:
        {
            sampler.setWrapS ( COLLADASW::Sampler::WRAP_MODE_WRAP );
            sampler.setWrapT ( COLLADASW::Sampler::WRAP_MODE_WRAP );
        }
        break;

        case COLLADASW::Sampler::SAMPLER_TYPE_3D:
        case COLLADASW::Sampler::SAMPLER_TYPE_CUBE:
        {
            sampler.setWrapS ( COLLADASW::Sampler::WRAP_MODE_WRAP );
            sampler.setWrapT ( COLLADASW::Sampler::WRAP_MODE_WRAP );
            sampler.setWrapP ( COLLADASW::Sampler::WRAP_MODE_WRAP );
        }
        break;
        }

        sampler.setMinFilter ( COLLADASW::Sampler::SAMPLER_FILTER_NONE );
        sampler.setMagFilter ( COLLADASW::Sampler::SAMPLER_FILTER_NONE );
        sampler.setMipFilter ( COLLADASW::Sampler::SAMPLER_FILTER_NONE );
    }
Пример #30
0
ATTR_TYPE getPlugAttrType(MPlug plug)
{
	MStatus stat = MS::kSuccess;

	MPlug p = plug;
	while (p.isChild())
		p = p.parent();
	plug = p;
	MObject attObj = plug.attribute(&stat);
	MFnAttribute att(attObj);

	if (!stat)
		return ATTR_TYPE::ATTR_TYPE_NONE;
	MString attName = att.name();

	// all 3 child attributes are vectors for osl
	if (p.numChildren() == 3)
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "input1")
	{
		if (plug.node().hasFn(MFn::kMultiplyDivide))
			return ATTR_TYPE::ATTR_TYPE_VECTOR;
	}
	if (attName == "input2")
	{
		if (plug.node().hasFn(MFn::kMultiplyDivide))
			return ATTR_TYPE::ATTR_TYPE_VECTOR;
	}

	if (attName == "output")
	{
		if (plug.node().hasFn(MFn::kMultiplyDivide))
			return ATTR_TYPE::ATTR_TYPE_VECTOR;
	}

	if (attName == "outValue")
	{
		if (plug.node().hasFn(MFn::kGammaCorrect))
			return ATTR_TYPE::ATTR_TYPE_COLOR;
	}
	if (attName == "outDPdu")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "outDPdv")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "outColor")
		return ATTR_TYPE::ATTR_TYPE_COLOR;

	if (attName == "uvCoord")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "outUV")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "color")
		return ATTR_TYPE::ATTR_TYPE_COLOR;

	if (attName == "normalCamera")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "pointWorld")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (attName == "rayDirection")
		return ATTR_TYPE::ATTR_TYPE_VECTOR;

	if (att.isUsedAsColor())
		return ATTR_TYPE::ATTR_TYPE_COLOR;
	if (attObj.apiType() == MFn::kNumericAttribute)
	{
		MFnNumericAttribute na(attObj, &stat);
		if (!stat)
			return ATTR_TYPE::ATTR_TYPE_NONE;
		if (na.unitType() == MFnNumericData::Type::kFloat)
			return ATTR_TYPE::ATTR_TYPE_FLOAT;
	}
	if (attObj.apiType() == MFn::kAttribute3Float)
	{
		return ATTR_TYPE::ATTR_TYPE_VECTOR;
	}
	return ATTR_TYPE::ATTR_TYPE_NONE;
}