OOModel::UnfinishedOperator* CommandDescriptor::createUnfinished(const QString& name,
		const QList<OOModel::Expression*>& arguments)
{
	auto unf = new OOModel::UnfinishedOperator();
	unf->delimiters()->append(new Model::Text("\\"));
	unf->operands()->append(new OOModel::ReferenceExpression(name));

	if (!arguments.isEmpty())
	{
		unf->delimiters()->append(new Model::Text("("));

		for(int i = 0; i< arguments.size(); ++i)
		{
			if (i > 0) unf->delimiters()->append(new Model::Text(","));
			unf->operands()->append(arguments[i]);
		}

		unf->delimiters()->append(new Model::Text(")"));
	}
	else unf->delimiters()->append(new Model::Text(QString())); // append an empty postfix if there are no arguments

	return unf;
}
		SoundEffectPtr ResourceLoader::load<SoundEffect>(std::string file){
			SoundEffectPtr res = nullptr;
			vector<char> delimiters(3);
			delimiters.push_back('.');
			delimiters.push_back('/');
			delimiters.push_back('\\');
			string file_ext = Utils::split(file,delimiters).back();

			if(file_ext == "wav"){
				res = loadWAV(file);
			}else{
				throw ServiceException("Unimplemented resource loader");
			}

			return res;
		}
Beispiel #3
0
void tokenize_dataline(string const& raw_line,vector<string> &tokens,char const *delim){
  
  string delimiters(delim);
  tokens.clear();

  int lpos = 0;
  int pos = raw_line.find_first_not_of(delimiters,lpos);
  while (pos != std::string::npos){
    lpos = pos;
    pos = raw_line.find_first_of(delimiters,lpos);
    tokens.push_back(raw_line.substr(lpos,pos-lpos));
    //cout << tokens.back()<<"*"<<endl;
    lpos = pos;
    pos = raw_line.find_first_not_of(delimiters,lpos);
  }
}
Beispiel #4
0
void Tokenize(const string &str, vector<string> &tokens, const char* DELIMITERS, int szDELIMITERS){
    // Skip delimiters at beginning.
	string delimiters(DELIMITERS,szDELIMITERS);		//WARNING, DELIMITERS ISNT NULL TERMINATED
	
	string::size_type lastPos = str.find_first_not_of(delimiters, 0);
	// Find first "non-delimiter".
	string::size_type pos     = str.find_first_of(delimiters, lastPos);
	
	while (string::npos != pos || string::npos != lastPos)
	{
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));
		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiters, pos);
		// Find next "non-delimiter"
		pos = str.find_first_of(delimiters, lastPos);
	}
}
Beispiel #5
0
QStringList KStandardDirs::systemPaths( const QString& pstr )
{
    QStringList tokens;
    QString p = pstr;

    if( p.isNull() )
    {
	p = getenv( "PATH" );
    }

    QString delimiters(QChar(KPATH_SEPARATOR));
    delimiters += "\b";
    tokenize( tokens, p, delimiters );

    QStringList exePaths;

    // split path using : or \b as delimiters
    for( unsigned i = 0; i < tokens.count(); i++ )
    {
	p = tokens[ i ];

        if ( p[ 0 ] == '~' )
        {
            int len = p.find( '/' );
            if ( len == -1 )
                len = p.length();
            if ( len == 1 )
            {
                p.replace( 0, 1, QDir::homeDirPath() );
            }
            else
            {
                QString user = p.mid( 1, len - 1 );
                struct passwd *dir = getpwnam( user.local8Bit().data() );
                if ( dir && strlen( dir->pw_dir ) )
                    p.replace( 0, len, QString::fromLocal8Bit( dir->pw_dir ) );
            }
        }

	exePaths << p;
    }

    return exePaths;
}
OperatorDescriptor::OperatorDescriptor(const QString& name, const QString& signature, int num_operands, int precedence, Associativity associativity)
	: name_(name), num_operands_(num_operands), precedence_(precedence), associativity_(associativity), transient_(false)
{
	signature_ = signature.split(" ", QString::SkipEmptyParts);
	signature_.replaceInStrings("SPACE", " ");

	// Compute prefix
	for(int i = 0; i < signature_.size() && signature_.at(i) != "expr" && signature_.at(i) != "id"; ++i)
		prefix_.append( signature_.at(i) );

	// Compute posfix
	for(int i = signature_.size()-1; i>=0 && signature_.at(i) != "expr" && signature_.at(i) != "id" ; --i)
		postfix_.prepend( signature_.at(i) );

	// Compute infixes
	infixes_ = delimiters();
	infixes_.removeAll("");
	if ( !prefix_.isEmpty() ) infixes_.removeFirst();
	if ( !postfix_.isEmpty() ) infixes_.removeLast();
}
Beispiel #7
0
void Entity::getTokens(std::string line)
{
	tokens.clear();
	std::string delimiters("\t");
	// Skip delimiters at beginning.
    std::string::size_type lastPos = line.find_first_not_of(delimiters, 0);
	
	// Find first "non-delimiter".
    std::string::size_type pos     = line.find_first_of(delimiters, lastPos);
	
	while (std::string::npos != pos || std::string::npos != lastPos)
    {
//		std::cout << "lastPos=" << lastPos << " diff" << (pos - lastPos) << std::endl;
        // Found a token, add it to the vector.
        tokens.push_back(line.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = line.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = line.find_first_of(delimiters, lastPos);
    }
}
Beispiel #8
0
void parse_string(std::string s)
{
  if(!s.c_str())
    return;

  std::string delimiters("RL");
  std::vector<std::string> tokens;
  boost::split(tokens,s,boost::is_any_of(delimiters));
  
  // First token is blank
  // Second is right
  // Third is left
  if (tokens.size() != 3) {
    //ROS_ERROR("Parsing error # of tokens = %d", tokens.size());
    return;
  } else {
    //ROS_INFO("Sup");
  }
  
  int r = atoi(tokens[1].c_str());
  int l = atoi(tokens[2].c_str());

  double right_speed = 0.0256*r; //m/s
  double left_speed = 0.0256*l;

  geometry_msgs::Twist msg;
  msg.linear.x = (right_speed + left_speed)/2.0;
  msg.linear.y = right_speed;
  msg.linear.z = left_speed;
  msg.angular.z = (right_speed - left_speed)*2.318;
  msg.angular.x = 0;
  msg.angular.y = 0;

  encoder_pub.publish(msg);

  last_arduino_message = ros::Time::now();
}
Beispiel #9
0
bool ReadCell::readData( const string& line )
{
	vector< string > argv;
	string delimiters( "\t " );
	tokenize( line, delimiters, argv ); 
	
	if ( argv.size() < 6 ) {
		cerr <<	"Error: ReadCell: Too few arguments in line: " << argv.size() <<
				", should be > 6.\n";
		cerr << "File: " << fileName_ << " Line: " << lineNum_ << endl;
		return 0;
	}
	
	double x0 = 0.0;
	double y0 = 0.0;
	double z0 = 0.0;
	double x, y, z;
	double d;
	int argOffset = 0;
	
	string name = argv[ 0 ];
	string parent = argv[ 1 ];
	
	if ( doubleEndpointFlag_ ) {
		argOffset = 3;
		
		x0 = 1.0e-6 * atof( argv[ 2 ].c_str() );
		y0 = atof( argv[ 3 ].c_str() );
		z0 = atof( argv[ 4 ].c_str() );
		if ( polarFlag_ ) {
			double r = x0;
			double theta = y0 * M_PI / 180.0;
			double phi = z0 * M_PI / 180.0;
			x0 = r * sin( phi ) * cos ( theta );
			y0 = r * sin( phi ) * sin ( theta );
			z0 = r * cos( phi );
		} else {
			y0 *= 1.0e-6;
			z0 *= 1.0e-6;
		}
	}
	
	x = 1.0e-6 * atof( argv[ argOffset + 2 ].c_str() );
	y = atof( argv[ argOffset + 3 ].c_str() );
	z = atof( argv[ argOffset + 4 ].c_str() );
	if ( polarFlag_ ) {
		double r = x;
		double theta = y * M_PI / 180.0;
		double phi = z * M_PI / 180.0;
		x = r * sin( phi ) * cos ( theta );
		y = r * sin( phi ) * sin ( theta );
		z = r * cos( phi );
	} else {
		y *= 1.0e-6;
		z *= 1.0e-6;
	}
	
	d = 1.0e-6 * atof( argv[ argOffset + 5 ].c_str() );
	
	double length;
	Id compt =
		buildCompartment( name, parent, x0, y0, z0, x, y, z, d, length, argv );
	
	if ( compt == Id() )
		return 0;
	
	return buildChannels( compt, argv, d, length );
}
Beispiel #10
0
bool ReadCell::readScript( const string& line )
{
	vector< string > argv;
	string delimiters( "\t " );
	tokenize( line, delimiters, argv ); 
	
	if ( argv[ 0 ] == "*cartesian" ) {
		polarFlag_ = 0;
	} else if ( argv[ 0 ] == "*polar" ) {
		polarFlag_ = 1;
	} else if ( argv[ 0 ] == "*relative" ) {
		relativeCoordsFlag_ = 1;
	} else if ( argv[ 0 ] == "*absolute" ) {
		relativeCoordsFlag_ = 0;
	} else if ( argv[ 0 ] == "*symmetric" ) {
		symmetricFlag_ = 1;
	} else if ( argv[ 0 ] == "*asymmetric" ) {
        symmetricFlag_ = 0;
    } else if ( argv[ 0 ] == "*set_global" || argv[ 0 ] == "*set_compt_param" ) {
		if ( argv.size() != 3 ) {
			cerr << "Error: ReadCell: Bad line: " <<
				"File: " << fileName_ <<
				"Line: " << lineNum_ << "\n";
			return 0;
		}
		
		if ( argv[ 1 ] == "RM" )
			RM_ = atof( argv[ 2 ].c_str() );
		if ( argv[ 1 ] == "RA" )
			RA_ = atof( argv[ 2 ].c_str() );
		if ( argv[ 1 ] == "CM" )
			CM_ = atof( argv[ 2 ].c_str() );
		if ( argv[ 1 ] == "EREST_ACT" ) {
			EREST_ACT_ = atof( argv[ 2 ].c_str() );
			erestFlag_ = 1;
		} if (argv[ 1 ] == "ELEAK" ) {
			ELEAK_ = atof( argv[ 2 ].c_str() );
			eleakFlag_ = 1;
		}
	} else if ( argv[ 0 ] == "*start_cell" ) {
		if ( argv.size() == 1 ) {
			graftFlag_ = 0;
			currCell_ = cell_;
		} else if ( argv.size() == 2 ) {
			graftFlag_ = 1;
			currCell_ = startGraftCell( argv[ 1 ] );
			if ( currCell_ == Id() )
				return 0;
		} else {
			cerr << "Error: ReadCell: Bad line: " <<
				"File: " << fileName_ <<
				"Line: " << lineNum_ << "\n";
			return 0;
		}
	} else if ( argv[ 0 ] == "*compt" ) {
		if ( argv.size() != 2 ) {
			cerr << "Error: ReadCell: Bad line: " <<
				"File: " << fileName_ <<
				"Line: " << lineNum_ << "\n";
			return 0;
		}
		
		Id protoId( argv[ 1 ] );
		if ( protoId.path() != argv[ 1 ] ) {
			cerr << "Error: ReadCell: Bad path: " << argv[ 1 ] << " " <<
				"File: " << fileName_ <<
				"Line: " << lineNum_ << "\n";
			return 0;
		}
		
		protoCompt_ = protoId;
		countProtos();
	} else if ( argv[ 0 ] == "*double_endpoint" ) {
		doubleEndpointFlag_ = 1;
	} else if ( argv[ 0 ] == "*double_endpoint_off" ) {
		doubleEndpointFlag_ = 0;
	} else if ( argv[ 0 ] == "*makeproto" ) {
		; // Nothing to be done.
	} else {
		cerr << "Warning: ReadCell: Command " <<
			argv[ 0 ] << " not recognized. Ignoring. " <<
			"File: " << fileName_ <<
			"Line: " << lineNum_ << "\n";
	}
	
	return 1;
}
int main(int argc, char *argv[])
{
    int ExitCode = 0;

    std::string			creoStartCommand;
    std::string			proeIsisExtensionsDir;

    std::string			templateFile_PathAndFileName;
    std::stringstream	exceptionErrorStringStream;

    bool Logging_Set_Up = false;

    isis::ProgramInputArguments  programInputArguments;
    ::boost::filesystem::path    workingDir;

    try
    {
        // Parse Input Arguments
        programInputArguments.ParseInputArguments(argc, argv);

        // Setup Boost logging
        SetupLogging(programInputArguments.logFileName, programInputArguments.logVerbosity);

        

        Logging_Set_Up = true;

        isis::ThrowException_If_InvalidInputArguments(argc, argv, programInputArguments);

        // Must get the complete path to the working directory.  This is necessary because when
        // isis_ProDirectoryChange is called to change to a STEP directory, workingDir must be fully
        // defined so that isis_ProDirectoryChange can be called to return to the original directory.
        workingDir = isis::SetupWorkingDirectory(programInputArguments.workingDirectory);

		isis::GlobalModelData::Instance.instanceId = programInputArguments.instanceID;

        // Log CADCreoParametricCreateAssembly version information
        std::string programName_Version_TimeStamp;
        programName_Version_TimeStamp = "CADCreoParametricMetaLink " + std::string(ISIS_PRODUCT_VERSION_WITH_v_AND_DOTS);

        ///////////////////
        // Add Time Stamp
        ///////////////////

        programName_Version_TimeStamp += isis_CADCommon::GetDayMonthTimeYear();
        isis_LOG(lg, isis_FILE, isis_INFO) << programName_Version_TimeStamp;

        isis_LOG(lg, isis_FILE, isis_INFO) << "Notes: " << isis_EOL
                                     << "   1. The \"Component Instance ID\"s in this file equate to ComponentInstanceIDs in CyPhy."  << isis_EOL
                                     << "   2. To map \"Component Instance ID\"s in this file to AVM-IDs, see .\\log\\CyPhy2CAD.log." << isis_EOL;

        time_t time_start; /* calendar time */
        time_start=time(NULL); /* get current cal time */

        // Log input line and parameters
        std::ostringstream inputLine;
        for(int i = 0; i < argc; ++i)
        {
            inputLine << argv[i] << std::string(" ");
        }
        isis_LOG(lg, isis_FILE, isis_INFO) << "Command line: " << inputLine.str();

		isis_LOG(lg, isis_FILE, isis_DEBUG) << "Input arguments (parsed): " << isis_EOL << programInputArguments;

        if(workingDir.generic_string().size() >= PRO_PATH_SIZE)      // PRO_PATH_SIZE   260
        {
            std::stringstream errorString;
            errorString << "WORKING_DIR string too long.  Maximum allowed number of characters: "  << PRO_PATH_SIZE - 1 << " WORKING_DIR string: " << workingDir;
            throw isis::application_exception(errorString);
        }

		isis::SetCreoEnvirVariable_RetrieveSystemSettings(programInputArguments.graphicsModeOn,
                programInputArguments.synchronizeWithCyPhy,
                creoStartCommand,
                proeIsisExtensionsDir,
                templateFile_PathAndFileName);

        std::map<std::string, isis::CADComponentData> CADComponentData_map;
        isis::CADAssemblies CADComponentAssemblies;

		writeConfigProFile(workingDir, programInputArguments);

        /////////////////////////////
        /////// Start Pro/E /////////
        /////////////////////////////

        const char* proeIsisExt = std::getenv("PROE_ISIS_EXTENSIONS");
        char* creoStartChar = const_cast<char*>(creoStartCommand.c_str());

        ::boost::filesystem::current_path(workingDir);
        std::string textPath=std::string(proeIsisExt)+"plugins\\";
        isis::isis_ProEngineerStart(creoStartChar, const_cast<char*>(textPath.c_str()));

        ProTermFuncSet(ProTermAction);

        isis_LOG(lg, isis_FILE, isis_INFO) << "Creo-Parametric successfully started.";

        boost::asio::io_service ios;
        std::string delimiters(":");
        std::vector<std::string> parts;
        boost::split(parts, programInputArguments.syncConnectionString, boost::is_any_of(delimiters));
        std::string host = "127.0.0.1";  // localhost may be subject to firewall and DNS restrictions and not work
        std::string service = "15152";   // it looks like ISIS with a zero

        if(parts.size() > 1)
        {
            host = parts[0];
            service = parts[1];
            isis_LOG(lg, isis_FILE, isis_INFO) << "host: " << host << ", service: " << service;
        }
        else if(parts.size() > 0)
        {
            host = parts[0];
            isis_LOG(lg, isis_FILE, isis_INFO) << "host: " << host << ", service: " << service << "(default)";
        }
        else
        {
            isis_LOG(lg, isis_FILE, isis_INFO) << "host: " << host << "(default), service: " << service << "(default)";
        }

        SetupCreoPlugins();
        SetupCreoSelectPlugin();

        ProNotificationSet(PRO_PARAM_MODIFY_POST, (ProFunction)metaParameterModifyAction);

        isis::cad::CadFactoryAbstract::ptr cad_factory = isis::cad::creo::create();

        isis::MetaLinkAssemblyEditor::Pointer assembler_ptr(new isis::MetaLinkAssemblyEditor(cad_factory, programInputArguments, isis::GlobalModelData::Instance.CadComponentData));

        boost::mutex eventloop_mutex;

        if(programInputArguments.is_passiveMode())
        {
            isis::GlobalModelData::Instance.designId = programInputArguments.designID;
        }

		isis::MetaLinkHandler metalink_handler(assembler_ptr, ios, host, service, programInputArguments.instanceID, programInputArguments.designID, eventloop_mutex);  // pass design ID pass in as argument

        isis::GlobalModelData::Instance.metalink_handler_ptr = &metalink_handler;
        isis::GlobalModelData::Instance.metalinkAssemblyEditorPtr = assembler_ptr;

        metalink_handler.change_m_operator("CAD");

        bool inputFileProcessed = false;

        while(!terminateProcess)
        {
            ProEventProcess();
            if(programInputArguments.inputXmlFileName.size()!=0 && !inputFileProcessed)
            {
                metalink_handler.CreateAssembly(programInputArguments.inputXmlFileName);
                inputFileProcessed = true;
            }
            if(metalink_handler.m_eventQueue.size()>0)
            {
                boost::unique_lock< boost::mutex > guard(eventloop_mutex);
                isis::EditPointer edit = metalink_handler.m_eventQueue.front();
                metalink_handler.m_eventQueue.pop();
                bool result = metalink_handler.processEdit(edit);
                if(result)
                {
                    isis::EditPointer ack(new meta::Edit());
                    ack->set_guid(edit->guid());
                    for(int i = 0; i < edit->topic_size(); i++)
                    {
                        *(ack->add_topic()) = edit->topic(i);
                    }
                    metalink_handler.send(ack);
                }
            }
        }

        metalink_handler.interrupt();
        metalink_handler.disconnect();

        ProEngineerEnd();


    } // END Try
    catch(isis::application_exception& ex)
    {
        exceptionErrorStringStream  << "application error: " << ex.what();
        ExitCode = -1;
    }
    catch(std::exception& ex)
    {
        exceptionErrorStringStream << "general exception: " << ex.what();
        ExitCode = -2;
    }
    catch(...)
    {
        exceptionErrorStringStream << "unspecified throwable (...):  Please report the error to the help desk.";
        ExitCode = -3;
    }

    if(ExitCode != 0)
    {
        // Write to _FAILED.txt
        std::string failedTxtFileName = "_FAILED.txt";
        bool addLineFeed = false;
        if(isis::FileExists(failedTxtFileName.c_str()))
        {
            addLineFeed = true;
        }

        ofstream failedTxtFileStream;
        failedTxtFileStream.open(failedTxtFileName, ios::app);
        if(failedTxtFileStream.is_open())
        {
            if(addLineFeed)
            {
                failedTxtFileStream << std::endl;
            }
            failedTxtFileStream <<  isis_CADCommon::GetDayMonthTimeYear() << ", CADCreoParametricCreateAssembly.exe error code: " << ExitCode << ".  For additional information, scroll to the bottom of " << programInputArguments.logFileName;
            failedTxtFileStream.close();
        }

        if(Logging_Set_Up)
        {
            
            isis_LOG(lg, isis_FILE, isis_ERROR) << exceptionErrorStringStream.str();
        }
        else
        {
            std::cerr << std::endl << std::endl << exceptionErrorStringStream.str() << std::endl << std::endl;
        }

    }


    /*
    ::boost::filesystem::current_path(original_directory);

    // Cleanup - Delete the working dir after execution
    ::boost::system::error_code ec;
    if (isis::GlobalModelData::Instance.mode == isis::DESIGNEDIT)
    {
    	// Remove files one-by-one so if the directory removal fails still something is removed
    	::boost::filesystem::path deleteFile = workingDir / "*";
    	isis_LOG(lg, isis_FILE, isis_DEBUG) << workingDir / "*";
    	if (::boost::filesystem::exists(deleteFile) ) {
    		::boost::filesystem::remove_all(deleteFile, ec);
    		if (ec != 0)
    		{
    			isis_LOG(lg, isis_FILE, isis_ERROR) << "Failed to remove working directory, ec: " << ec;
    		}
    	}
    	deleteFile = workingDir;
    	isis_LOG(lg, isis_FILE, isis_DEBUG) << workingDir;
    	if (::boost::filesystem::exists(deleteFile) ) {
    		::boost::filesystem::remove_all(deleteFile, ec);
    		if (ec != 0)
    		{
    			isis_LOG(lg, isis_FILE, isis_ERROR) << "Failed to remove working directory, ec: " << ec;
    		}
    	}
    } else if (isis::GlobalModelData::Instance.mode == isis::COMPONENTEDIT)
    {
    	::boost::filesystem::path deleteFile = workingDir / "config.pro";
    	isis_LOG(lg, isis_FILE, isis_DEBUG) << workingDir / "config.pro";
    	if (::boost::filesystem::exists(deleteFile) ) {
    		::boost::filesystem::remove_all(deleteFile, ec);
    		if (ec != 0)
    		{
    			isis_LOG(lg, isis_FILE, isis_ERROR) << "Failed to remove working directory, ec: " << ec;
    		}
    	}
    	deleteFile = workingDir / "std.err";
    	isis_LOG(lg, isis_FILE, isis_DEBUG) << workingDir / "std.err";
    	if (::boost::filesystem::exists(deleteFile) ) {
    		::boost::filesystem::remove_all(deleteFile, ec);
    		if (ec != 0)
    		{
    			isis_LOG(lg, isis_FILE, isis_ERROR) << "Failed to remove working directory, ec: " << ec;
    		}
    	}
    	deleteFile = workingDir / "trail.txt.*";
    	isis_LOG(lg, isis_FILE, isis_DEBUG) << workingDir / "trail.txt.*";
    	if (::boost::filesystem::exists(deleteFile) ) {
    		::boost::filesystem::remove_all(deleteFile, ec);
    		if (ec != 0)
    		{
    			isis_LOG(lg, isis_FILE, isis_ERROR) << "Failed to remove working directory, ec: " << ec;
    		}
    	}
    }
    */
  

    exit(ExitCode);
}
Beispiel #12
0
int CXXSurface::readGraspFile(string path)
{
	char buffer[1024];
	string text;
	float *coordBuffer;
	int *triangleBuffer;
	
	Delimiters delimiters(" \0\t\n~;()\"<>:{}[]+-=&*#.,/\\");	
	int hasVertices, hasAccessibles, hasNormals, hasTriangles, hasPotential, 
    hasProperty1, hasProperty2;	
	hasVertices= hasAccessibles= hasNormals= hasTriangles= hasPotential= 
    hasProperty1= hasProperty2 = 0;
	
	CXXFortranFile graspFile(path,"r");
	if (!graspFile.bad()) std::cout << "Opened grasp file [" << path << "]\n";
	else {
        std::cout << "Failed to open grasp file [" << path << "]\n";
        return 1;
    }
	//Grasp Surface file format
	graspFile.getFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	text = buffer;
	cout << "[" << text << "]\n";
	if (text.find("format=2",0) == string::npos) cout << "Unknown format" << text << endl;
	
	//information about what things are in the file
	graspFile.getFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	text = buffer;
	cout << "[" << text << "]\n";
	hasVertices =  (text.find("vertices",0) != string::npos);
	hasAccessibles =  (text.find("accessibles",0) != string::npos);
	hasNormals =  (text.find("normals",0) != string::npos);
	hasTriangles =  (text.find("triangles",0) != string::npos);
	
	//information about what properties are in the file
	graspFile.getFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	text = buffer;
	cout << "[" << text << "]\n";
	hasPotential = (text.find("potential",0)  != string::npos);
	hasProperty1 = (text.find("gproperty1",0) != string::npos);
	hasProperty2 = (text.find("gproperty2",0) != string::npos);
	
	//Number of vertices and triangles:  Here use the fancy tokeniterator to break down line into strings
	graspFile.getFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	text = buffer;
	cout << "[" << text << "]\n";
	TokenIterator<char*, Delimiters>
    charIter(buffer, buffer + strlen(buffer), delimiters), end2;
	string token;
	token = *charIter++;
	int nVertices = atoi(token.c_str());
	token = *charIter++;
	nTriangles = atoi(token.c_str());
	
	vertices.resize(nVertices);
	triangles.resize(nTriangles);
	
	std::cout << "Number of vertices is " << vertices.size() << " in " << triangles.size() << " nTriangles\n";
	//	ostream_iterator<string> out(cout, "\n");
	//	copy (wordlist.begin(), wordlist.end(), out);
	
	// A line to skip
	graspFile.getFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	text = buffer;
	cout << "[" << text << "]\n";
	
	//Read vertices if present
	if (hasVertices){
		coordBuffer = new float[3*nVertices];
		double *coordDoubleBuffer = new double[3*nVertices];
		graspFile.getFortranData((char *) coordBuffer, sizeof(float), 
								 3*nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<3*nVertices; i++) coordDoubleBuffer[i] = coordBuffer[i];
		(void) addPerVertexVector ("vertices", coordDoubleBuffer);	
		delete [] coordBuffer;
		delete [] coordDoubleBuffer;
	}
	
	//Read accessibles if present
	if (hasAccessibles){
		coordBuffer = new float[3*nVertices];
		double *coordDoubleBuffer = new double[3*nVertices];
		graspFile.getFortranData((char *) coordBuffer, sizeof(float), 
								 3*nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<3*nVertices; i++) coordDoubleBuffer[i] = coordBuffer[i];
		(void) addPerVertexVector ("accessibles", coordDoubleBuffer);	
		delete [] coordBuffer;
		delete [] coordDoubleBuffer;
	}
	
	//Read normals if present
	if (hasNormals){
		coordBuffer = new float[3*nVertices];
		double *coordDoubleBuffer = new double[3*nVertices];
		graspFile.getFortranData((char *) coordBuffer, sizeof(float), 
								 3*nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<3*nVertices; i++) coordDoubleBuffer[i] = coordBuffer[i];
		(void) addPerVertexVector ("normals", coordDoubleBuffer);	
		delete [] coordBuffer;
		delete [] coordDoubleBuffer;
	}
	//Read triangles if present
	if (hasTriangles){
		triangleBuffer = new int[3*nTriangles];
		graspFile.getFortranData((char *) triangleBuffer, sizeof(int), 
								 3*nTriangles, CXXFortranFile::FortranIntData);
		for (int i=0; i<nTriangles; i++){
			triangles[i] = CXXTriangle (triangleBuffer[3*i]-1, 
										triangleBuffer[3*i+1]-1, 
										triangleBuffer[3*i+2]-1);
		}
		delete [] triangleBuffer;
	}
	
	//Read potential if present
	if (hasPotential){
		float *potentialBuffer = new float[nVertices];
		double *potentialDoubleBuffer = new double[nVertices];
		graspFile.getFortranData((char *) potentialBuffer, sizeof(float), 
								 nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<nVertices; i++) potentialDoubleBuffer[i] = potentialBuffer[i];
		addPerVertexScalar("potential", potentialDoubleBuffer);
		delete [] potentialBuffer;
		delete [] potentialDoubleBuffer;
	}
	
	//Read gproperty1 if present
	if (hasProperty1){
		float *potentialBuffer = new float[nVertices];
		double *potentialDoubleBuffer = new double[nVertices];
		graspFile.getFortranData((char *) potentialBuffer, sizeof(float), 
								 nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<nVertices; i++) potentialDoubleBuffer[i] = potentialBuffer[i];
		addPerVertexScalar("gproperty1", potentialDoubleBuffer);
		delete [] potentialBuffer;
		delete [] potentialDoubleBuffer;
	}
	
	//Read gproperty2 if present
	if (hasProperty2){
		float *potentialBuffer = new float[nVertices];
		double *potentialDoubleBuffer = new double[nVertices];
		graspFile.getFortranData((char *) potentialBuffer, sizeof(float), 
								 nVertices, CXXFortranFile::FortranFloatData);
		for (int i=0; i<nVertices; i++) potentialDoubleBuffer[i] = potentialBuffer[i];
		addPerVertexScalar("gproperty2", potentialDoubleBuffer);
		delete [] potentialBuffer;
		delete [] potentialDoubleBuffer;
	}
	return 0;
}
Beispiel #13
0
int CXXSurface::writeAsGrasp (const std::string &path)
{
	char buffer[1024];
	string text;
	int i;
	float *coordBuffer;
	int *triangleBuffer;
	std::cout << "writeAsGrasp" << path << "\n";
    
	Delimiters delimiters(" \0\t\n~;()\"<>:{}[]+-=&*#.,/\\");	
	
	CXXFortranFile graspFile(path,"w");
	if (!graspFile.bad()) std::cout << "Opened grasp file [" << path << "]\n";
	else {
        std::cout << "Failed to open grasp file [" << path << "]\n";
        return 1;
    }
    
	//Grasp Surface file format
	strcpy (buffer,"format=2");
	for (i=strlen(buffer); i<80; i++) buffer[i] = ' ';
	graspFile.putFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	
	//information about what things are in the file
	strcpy (buffer,"vertices");
	if (vectors.find("accessibles") != vectors.end()) strcat (buffer,",accessibles");
	if (vectors.find("normals") != vectors.end()) strcat (buffer,",normals");
	strcat (buffer,",triangles");
	for (i=strlen(buffer); i<80; i++) buffer[i] = ' ';
	graspFile.putFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	
	//information about what properties are in the file
	int firstPotential = 1;
	buffer[0] = '\0';
	if (scalars.find("potential") != scalars.end()) {
		firstPotential = 0;
		strcat (buffer,"potential");
	}
	if (scalars.find("gproperty1") != scalars.end()) {
		if (!firstPotential) strcat(buffer,",");
		strcat (buffer,"gproperty1");
	}
	if (scalars.find("gproperty2") != scalars.end()) {
		if (!firstPotential) strcat(buffer,",");
		strcat (buffer,"gproperty2");
	}
	for (i=strlen(buffer); i<80; i++) buffer[i] = ' ';
	graspFile.putFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	
	//Number of vertices and triangles, grid, and the number 3.0
	sprintf(buffer,"%8d%8d%8d%8.5f                                ",
			int(vertices.size()), nTriangles, 65, 3.0);
	graspFile.putFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	
	// A line that seems to mention the origin
	sprintf(buffer,"%8.3f%8.3f%8.3f                                        ",
			0., 0., 0.);
	graspFile.putFortranData(buffer, 1, 64, CXXFortranFile::FortranCharData);
	
	coordBuffer = new float[3*vertices.size()];
	
	//Output vertices
	for (i=0; i<int(vertices.size()); i++){
		CXXCoord_ftype *xyz = vertices[i].xyzPntr(vectors["vertices"]); 
		for (int j=0; j<3; j++){
			coordBuffer[3*i + j] = xyz[j];
		}
	}
	graspFile.putFortranData((char *) coordBuffer, sizeof(float), 
							 3*vertices.size(), CXXFortranFile::FortranFloatData);
	
	//Write accessibles if present
	if (vectors.find("accessibles") != vectors.end()){
		for (i=0; i<int(vertices.size()); i++){
			CXXCoord_ftype *xyz = vertices[i].xyzPntr(vectors["accessibles"]); 
			for (int j=0; j<3; j++){
				coordBuffer[3*i + j] = xyz[j];
			}
		}
		graspFile.putFortranData((char *) coordBuffer, sizeof(float), 
								 3*vertices.size(), CXXFortranFile::FortranFloatData);
	}
	
	//Write normals if present
	if (vectors.find("normals") != vectors.end()){
		for (i=0; i<int(vertices.size()); i++){
			CXXCoord_ftype *xyz = vertices[i].xyzPntr(vectors["normals"]); 
			for (int j=0; j<3; j++){
				coordBuffer[3*i + j] = xyz[j];
			}
		}
		graspFile.putFortranData((char *) coordBuffer, sizeof(float), 
								 3*vertices.size(), CXXFortranFile::FortranFloatData);
	}
	
	delete [] coordBuffer;
	
	
	//Write triangles
	if (triangles.size()>1){
		triangleBuffer = new int[3 * nTriangles];
		for (i=0; i<nTriangles; i++){
			for (int j=0; j<3; j++){
				triangleBuffer[3*i + j] = 1 + triangles[i][j];
			}
		}
		graspFile.putFortranData((char *) triangleBuffer, sizeof(int), 
								 3*nTriangles, CXXFortranFile::FortranIntData);
		delete [] triangleBuffer;
	}
	
	//Write potential if present
	if (scalars.find("potential")!=scalars.end()){
		int scalarHandle = getScalarHandle("potential");
		float *potentialBuffer =new float[vertices.size()];
		for (i=0; i<int(vertices.size()); i++){
			potentialBuffer[i] = vertices[i].scalar(scalarHandle);
		}
		graspFile.putFortranData((char *) potentialBuffer, sizeof(float), 
								 vertices.size(), CXXFortranFile::FortranFloatData);
		delete [] potentialBuffer;
	}
	
	//Write potential if present
	if (scalars.find("gproperty1")!=scalars.end()){
		float *potentialBuffer =new float[vertices.size()];
		for (i=0; i<int(vertices.size()); i++){
			potentialBuffer[i] = vertices[i].scalar(scalars["gproperty1"]);
		}
		graspFile.putFortranData((char *) potentialBuffer, sizeof(float), 
								 vertices.size(), CXXFortranFile::FortranFloatData);
		delete [] potentialBuffer;
	}
	
	//Write potential if present
	if (scalars.find("gproperty2")!=scalars.end()){
		float *potentialBuffer =new float[vertices.size()];
		for (i=0; i<int(vertices.size()); i++){
			potentialBuffer[i] = vertices[i].scalar(scalars["gproperty2"]);
		}
		graspFile.putFortranData((char *) potentialBuffer, sizeof(float), 
								 vertices.size(), CXXFortranFile::FortranFloatData);
		delete [] potentialBuffer;
	}
	return 0;
}
Beispiel #14
0
VectorFont::Glyph::Glyph( const std::list<std::string> &cxf_glyph_definition, const double word_space_percentage, const double character_space_percentage )
{
	m_word_space_percentage = word_space_percentage;
	m_character_space_percentage = character_space_percentage;

	for (std::list<std::string>::const_iterator l_itLine = cxf_glyph_definition.begin(); l_itLine != cxf_glyph_definition.end(); l_itLine++)
	{
		wxString line( Ctt(l_itLine->c_str()) );
		wxString delimiters( _T(" \t\r\n,") );

		std::vector<wxString> tokens = Tokens( line, delimiters );
		if (tokens.size() == 0)
		{
			std::ostringstream l_ossError;
			l_ossError << "Expected tokens in glyph definition";
			throw(std::runtime_error(l_ossError.str().c_str()));
		}

		// Replace dot (.) for comma (,) if the locale settings require it.
		for (std::vector<wxString>::iterator token = tokens.begin(); token != tokens.end(); token++)
		{
			*token = PrepareStringForConversion( *token );
		}
		const wxChar * c_str = tokens[0].c_str();
		switch (c_str[0])
		{
		case 'L':
			if (tokens.size() != 5)
			{
				std::ostringstream l_ossError;
				l_ossError << "Expected 5 tokens when defining a line.  We got "
							<< tokens.size() << " tokens from '" << l_itLine->c_str() << "\n";
				throw(std::runtime_error(l_ossError.str().c_str()));
			}
			else
			{
				GlyphLine *line = new GlyphLine(	 PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[4].c_str()), NULL )) );
				m_graphics_list.push_back( line );
				m_bounding_box.Insert( line->BoundingBox() );
			}
			break;

		case 'A':

			if (tokens.size() != 6)
			{
				std::ostringstream l_ossError;
				l_ossError << "Expected 6 tokens when defining an arc";
				throw(std::runtime_error(l_ossError.str().c_str()));
			}
			else
			{
				if ((tokens[0].size() == 2) && (c_str[1] == 'R'))
				{
					// Reverse the starting and ending points.
					GlyphArc *arc = new GlyphArc( PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )),
										 strtod( Ttc(tokens[5].c_str()), NULL) ,
										 strtod( Ttc(tokens[4].c_str()), NULL ));
					m_graphics_list.push_back( arc );
					m_bounding_box.Insert( arc->BoundingBox() );
				} // End if - then
				else
				{
					GlyphArc *arc = new GlyphArc( PointToMM(strtod( Ttc(tokens[1].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[2].c_str()), NULL )),
										 PointToMM(strtod( Ttc(tokens[3].c_str()), NULL )),
										 strtod( Ttc(tokens[4].c_str()), NULL ),
										 strtod( Ttc(tokens[5].c_str()), NULL ) );
					m_graphics_list.push_back( arc );
					m_bounding_box.Insert( arc->BoundingBox() );
				}
			}
			break;

		default:
			std::ostringstream l_ossError;
			l_ossError << "Unexpected graphics element type '" << c_str[0] << "'";
			throw(std::runtime_error(l_ossError.str().c_str()));
		} // End switch
	} // End for
} // End constructor