MPxFileTranslator::MFileKind metro_model_translator::identifyFile(const MFileObject &file, const char *buffer, short size) const
{
	MString name = file.name();
	MString ext = name.substring( name.rindex( '.' ), name.length() ).toLowerCase();
	if( ext != MString( ".model" ) )
		return MPxFileTranslator::kNotMyFileType;

	return MPxFileTranslator::kIsMyFileType;
}
    //---------------------------
	String DocumentExporter::mayaNameToColladaName(const MString& str, bool removeNamespace, bool removeFirstNamespace)
    {
        // Replace characters that are supported in Maya,
        // but not supported in collada names
        if ( str == 0 ) return EMPTY_STRING;

        // NathanM: Strip off namespace prefixes
        // TODO: Should really be exposed as an option in the Exporter
        MString mayaName;
        if ( removeNamespace )
        {
            int prefixIndex = str.rindex ( ':' );
            mayaName = ( prefixIndex < 0 ) ? str : str.substring ( prefixIndex + 1, str.length() );
        }
		else if (removeFirstNamespace)
		{
			// Keep potential '|' character at the beginning 
			bool startsWithVerticalLine = str.index('|') == 0;
			int colonIndex = str.index(':');
			mayaName = (colonIndex < 0) ? str : str.substring(colonIndex + 1, str.length());
			if (colonIndex >= 0 && startsWithVerticalLine)
			{
				mayaName = MString("|") + mayaName;
			}
		}
        else mayaName = str;

        const char* c = mayaName.asChar();
        uint length = mayaName.length();
        char* buffer = new char[length+1];

        // Replace offending characters by some that are supported within xml:
        // ':', '|' are replaced by '_'.
        // Ideally, these should be encoded as '%3A' for ':', etc. and decoded at import time.
        //
        for ( uint i = 0; i < length; ++i )
        {
            char d = c[i];

            if ( d == '|' || d == ':' || d == '/' || d == '\\' || d == '(' || d == ')' || d == '[' || d == ']' )
                d = '_';

            buffer[i] = d;
        }
        buffer[length] = '\0';

        MString mayaReturnString ( buffer );
        delete [] buffer;

        return COLLADABU::Utils::checkNCName( mayaReturnString.asChar() );
    }
MString ValveMaya::RemoveNameSpace( const MString &mString )
{
	const int cIndex( mString.rindex( ':' ) );
	if ( cIndex >= 0 )
	{
		const int l( mString.length() );
		if ( cIndex + 1 < l )
		{
			return mString.substring( cIndex + 1, l - 1 );
		}
	}

	return mString;
}
示例#4
0
bool isConnected(const char *attrName, MFnDependencyNode& depFn, bool dest, bool primaryChild = false)
{
    MStatus stat;
    MPlugArray pa;
    depFn.getConnections(pa);
    std::vector<std::string> stringParts;
    pystring::split(attrName, stringParts, ".");
    MString attName = attrName;
    if (stringParts.size() > 1)
        attName = stringParts.back().c_str();
    if (pystring::endswith(attrName, "]"))
    {
        int found = attName.rindex('[');
        if (found >= 0)
            attName = attName.substring(0, found-1);
    }

    for (uint pId = 0; pId < pa.length(); pId++)
    {
        if (dest)
        {
            if (!pa[pId].isDestination())
                continue;
        }
        else
        {
            if (!pa[pId].isSource())
                continue;
        }
        MPlug plug = pa[pId];
        if (primaryChild)
            while (plug.isChild())
                plug = plug.parent();
        MString plugName = plug.name();
        if (plug.isElement())
            plug = plug.array();
        MString attNameFromPlug = getAttributeNameFromPlug(plug);
        if ((attNameFromPlug == attName))
            return true;
    }
    return false;
}
示例#5
0
// *****************************************************************************
MStatus GtoIO::writer( const MFileObject &file, 
                       const MString &optionsString,
                       MPxFileTranslator::FileAccessMode mode )
{
    MTime fs = MAnimControl::currentTime(); 
    MTime fe = fs;
    double shutter = 0.0;
    MString filename = file.fullName();
    bool subd = false;
    bool normals = false;
    bool exportST = false;
    int maxRecurse = 1;
    bool normalize = false;
    bool hidden = true;
    bool verify = true;
    bool doAnim = false;
    bool diffPoints = false;
    bool diffMatrix = false;
    bool diffNormals = false;
    bool isDifferenceFile = false;
    bool quiet = false;
    bool allUserAttributes = false;
    bool allMayaAttributes = false;
    bool allXformAttributes = false;
    bool faceMaterials = false;
    bool ascii = false;

    if( ( mode == MPxFileTranslator::kExportAccessMode ) ||
        ( mode == MPxFileTranslator::kSaveAccessMode ) )
    {
        MGlobal::displayError( "The GTO plugin can only be used for Export "
                               "Selection...");
        return MS::kFailure;
    }

    MStringArray args;
    optionsString.split( ';', args );
    for( size_t i = 0; i < args.length(); ++i )
    {
        MStringArray thisArg;
        args[i].split( '=', thisArg );
        MString argName( thisArg[0] );
        MString argValue( thisArg[1] );

        if( argName == "recurse" && argValue == "1" )
        {
            maxRecurse = 100000;
        }
        else if( argName == "quiet" && argValue == "1" )
        {
            quiet = true;
        }
        else if( argName == "ascii" && argValue == "1" )
        {
            ascii = true;
        }
        else if( argName == "subd" && argValue == "1" )
        {
            subd = true;
        }
        else if( argName == "normals" && argValue == "1" )
        {
            normals = true;
        }
        else if( argName == "st" && argValue == "1" )
        {
            exportST = true;
        }
        else if( argName == "faceMat" && argValue == "1" )
        {
            faceMaterials = true;
        }
        else if( argName == "diffpositions" && argValue == "1" )
        {
            diffPoints = true;
        }
        else if( argName == "diffmatrices" && argValue == "1" )
        {
            diffMatrix = true;
        }
        else if( argName == "diffnormals" && argValue == "1" )
        {
            diffNormals = true;
        }
        else if( argName == "isdifference" && argValue == "1" )
        {
            isDifferenceFile = true;
        }
        else if( argName == "normalize" && argValue == "1" )
        {
            normalize = true;
        }
        else if( argName == "hidden" && argValue == "0" )
        {
            hidden = false;
        }
        else if( argName == "verify" && argValue == "0" )
        {
            verify = false;
        }
        else if( argName == "userAttr" && argValue == "1" )
        {
            allUserAttributes = true;
        }
        else if( argName == "mayaAttr" && argValue == "1" )
        {
            allMayaAttributes = true;
        }
        else if( argName == "xformAttr" && argValue == "1" )
        {
            allXformAttributes = true;
        }
        else if( argName == "anim" && argValue == "1" )
        {
            doAnim = true;
            // If user didn't include a # in the filename, but
            // is exporting multiple frames, do it automatically
            if( filename.index( '#' ) < 0 )
            {
                // By this point, Maya will have already appended a 
                // ".gto" to the filename if the user didn't include it,
                // so we're guaranteed to find a '.' in the filename
                filename = filename.substring( 0, filename.rindex( '.' ) )
                           + "#.gto";
            }
        }
        else if( argName == "fs" && doAnim )
        {
            fs = MTime( argValue.asDouble(), MTime::uiUnit() );
        }
        else if( argName == "fe" && doAnim  )
        {
            fe = MTime( argValue.asDouble(), MTime::uiUnit() );
        }
        else if( argName == "shutter" && doAnim )
        {
            shutter = argValue.asDouble() / 360.0;
        }
        else if( argName == "recurseLimit" )
        {
            if( argValue.asInt() > 0 )
            {
                maxRecurse = argValue.asInt();
            }
        }
    }
    
    if( ! isDifferenceFile )
    {
        diffPoints = false;
        diffMatrix = false;
        diffNormals = false;
    }
    
    // TODO: Find a more graceful way to get options to GtoExporter

    GtoExporter exporter( fs, fe, quiet, shutter, subd, normals, exportST, filename, 
                          maxRecurse, normalize, hidden, verify, 
                          isDifferenceFile, diffPoints, diffMatrix, 
                          diffNormals, allUserAttributes, allMayaAttributes, 
                          faceMaterials, ascii, allXformAttributes );

    MStatus result = exporter.doIt();
    return result;
}
    // --------------------------------------
    void ReferenceManager::processReference ( const MObject& referenceNode )
    {
        MStatus status;
        MFnDependencyNode referenceNodeFn ( referenceNode, &status );
        if (status != MStatus::kSuccess) return;

#if MAYA_API_VERSION >= 600
        MString referenceNodeName = MFnDependencyNode( referenceNode ).name();

        Reference* reference = new Reference();
        reference->referenceNode = referenceNode;
        mReferences.push_back ( reference );

        // Get the paths of the root transforms included in this reference
        MObjectArray subReferences;
        getRootObjects ( referenceNode, reference->paths, subReferences );
        uint pathCount = reference->paths.length();

        // Process the sub-references first
        uint subReferenceCount = subReferences.length();
        for (uint i = 0; i < subReferenceCount; ++i)
        {
            MObject& subReference = subReferences[i];
            if ( subReference != MObject::kNullObj ) processReference ( subReference );
        }

        // Retrieve the reference node's filename
        MString command = MString("reference -rfn \"") + referenceNodeFn.name() + MString("\" -q -filename;");
        MString filename;
        status = MGlobal::executeCommand ( command, filename );
        if (status != MStatus::kSuccess || filename.length() == 0) return;

        // Strip the filename of the multiple file token
        int stripIndex = filename.index('{');
        if (stripIndex != -1) filename = filename.substring(0, stripIndex - 1);

        // Avoid transform look-ups on COLLADA references.
        int extLocation = filename.rindex('.');
        if (extLocation > 0)
        {
            MString ext = filename.substring(extLocation + 1, filename.length() - 1).toLowerCase();
            if (ext == "dae" || ext == "xml") return;
        }

        // Check for already existing file information
        // Otherwise create a new file information sheet with current node names
        for ( ReferenceFileList::iterator it = mFiles.begin(); it != mFiles.end(); ++it )
        {
            if ((*it)->filename == filename) 
            { 
                reference->file = (*it); 
                break; 
            }
        }

        if ( reference->file == NULL ) reference->file = processReferenceFile(filename);

        // Get the list of the root transform's first child's unreferenced parents.
        // This is a list of the imported nodes!
        for (uint j = 0; j < pathCount; ++j)
        {
            MDagPath path = reference->paths[j];
            if (path.childCount() > 0)
            {
                path.push ( path.child(0) );
                MFnDagNode childNode ( path );
                if (!childNode.object().hasFn(MFn::kTransform)) continue;

                uint parentCount = childNode.parentCount();
                for (uint k = 0; k < parentCount; ++k)
                {
                    MFnDagNode parentNode(childNode.parent(k));
                    if (parentNode.object() == MObject::kNullObj || parentNode.isFromReferencedFile()) continue;

                    MDagPath parentPath = MDagPath::getAPathTo(parentNode.object());
                    if (parentPath.length() > 0)
                    {
                        ReferenceRootList::iterator it = 
                            reference->reroots.insert( reference->reroots.end(), ReferenceRoot() );
                        (*it).index = j;
                        (*it).reroot = parentPath;
                    }
                }
            }
        }
#endif
    }
示例#7
0
void cgfxVaryingParameter::setupAttributes( cgfxRCPtr<cgfxVertexAttribute>& vertexAttributes, CGprogram program)
{
	// Make sure our parameter name is acceptable is a Maya attribute name
	MString attrName = fName;
	int lastDot = attrName.rindex( '.');
	if( lastDot >= 0)
		attrName = attrName.substring( lastDot + 1, attrName.length() - 1);
	
    MString semanticName = cgGetParameterSemantic( fParameter);

    MString semantic(semanticName);
    cgGetParameterSemantic( fParameter);
	semantic.toUpperCase();

	// Is this varying parameter packed or atomic?
	CGtype type = cgGetNamedUserType( program, attrName.asChar());
	if( type != CG_UNKNOWN_TYPE)
	{
		// It's packed: explode the inputs into the structure elements
		CGcontext context = cgGetProgramContext( program); 
		CGparameter packing = cgCreateParameter( context, type);
		fVertexStructure = new cgfxVaryingParameterStructure();
		fVertexStructure->fLength = 0;
		fVertexStructure->fSize = 0;
		CGparameter element = cgGetFirstStructParameter( packing);
		while( element)
		{
			MString elementName = cgGetParameterName( element);
			int lastDot = elementName.rindex( '.');
			if( lastDot >= 0)
				elementName = elementName.substring( lastDot + 1, elementName.length() - 1);
			cgfxRCPtr<cgfxVertexAttribute> attr = setupAttribute( elementName, semantic, element, vertexAttributes);
			fVertexStructure->fElements[ fVertexStructure->fLength].fVertexAttribute = attr;
			int size = cgGetParameterRows( element) * cgGetParameterColumns( element);
			CGtype type = cgGetParameterBaseType( element);
			if( type == CG_FLOAT) size *= sizeof( GLfloat);
			else if( type == CG_INT) size *= sizeof( GLint);
			fVertexStructure->fElements[ fVertexStructure->fLength].fSize = size;
			fVertexStructure->fLength++;
			fVertexStructure->fSize += size;
			element = cgGetNextParameter( element);
		}
		cgDestroyParameter( packing); 
	}
	else
	{
		// It's atomic - create a single, simple input
		fVertexAttribute = setupAttribute( attrName, semantic, fParameter, vertexAttributes);
	}

	// Now pull apart the semantic string to work out where to bind
	// this value in open GL (as the automagic binding through cgGL
	// didn't work so well when this was written)
	int radix = 1;
	fGLIndex = 0;
	unsigned int length = semantic.length();
	const char* str = semantic.asChar();

	// If sematic is NULL then stop here, bug 327649
	if (length == 0) {
		 fGLType = glRegister::kUnknown;
		 return;
	}

	for(;;)
	{
		char c = str[ length - 1];
		if( c < '0' || c > '9') break;
		fGLIndex += radix * (c - '0');
		radix *= 10;
		--length;
	}
	if( semantic.length() != length)
		semantic = semantic.substring( 0, length - 1);
	
	// Determine the semantic and setup the gl binding type we should use
	// to set this parameter. If there's a sensible default value, set that
	// while we're here.
	// Note there is no need to set the source type, this gets determined
	// when the vertex attribute sources are analysed
	if( semantic == "POSITION")
	{
		fGLType = glRegister::kPosition;
		fVertexAttribute->fSourceName = "position";
	}
	else if( semantic == "NORMAL")
	{
		fGLType = glRegister::kNormal;
		if( fVertexAttribute.isNull() == false ) 
			fVertexAttribute->fSourceName = "normal";
	}
	else if( semantic == "TEXCOORD")
	{
		fGLType = glRegister::kTexCoord;
		if( fVertexAttribute.isNull() == false ) 
		{
			if( attrName.toLowerCase() == "tangent")
				fVertexAttribute->fSourceName = "tangent:map1";
			else if( attrName.toLowerCase() == "binormal")
				fVertexAttribute->fSourceName = "binormal:map1";
			else
				fVertexAttribute->fSourceName = "uv:map1";
		}
	}
	else if( semantic == "TANGENT")
	{
		fGLType = glRegister::kTexCoord;
		fGLIndex += 6; // TANGENT is TEXCOORD6
		if( fVertexAttribute.isNull() == false ) 
			fVertexAttribute->fSourceName = "tangent:map1";
	}
	else if( semantic == "BINORMAL")
	{
		fGLType = glRegister::kTexCoord;
		fGLIndex += 7; // BINORMAL is TEXCOORD7
		if( fVertexAttribute.isNull() == false ) 
			fVertexAttribute->fSourceName = "binormal:map1";
	}
	else if( semantic == "COLOR")
	{
		fGLType = fGLIndex == 1 ? glRegister::kSecondaryColor : glRegister::kColor;
	}
	else if( semantic == "ATTR")
	{
		fGLType = glRegister::kVertexAttrib;
        if( fVertexAttribute.isNull() == false ) 
        {
            fVertexAttribute->fSourceName = semanticName;
        }
	}
	else if( semantic == "PSIZE")
	{
		fGLType = glRegister::kVertexAttrib;
		fGLIndex = 6;
	}
	else
	{
		fGLType = glRegister::kUnknown;
	}
}
示例#8
0
MString cgfxFindFile(const MString& name, bool projectRelative)
{
	// Our result
	MString fileName;

	// Do we have an image to look for?
    if (name.length() > 0)
    {
		// Build a list of places we'll look for textures
		MString texturePath;

		// Add the standard Maya project paths
		MString workspace;
		MStatus status = MGlobal::executeCommand(MString("workspace -q -rd;"),
										workspace);
        if ( status == MS::kSuccess)
		{
			texturePath += workspace;
			texturePath += ";";
			texturePath += workspace;
			texturePath += "/textures;";
			texturePath += workspace;
			texturePath += "/images;";
			texturePath += workspace;
			texturePath += "/sourceimages";
		}

		// Finally, see if any CgFX environment variable paths are set
		char * cgfxPath = getenv("CGFX_TEXTURE_PATH");
		if (cgfxPath)
		{
            if (texturePath.length() > 0) {
                texturePath += ";";
            }
			texturePath += cgfxPath;
		}
		else
		{
			char * cgfxRoot = getenv("CGFX_ROOT");
			if (cgfxRoot)
			{
                if (texturePath.length() > 0) {
                    texturePath += ";";
                }
				texturePath += cgfxRoot;
				texturePath += "/textures/2D;";
				texturePath += cgfxRoot;
				texturePath += "/textures/cubemaps;";
				texturePath += cgfxRoot;
				texturePath += "/textures/3D;";
				texturePath += cgfxRoot;
				texturePath += "/textures/rectangles;";
				texturePath += cgfxRoot;
				texturePath += "/CgFX_Textures;";
				texturePath += cgfxRoot;
				texturePath += "/CgFX";
			}
		}

		OutputDebugString("CgFX texture path is: ");
		OutputDebugString(texturePath.asChar());
		OutputDebugString("\n");

	    fileName = cgfxFindFile(name, texturePath);

        int hasFile = fileName.length() > 0;

	    if (hasFile == 0)
        {
            // lets extract the filename and try it again...
            int idx = name.rindex('/');
            if (idx == -1)
                idx = name.rindex('\\');
            if (idx != -1)
            {
                MString filename = name.substring(idx+1,name.length()-1);
                fileName = cgfxFindFile(filename, texturePath);
                hasFile = fileName.length() > 0;
            }
        }
            
		// If we found the file and the user wants project relative, try
		// to strip the project directory off the front of our result
		if( hasFile && projectRelative)
		{
			if( fileName.length() > workspace.length() && 
				workspace.length() > 0 &&
				fileName.substring( 0, workspace.length() - 1) == workspace)
				// Strip the project path off the front INCLUDING the
				// separating '/' (otherwise we'd create an absolute path)
				fileName = fileName.substring( workspace.length(), fileName.length() - 1);
		}

        if (hasFile == 0)
		    OutputDebugString("Error: file not found.\n");
    }
    return fileName;
}