MStatus FileTranslator::writer ( const MFileObject& file,
                                     const MString& options,
                                     MPxFileTranslator::FileAccessMode mode )
    {
        MStatus status = MStatus::kFailure;

        try
        {
            // Extract the filename
#if defined (OSMac_)
            char nameBuffer[MAXPATHLEN];
            strcpy ( nameBuffer, file.fullName().asChar() );
            const MString fileName ( nameBuffer );
#else
            const MString fileName = file.fullName();
#endif // OSMac

            // TODO Export the referenced files!
            // Maya forces the write of all the references, on export.
            // Intentionally skip known reference file paths.
            for ( MItDependencyNodes it ( MFn::kReference ); !it.isDone(); it.next() )
            {
                MObject refNode = it.item();
                MString refNodeName = MFnDependencyNode ( refNode ).name();

                MString refNodeFilename;
                MGlobal::executeCommand ( MString ( "reference -rfn \"" ) + refNodeName + MString ( "\" -q -filename" ),
                                          refNodeFilename );

                if ( refNodeFilename == fileName ) return MStatus::kSuccess;

                if ( ExportOptions::exportXRefs() )
                {
                    // TODO Open file export dialog ( !? HOW ?! ) to get a DAE filename 
                    // to export the referenced file.
                    
                }
            }

            // Parse the export options
            ExportOptions::set ( options );

            // Check, if we should just export the selected Objects
            exportSelection = mode == MPxFileTranslator::kExportActiveAccessMode;

            // Do the actual export now
            status = exportIntoFile ( fileName, exportSelection );
        }
        catch ( COLLADASW::StreamWriterException* swException  )
        {
            String message = "StreamWriterException: " + swException->getMessage();
            MGlobal::displayError ( message.c_str() );
        }
        catch ( ... )
        {
            MGlobal::displayError ( "ColladaMaya has thrown an exception!" );
        }

        return status;
    }
Beispiel #2
0
MStatus ObjTranslator::writer ( const MFileObject& file,
                                const MString& options,
                                FileAccessMode mode )

{
    MStatus status;
    
    MString mname = file.fullName(), unitName;
   
//just pass in the filename

#if defined (OSMac_)
	char fname[256];//MAXPATHLEN];
	strcpy (fname, file.fullName().asChar());
//	fp = fopen(fname,"wb");//MAYAMACTODO
#else
    const char *fname = mname.asChar();
  //  fp = fopen(fname,"w");
#endif

shared_ptr<solver_impl_t> solv = solver_t::get_solver();

solv->export_collada_file(fname);

return status;

}
Beispiel #3
0
MStatus polyExporter::writer(const MFileObject& file,
							 const MString& /*options*/,
							 MPxFileTranslator::FileAccessMode mode) 
//Summary:	saves a file of a type supported by this translator by traversing
//			the all or selected objects (depending on mode) in the current
//			Maya scene, and writing a representation to the given file
//Args   :	file - object containing the pathname of the file to be written to
//			options - a string representation of any file options 
//			mode - the method used to write the file - export, or export active
//				   are valid values; method will fail for any other values 
//Returns:	MStatus::kSuccess if the export was successful;
//			MStatus::kFailure otherwise
{
	#if defined (OSMac_)
		char nameBuffer[MAXPATHLEN];
		strcpy (nameBuffer, file.fullName().asChar());
		const MString fileName(nameBuffer);
	#else
		const MString fileName = file.fullName();
	#endif

	ofstream newFile(fileName.asChar(), ios::out);
	if (!newFile) {
		MGlobal::displayError(fileName + ": could not be opened for reading");
		return MS::kFailure;
	}
	newFile.setf(ios::unitbuf);

	writeHeader(newFile);

	//check which objects are to be exported, and invoke the corresponding
	//methods; only 'export all' and 'export selection' are allowed
	//
	if (MPxFileTranslator::kExportAccessMode == mode) {
		if (MStatus::kFailure == exportAll(newFile)) {
			return MStatus::kFailure;
		}
	} else if (MPxFileTranslator::kExportActiveAccessMode == mode) {
		if (MStatus::kFailure == exportSelection(newFile)) {
			return MStatus::kFailure;
		}
	} else {
		return MStatus::kFailure;
	}

	writeFooter(newFile);
	newFile.flush();
	newFile.close();

	MGlobal::displayInfo("Export to " + fileName + " successful!");
	return MS::kSuccess;
}
    MStatus FileTranslator::reader ( const MFileObject& file,
                                     const MString& options,
                                     MPxFileTranslator::FileAccessMode mode )
    {
        MStatus status ( MS::kSuccess );

        try
        {
#if MAYA_API_VERSION >= 800

            if ( mode == MPxFileTranslator::kReferenceAccessMode )
            {
                int optionValue;
                MGlobal::executeCommand ( "optionVar -q \"referenceOptionsSharedReference\";", optionValue );

                if ( optionValue != 0 )
                {
#ifdef WIN32
                    MessageBox ( NULL, "Maya may now hang. Do disable the reference option named: \"Shared Reference Nodes\".", "POSSIBLE HANG", MB_OK );
#endif
                }
            }

#endif // Maya 8.0 and 8.5


#if defined (OSMac_)
            char nameBuffer[MAXPATHLEN];
            strcpy ( nameBuffer, file.fullName().asChar() );
            const MString filename ( nameBuffer );
#else
            const MString filename = file.fullName();
#endif  // OSMac

            // Process the import options
            ImportOptions::set ( options, mode );
            if (ImportOptions::hasError()) status = MStatus::kFailure;

            // Import the COLLADA DAE file
			status = importFromFile ( filename.asChar() );
        }
        catch ( COLLADABU::Exception* exception  )
        {
            MGlobal::displayWarning ( exception->getMessage().c_str() );
        }
        catch ( ... )
        {
            MGlobal::displayWarning ( "ColladaMaya has thrown an exception!" );
        }

        return status;
    }
Beispiel #5
0
MStatus CXRayObjectExport::writer ( const MFileObject& file, const MString& options, FileAccessMode mode )
{
	MStatus status= MS::kFailure;

	//move default extesion here..
	MString mname = file.fullName()+".object";
	LPCSTR	fname = mname.asChar();

	Log("Export object: ",fname);
	CEditableObject* OBJECT = new CEditableObject(fname);
	OBJECT->SetVersionToCurrent(TRUE,TRUE);
	if((mode==MPxFileTranslator::kExportAccessMode)||(mode==MPxFileTranslator::kSaveAccessMode)){
		status = ExportAll(OBJECT)?MS::kSuccess:MS::kFailure;
	}else if(mode==MPxFileTranslator::kExportActiveAccessMode){
		status = ExportSelected(OBJECT)?MS::kSuccess:MS::kFailure;
	}
	if (MS::kSuccess==status){ 
		OBJECT->Optimize	();
		OBJECT->SaveObject	(fname);
		Log("Object succesfully exported.");
		Msg("%d vertices, %d faces", OBJECT->GetVertexCount(), OBJECT->GetFaceCount());
	}else{
		Log("! Export failed.");
	}
	xr_delete(OBJECT);

	return status;
}
//
// Maya calls this method to have the translator write out a file.
//
MStatus colorTransformDataTranslator::writer(
		const MFileObject& file,
		const MString& /* options */,
		MPxFileTranslator::FileAccessMode mode
)
{
	//
	// For simplicity, we only do full saves/exports.
	//
	if ((mode != kSaveAccessMode) && (mode != kExportAccessMode))
	   	return MS::kNotImplemented;

	//
	// Let's see if we can open the output file.
	//
	fstream	output(file.fullName().asChar(), ios::out | ios::trunc);

	if (!output.good()) return MS::kNotFound;

    writeColorSpaceForNodes(output);
    writeOutputTransformId(output);
    writeColorTransformData(output);

	output.close();

	return MS::kSuccess;
}
    MStatus writer (const MFileObject& file, const MString& optionsString, MPxFileTranslator::FileAccessMode mode)
    {
        AFX_MANAGE_STATE(AfxGetStaticModuleState());
        
        CMayaInterface mayaInterface;

        if (!mayaInterface.Create (mode == MPxFileTranslator::kExportActiveAccessMode))
        {
            MGlobal::displayError("Failed to initialize cal3d CMayaInterface.");
            return MS::kFailure;
        }

        // create an exporter instance
        if(!theExporter.Create(&mayaInterface))
        {
            MGlobal::displayError(theExporter.GetLastError().c_str());
            return MS::kFailure;
        }

        if (!theExporter.ExportSkeleton (file.fullName().asChar()))
        {
            MGlobal::displayError(theExporter.GetLastError().c_str());
            return MS::kFailure;
        }
        
        return MS::kSuccess;
    }
Beispiel #8
0
MStatus BinMeshTranslator::reader(const MFileObject& file,
							 const MString& opts,
							 MPxFileTranslator::FileAccessMode mode) 
{
	options = opts;
	#if defined (OSMac_)
		char nameBuffer[MAXPATHLEN];
		strcpy (nameBuffer, file.fullName().asChar());
		fileName(nameBuffer);
	#else
		fileName = file.fullName();
	#endif
	
	MGlobal::displayInfo("Options " + options);
	
	return this->importObjects();
}
//This routine is called by Maya when it is necessary to load a file of a type supported by this translator.
//Responsible for reading the contents of the given file, and creating Maya objects via API or MEL calls to reflect the data in the file.
MStatus NifTranslator::reader(const MFileObject& file, const MString& optionsString, MPxFileTranslator::FileAccessMode mode)
{
	NifTranslatorDataRef translator_data(new NifTranslatorData());
	NifTranslatorOptionsRef translator_options(new NifTranslatorOptions());
	NifTranslatorUtilsRef translator_utils(new NifTranslatorUtils(translator_data, translator_options));
	NifImportingFixtureRef importer;

	ImportType import_type = ImportType::Default;
	Header file_header = ReadHeader(file.fullName().asChar());

	vector<string> block_types = file_header.getBlockTypes();
	vector<unsigned short> block_types_index = file_header.getBlockTypeIndex();

	translator_options->ParseOptionsString(optionsString);

	if (block_types[block_types_index[0]] == NiControllerSequence::TYPE.GetTypeName())
	{
		import_type = ImportType::AnimationKF;
	}
	else if (file_header.getUserVersion() == 12 && file_header.getUserVersion2() == 83)
	{
		import_type = ImportType::SkyrimFallout;
	} else if (file_header.getUserVersion() == 12  && file_header.getUserVersion2() == 130)
	{
		import_type = ImportType::Fallout4;
	}
	else
	{
		for (int i = 0; i < block_types.size(); i++)
		{
			if (block_types[i] == BSDismemberSkinInstance::TYPE.GetTypeName() || block_types[i] == BSShaderTextureSet::TYPE.GetTypeName())
			{
				import_type = ImportType::SkyrimFallout;
			}
		}
	}

	if (import_type == ImportType::AnimationKF)
	{
		importer = new NifKFImportingFixture(translator_options, translator_data, translator_utils);
	}
	else if (import_type == ImportType::SkyrimFallout)
	{
		importer = new NifImportingFixtureSkyrim(translator_options, translator_data, translator_utils);
	} else if (import_type == ImportType::Fallout4)
	{
		importer = new NifImportingFixtureFallout4(translator_options, translator_data, translator_utils);
	}
	else if (import_type == ImportType::Default)
	{
		importer = new NifDefaultImportingFixture(translator_data, translator_options, translator_utils);
	} 

	return importer->ReadNodes(file);
}
Beispiel #10
0
    MStatus writer (const MFileObject& dest_path, const MString& options, FileAccessMode mode) try
    {
      std::ofstream file (dest_path.fullName ().asChar ());
      if (!file)
        throw std::runtime_error ("Error opening output file");


    }
    catch (std::exception& e)
    {
      MGlobal::displayError (e.what ());
      return MS::kFailure;
    }
MStatus eae6320::cMayaMeshExporter::writer( const MFileObject& i_file, const MString& i_options, FileAccessMode i_mode )
{
    MStatus status;

    // Gather the vertex and index buffer information
    std::map<std::string, sVertex_maya> uniqueVertices;
    std::vector<sTriangle> triangles;
    std::vector<MObject> shadingGroups;
    {
        // The user decides whether to export the entire scene or just a selection
        if ( i_mode == MPxFileTranslator::kExportAccessMode )
        {
            status = ProcessAllMeshes( uniqueVertices, triangles, shadingGroups );
            if ( !status )
            {
                return status;
            }
        }
        else if ( i_mode == MPxFileTranslator::kExportActiveAccessMode )
        {
            status = ProcessSelectedMeshes( uniqueVertices, triangles, shadingGroups );
            if ( !status )
            {
                return status;
            }
        }
        else
        {
            MGlobal::displayError( "Unexpected file access mode" );
            return MStatus::kFailure;
        }
    }

    // Convert the mesh information to vertex and index buffers
    std::vector<sVertex_maya> vertexBuffer;
    std::vector<size_t> indexBuffer;
    std::vector<sMaterialInfo> materialInfo;
    {
        status = FillVertexAndIndexBuffer( uniqueVertices, shadingGroups, triangles, vertexBuffer, indexBuffer, materialInfo );
        if ( !status )
        {
            return status;
        }
    }

    // Write the mesh to the requested file
    {
        const MString filePath = i_file.fullName();
        return WriteMeshToFile( filePath, vertexBuffer, indexBuffer, materialInfo );
    }
}
Beispiel #12
0
MStatus BinMeshTranslator::writer(const MFileObject& file,
							 const MString& opts,
							 MPxFileTranslator::FileAccessMode mode) 
//Summary:	saves a file of a type supported by this translator by traversing
//			the all or selected objects (depending on mode) in the current
//			Maya scene, and writing a representation to the given file
//Args   :	file - object containing the pathname of the file to be written to
//			options - a string representation of any file options 
//			mode - the method used to write the file - export, or export active
//				   are valid values; method will fail for any other values 
//Returns:	MStatus::kSuccess if the export was successful;
//			MStatus::kFailure otherwise
{
	options = opts;
	#if defined (OSMac_)
		char nameBuffer[MAXPATHLEN];
		strcpy (nameBuffer, file.fullName().asChar());
		fileName(nameBuffer);
	#else
		fileName = file.fullName();
	#endif

	if (MPxFileTranslator::kExportAccessMode == mode) 
	{
		MGlobal::displayInfo("writer - export all.");
		return exportObjects("all");
	}

	if (MPxFileTranslator::kExportActiveAccessMode == mode) 
	{
		MGlobal::displayInfo("writer - export selected.");
		return exportObjects("selected");
	}

	return MS::kSuccess;
}
Beispiel #13
0
MStatus AnmExporter::writer(const MFileObject& file, 
                         const MString& /*options*/, 
                         MPxFileTranslator::FileAccessMode mode) 
{
    if (MPxFileTranslator::kExportAccessMode != mode)
    {
        MGlobal::displayInfo("AnmExporter: only support \"export all\" \n(will export from start to end time)");
        return MStatus::kFailure;
    }

    #if defined (OSMac_)
        FAILURE("Sorry guys, I hate Apple.");
        /*
        char name_buffer[MAXPATHLEN];
        strcpy(name_buffer, file.fullName().asChar());
        const MString file_name(nameBuffer);
        */
    #else
        const MString file_name = file.fullName();
    #endif

    ofstream fout(file_name.asChar(), ios::binary);

    if (!fout)
        FAILURE("AnmExporter: " + file_name + " : could not be opened for reading");

    AnmWriter *writer = new AnmWriter();

    if (MStatus::kFailure == writer->dumpData())
    {
        delete writer;
        FAILURE("AnmExporter: writer->dumpData(): failed");
    }
    if (MStatus::kFailure == writer->write(fout))
    {
        delete writer;
        FAILURE("AnmExporter: writer->write(" + file_name + "); failed");
    }

    fout.flush();
    fout.close();
    delete writer;

    MGlobal::displayInfo("AnmExporter: export successful!");
    
    return MS::kSuccess;
}
Beispiel #14
0
/*
 * Helper method for obtaining the two filenames.
 */
void get_filenames(const MFileObject& file, MString & topology_filename, MString & configuration_filename, MString & vhelix_filename) {
    const MString filename(file.fullName());

    int extension = filename.rindexW("." HELIX_OXDNA_CONF_FILE_TYPE);

    if (extension != int(filename.length()) - int(strlen(HELIX_OXDNA_CONF_FILE_TYPE)) - 1) {
        extension = filename.rindexW("." HELIX_OXDNA_TOP_FILE_TYPE);

        if (extension != int(filename.length()) - int(strlen(HELIX_OXDNA_TOP_FILE_TYPE)) - 1)
            extension = -1;
    }

    const MString stripped_filename(filename.asChar(), extension != -1 ? extension : filename.length());
    configuration_filename = stripped_filename + "." HELIX_OXDNA_CONF_FILE_TYPE;
    topology_filename = stripped_filename + "." HELIX_OXDNA_TOP_FILE_TYPE;
    vhelix_filename = stripped_filename + "." HELIX_OXDNA_VHELIX_FILE_TYPE;
}
MStatus DCTranslator::writer(
	const MFileObject &file,
	const MString &,
	MPxFileTranslator::FileAccessMode mode)
{
	MString fileName = file.fullName();
	m_ExportPath = file.path();
	MString pathInfo = "Export Model Path: ";
	MGlobal::displayInfo(pathInfo + m_ExportPath);
	MGlobal::displayInfo("Exporting Mesh...\n");

	m_MeshFilePtr = GetIODevice<File>();
	//m_PhysxAssetFilePtr = GetIODevice<File>();
	if (m_MeshFilePtr->Open(fileName.asChar(), IOWrite)) {
		//m_PhysxAssetFilePtr->Open((fileName+".pxasset").asChar(), IOWrite);
		m_MeshArch = new Archive;
		m_MeshArch->SetIODevice(m_MeshFilePtr);
		//////         write the header            ///////
		MeshHeader header;
		header.Version = VERSION_1_1;
		//////
		(*m_MeshArch) << header;

		if ((mode == MPxFileTranslator::kExportAccessMode) ||
			(mode == MPxFileTranslator::kSaveAccessMode))
		{
			exportAll();
		}
		else if (mode == MPxFileTranslator::kExportActiveAccessMode)
		{
			exportSelected();
		}

		char EndCode[64] = "End";
		m_MeshFilePtr->Write(EndCode, 64);
		m_MeshFilePtr->Close();
		delete m_MeshFilePtr;
		m_MeshFilePtr = 0;

		return MS::kSuccess;
	}
	else {
		return MStatus::kFailure;
	}
}
Beispiel #16
0
MPxFileTranslator::MFileKind usdTranslatorExport::identifyFile(
    const MFileObject &fileName,
    const char*,
    short) const {

    MFileKind retValue = kNotMyFileType;
    MString fName = fileName.fullName();
    int sLen=fName.length();
    if (sLen>5) {
        if (fName.substring(sLen-4, sLen-1)==".usd" || 
            fName.substring(sLen-5, sLen-1)==".usda" ||
            fName.substring(sLen-5, sLen-1)==".usdb" ||
            fName.substring(sLen-5, sLen-1)==".usdc") {
            retValue = kIsMyFileType;
        }
    }
    return retValue;
}
MStatus CVsDmxIOTranslator::reader(
  const MFileObject &i_mFileObject,
  const MString &i_optionsString,
  const FileAccessMode i_fileAccessMode )
{
	MString cmd( "vsDmxIO -import" );

	if ( i_optionsString.length() )
	{
		MStringArray options;
		if ( !i_optionsString.split( ';', options ) )
		{
			merr << "Can't split " << s_name << " translator arguments" << std::endl;
			return MS::kFailure;
		}

		for ( unsigned oi( 0 ); oi < options.length(); ++oi )
		{
			MStringArray keyValue;
			if ( options[ oi ].split( '=', keyValue ) && keyValue.length() == 2 )
			{
				const MString &key( keyValue[ 0 ] );
				const MString &val( keyValue[ 1 ] );

				if ( key == "timeOffset" )
				{
					cmd += " -timeOffset ";
					cmd += val.asDouble();
					continue;
				}
			}	
		}
	}

	cmd += " -filename \"";
	cmd += i_mFileObject.fullName();
	cmd += "\";";

	return MGlobal::executeCommand( cmd, true, true );
}
MStatus	
XFileTranslator::writer(
			const MFileObject& mfoXFile,			// save file object
			const MString& msOptions,				// options string
			MPxFileTranslator::FileAccessMode mode)	// options string
{
	HRESULT hr = S_OK;
	MStatus stat = MS::kSuccess;

	MString	msFile= mfoXFile.fullName();

	hr= g_PreviewPipeline.Scene_Export(msFile.asChar(), msOptions.asChar(), mode);
	if(FAILED(hr))
	{
		stat= MS::kFailure;
		goto e_Exit;
	};


e_Exit:
	return stat;
}
Beispiel #19
0
// An LEP file is an ascii whose first line contains the string <LEP>.
// The read does not support comments, and assumes that the each
// subsequent line of the file contains a valid MEL command that can
// be executed via the "executeCommand" method of the MGlobal class.
//
MStatus LepTranslator::reader ( const MFileObject& file,
                                const MString& options,
                                MPxFileTranslator::FileAccessMode mode)
{    
    const MString fname = file.fullName();

    MStatus rval(MS::kSuccess);
    const int maxLineSize = 1024;
    char buf[maxLineSize];

    ifstream inputfile(fname.asChar(), ios::in);
    if (!inputfile) {
        // open failed
        cerr << fname << ": could not be opened for reading\n";
        return MS::kFailure;
    }

    if (!inputfile.getline (buf, maxLineSize)) {
        cerr << "file " << fname << " contained no lines ... aborting\n";
        return MS::kFailure;
    }

    if (0 != strncmp(buf, magic.asChar(), magic.length())) {
        cerr << "first line of file " << fname;
        cerr << " did not contain " << magic.asChar() << " ... aborting\n";
        return MS::kFailure;
    }

    while (inputfile.getline (buf, maxLineSize)) {
        MString cmdString;

        cmdString.set(buf);
        if (!MGlobal::executeCommand(cmdString))
            rval = MS::kFailure;
    }
    inputfile.close();

    return rval;
}
	MStatus JSONTranslator::reader (const MFileObject& file, const MString & options, MPxFileTranslator::FileAccessMode mode) {
		return m_operator.parseFile(file.fullName().asChar());
	}
Beispiel #21
0
// *****************************************************************************
MStatus GtoIO::reader( const MFileObject &file, 
                       const MString &optionsString,
                       MPxFileTranslator::FileAccessMode mode )
{
    MString filename = file.fullName();
    bool readAsDifference = false;
    int fs = 0;
    int fe = 0;

    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 == "readDiff" && argValue == "1" )
        {
            readAsDifference = true;
        }
        else if( argName == "fs" )
        {
            fs = argValue.asInt();
        }
        else if( argName == "fe" )
        {
            fe = argValue.asInt();
        }
    }

    if( readAsDifference )
    {
        MGlobal::displayInfo( "PreMunge name: " + filename );

        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.index( '.' ) )
                       + "#.gto";
        }

        for( int f = fs; f <= fe; ++f )
        {
            MGlobal::viewFrame( MTime( double(f) ) );

            MString fname = replaceFrameCookies( filename, f );

            MGlobal::displayInfo( "Reading " + fname );

            DataBase dataBase;
            Set *set = dataBase.set( fname.asChar() );
            if( set == NULL )
            {
                MGlobal::displayError( "Unable to open file for some "
                                       "reason.  Permissions?" );
                return MS::kFailure;
            }

            set->computeLocalTransforms();

            set->declareMayaDiff();

            dataBase.destroyAll();
        }
    }
    else
    {
        DataBase dataBase;
        Set *set = dataBase.set( filename.asChar() );
        if( set == NULL )
        {
            MGlobal::displayError( "Unable to open file for some "
                                   "reason.  Permissions?" );
            return MS::kFailure;
        }

        set->computeLocalTransforms();

        set->declareMaya();

        set->reparentAll();

        dataBase.destroyAll();
    }

    return MS::kSuccess;
}
Beispiel #22
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;
}
MStatus MayaFileTranslator::writer( 	const MFileObject& file,
const MString& options,
FileAccessMode mode){

//-------------------détection des options transmises par le script MEL---------------


	// this will store our option strings
	MStringArray optionList;

	// seperate the option string
	options.split(' ', optionList);

	
	// check all of the options
	int len = optionList.length();

	for( int i = 0; i < len; ++i ){
  		MString Option = optionList[i];

	

		// if we recognised option 1
		if( Option == "vertexcolorFlag" ) {
  			// check for true or false
			if(optionList[++i]=="0")
				Flags.vertex_colors=0;
			else
				Flags.vertex_colors=1;

		}

		// if we recognised our second option
		if( Option == "vertexnormalFlag" ) {
  		// check for true or false
			if(optionList[++i]=="0")
				Flags.Normals=0;
			else
  				Flags.Normals=1;

		}



		// if we recognised our third option
		if( Option == "brushFX" ) {
  			// check for true or false
			if(optionList[++i]=="0")
				Flags.use_vertex_colors=1;
			else
  				Flags.use_vertex_colors=0;

		}
		
	}

	//----------------------------------fin------------------------

	//export Selected Objects
    if(mode == kExportActiveAccessMode) 
	{
		//liste des objets sélectionnés
		MSelectionList selection;
		MGlobal::getActiveSelectionList( selection );
		
		//MStringArray strings;
		//MDagPath dagPath;

			MObject components;
			MDagPath path;

		//-----

//		int temp;
		//MGlobal::displayInfo("Début exportation des objets sélectionnés");
		// ouverture du fichier [BB3D]
		MString output_filename = file.fullName();
		::output.open(output_filename.asChar(),ios::out |ios::binary);
		// ecriture header fichier
		
		::output << "BB3D"; // mise en place du Header fichier B3D
		StartChunck();

		// sauv garde de la position du début de fichier
		//write_int(1);// mise en place d'une valeur entière quelconque pour mise en place ultérieure de la longeur du fichier
		write_int(1);//écriture de la version BB3D
	

#ifdef OLD_TEXS
		// écriture des textures si présentent [TEXS]|detection des textures à enregistrer| + fermeture texs
::output << "TEXS";//header Brush
								StartChunck();
		OutputTextures(selection);
EndChunck();

		// écriture des matériaux [BRUS]|detection des materiaux à enregistrer| +fermeture brus
	
		
//Matid.clear();
		
OutputMaterials(selection);

#else

		//nouvelles textures

#endif	
		
	//------------------------------------fin materials----------------------------------


#ifdef SCENE_ROOT
		// algo des nodes [NODE] réplication de la hierarchie, 
		::output << "NODE"; // mise en place du Header fichier B3D
		StartChunck();
		

		//write_int(1);// mise en place d'une valeur quelconque
		::output << "Scene Root";//nom du Node
		::output << char(0x00);//fin de chaîne

		//écriture des coordonnées spatiales
		//transaltion
		write_float(0);// translation x
		write_float(0);// translation y
		write_float(0);// translation z
		
		write_float(1);//scale x
		write_float(1);//scale y
		write_float(1);//scale z
		
		write_float(0);// rotation  x
		write_float(0);// rotation  y
		write_float(0);// rotation  z
		write_float(0);// rotation  w
		
#else
#endif
		



		int pos_objet=0,pos_nouvel_objet;
		MString nom_objet_precedent;


 	

		// create an iterator to go through all transforms
		//MItDag it(MItDag::depth, MFn::kTransform); 
		MItDag it(MItDag::kDepthFirst, MFn::kTransform);
		// keep looping until done
		int position_hierarchie=0;
		int pos=0;
		while(!it.isDone())
		{
  				MString temp;
				MDagPath path;
				it.getPath(path);
				MFnTransform trans(path);	
				MObject obj=it.item();

	
			
		

				MStringArray chemin_split;
			MString chemin=path.fullPathName();

		
			chemin.split((char)'|',chemin_split);

			pos=chemin_split.length();
			//temp=pos;

			//MGlobal::displayInfo(temp);
		
			if(obj.apiType()== MFn::kTransform && path.child(0).apiType()== MFn::kMesh){
						//MGlobal::displayInfo("Transform trouvé avec child Kmesh");
						//écriture du node avec transform
						//incrément de la hierarchie
						if(pos<position_hierarchie || pos==position_hierarchie){
							//MGlobal::displayInfo("fermeture des nodes précédents");
							for(int i=position_hierarchie;i>pos-1;i--){
							//temp = i;
							//MGlobal::displayInfo(temp);

							EndChunck();
							}//fin for
						
						}//fin if
							
								//MGlobal::displayInfo("Ouverture node");
								::output << "NODE"; // mise en place du Header node
								StartChunck();
								MString nom_objet;
								nom_objet=chemin_split[chemin_split.length()-1];
								
							
									::output << nom_objet.substring(0,nom_objet.length());//nom du Node
								
									::output << char(0x00);//caractêre de fin de chaîne


									
			

			
MVector Translation;
				// get the transforms local translation
		
Translation = trans.getTranslation(MSpace::kTransform);
		
			
			float temp=(float)Translation.x;
			//écriture des coordonnées spaciales
			//transaltion
			write_float(temp);// translation x
			temp=(float)Translation.y;
			write_float(temp);// translation y
			temp=-(float)Translation.z;
			write_float(temp);// translation z
			
				
			double scale[3];
			trans.getScale(scale);
			temp=(float)scale[0];
			write_float(temp);
			temp=(float)scale[1];
			write_float(temp);
			temp=(float)scale[2];
			write_float(temp);

			
			MQuaternion Rotation;
			
			trans.getRotation(Rotation,MSpace::kTransform);



			temp=(float)Rotation.w;
			write_float(temp);
			temp=(float)Rotation.x;
			write_float(temp);
			temp=(float)Rotation.y;
			write_float(temp);
			temp=(float)Rotation.z; 
			write_float(temp);

		


							
		
			


						path.getPath(path);
						if(selection.hasItem(path)!=MStatus::kSuccess){
							//MGlobal::displayInfo("présent dans la liste de selection");
							
							//---------exportation du mesh

						//mais avec des nodes vides, pour les mesh non sélectionnés
					//----------------------------ecriture mesh si objet polygonal présent
						::output << "MESH"; // mise en place du Header mesh
						StartChunck();
										MPointArray vertexArray;// coordonnées des point format double x,y,z;
										MIntArray vertexList;// stockage des indexs des points pour les triangles
										MVector Normal;//stockage d'une normal d'un vertex
		
						//----------------------coordonnées Vertexs  (normal & color si présent et demandés)
						//master brush
						//write_int(0xffffffff);
						write_int(-1);//-1 master brush
						
						MFnMesh meshFn(path.child(0)); // crée une fonction pour le mesh
										
						MItMeshVertex polyperVertex(path, MObject::kNullObj);// crée une fonction pour le mesh , mais avec les fonctions de itmesh
						
						//récupération des coordonnées des points
						//obtient les coordonnées des vertex en mode global
						//meshFn.getPoints(vertexArray,MSpace::kObject);
						meshFn.getPoints(vertexArray,MSpace::kTransform);

						//MFloatArray uArray;
						//MFloatArray vArray;

						//meshFn.getUVs(uArray,vArray);//getUVs( MFloatArray& uArray, MFloatArray& vArray,const MString * uvSet = NULL )
						
						MIntArray uvCounts,uvIds;

						meshFn.getAssignedUVs(uvCounts,uvIds,0);



						//ecriture VRTS
						::output<<"VRTS";
						StartChunck();

										//flags 0=none just vertices coords 1=normal values present, 2=rgba values present
										//The way the flags work, is that you combine them.
										//1 = Vertex Normal
										//2 = Vertex Color
										//3 = Vertex Normal + Color
int flag_normal_colors=0;
//info = "Normals ";
//info += Flags.Normals;
//Affich(info);
//info = "vertex colors ";
//info += Flags.vertex_colors;
//Affich(info);
flag_normal_colors = Flags.Normals+((Flags.use_vertex_colors && Flags.vertex_colors)*2);
//info = flag_normal_colors;
//Affich(info);
						write_int(flag_normal_colors);//présence normale
						
						//int tex_coord_sets          ;texture coords per vertex (eg: 1 for simple U/V) max=8
						write_int(1);//uv simple
						//  int tex_coord_set_size      ;components per set (eg: 2 for simple U/V) max=4
						write_int(2);//2 coordonées textures






										
										




						float x,y,z,normx,normy,normz;//,normx,normy,normz;
						for (unsigned int i=0;i<vertexArray.length();i++){


							x =float(vertexArray[i].x); // -  pour replacer l'axe X dans le sens de celui de blitz
							y =float(vertexArray[i].y);
							z =-float(vertexArray[i].z);// -



							//vertices coords

							write_float(x);
							write_float(y);
							write_float(z);

							//récupère la normale du point
							if(flag_normal_colors==1 || flag_normal_colors==3){
											meshFn.getVertexNormal(i, Normal ,MSpace::kObject);
											normx=float(Normal.x);
											normy=float(Normal.y);
											normz=float(Normal.z);

											
											
											write_float(normx);
											write_float(normy);
											write_float(normz);
							}
											


							//-----------------------------------------
											//vertex_colors_present=1;
											
											if (flag_normal_colors == 2 || flag_normal_colors==3){
											
											
											MStringArray colorsets;
											MColorArray color;
											
											//status = meshFn.getColorSetNames(colorsets);
											meshFn.getColorSetNames(colorsets);
										
												   
												MColor couleur;
												MString colorset = colorsets[0];
												//récupère la couleur moyenne des faces connectés au point
												meshFn.getVertexColors(color,&colorset);

												
												
												
												//polyperVertex.getColor
												//int a;
												//meshFn.getColor(a,couleur);
												//meshFn.getColors(color);
												couleur=color[i];
												float col=float(couleur.r);
												//R
												::output.write((char*)&couleur.r,sizeof(couleur.r));
												//write_float(col);
												col=float(couleur.g);
												//G
												::output.write((char*)&couleur.g,sizeof(couleur.g));
												//write_float(col);
												col=float(couleur.b);
												//B
												::output.write((char*)&couleur.b,sizeof(couleur.b));
												//write_float(col);
												col=float(couleur.a);
												//Alpha
												::output.write((char*)&couleur.a,sizeof(couleur.a));
												//write_float(col);
											
											
											
											}
											//-----------------------------------------
											

//float tempo;
float u,v;

MFloatArray uArray;
MFloatArray vArray;
MIntArray FaceIds;

polyperVertex.getUVs(uArray,vArray,FaceIds);

//meshFn.getUV(i*2,u,v);

u=uArray[0];
v=vArray[0];



//tempo = uArray[0];
//write_float(tempo);

//tempo = vArray[0];
//write_float(tempo);

write_float(u);
write_float(-v);


polyperVertex.next();













						}//fin for

	

						//-----------------fermeture coordonées Vertex
						EndChunck();
						// ----------------------------------export des triangles


#ifdef OLD_TRIS

							//ecriture TRIS
						::output<<"TRIS";
						StartChunck();

										//brush ID
										write_int(-1);//write_int(0);




										//MItMeshPolygon  itPolygon( path, MObject::kNullObj );
										MItMeshPolygon  itPolygon(path.child(0));

	

										for ( /* nothing */; !itPolygon.isDone(); itPolygon.next() )
										{		
					
	

											// Get triangulation of this poly.
											int  numTriangles; 
											itPolygon.numTriangles(numTriangles);

											while ( numTriangles-- )
											{
												//MGlobal::displayInfo("  triangle");
												MStatus status;

												MIntArray                           polygonVertices;

												itPolygon.getVertices( polygonVertices );

												MPointArray                     nonTweaked;
												// object-relative vertex indices for each triangle
												MIntArray                       triangleVertices;
												// face-relative vertex indices for each triangle
												MIntArray                       localIndex;

												status = itPolygon.getTriangle( numTriangles,
												nonTweaked,
												triangleVertices,
												MSpace::kObject );
		
												if ( status == MS::kSuccess )
												{



													//traitement du triangle
			
													// Get face-relative vertex indices for this triangle

			
													//int temp=triangleVertices[0];
						
						
													write_int(triangleVertices[0]);
													write_int(triangleVertices[2]);
													write_int(triangleVertices[1]);
													//::output.write((char*)&triangleVertices[0],sizeof(triangleVertices[0]));
													//::output.write((char*)&triangleVertices[2],sizeof(triangleVertices[2]));
													//::output.write((char*)&triangleVertices[1],sizeof(triangleVertices[1]));
			
			

												} // fin if	


											};// fin while



									}; //fin for

										EndChunck();

#else

			

	unsigned int instancenumbers;
	MObjectArray shaders;
	MIntArray indices;
	//MFnMesh		Fn(path.instanceNumber);
	meshFn.getConnectedShaders(instancenumbers,shaders,indices);
	MString info="shaders.lenght ";
	info += shaders.length();
	Affich(info);

	for (int i=-1;i<shaders.length();i++){//création de tris en fonction du nombre de brush appliqué
		//___________ouput tris________
	
		info = "shader ";
		info += i;
	Affich(info);

							//ecriture TRIS
						::output<<"TRIS";
						StartChunck();
						


	//trouver le brush id par rapport à matid
	//recup nom shader et compare à matid
	MString nameshader;
	nameshader=GetShaderName(shaders[i]);

	info = "Matid id lenght";
	info += Matid.length();
	Affich(info);

int BrushId=0;
	for (int b=0;b<Matid.length();b++){
		if (nameshader==Matid[b]){
		BrushId=b;
		}	
	}

							//brush ID
						write_int(BrushId);
						//write_int(-1);//default
			info= "BrushId ";
		info += BrushId;
	Affich(info);

	info = Matid[BrushId];
	Affich(info);

	MItMeshPolygon  itPolygon(path.child(0));
	int d=0;
	for ( /* nothing */; !itPolygon.isDone(); itPolygon.next() )
		{

			nameshader=GetShaderName(shaders[indices[d]]);
			if(nameshader==Matid[BrushId]){

				// Get triangulation of this poly.
				int  numTriangles; 
				itPolygon.numTriangles(numTriangles);
				while ( numTriangles-- )
											{
												//MGlobal::displayInfo("  triangle");
												MStatus status;

												MIntArray                           polygonVertices;

												itPolygon.getVertices( polygonVertices );
											
												MPointArray                     nonTweaked;
												// object-relative vertex indices for each triangle
												MIntArray                       triangleVertices;
												// face-relative vertex indices for each triangle
												MIntArray                       localIndex;

												status = itPolygon.getTriangle( numTriangles,
												nonTweaked,
												triangleVertices,
												MSpace::kObject );
		
												if ( status == MS::kSuccess )
												{



													
						
						
													write_int(triangleVertices[0]);
													write_int(triangleVertices[2]);
													write_int(triangleVertices[1]);
													
			

												} // fin if	


											};// fin while


			}
		d++;

		}
					
	for (int i=0;i<indices.length();i++){
		//info = " indice ";
		//info += indices[i];
		//Affich(info);

		nameshader=GetShaderName(shaders[indices[i]]);
		if(nameshader==Matid[BrushId]){
		//info=nameshader;
		//Affich(info);

//*********************ecrire triangle*******


		}

	}

	
						EndChunck();

	}
	//for (int i=0;i<Matid.length();i++){
	//	info = Matid[i];
	//	Affich(info);
	//}
//Affich("fin objet");

#endif

						


					//---------------------fermeture mesh
						EndChunck();

							//------------------------------------------------------------
						
						}
						position_hierarchie=pos;
				}
				// move on to next node
				it.next();
			 
			
		}//fin while
		

				//fermeture du node
		//fermeture fichier
		//fermeture de tous les nodes ouverts
			//for (int i=posfichier.length();i>0;i--){

#ifdef SCENE_ROOT
				EndChunck();
#else
#endif

				//}
		//écriture de la longueur du fichier

		output.close();
		Matid.clear();
		Texid.clear();
		nb_Tex_by_Brush.clear();
		Texids_by_brush.clear();
	}
	else		
		//export all polygonal scene objects
	{
	}
	


	return MS::kSuccess;
}
Beispiel #24
0
// Write method of the GE2.0 translator / file exporter
MStatus ge2Translator::writer ( const MFileObject & fileObject,
								  const MString & options,
								  MPxFileTranslator::FileAccessMode mode)
{
	char            LTmpStr[MAXPATHLEN];
	unsigned int	i,
					LN;

	// const MString   fname = fileObject.fullName ();
	MString         extension;
	MString         baseFileName;


	// Lets strip off the known extension of .grp if it is there.
	extension.set (".grp");
	int  extLocation = fileObject.name ().rindex ('.');

	if ( (extLocation != -1) && // no '.' in name
		 (extLocation != 0) && // name was ".grp" -- that's ok??
		 (fileObject.name ().substring (extLocation, fileObject.name ().length () - 1) == extension) )
	{
		baseFileName = fileObject.name ().substring (0, extLocation - 1);
	} else
	{
		baseFileName = fileObject.name ();
		extension.clear ();
	}

	geWrapper.setBaseFileName( baseFileName );
	geWrapper.setPathName( fileObject.fullName() );

	geWrapper.pluginVersion = version;

	// Set the directory at the Dt level
	strncpy( LTmpStr, geWrapper.getPathName().asChar(), MAXPATHLEN );
	LN = (int)strlen( LTmpStr );
	if ( LTmpStr[LN - 1] == '/' )
		LTmpStr[LN - 1] = '\0';
	DtSetDirectory( LTmpStr );	

	// in an ideal world, everything in setDefaults() should be overridden
	// with the option parsing. If the mel script doesn't get run for whatever
	// reason, or neglects to return some values, hopefully setDefaults will
	// enable the export to go through anyway
	geWrapper.setDefaults();

// Turn off this pesky warning on NT - performance warning
// for int -> bool conversion.
#ifdef WIN32
#pragma warning ( disable : 4800 )
#endif

	// Lets now do all of the option processing	
	if ( options.length () > 0 )
	{
		//Start parsing.

		MStringArray optionList;
		MStringArray    theOption;

		options.split(';', optionList);

		//break out all the options.

		for ( i = 0; i < optionList.length (); ++i )
		{
			theOption.clear ();
			optionList[i].split( '=', theOption );
			if ( theOption.length () > 1 )
			{
				if ( theOption[0] == MString( "enableAnim" ) )
				{
					geWrapper.enableAnim = (bool) ( theOption[1].asInt() );
				}  else if ( theOption[0] == MString( "animStart" ) )
				{
					geWrapper.frameStart = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animEnd" ) )
				{
					geWrapper.frameEnd = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animStep" ) )
				{
					geWrapper.frameStep = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animVertices" ) )
				{
					geWrapper.animVertices = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animDisplacement" ) )
				{
					if ( theOption[1].asInt() == 1 )
						geWrapper.vertexDisplacement = ge2Wrapper::kVDRelative;
					else
						geWrapper.vertexDisplacement = ge2Wrapper::kVDAbsolute;
				} else if ( theOption[0] == MString( "animTransforms" ) )
				{
					geWrapper.animTransforms = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animShaders" ) )
				{
					geWrapper.animShaders = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animLights" ) )
				{
					geWrapper.animLights = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "animCamera" ) )
				{
					geWrapper.animCamera = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "keyCurves" ) )
				{
					geWrapper.keyCurves = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "keySample" ) )
				{
					geWrapper.keySample = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "sampRate" ) )
				{
					geWrapper.sampleRate = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "sampTol" ) )
				{
					geWrapper.sampleTolerance = (float) ( theOption[1].asFloat() );
				} else if ( theOption[0] == MString( "useGL" ) )
				{
					geWrapper.useDomainGL = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "usePSX" ) )
				{
					geWrapper.useDomainPSX = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "useN64" ) )
				{
					geWrapper.useDomainN64 = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "useCustom" ) )
				{
					geWrapper.useDomainCustom = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "hrcType" ) )
				{
					geWrapper.hrcMode = static_cast <ge2Wrapper::GEHrcMode> ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportSel" ) )
				{					
					geWrapper.selType = static_cast <ge2Wrapper::GESelType> ( theOption[1].asInt() );
					if ( (mode == MPxFileTranslator::kExportActiveAccessMode) &&
						 (geWrapper.selType == ge2Wrapper::kSelAll) )
					{
						geWrapper.selType = ge2Wrapper::kSelActive;
					}
				} else if ( theOption[0] == MString( "exportLights" ) )
				{
					geWrapper.outputLights = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportCamera" ) )
				{
					geWrapper.outputCamera = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportJoints" ) )
				{
					geWrapper.outputJoints = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportNormals" ) )
				{
					geWrapper.outputNormals = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "opposite" ) )
				{
					geWrapper.oppositeNormals = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportGeometry" ) )
				{ 
					geWrapper.outputGeometry = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "reverse" ) )
				{
					geWrapper.reverseWinding = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "exportTextures" ) )
				{
					geWrapper.outputTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "tesselation" ) )
				{
					if ( theOption[1].asInt() == 2 )
						DtExt_setTesselate( kTESSQUAD );
					else
						DtExt_setTesselate( kTESSTRI );
				} else if ( theOption[0] == MString( "texsample" ) )
				{
					geWrapper.sampleTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texevaluate" ) )
				{
					geWrapper.evalTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texOriginal" ) )
				{
					geWrapper.useOriginalFileTextures = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "Xtexres" ) )
				{
					geWrapper.xTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "Ytexres" ) )
				{
					geWrapper.yTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "MaxXtexres" ) )
				{
					geWrapper.xMaxTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "MaxYtexres" ) )
				{
					geWrapper.yMaxTexRes = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "texType" ) )
				{
					geWrapper.texType = theOption[1];
				} else if ( theOption[0] == MString( "precision" ) )
				{
					geWrapper.precision = (int) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "format" ) )
				{
					geWrapper.useTabs = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "comments" ) )
				{
					geWrapper.writeComments = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseGeom" ) )
				{
					geWrapper.verboseGeom = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseLgt" ) )
				{
					geWrapper.verboseLgt = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "verboseCam" ) )
				{
					geWrapper.verboseCam = (bool) ( theOption[1].asInt() );
				} else if ( theOption[0] == MString( "script" ) )
				{
					geWrapper.userScript = theOption[1];
				} else if ( theOption[0] == MString( "scriptAppend" ) )
				{
					geWrapper.scriptAppendFileName = (int) ( theOption[1].asInt() );
				}
			}
		}
	}

#ifdef WIN32
#pragma warning ( default : 4800 )
#endif

	geWrapper.initScene(); // do some initialization
	geWrapper.writeScene(); // write it to the appropriate files
	geWrapper.killScene(); // clean-up

	return MS::kSuccess;
}
MStatus CVsDmxIOTranslator::writer(
	const MFileObject &i_mFileObject,
	const MString &i_optionsString,
	const FileAccessMode i_fileAccessMode )
{
	MString cmd( "vsDmxIO -export" );

	if ( i_optionsString.length() )
	{
		bool useTimeline( true );
		double fs( MAnimControl::minTime().as( MTime::uiUnit() ) );
		double fe( MAnimControl::maxTime().as( MTime::uiUnit() ) );
		double fi( 1.0 );

		MStringArray options;
		if ( !i_optionsString.split( ';', options ) )
		{
			merr << "Can't split " << s_name << " translator arguments" << std::endl;
			return MS::kFailure;
		}

		for ( unsigned int oi( 0 ); oi != options.length(); ++oi )
		{
			MStringArray keyValue;
			if ( options[ oi ].split( '=', keyValue ) && keyValue.length() == 2 )
			{
				const MString &key( keyValue[ 0 ] );
				const MString &val( keyValue[ 1 ] );

				if ( key == "useTimeline" )
				{
					useTimeline = val.asInt() ? true : false;
					continue;
				}

				if ( !useTimeline )
				{
					if ( key == "fs" )
					{
						fs = val.asDouble();
						continue;
					}

					if ( key == "fe" )
					{
						fe = val.asDouble();
						continue;
					}

					if ( key == "fi" )
					{
						fi = val.asDouble();
						continue;
					}
				}
			}	
		}

		if ( !useTimeline )
		{
			if ( fs > fe )
			{
				merr << "Invalid frame start " << fs << " > frame end " << fe << ", ignoring and using timeline" << std::endl;
			}
			else
			{
				cmd += " -time \"";
				cmd += fs;
				cmd += "-";
				cmd += fe;
				if ( fi <= 0 )
				{
					mwarn << "Invalid frame increment " << fi << " specified, using 1" << std::endl;
				}
				else
				{
					cmd += "x";
					cmd += fi;
				}
				cmd += "\"";
			}
		}
	}

	if ( i_fileAccessMode == MPxFileTranslator::kExportActiveAccessMode )
	{
		cmd += " -selection";
	}

	cmd += " -filename \"";
	cmd += i_mFileObject.fullName();
	cmd += "\";";

	return MGlobal::executeCommand( cmd, true, true );
}
Beispiel #26
0
MStatus atomImport::reader(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;

	MString fileName = file.fullName();
#if defined (OSMac_)	
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ifstream animFile(fname);
#else
	ifstream animFile(fileName.asChar());
#endif
	// 	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//

	if(animFile.good()==false)
		return status;
	MString pasteFlags;
	MString	prefix;
	MString	suffix;
	MString	search;
	MString	replace;
	MString	mapFile;
	bool replaceLayers = false;
	MString	exportEditsFile;	
	bool includeChildren = false;
	atomNodeNameReplacer::ReplaceType type = atomNodeNameReplacer::eHierarchy;
	MString templateName;
	MString viewName;
	bool useTemplate = false;

	if (options.length() > 0) {
		//	Set up the flags for the paste command.
		//
		const MString flagSrcTime("srcTime");
		const MString flagDstTime("dstTime");
		const MString flagOldDstTime("time");
		const MString flagCopies("copies");
		const MString flagOption("option");
		const MString flagConnect("connect");
		const MString flagMatch("match");
		const MString flagSearch("search");
		const MString flagReplace("replace");
		const MString flagPrefix("prefix");
		const MString flagSuffix("suffix");
		const MString flagMapFile("mapFile");
		const MString flagHierarchy("hierarchy");
		const MString flagString("string");
		const MString flagSelected("selected");
		const MString flagTemplate("template");
		const MString flagView("view");
		const MString optionChildrenToo("childrenToo");
		const MString optionTemplate("template");
		const MString flagExportEdits("exportEdits");
		MString copyValue;
		MString flagValue;
		MString connectValue;
		MString match;
		MString srcTimeValue;
		MString dstTimeValue;

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {

			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagCopies && theOption.length() > 1) {
				copyValue = theOption[1];;
			} else if (theOption[0] == flagOption && theOption.length() > 1) {
				flagValue = theOption[1];
			} else if (theOption[0] == flagConnect && theOption.length() > 1) {
				if (theOption[1].asInt() != 0) {
					connectValue += theOption[1];
				}
			} 
			else if( theOption[0] == flagTemplate && theOption.length() > 1)
			{
				templateName = theOption[1];
			}
			else if( theOption[0] == flagView && theOption.length() > 1)
			{
				viewName = theOption[1];
			}
			else if (theOption[0] == flagSrcTime && theOption.length() > 1) {
				srcTimeValue += theOption[1];
			}
			else if ((theOption[0] == flagDstTime || theOption[0] == flagOldDstTime )&& theOption.length() > 1) {
				dstTimeValue += theOption[1];
			}
			else if (theOption[0] == flagMatch && theOption.length() > 1) {
				match =  theOption[1];
			} 
			else if (theOption[0] == flagSearch && theOption.length() > 1) {
				search =  theOption[1];
			} 
			else if (theOption[0] == flagReplace && theOption.length() > 1) {
				replace =  theOption[1];
			} 
			else if (theOption[0] == flagPrefix && theOption.length() > 1) {
				prefix =  theOption[1];
			} 
			else if (theOption[0] == flagSuffix && theOption.length() > 1) {
				suffix =  theOption[1];
			} 
			else if (theOption[0] == flagMapFile && theOption.length() > 1) {
				mapFile =  theOption[1];
			}
			else if (theOption[0] == flagSelected && theOption.length() > 1) {
				includeChildren =   (theOption[1] == optionChildrenToo) ? true : false;
				if(theOption[1] == optionTemplate)
					useTemplate = true;
			}
			else if (theOption[0] == flagExportEdits && theOption.length() > 1) {
				exportEditsFile =  theOption[1];
			}
		}
	
		if (copyValue.length() > 0) {
			pasteFlags += " -copies ";
			pasteFlags += copyValue;
			pasteFlags += " ";
		} 
		if (flagValue.length() > 0) {
			pasteFlags += " -option \"";
			pasteFlags += flagValue;
			pasteFlags += "\" ";
			if(flagValue == MString("replace"))
				replaceLayers = true;
		} 
		if (connectValue.length() > 0) {
			pasteFlags += " -connect ";
			pasteFlags += connectValue;
			pasteFlags += " ";
		} 
		if (dstTimeValue.length() > 0) {
			bool useQuotes = !dstTimeValue.isDouble();
			pasteFlags += " -time ";
			if (useQuotes) pasteFlags += "\"";
			pasteFlags +=  dstTimeValue;
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += " ";
		} 		
		if (srcTimeValue.length() > 0) 
		{
			MTime lClipStartTime;
			MTime lClipEndTime;
			MStringArray lTimes;

			if ( MStatus::kSuccess == srcTimeValue.split( L':', lTimes ) )
			{
				if ( lTimes.length() > 0 )
				{
					double lImportStartFrame = lTimes[0].asDouble();
					double lImportEndFrame   = lImportStartFrame;
					
					if ( lTimes.length() > 1 )
					{
						lImportEndFrame = lTimes[1].asDouble();
					}
					fReader.setImportFrameRange( lImportStartFrame, lImportEndFrame );
				}
				else
				{
					fReader.clearImportFrameRange();
				}
			}
		} 
        else
        {
            fReader.clearImportFrameRange();
        }
		if(match.length() >0)
		{
			if(match == flagHierarchy)
				type = atomNodeNameReplacer::eHierarchy;
			else if(match == flagString)
				type = atomNodeNameReplacer::eSearchReplace;
			else if(match == flagMapFile)
				type = atomNodeNameReplacer::eMapFile;
		} //not set, then we leave what we had

		
	}

	//	If the selection list is empty, there is nothing to import.
	//
	MSelectionList sList;
	std::vector<unsigned int> depths;
	atomTemplateReader templateReader;
	if(useTemplate == true)
	{
		templateReader.setTemplate(templateName,viewName);
		includeChildren = false;
		templateReader.selectNodes(); //make the selection set be us.
	}
	SelectionGetter::getSelectedObjects(includeChildren,sList,depths);
	if (sList.isEmpty()) {
		MString msg = MStringResource::getString(kNothingSelected, status);
		MGlobal::displayError(msg);
		return (MS::kFailure);
	}


	atomNodeNameReplacer replacer(type,sList,depths,prefix,suffix,search,replace,mapFile);
	if (mode == kImportAccessMode) {
		status = importAnim(sList,animFile,pasteFlags,replacer,exportEditsFile,templateReader,replaceLayers);
	}

	animFile.close();
	return status;
}
Beispiel #27
0
MStatus
usdTranslatorExport::writer(const MFileObject &file, 
                 const MString &optionsString,
                 MPxFileTranslator::FileAccessMode mode ) {

    std::string fileName(file.fullName().asChar());
    JobExportArgs jobArgs;
    double startTime=1, endTime=1;
    bool append=false;
    
    // Get the options 
    if ( optionsString.length() > 0 ) {
        MStringArray optionList;
        MStringArray theOption;
        optionsString.split(';', optionList);
        for(int i=0; i<(int)optionList.length(); ++i) {
            theOption.clear();
            optionList[i].split('=', theOption);            
            if (theOption[0] == MString("exportReferencesAsInstanceable")) {
                jobArgs.exportRefsAsInstanceable = theOption[1].asInt();
            }
            if (theOption[0] == MString("shadingMode")) {
                // Set default (most common) options
                jobArgs.exportDisplayColor = true;
                jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->none;
                
                if (theOption[1]=="None") {
                    jobArgs.exportDisplayColor = false;
                }else if (theOption[1]=="Look Colors") {
                    jobArgs.shadingMode = PxrUsdMayaShadingModeTokens->displayColor;
                } else if (theOption[1]=="RfM Shaders") {
                    TfToken shadingMode("pxrRis");
                    if (PxrUsdMayaShadingModeRegistry::GetInstance().GetExporter(shadingMode)) {
                        jobArgs.shadingMode = shadingMode;
                    }
                }
            }
            if (theOption[0] == MString("exportUVs")) {
                jobArgs.exportMeshUVs = theOption[1].asInt();
                jobArgs.exportNurbsExplicitUV = theOption[1].asInt();
            }
            if (theOption[0] == MString("normalizeUVs")) {
                jobArgs.normalizeMeshUVs = theOption[1].asInt();
                jobArgs.nurbsExplicitUVType = PxUsdExportJobArgsTokens->Uniform;
            }
            if (theOption[0] == MString("exportColorSets")) {
                jobArgs.exportColorSets = theOption[1].asInt();
            }
            if (theOption[0] == MString("renderableOnly")) {
                jobArgs.excludeInvisible = theOption[1].asInt();
            }
            if (theOption[0] == MString("allCameras")) {
                jobArgs.exportDefaultCameras = theOption[1].asInt();
            }
            if (theOption[0] == MString("renderLayerMode")) {
                jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->defaultLayer;

                if (theOption[1]=="Use Current Layer") {
                    jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->currentLayer;
                } else if (theOption[1]=="Modeling Variant Per Layer") {
                    jobArgs.renderLayerMode = PxUsdExportJobArgsTokens->modelingVariant;
                }
            }
            if (theOption[0] == MString("mergeXForm")) {
                jobArgs.mergeTransformAndShape = theOption[1].asInt();
            }
            if (theOption[0] == MString("defaultMeshScheme")) {            
                if (theOption[1]=="Polygonal Mesh") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->none;
                } else if (theOption[1]=="Bilinear SubDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->bilinear;
                } else if (theOption[1]=="CatmullClark SDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->catmullClark;
                } else if (theOption[1]=="Loop SDiv") {
                    jobArgs.defaultMeshScheme = UsdGeomTokens->loop;
                }
            }
            if (theOption[0] == MString("exportVisibility")) {
                jobArgs.exportVisibility = theOption[1].asInt();
            }
            if (theOption[0] == MString("animation")) {
                jobArgs.exportAnimation = theOption[1].asInt();
            }
            if (theOption[0] == MString("startTime")) {
                startTime = theOption[1].asDouble();
            }
            if (theOption[0] == MString("endTime")) {
                endTime = theOption[1].asDouble();
            }
        }
        // Now resync start and end frame based on animation mode
        if (jobArgs.exportAnimation) {
            if (endTime<startTime) endTime=startTime;
        } else {
            startTime=MAnimControl::currentTime().value();
            endTime=startTime;
        }
    }

    MSelectionList objSelList;
    if(mode == MPxFileTranslator::kExportActiveAccessMode) {
        // Get selected objects
        MGlobal::getActiveSelectionList(objSelList);
    } else if(mode == MPxFileTranslator::kExportAccessMode) {
        // Get all objects at DAG root
        objSelList.add("|*", true);
    }

    // Convert selection list to jobArgs dagPaths
    for (unsigned int i=0; i < objSelList.length(); i++) {
        MDagPath dagPath;
        if (objSelList.getDagPath(i, dagPath) == MS::kSuccess) {
            jobArgs.dagPaths.insert(dagPath);
        }
    }
    
    if (jobArgs.dagPaths.size()) {
        MTime oldCurTime = MAnimControl::currentTime();
        usdWriteJob writeJob(jobArgs);
        if (writeJob.beginJob(fileName, append, startTime, endTime)) {
            for (double i=startTime;i<(endTime+1);i++) {
                MGlobal::viewFrame(i);
                writeJob.evalJob(i);
            }
            writeJob.endJob();
            MGlobal::viewFrame(oldCurTime);
        }
    } else {
        MGlobal::displayWarning("No DAG nodes to export. Skipping");
    }
    
    return MS::kSuccess;
}
Beispiel #28
0
MStatus animExport::writer(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;


	MString fileName = file.fullName();
#if defined (OSMac_)
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ofstream animFile(fname);
#else
	ofstream animFile(fileName.asChar());
#endif
	//	Defaults.
	//
	MString copyFlags("copyKey -cb api -fea 1 ");
	int precision = kDefaultPrecision;
	bool nodeNames = true;
	bool verboseUnits = false;

	//	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	MString exportFlags;
	if (options.length() > 0) {
		const MString flagPrecision("precision");
		const MString flagNodeNames("nodeNames");
		const MString flagVerboseUnits("verboseUnits");
		const MString flagCopyKeyCmd("copyKeyCmd");

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {
			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagPrecision && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					precision = theOption[1].asInt();
				}
			} else if (	theOption[0] == 
						flagNodeNames && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					nodeNames = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
					flagVerboseUnits && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					verboseUnits = (theOption[1].asInt()) ? true : false;
				}
			} else if (	theOption[0] == 
						flagCopyKeyCmd && theOption.length() > 1) {

				//	Replace any '>' characters with '"'. This is needed
				//	since the file translator option boxes do not handle
				//	escaped quotation marks.
				//
				const char *optStr = theOption[1].asChar();
				size_t nChars = strlen(optStr);
				char *copyStr = new char[nChars+1];

				copyStr = strcpy(copyStr, optStr);
				for (size_t j = 0; j < nChars; j++) {
					if (copyStr[j] == '>') {
						copyStr[j] = '"';
					}
				}
		
				copyFlags += copyStr;
				delete [] copyStr;
			}
		}
	}
	
	//	Set the precision of the ofstream.
	//
	animFile.precision(precision);

	status = exportSelected(animFile, copyFlags, nodeNames, verboseUnits);

	animFile.flush();
	animFile.close();

	return status;
}
Beispiel #29
0
MStatus atomExport::writer(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;


	MString fileName = file.fullName();
#if defined (OSMac_)
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ofstream animFile(fname);
#else
	ofstream animFile(fileName.asChar());
#endif
	//	Defaults.
	//
	MString copyFlags("copyKey -cb api -fea 1 ");
	int precision = kDefaultPrecision;
	bool statics = false;
	bool includeChildren = false;
	std::set<std::string> attrStrings;
	//	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	bool useSpecifiedRange = false;
	bool useTemplate = false;
	bool cached = false;
	bool constraint = false;
	bool sdk = false;
	bool animLayers = true;
	MString templateName;
	MString viewName;
	MTime startTime = MAnimControl::animationStartTime();
	MTime endTime = MAnimControl::animationEndTime();
	MString	exportEditsFile;

	MString exportFlags;
	if (options.length() > 0) {
		const MString flagPrecision("precision");
		const MString flagStatics("statics");
		const MString flagConstraint("constraint");
		const MString flagSDK("sdk");
		const MString flagAnimLayers("animLayers");
		const MString flagCopyKeyCmd("copyKeyCmd");
		const MString flagSelected("selected");
		const MString flagTemplate("template");
		const MString flagView("view");
		const MString optionChildrenToo("childrenToo");
		const MString optionTemplate("template");
		const MString flagAttr("at");
		const MString flagWhichRange("whichRange");
		const MString flagRange("range");
		const MString flagExportEdits("exportEdits");		
		const MString flagCached("baked");		
		
		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {
			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagPrecision && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					precision = theOption[1].asInt();
				}
			} 
			else if( theOption[0] == flagTemplate && theOption.length() > 1)
			{
				templateName = theOption[1];
			}
			else if( theOption[0] == flagView && theOption.length() > 1)
			{
				viewName = theOption[1];
			}
			else if (	theOption[0] == 
						flagWhichRange && theOption.length() > 1) {
				if (theOption[1].isInt()) 
					useSpecifiedRange = (theOption[1].asInt() ==1) ? false : true;
			}
			else if (	theOption[0] == 
						flagRange && theOption.length() > 1) 
			{
				MStringArray rangeArray;
				theOption[1].split(':',rangeArray);
				if(rangeArray.length()==2)
				{
					if(rangeArray[0].isDouble())
					{
						double val = rangeArray[0].asDouble();
						startTime = MTime(val,MTime::uiUnit());
					}
					else if(rangeArray[0].isInt())
					{
						double val = (double)rangeArray[0].asInt();
						startTime = MTime(val,MTime::uiUnit());
					}
					if(rangeArray[1].isDouble())
					{
						double val = rangeArray[1].asDouble();
						endTime = MTime(val,MTime::uiUnit());
					}
					else if(rangeArray[1].isInt())
					{
						double val = (double)rangeArray[1].asInt();
						endTime = MTime(val,MTime::uiUnit());
					}
				}
			}
			else if (	theOption[0] == 
						flagStatics && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					statics = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagSDK && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					sdk = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagConstraint && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					constraint = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagAnimLayers && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					animLayers = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (	theOption[0] == 
						flagCached && theOption.length() > 1) {
				if (theOption[1].isInt()) {
					cached = (theOption[1].asInt()) ? true : false;
				}
			}
			else if (theOption[0] == flagSelected && theOption.length() > 1) {
				includeChildren = (theOption[1] == optionChildrenToo) ? true : false;
				if(theOption[1] == optionTemplate)
					useTemplate = true;
			} 
			else if (theOption[0] == flagAttr && theOption.length() > 1) {
				std::string str(theOption[1].asChar());
				attrStrings.insert(str);
			} 
			else if (	theOption[0] == 
						flagCopyKeyCmd && theOption.length() > 1) {

				//	Replace any '>' characters with '"'. This is needed
				//	since the file translator option boxes do not handle
				//	escaped quotation marks.
				//
				const char *optStr = theOption[1].asChar();
				size_t nChars = strlen(optStr);
				char *copyStr = new char[nChars+1];

				copyStr = strcpy(copyStr, optStr);
				for (size_t j = 0; j < nChars; j++) {
					if (copyStr[j] == '>') {
						copyStr[j] = '"';
					}
				}
		
				copyFlags += copyStr;
				delete [] copyStr;
			}
			else if (theOption[0] == flagExportEdits && theOption.length() > 1)
			{
				exportEditsFile =  theOption[1];
			}
		}
	}
	
	//	Set the precision of the ofstream.
	//
	animFile.precision(precision);


	atomTemplateReader templateReader;
	if(useTemplate == true)
	{
		includeChildren = false;
		templateReader.setTemplate(templateName,viewName);
		templateReader.selectNodes(); //make the template nodes be the selection
	}
	status = exportSelected(animFile, copyFlags, attrStrings, includeChildren,
							useSpecifiedRange, startTime, endTime, statics,
							cached,sdk,constraint, animLayers, exportEditsFile,templateReader);

	animFile.flush();
	animFile.close();

	return status;
}
Beispiel #30
0
MStatus animImport::reader(	const MFileObject& file,
								const MString& options,
								FileAccessMode mode)
{
	MStatus status = MS::kFailure;

	MString fileName = file.fullName();
#if defined (OSMac_)	
	char fname[MAXPATHLEN];
	strcpy (fname, fileName.asChar());
	ifstream animFile(fname);
#else
	ifstream animFile(fileName.asChar());
#endif
	// 	Parse the options. The options syntax is in the form of
	//	"flag=val;flag1=val;flag2=val"
	//
	MString pasteFlags;
	if (options.length() > 0) {
		//	Set up the flags for the paste command.
		//
		const MString flagTargetTime("targetTime");
		const MString flagTime("time");
		const MString flagCopies("copies");
		const MString flagOption("option");
		const MString flagConnect("connect");

		MString copyValue;
		MString flagValue;
		MString connectValue;
		MString timeValue;

		//	Start parsing.
		//
		MStringArray optionList;
		MStringArray theOption;
		options.split(';', optionList);

		unsigned nOptions = optionList.length();
		for (unsigned i = 0; i < nOptions; i++) {

			theOption.clear();
			optionList[i].split('=', theOption);
			if (theOption.length() < 1) {
				continue;
			}

			if (theOption[0] == flagCopies && theOption.length() > 1) {
				copyValue = theOption[1];;
			} else if (theOption[0] == flagOption && theOption.length() > 1) {
				flagValue = theOption[1];
			} else if (theOption[0] == flagConnect && theOption.length() > 1) {
				if (theOption[1].asInt() != 0) {
					connectValue += theOption[1];
				}
			} else if (theOption[0] == flagTime && theOption.length() > 1) {
				timeValue += theOption[1];
			}
		}
	
		if (copyValue.length() > 0) {
			pasteFlags += " -copies ";
			pasteFlags += copyValue;
			pasteFlags += " ";
		} 
		if (flagValue.length() > 0) {
			pasteFlags += " -option \"";
			pasteFlags += flagValue;
			pasteFlags += "\" ";
		} 
		if (connectValue.length() > 0) {
			pasteFlags += " -connect ";
			pasteFlags += connectValue;
			pasteFlags += " ";
		} 
		if (timeValue.length() > 0) {
			bool useQuotes = !timeValue.isDouble();
			pasteFlags += " -time ";
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += timeValue;
			if (useQuotes) pasteFlags += "\"";
			pasteFlags += " ";
		} 
	}

	if (mode == kImportAccessMode) {
		status = importAnim(animFile, pasteFlags);
	}

	animFile.close();
	return status;
}