Beispiel #1
0
bool demo_csgo::handle_cmdheader<DEMO_USERCMD>(std::istream& is, demo_cmdheader& cmdheader) {
    int32_t seq_num_out;
    if(!stream_read_primitive<int32_t>(is, seq_num_out)) {
        std::cerr << "handle_cmdheader<DEMO_USERCMD>(): !stream_read_primitive<int32_t>(is, seq_num_out)" << std::endl;
        return false;
    }

    int32_t data_length = 0;
    if(!stream_read_primitive<int32_t>(is, data_length)) {
        std::cerr << "handle_cmdheader<DEMO_USERCMD>(): !stream_read_primitive<int32_t>(is, data_length)" << std::endl;
        return false;
    }

    char* buffer = new char[data_length];
    is.read(buffer, data_length);
    CBitRead bs(buffer, data_length);

    usercmd ucmd = this->progressive_usercmd;

    if(bs.ReadOneBit()) { // bs.read(1);
        ucmd.command_number = bs.ReadUBitLong(32); // bs.nReadUInt(32);
    } else {
        ucmd.command_number = this->progressive_usercmd.command_number + 1;
    }

    if(bs.ReadOneBit()) { // bs.read(1)
        ucmd.tick_count = bs.ReadUBitLong(32); // bs.nReadUInt(32);
    } else {
        ucmd.tick_count = this->progressive_usercmd.tick_count + 1;
    }

    if(bs.ReadOneBit()) { // bs.read(1)
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.viewangles[0] = v;
    }

    if(bs.ReadOneBit()) { // bs.read(1)
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.viewangles[1] = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.viewangles[2] = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.aimdirection[0] = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.aimdirection[1] = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.aimdirection[2] = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.forwardmove = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.sidemove = v;
    }

    if(bs.ReadOneBit()) {
        float v;
        bs.ReadBits(reinterpret_cast<char*>(&v), 32);
        ucmd.upmove = v;
    }

    if(bs.ReadOneBit()) {
        ucmd.buttons = bs.ReadUBitLong(32); // bs.nReadUInt(32);
    }

    if(bs.ReadOneBit()) {
        ucmd.impulse = bs.ReadUBitLong(8); // bs.nReadUInt(8);
    }

    if(bs.ReadOneBit()) {
        ucmd.weapon_select = bs.ReadUBitLong(MAX_EDICT_BITS); // bs.nReadUInt(MAX_EDICT_BITS);
        if(bs.ReadOneBit()) {
            ucmd.weapon_subtype = bs.ReadUBitLong(WEAPON_SUBTYPE_BITS); // bs.nReadUInt(WEAPON_SUBTYPE_BITS);
        }
    }

    ucmd.random_seed = 0; // MD5_PseudoRandom( move->command_number ) & 0x7fffffff;

    if(bs.ReadOneBit()) {
        ucmd.mousedx = bs.ReadShort(); // bs.nReadUInt(16);
    }

    if(bs.ReadOneBit()) {
        ucmd.mousedx = bs.ReadShort(); // bs.nReadUInt(16);
    }

    // TODO: entitygroundcontact

    this->progressive_usercmd = ucmd;
    delete[] buffer;
    return true;
}
Beispiel #2
0
bool PolyModel::loadModel(std::istream& istr)
{

    int vertex_count;
    int face_count;
    string data;

    if (!istr.good())
        return false;

    char line[1024];
    istr.getline(line, 1024);

    std::istringstream sstr(line);
    sstr >> data >> vertex_count >> face_count;
    std::string attrib_type;
    bool has_texcoords = false;
    while (!sstr.eof() && sstr.good()) {
        sstr >> attrib_type;
        if (attrib_type == "tex-coords1")
            has_texcoords = true;
    }
    //m_verts.clear();
    //m_polys.clear();
    m_verts.resize(vertex_count);
    m_polys.resize(face_count);
    for(int i = 0; i < m_verts.capacity(); i++)//STORE VERTEX
    {
        string temp1,temp2,temp3;
        istr.getline(line, 1024);
        std::istringstream sstr(line);
        sstr >> temp1 >> temp2 >> temp3;
        m_verts[i].set(atof(temp1.c_str()), atof(temp2.c_str()), atof(temp3.c_str()));


    }


    for(int i = 0; i < m_polys.capacity(); i++)//STORE PLOY NUMBERS
    {
        string temp1,temp;
        istr.getline(line, 1024);
        std::istringstream sstr(line);
        sstr>>temp1;
        m_polys[i].insert(m_polys[i].begin(), atoi(temp1.c_str()));

        for(int j = 0; j < atoi(temp1.c_str()); j++)
        {
            sstr>>temp;
            atoi(temp.c_str());
            m_polys[i].insert(m_polys[i].begin()+j+1,atoi(temp.c_str()));
        }


    }
    /* for(int i =0;i<2;i++)
      {
      for(int j =0;j<4;j++)
      cout<<m_polys[i][j]<<" ";
      cout<<"\n";
      }*/
    m_center = 0.0f;
    m_max_bounding = -numeric_limits<float>::max();
    m_min_bounding = numeric_limits<float>::max();


    computeFaceNormals();
    computeVertexNormals();

    return true;
}
Beispiel #3
0
 bool eof() const
 { return inf->eof(); }
bool
CompareTestBaseline
::DoComparison( std::istream & testCSV,
	std::istream & baselineCSV )
{
	this->StringError.clear();
	this->AbsoluteError.clear();
	this->FractionalError.clear();
	this->RowCount = 0;
	this->MaxColumnCount = 1;
	this->StringErrorCount = 0;
	this->AbsoluteErrorCount = 0;
	this->FractionalErrorCount = 0;

	// the stream gets partitioned into lines, then tokens, then type
	// converted to a double or white-space removed string.
	std::string testLine;
	std::string baselineLine;
	std::istringstream testLineStream;
	std::istringstream baselineLineStream;
	std::string testToken;
	std::string baselineToken;
	std::istringstream testTokenStream;
	std::istringstream baselineTokenStream;
	double testTokenAsDouble;
	double baselineTokenAsDouble;
	std::string testTokenAsString;
	std::string baselineTokenAsString;
	bool fractionalErrorOccured = false;
	bool absoluteErrorOccurred = false;
	bool stringErrorOccurred = false;

	// for every line
	while( testCSV.good() )
		{
		++this->RowCount;
		StringErrorRowType stringErrorRow;
		NumericalErrorRowType fractionalErrorRow;
		NumericalErrorRowType absoluteErrorRow;

		getline( testCSV, testLine );
		getline( baselineCSV, baselineLine );
		if( testCSV.good() && !baselineCSV.good() || !testCSV.good() && baselineCSV.good() )
			{
			std::ostringstream ostrm;
			ostrm << "The Baseline does not have the same number of rows"
			      << " as the Test.";
			this->ComparisonMessage = ostrm.str();
			return false;
			}
		testLineStream.str( testLine );
		baselineLineStream.str( baselineLine );

		IndexValueType columnCount = 0;
		// for every token in a line
		while( testLineStream.good() )
			{
			++columnCount;
			// get the token
			getline( testLineStream, testToken, this->Parameters->Delimiter );
			getline( baselineLineStream, baselineToken, this->Parameters->Delimiter );
			if( testLineStream.good() && !baselineLineStream.good() || !testLineStream.good() && baselineLineStream.good() )
				{
				std::ostringstream ostrm;
				ostrm << "The Baseline does not have the same number of columns"
				      << " as the Test in row " << this->RowCount << ".";
				this->ComparisonMessage = ostrm.str();
				return false;
				}

			testTokenStream.clear();
			baselineTokenStream.clear();
			testTokenStream.str( testToken );
			baselineTokenStream.str( baselineToken );

			baselineTokenStream >> baselineTokenAsDouble;
			if( !baselineTokenStream.fail() )
				{
				testTokenStream >> testTokenAsDouble;
				if( testTokenStream.fail() )
					{
					std::ostringstream ostrm;
					ostrm << "Test entry was not a number when Baseline was a number"
					      << " in row " << this->RowCount << " column " << columnCount << ".";
					this->ComparisonMessage = ostrm.str();
					return false;
					}
				double fractionalError = fabs( testTokenAsDouble - baselineTokenAsDouble ) / fabs( baselineTokenAsDouble );
				if( fractionalError >= this->Parameters->FractionalTolerance )
					{
					NumericalErrorPairType error( columnCount - 1, fractionalError );
					fractionalErrorRow.push_back( error );
					fractionalErrorOccured = true;
					++this->FractionalErrorCount;
					}
				double absoluteError = fabs( testTokenAsDouble - baselineTokenAsDouble ); 
				if( absoluteError >= this->Parameters->AbsoluteTolerance )
					{
					NumericalErrorPairType error( columnCount - 1, absoluteError );
					absoluteErrorRow.push_back( error );
					absoluteErrorOccurred = true;
					++this->AbsoluteErrorCount;
					}
				}
			else // not a number, so treat it as a string
				{
				baselineTokenStream.seekg( 0 );
				baselineTokenStream.clear();
				testTokenAsString = "";
				baselineTokenAsString = "";
				// Initialize with non-empty string so we can
				// skip trailing whitespace in the while loop.
				std::string testWord;
				std::string baselineWord;
				while( !baselineTokenStream.eof() )
					{
					testTokenStream >> testWord;
					baselineTokenStream >> baselineWord;
					// trailing whitespace
					if( baselineTokenStream.fail() )
						{
						continue;
						}
					testTokenAsString += testWord;
					baselineTokenAsString += baselineWord;
					}
				if( baselineTokenAsString.compare( testTokenAsString ) )
					{
					stringErrorRow.push_back( columnCount -1 );
					stringErrorOccurred = true;
					++this->StringErrorCount;
					}
				}
			}
//---------------------------------------------------------------------
void OgreMeshDeserializer::readInts(std::istream& stream, std::uint32_t* pDest, size_t count)
{
    stream.read(reinterpret_cast<char*>(pDest), sizeof(std::uint32_t) * count);
    flipFromLittleEndian(pDest, sizeof(std::uint32_t), count);
}
task4_4::a_message::a_message( std::istream& inp )
{
	inp.read( content_, content_size );
	if ( inp.eof() )
		throw std::logic_error("bad input stream, a_message cannot be readed");
}
bool ossimMultiResLevelHistogram::importHistogram(std::istream& in)
{
   if (!in) // Check stream state.
   {
      return false;
   }
   
   ossimString buffer;
   getline(in, buffer);

   if ( in.eof() ) // Zero byte files will hit here.
   {
      return false;
   }

   // check to see if it is a proprietary histogram file
   // 
   if((buffer =="") || (buffer.c_str()[0] != 'F' ||
      buffer.c_str()[1] != 'i'))
   {
      in.seekg(0, ios::beg);
      ossimKeywordlist kwl;
      if (kwl.parseStream(in) == true)
      {
         return loadState(kwl);
      }
      else
      {
         return false;
      }
   }
   
   ossimProprietaryHeaderInformation header;
   in.seekg(0, ios::beg);
   deleteHistograms();
   if(header.parseStream(in))
   {
      ossim_uint32 numberOfResLevels = header.getNumberOfResLevels();
      
      if(numberOfResLevels)
      {
         theHistogramList.resize(numberOfResLevels);

         for(ossim_uint32 counter = 0; counter < (ossim_uint32)theHistogramList.size(); ++counter)
         {
            theHistogramList[counter] = NULL;
         }
         ossimString reslevelBuffer;
         ossimString buffer;
         
         for(ossim_uint32 idx = 0; idx < numberOfResLevels; ++idx)
         {
            getline(in, buffer);
            if(buffer.find("RR Level") != string::npos)
            {
               std::string::size_type offset = buffer.find(":");
               if(offset != string::npos)
               {
                  reslevelBuffer = buffer.substr(offset+1);
               }
               else
               {
                  deleteHistograms();
                  return false;
               }
            }
            else
            {
               deleteHistograms();
               return false;
            }
            ossim_uint32 resLevelIdx = reslevelBuffer.toUInt32();

            if(resLevelIdx < (ossim_uint32)theHistogramList.size())
            {
               if(!theHistogramList[resLevelIdx])
               {
                  ossimRefPtr<ossimMultiBandHistogram> histogram = new ossimMultiBandHistogram;
                  if(histogram->importHistogram(in))
                  {
                     theHistogramList[resLevelIdx] = histogram;
                  }
                  else
                  {
                     deleteHistograms();
                     return false;
                  }
               }
            }
            else
            {
               deleteHistograms();
               return false;
            }
            ossimString skipDot;
            getline(in, skipDot);
         }
      }
      else
      {
         return false;
      }
   }  

   return true;
}
Beispiel #8
0
void ossimDoqq::ldstr_v1(std::istream& in)
{
   static const char MODULE[] = "ossimDoqq::ldstr_v1(istream& in)";

   if (!in)
   {
      theErrorStatus = OSSIM_ERROR;
      return;
   }

   char tmp1[DATA_ORDER_SIZE+1];
   in.seekg(DATA_ORDER_OFFSET, std::ios::beg);
   in.get(tmp1, DATA_ORDER_SIZE+1);
   theDataOrder = tmp1;

   //***
   // Perform a sanity check on the data order just in case this isn't a
   // ossimDoqq file.
   //***  
   tmp1[DATA_ORDER_SIZE] = '\0';
   int data_order = atoi(tmp1);
   if ( (data_order != 1) && (data_order != 2) )
   {
      theErrorStatus = OSSIM_ERROR;

      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE << " NOTICE:\n"
            << "Invalid data ordering.  Not a doq?" << std::endl;
      }
   }
   
   char tmp2[LINE_SIZE+1];
   in.seekg(LINE_OFFSET, std::ios::beg);
   in.get(tmp2, LINE_SIZE+1);
   theLine = atoi(tmp2);

   char tmp3[SAMPLE_SIZE+1];
   in.seekg(SAMPLE_OFFSET,std::ios::beg);
   in.get(tmp3, SAMPLE_SIZE+1); 
   theSample = atoi(tmp3);

   // Check for valid lines and samples.
   if (theLine <= 0 || theSample <= 0)
   {
      theErrorStatus = OSSIM_ERROR;

      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE << " ERROR:\n"
            << "\tInvalid lines or samples."
            << std::endl;
      }
      
      return;
   }
   
   char tmp4[PROJECTION_SIZE+1];
   in.seekg(PROJECTION_OFFSET, std::ios::beg);
   in.get(tmp4, PROJECTION_SIZE+1);
   theProjection = tmp4;

   char tmp5[UTM_ZONE_SIZE+1];
   in.seekg(UTM_ZONE_OFFSET, std::ios::beg);
   in.get(tmp5, UTM_ZONE_SIZE+1);
   theUtmZone = atoi(tmp5);

   char tmp8[DATUM_SIZE+1];
   in.seekg(DATUM_OFFSET, std::ios::beg);
   in.get(tmp8, DATUM_SIZE+1);
   theDatum = tmp8;

   char rgbType[RGB_SIZE+1];
   in.seekg(RGB_OFFSET, std::ios::beg);
   in.get(rgbType, RGB_SIZE+1);


   if(atoi(rgbType) == 5)
   {
      theRgb = 3;
   }
   else
   {
      theRgb = 1;
   }
   
   theHeaderSize = (theSample * theRgb * 4);

   // Calculate the size of each record.
   theRecordSize = (theSample * theRgb);

   char tmp6[UL_EASTING_SIZE+1];
   in.seekg( (theRecordSize * 2) + UL_EASTING_OFFSET, std::ios::beg);
   in.get(tmp6, UL_EASTING_SIZE+1);

   char tmp7[UL_NORTHING_SIZE+1];
   in.seekg( (theRecordSize * 2) + UL_NORTHING_OFFSET, std::ios::beg);
   in.get(tmp7, UL_NORTHING_SIZE+1);
   
   // Get Easting and Northing.
   theEasting = convertStr(tmp6);
   theNorthing = convertStr(tmp7);

   char tmp10[GSD_SIZE+1];
   in.seekg( (theRecordSize*3) + GSD_X_OFFSET, std::ios::beg);
   in.get(tmp10, GSD_SIZE+1);
   theGsd.x = std::abs(ossimString(tmp10, tmp10+GSD_SIZE).toDouble());
   in.seekg( (theRecordSize*3) + GSD_Y_OFFSET, std::ios::beg);
   in.get(tmp10, GSD_SIZE+1);
   theGsd.y = std::abs(ossimString(tmp10, tmp10+GSD_SIZE).toDouble());
   
}
Beispiel #9
0
void ossimDoqq::ldstr_v2(std::istream& in)
{
   static const char MODULE[] = "ossimDoqq::ldstr_v2(istream& in)";

   if (!in)
   {
      theErrorStatus = OSSIM_ERROR;
      return;
   }

   char line[100];
   char dum1[30];
   char dum2[30];
   char dum3[30];
   char dum4[30];

   while((strncmp(line, "END_USGS_HEADER", 15) != 0)&&
			(in.good()))
   {
      // Read in one line of header at a time.
      in.getline(line, 100);
      
      if(strncmp(line, "SAMPLES_AND_LINES", 17) == 0)
      {
         sscanf(line, "%s %s %s", dum1, dum2, dum3);
         theLine = atoi(dum3);
         theSample = atoi(dum2);
      }

      else if(strncmp(line, "HORIZONTAL_COORDINATE_SYSTEM", 28) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theProjection = dum2;
      }
      
      else if(strncmp(line, "NW_QUAD_CORNER_XY", 17) == 0)
      {         
         sscanf(line, "%s %s %s", dum1, dum2, dum3);
         
         theUE = atof(dum2);
         theUN = atof(dum3);
      }
      
      else if(strncmp(line, "NE_QUAD_CORNER_XY", 17) == 0)
      {
         sscanf(line, "%s %s %s", dum1, dum2, dum3);
         theLE = atof(dum2);
         theLN = atof(dum3);
      }

      else if(strncmp(line, "COORDINATE_ZONE", 15) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theUtmZone = atoi(dum2);
      }

      else if(strncmp(line, "SOURCE_IMAGE_DATE", 17) == 0)
      {
         sscanf(line, "%s %s %s %s", dum1, dum2, dum3, dum4);
         theAcqYear  = ossimString(dum2);
         theAcqMonth = ossimString(dum3);
         theAcqDay   = ossimString(dum4);
      }

      else if((strncmp(line, "XY_ORIGIN", 9) == 0))
      {
         sscanf(line, "%s %s %s", dum1, dum2, dum3);
         theEasting = atof(dum2);
         theNorthing = atof(dum3);        
      }

      else if((strncmp(line, "HORIZONTAL_DATUM", 16) == 0) && theDatum.empty())
      {
         ossimString datum;         
         sscanf(line, "%s %s", dum1, dum2);
         datum = dum2; 
         
         if(datum.contains("NAD27"))
            theDatum = "NAD";
         else
            theDatum = "NAR";
      }

      else if(strncmp(line, "BYTE_COUNT", 10) == 0)
      {
         ossimString header;         
         sscanf(line, "%s %s", dum1, dum2);
         header = dum2;
         
         theHeaderSize = atoi(header.chars());
      }

      else if(strncmp(line, "BAND_CONTENT", 12) == 0)
      {
         ossimString rgbType;        
         sscanf(line, "%s %s", dum1, dum2);
         rgbType = dum2;

         if(rgbType.contains("BLACK&WHITE"))
            theRgb = 1;
         else
            theRgb = 3;
      }

      else if(strncmp(line, "HORIZONTAL_RESOLUTION", 21) == 0)
      {
         ossimString gsd;
         sscanf(line, "%s %s", dum1, dum2);
         gsd = dum2;

         theGsd.x = gsd.toDouble();
         theGsd.y = gsd.toDouble();
      }

      else if(strncmp(line, "QUADRANGLE_NAME", 15) == 0)
      {
         sscanf(line, "%s %29c", dum1, dum2);
         dum2[29] = 0;
         theQuadName = dum2;
      }

      else if(strncmp(line, "QUADRANT", 8) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theQuad = dum2;
      }

      else if(strncmp(line, "NATION", 6) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theNation = dum2;
      }

      else if(strncmp(line, "STATE", 5) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theState = dum2;
      }

      else if(strncmp(line, "RMSE_XY", 7) == 0)
      {
         sscanf(line, "%s %s", dum1, dum2);
         theRMSE = ossimString(dum2).toDouble();
      }

      else if(strncmp(line, "IMAGE_SOURCE", 12) == 0)
      {
         sscanf(line, "%s %29c", dum1, dum2);
         dum2[29] = 0;
         theImageSource = dum2;
      }

      else if(strncmp(line, "SOURCE_IMAGE_ID", 15) == 0)
      {
         sscanf(line, "%s %29c", dum1, dum2);
         dum2[29] = 0;
         theSourceImageID = dum2;
      }
   }

	if (!in.good())
	{
      theErrorStatus = OSSIM_ERROR;
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
			<< MODULE << " ERROR:\n"
			<< "\tHeader stream is bad."
			<< std::endl;
      }
		return;
	}

   // Check for valid lines and samples and header size.
   if(theLine <= 0 || theSample <= 0 || theHeaderSize <= 0)
   {
      theErrorStatus = OSSIM_ERROR;
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_WARN)
            << MODULE << " ERROR:\n"
            << "\tInvalid lines or samples or header size."
            << std::endl;
      }
      return;
   }

   // Assign concatenated acquisition date:
   theAcqYearMonthDay = theAcqYear;
   theAcqYearMonthDay += "-";
   theAcqYearMonthDay += theAcqMonth;
   theAcqYearMonthDay += "-";
   theAcqYearMonthDay += theAcqDay;

}
void matrix::Load(std::istream& in)
{
	int i,j;
    for(  i=0; i<vert; i++ ) for(  j=0; j<horz; j++ )
	in.read((char*) &(*this)(i, j), sizeof(float));
}
Beispiel #11
0
bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
	const std::string &end, u32 tab_depth)
{
	std::map<std::string, SettingsEntry>::const_iterator it;
	std::set<std::string> present_entries;
	std::string line, name, value;
	bool was_modified = false;
	bool end_found = false;

	// Add any settings that exist in the config file with the current value
	// in the object if existing
	while (is.good() && !end_found) {
		std::getline(is, line);
		SettingsParseEvent event = parseConfigObject(line, end, name, value);

		switch (event) {
		case SPE_END:
			os << line << (is.eof() ? "" : "\n");
			end_found = true;
			break;
		case SPE_MULTILINE:
			value = getMultiline(is);
			/* FALLTHROUGH */
		case SPE_KVPAIR:
			it = m_settings.find(name);
			if (it != m_settings.end() &&
				(it->second.is_group || it->second.value != value)) {
				printEntry(os, name, it->second, tab_depth);
				was_modified = true;
			} else {
				os << line << "\n";
				if (event == SPE_MULTILINE)
					os << value << "\n\"\"\"\n";
			}
			present_entries.insert(name);
			break;
		case SPE_GROUP:
			it = m_settings.find(name);
			if (it != m_settings.end() && it->second.is_group) {
				os << line << "\n";
				sanity_check(it->second.group != NULL);
				was_modified |= it->second.group->updateConfigObject(is, os,
					"}", tab_depth + 1);
			} else {
				printEntry(os, name, it->second, tab_depth);
				was_modified = true;
			}
			present_entries.insert(name);
			break;
		default:
			os << line << (is.eof() ? "" : "\n");
			break;
		}
	}

	// Add any settings in the object that don't exist in the config file yet
	for (it = m_settings.begin(); it != m_settings.end(); ++it) {
		if (present_entries.find(it->first) != present_entries.end())
			continue;

		printEntry(os, it->first, it->second, tab_depth);
		was_modified = true;
	}

	return was_modified;
}
Beispiel #12
0
bool demo_sequence_info_read(std::istream& is, demo_sequence_info& s) {
    is.read(reinterpret_cast<char*>(&s.seq_number_in), sizeof(s.seq_number_in));
    is.read(reinterpret_cast<char*>(&s.seq_number_out), sizeof(s.seq_number_out));

    return is.good();
}
Beispiel #13
0
bool demo_cmdinfo_read(std::istream& is, demo_cmdinfo& s) {
    demo_cmdinfo_player_read(is, s.players[0]);
    demo_cmdinfo_player_read(is, s.players[1]);

    return is.good();
}
Beispiel #14
0
bool demo_csgo::handle_cmdheader<DEMO_STRINGTABLES>(std::istream& is, demo_cmdheader& cmdheader) {
    int32_t data_length = 0;
    if(!stream_read_primitive<int32_t>(is, data_length)) {
        std::cerr << "handle_cmdheader<DEMO_STRINGTABLES>(): !stream_read_primitive<int32_t>(is, data_length)" << std::endl;
        return false;
    }

    char* buffer = new char[data_length];
    is.read(buffer, data_length);
    CBitRead bs(buffer, data_length);
    bs.Seek(0);

    int num_tables = bs.ReadByte();
    for(auto i = 0; i < num_tables; ++i) {
        char tablename[256];
        bs.ReadString(tablename, sizeof(tablename), false, 0);
        int num_strings = bs.ReadWord();

        bool is_userinfo = 0 == std::string("userinfo").compare(tablename);
        if(is_userinfo) {
            m_player_infos.clear();
        }

        for(auto j = 0; j < num_strings; ++j) {
            char stringname[4096];
            bs.ReadString(stringname, sizeof(stringname), false, 0);

            if(std::string(stringname).length() >= 100) {
                std::cerr << "demo_csgo::handle_cmdheader<DEMO_STRINGTABLES>(): std::string(stringname).length() >= 100, stringname := " << stringname << std::endl;
                return false;
            }

            if(bs.ReadOneBit()) {
                int user_data_size = (int)bs.ReadWord();
                if(user_data_size <= 0) {
                    std::cerr << "demo_csgo::handle_cmdheader<DEMO_STRINGTABLES>(): user_data_size <= 0, user_data_size := " << std::dec << user_data_size << std::endl;
                    return false;
                }

                uint8_t* data = new uint8_t[user_data_size+4];
                bs.ReadBytes(data, user_data_size);

                if(is_userinfo) {
                    player_info_t* player_info_inverse = reinterpret_cast<player_info_t*>(data);
                    player_info_t player_info = *player_info_inverse;

                    inverse_bytes(&player_info.xuid, &player_info_inverse->xuid);
                    inverse_bytes(&player_info.userID, &player_info_inverse->userID);
                    inverse_bytes(&player_info.friendsID, &player_info_inverse->friendsID);

                    m_player_infos.push_back(player_info);
                } else {
                }

                delete[] data;
            } else {
                //
            }
        }

        if(bs.ReadOneBit()) {
            int num_strings = bs.ReadWord();
            for(auto i = 0; i < num_strings; ++i) {
                char stringname[4096];
                bs.ReadString(stringname, sizeof(stringname), false, 0);

                if(bs.ReadOneBit()) {
                    int user_data_size = (int)bs.ReadWord();
                    if(user_data_size <= 0) {
                        std::cerr << "demo_csgo::handle_cmdheader<DEMO_STRINGTABLES>(): user_data_size <= 0, user_data_size := " << std::dec << user_data_size << std::endl;
                        return false;
                    }

                    uint8_t* data = new uint8_t[user_data_size+4];
                    bs.ReadBytes(data, user_data_size);

                    if(i >= 2){
                        //
                    }

                    delete[] data;
                } else {
                    if(i >= 2) {
                        //
                    }
                }
            }
        }
    }

    delete[] buffer;
    return true;
}
Beispiel #15
0
        }
    };

    std::ostream& operator<<(std::ostream& out, const ostrstream& x) {
        out << static_cast<strstreambuf*>(x.rdbuf())->str();
        return out;
    }

    class istrstream : public std::istream {
        strstreambuf sb;
    public:
        istrstream(char* buf) : sb(buf) { }

        template<class T>
        istrstream& operator>>(T& x) {
            std::istream in(&sb);
            in.copyfmt(*this);
            in >> x;
            setstate(in.rdstate());
            return *this;
        }
    };
}

int main() {
    using namespace std;
    using namespace ch21;

    char buf[1024];
    ostrstream out(buf, 1024);
    out << "foo bar " << 12345;
Beispiel #16
0
fourcc::fourcc( std::istream &in )
{
	in.read( _char, 4 );
}
Beispiel #17
0
	Bool TgaFile::LoadFromStream( std::istream & p_Stream )
	{
		// Read the stream size.
		p_Stream.seekg( 0, std::fstream::end );
		SizeType fileSize = static_cast<SizeType>( p_Stream.tellg( ) );
		p_Stream.seekg( 0, std::fstream::beg );

		// Error check the stream size
		if( fileSize < 18 )
		{
			bitLogGraErr(  "Missing header field." );
			p_Stream.seekg( 0, std::fstream::beg ); // Go back to the begining of the stream
			return false;
		}

		// Read the header.
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_IdLength ), 1 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ColorMapType ), 1 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageType ), 1 );
		// Read color map specifications
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ColorMapSpec.m_Offset ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ColorMapSpec.m_Length ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ColorMapSpec.m_EntrySize ), 1 );
		// Read image specifications
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_OriginX ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_OriginY ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_ImageWidth ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_ImageHeight ), 2 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_PixelDepth ), 1 );
		p_Stream.read( reinterpret_cast<char *>( &m_Header.m_ImageSpec.m_ImageDescriptor ), 1 );

		// Error check the header field.
		if( m_Header.m_ImageSpec.m_PixelDepth != 8 &&
			m_Header.m_ImageSpec.m_PixelDepth != 16 &&
			m_Header.m_ImageSpec.m_PixelDepth != 24 &&
			m_Header.m_ImageSpec.m_PixelDepth != 32 )
		{
			bitLogGraErr( "Not supporting " << (int)m_Header.m_ImageSpec.m_PixelDepth << " bit pixel depth."  );
			p_Stream.seekg( 0, std::fstream::beg ); // Go back to the begining of the stream
			return false;
		}

		// Error check the image type
		if( m_Header.GetImageType( ) != UncompressedTrueColorImage &&
			m_Header.GetImageType( ) != UncompressedGrayscaleImage )
		{
			bitLogGraErr(  "Not supporting color mapped or compressed images." );
			p_Stream.seekg( 0, std::fstream::beg ); // Go back to the begining of the stream
			return false;
		}

		if(	m_Header.GetImageType( ) == UncompressedGrayscaleImage && m_Header.m_ImageSpec.m_PixelDepth != 8 )
		{
			bitLogGraErr(  "Not supporting non 8 bit grayscale iamges." );
			p_Stream.seekg( 0, std::fstream::beg ); // Go back to the begining of the stream
			return false;
		}

		// Clear the old pixel data.
		if( m_pData )
		{
			delete m_pData;
		}

		// Calcualte the data size.
		m_DataSize =	static_cast<SizeType>( m_Header.m_ImageSpec.m_ImageWidth ) *
						static_cast<SizeType>( m_Header.m_ImageSpec.m_ImageHeight ) *
						static_cast<SizeType>( m_Header.m_ImageSpec.m_PixelDepth / 8 );

		// Read the data if we are expecting any data.
		if( m_DataSize != 0 )
		{
			// Check if the data fits in the file
			if( fileSize < m_DataSize + 18 )
			{
				bitLogGraErr(  "The expected data size is too large." );
				p_Stream.seekg( 0, std::fstream::beg ); // Go back to the begining of the stream
				return false;
			}

			// Allocate the data
			m_pData = new Uint8[ m_DataSize ];

			// Read the bitmap data
			p_Stream.read( reinterpret_cast<char *>( m_pData ), m_DataSize );
		}

		// Read the footer( optional )
		if( fileSize >= 44 + m_DataSize )
		{
			// Seek to the end where the footer is expected to be
			p_Stream.seekg( 26, std::fstream::end );

			// Read the footer
			p_Stream.read( reinterpret_cast<char *>( &m_Footer.m_ExtensionOffset ), 4 );
			p_Stream.read( reinterpret_cast<char *>( &m_Footer.m_DeveloperAreaOffset ), 4 );
			p_Stream.read( reinterpret_cast<char *>( m_Footer.m_Signature ), 16 );
			p_Stream.read( reinterpret_cast<char *>( &m_Footer.m_Dot ), 1 );
			p_Stream.read( reinterpret_cast<char *>( &m_Footer.m_End ), 1 );
		}

		// Go back to the begining of the stream
		p_Stream.seekg( 0, std::fstream::beg );

		// Succeeded.
		return true;
	}
void CompressedPixmap::loadFromStream(std::istream& inputStream)
{
    PixmapHeader header;

    inputStream.read((char*)&header, sizeof(PixmapHeader));

    int bitAccessor = 1;

    for (int i = 0; i < header.domainRegionCount; ++i)
    {
        unsigned long packed;
        inputStream.read((char*)&packed, 4);

        std::bitset<32> bitset(packed);
        DomainRegionDescriptor domainRegion = { 0, 0, 0 };

        for (int j = 0; j < 13; ++j)
        {
            if (bitset[j])
                domainRegion.x += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 13; ++j)
        {
            if (bitset[13 + j])
                domainRegion.y += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 6; ++j)
        {
            if (bitset[26 + j])
                domainRegion.size += bitAccessor;

            bitAccessor <<= 1;
        }

        m_domainRegions.push_back(domainRegion);

        bitAccessor = 1;
    }

    for (int i = 0; i < header.rangeRegionCount; ++i)
    {
        unsigned long long packed;
        inputStream.read((char*)&packed, 7);

        std::bitset<58> bitset(packed);
        RangeRegionDescriptor rangeRegion = { 0, 0, 0, 0, 0, 0 };

        for (int j = 0; j < 13; ++j)
        {
            if (bitset[j])
                rangeRegion.x += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 13; ++j)
        {
            if (bitset[13 + j])
                rangeRegion.y += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 4; ++j)
        {
            if (bitset[26 + j])
                rangeRegion.size += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 14; ++j)
        {
            if (bitset[30 + j])
                rangeRegion.domainRegionIndex += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 4; ++j)
        {
            if (bitset[44 + j])
                rangeRegion.transformation += bitAccessor;

            bitAccessor <<= 1;
        }

        bitAccessor = 1;
        for (int j = 0; j < 8; ++j)
        {
            if (bitset[48 + j])
                rangeRegion.firstPixelValue += bitAccessor;

            bitAccessor <<= 1;
        }

        m_rangeRegions.push_back(rangeRegion);

        bitAccessor = 1;
    }

    refreshSize();
}
bool rspfApplanixEOFile::parseStream(std::istream& in)
{
    theRecordIdMap.clear();
    rspfString line;
    int c = '\0';
    if(!parseHeader(in, theHeader))
    {
        return false;
    }

    // now parse parameters
    in>>applanix_skipws;
    line = "";
    while(in.good()&&
            !line.contains("RECORD FORMAT"))
    {
        std::getline(in, line.string());
        line = line.upcase();
        line = line.substitute("\r","\n", true);
        if(line.contains("KAPPA CARDINAL"))
        {
            theKappaCardinal = line;
            theKappaCardinal = theKappaCardinal.substitute("KAPPA CARDINAL ROTATION","");
            theKappaCardinal = theKappaCardinal.substitute(":","");
            theKappaCardinal = theKappaCardinal.substitute("\n","");
        }
        else if(line.contains("LEVER ARM"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("LEVER ARM VALUES:",
                                   "");
            line = line.substitute(",",
                                   "\n",
                                   true);
            std::istringstream in(line);

            kwl.parseStream(in);

            theLeverArmLx = kwl.find("LX");
            theLeverArmLy = kwl.find("LY");
            theLeverArmLz = kwl.find("LZ");
        }
        else if(line.contains("BORESIGHT VALUES"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("BORESIGHT VALUES:",
                                   "");
            line = line.substitute(",",
                                   "\n",
                                   true);

            std::istringstream in(line);

            kwl.parseStream(in);


            theBoreSightTx = kwl.find("TX");
            theBoreSightTy = kwl.find("TY");
            theBoreSightTz = kwl.find("TZ");
        }
        else if(line.contains("SHIFT VALUES:"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute("SHIFT VALUES:","");
            line = line.substitute(",",
                                   "\n",
                                   true);

            std::istringstream in(line);
            kwl.parseStream(in);


            theShiftValuesX = kwl.find("X");
            theShiftValuesY = kwl.find("Y");
            theShiftValuesZ = kwl.find("Z");

        }
        else if(line.contains("GRID:"))
        {
            rspfKeywordlist kwl(':');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);
            theUtmZone = kwl.find("ZONE");

            if(theUtmZone.contains("NORTH"))
            {
                theUtmHemisphere = "North";
            }
            else
            {
                theUtmHemisphere = "South";
            }
            theUtmZone = theUtmZone.replaceAllThatMatch("UTM|\\(.*\\)|NORTH|SOUTH","");
            theUtmZone = theUtmZone.trim();
        }
        else if(line.contains("FRAME DATUM"))
        {
            rspfKeywordlist kwl(':');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theMappingFrameDatum = kwl.find("MAPPING FRAME DATUM");
            theMappingFrameProjection = kwl.find("MAPPING FRAME PROJECTION");
            theMappingFrameDatum = theMappingFrameDatum.trim();
            theMappingFrameProjection = theMappingFrameProjection.trim();
        }
        else if(line.contains("POSPROC SBET"))
        {
            theSbetField = line.after(":");
            theSbetField = theSbetField.trim();
        }
        else if(line.contains("CENTRAL MERIDIAN"))
        {
            theCentralMeridian = line;
            theCentralMeridian = theCentralMeridian.substitute("CENTRAL MERIDIAN","");
            theCentralMeridian = theCentralMeridian.substitute("=","");
            theCentralMeridian = theCentralMeridian.substitute("DEG","");
            theCentralMeridian = theCentralMeridian.substitute(";","");
        }
        else if(line.contains("LATITUDE OF THE GRID ORIGIN"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theOriginLatitude  = kwl.find("LATITUDE OF THE GRID ORIGIN");
            theGridScaleFactor = kwl.find("GRID SCALE FACTOR");
        }
        else if(line.contains("FALSE EASTING"))
        {
            rspfKeywordlist kwl('=');
            line = line.substitute(";",
                                   "\n",
                                   true);
            std::istringstream in(line);
            kwl.parseStream(in);

            theFalseEasting  = kwl.find("FALSE EASTING");
            theFalseNorthing = kwl.find("FALSE NORTHING");
        }
    }

    in>>applanix_skipws;

    c = in.get();

    std::vector<rspfString> fieldArray;
    rspfString field;

    while(in.good()&&
            (c!='\n')&&
            (c!='\r'))
    {
        field = "";
        while((c != ',')&&
                (c != '\n')&&
                (c != '\r'))
        {
            field += (char)c;
            c = in.get();
        }
        if((c!='\n')&&
                (c!='\r'))
        {
            c = in.get();
        }
        field = field.trim();
        if(field != "")
        {
            theRecordFormat.push_back(field);
        }
    }
    in>>applanix_skipws;

    if(in.peek() == '(')
    {
        std::getline(in, line.string());
    }
    in>>applanix_skipws;
    rspfRefPtr<rspfApplanixEORecord> record = new rspfApplanixEORecord((rspf_uint32)theRecordFormat.size());
    rspf_int32 latIdx = getFieldIdx("LAT");
    rspf_int32 lonIdx = getFieldIdx("LONG");;
    bool hasLatLon = (latIdx >=0)&&(lonIdx >= 0);


    if(hasLatLon)
    {
        theMinLat = 90.0;
        theMaxLat = -90.0;
        theMinLon = 180.0;
        theMaxLon = -180.0;
    }
    else
    {
        theMinLat = rspf::nan();
        theMaxLat = rspf::nan();
        theMinLon = rspf::nan();
        theMaxLon = rspf::nan();
    }

    while(in.good()&&theRecordFormat.size())
    {
        std::getline(in, line.string());
        line = line.trim();
        if(line != "")
        {
            std::istringstream inStr(line);
            rspf_uint32 idx;
            rspfString value;

            for(idx = 0; idx < theRecordFormat.size(); ++idx)
            {
                inStr >> (*record)[idx];
            }
            if(hasLatLon)
            {
                double lat = (*record)[latIdx].toDouble();
                double lon = (*record)[lonIdx].toDouble();

                if(lat<theMinLat) theMinLat = lat;
                if(lat>theMaxLat) theMaxLat = lat;
                if(lon<theMinLon) theMinLon = lon;
                if(lon>theMaxLon) theMaxLon = lon;

            }
            theApplanixRecordList.push_back(new rspfApplanixEORecord(*record));
        }
    }
Beispiel #20
0
void EatWhitespace(std::istream& in)
{
  while(in && isspace(in.peek())) in.get();
}
//I/O facilities - FIXME: read( char *fname ), etc. missing
int BSplineCurve2D::read(std::istream &infile)
{
    //FIXME: maybe we need more checks!!!
    char txtbuffer[256];
    bool israt       = false;
    bool isemptyknot = false;


    infile.getline(txtbuffer, 255);   //read line
    if(strcmp(txtbuffer, ff_const_1) &&
       strcmp(txtbuffer, ff_const_4))
    {
        return -1; //bad file format
    }
    if(!strcmp(txtbuffer, ff_const_4))
    {
        israt = true;
    }
    infile >> txtbuffer; //FIXME: error prone: too long string causes problem!!!
    if(strcmp(txtbuffer, ff_const_2) )
        return -1;                                     //yeah, bad file format again

    infile >> dimension >> std::ws;
    if(dimension < 1)
        return -2;                  //ah, bad dimension

    int knoterr = basis_function.read(infile);
    if(knoterr == -3)  // FIXME: hardwired val...
    {
        isemptyknot = true;
    }
    else if(knoterr)
    {
        return -3; //error reading basis function
    }
    if(CheckKnotPoints(basis_function.getKnotVector(), dimension) )
        return -4;

    infile >> txtbuffer; //FIXME: error prone: too long string causes problem!!!
    if(strcmp(txtbuffer, ff_const_3) )
        return -1;                                    //bad file format once again

    DCTPVec3dvector::size_type num_of_cps;
    infile >> num_of_cps >> std::ws;
    if(num_of_cps < 1)
        return -5;                   //too few control points
    control_points.resize(num_of_cps);   //FIXME: whatif not enoght memory?

    for(DCTPdvector::size_type i = 0; i < num_of_cps; ++i)
    {
        Vec3d cp;
        if(israt)
        {
            infile >> cp[0] >> cp[1] >> cp[2] >> std::ws;
        }
        else
        {
            infile >> cp[0] >> cp[1] >> std::ws;
            cp[2] = 1.0;
        }
        control_points[i] = cp;   //FIXME: ya see, we need ERROR CHECKS!!!
    }
void SpmdMultiVectorSerializer<Scalar>::deserialize(
  std::istream& in, MultiVectorBase<Scalar>* mv
  ) const
{
  Teuchos::RCP<const SpmdVectorSpaceBase<Scalar> >
    mpi_vec_spc = Teuchos::rcp_dynamic_cast<const SpmdVectorSpaceBase<Scalar> >(mv->range());
  if( mpi_vec_spc.get() ) {
    // This is a mpi-based vector space so let's just read the local
    // multi-vector elements (row-by-row).
    const Ordinal
      localOffset = mpi_vec_spc->localOffset(),
      localSubDim = mpi_vec_spc->localSubDim();
    const Range1D localRng( localOffset, localOffset+localSubDim-1 );
    DetachedMultiVectorView<Scalar> local_mv(*mv,localRng,Range1D());
#ifdef TEUCHOS_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      !in, std::logic_error
      ,"Error: The input stream given is empty before any reading has began!\n"
      "If this stream came from a file, then the file may not exist!"
      );
#endif
    Ordinal localSubDim_in;
    in >> localSubDim_in;
#ifdef TEUCHOS_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      localSubDim != localSubDim_in, std::logic_error
      , "Error, localSubDim = "<<localSubDim<<" does not match the read in value of "
      "localSubDim_in = "<<localSubDim_in<<"!"
      );
#endif
    Ordinal numSubCols_in;
    in >> numSubCols_in;
#ifdef TEUCHOS_DEBUG
    TEUCHOS_TEST_FOR_EXCEPTION(
      local_mv.numSubCols() != numSubCols_in, std::logic_error
      , "Error, numSubCols = "<<local_mv.numSubCols()<<" does not match the read in value of "
      "numSubCols_in = "<<numSubCols_in<<"!"
      );
#endif
    // Get rid of extra newline after first line
    in >> std::ws;
    // Get the elements
    if( binaryMode() ) {
      // Column-wise
      for( Ordinal j = 0; j < local_mv.numSubCols(); ++j )
        in.read( reinterpret_cast<char*>(&local_mv(0,j)), sizeof(Scalar)*localSubDim );
    }
    else {
      // Row-wise
      for( Ordinal i = 0; i < localSubDim; ++i ) {
#ifdef TEUCHOS_DEBUG
        TEUCHOS_TEST_FOR_EXCEPTION( !in, std::logic_error, "Error, premature end of input!"	);
#endif
        Ordinal i_in;
        in >> i_in;
#ifdef TEUCHOS_DEBUG
        TEUCHOS_TEST_FOR_EXCEPTION(
          i != i_in, std::logic_error
          , "Error, i = "<<i<<" does not match the read in value of "
          "i_in = "<<i_in<<"!"
          );
#endif
        for( Ordinal j = 0; j < local_mv.numSubCols(); ++j ) {
#ifdef TEUCHOS_DEBUG
          TEUCHOS_TEST_FOR_EXCEPTION(
            !in, std::logic_error
            ,"Error: The input stream ran out at j="<<j<<" before"
            " reaching the promised " << local_mv.numSubCols()
            << " rows of the (multi)vector!"
            );
#endif
          in >> local_mv(i,j);
        }
      }
    }
  }
  else {
//---------------------------------------------------------------------
void OgreMeshDeserializer::readShorts(std::istream& stream, unsigned short* pDest, size_t count)
{
    stream.read(reinterpret_cast<char*>(pDest), sizeof(unsigned short) * count);
    flipFromLittleEndian(pDest, sizeof(unsigned short), count);
}
void copyStream(std::istream &is, std::ostream &os) {
    char ch;
    while (is.get(ch)) {
        os.put(ch);
    }
}
void OgreMeshDeserializer::skipChunk(std::istream& stream)
{
    stream.seekg(mCurrentstreamLen - calcChunkHeaderSize(), std::ios_base::cur);
}
Beispiel #26
0
void Parser::skip_item(std::istream &stream)
{
    auto size = read_size(stream);
    if (!stream.seekg(size, std::ios_base::cur))
        throw std::runtime_error("Failed to skip chunk");
}
Beispiel #27
0
/** This method replaces all the tags in the UTF-8 encoded input stream by spaces or underscores in the output stream.
Underscores are written when the tag is adjacent to a word (directly or by another) tag. Spaces are written otherwise.
If an unclosed tag finishes the input stream, the result is written but an error message is written in <I>status</I> and a non zero-value is returned.
If an opening '<' is found inside a tag, it is ignored (replaced) but an error message is written in <I>status</I> and a non zero-value will be returned.
If a closing '>' is found outside a tag, it is ignored (replaced) but an error message is written in <I>status</I> and a non zero-value will be returned.
This method does not modify its receiver and thus is constant.
Throws a runtime_error in case of an unknown internal state
It does not record the removed tags. Should be done in another method;

@param std::ostream& status the stream where errors and warning will be written
@param std::istream& input the input stream. Should contain a valid SGML file
@param std::ostream& output the output stream. The result stream where un-tagged results are written
@return int 0 if there is no error nor warning ; non-zero otherwise.
 */
int TextFormater::untaggingWithSpaces(std::ostream& status, std::istream& input,
        std::ostream& output, bool wide, 
        const std::string& endSentenceTag) const
{
  LIMA_UNUSED(wide);
    LILOGINIT;
    setlocale(LC_CTYPE,"fr_FR.UTF-8");
    
    size_t nb = 0; // the number of chars in the current tag when we cannot know
                            // if it is bond to the following text (tag after a white space)
    size_t nbNewLines = 0; // the number of newlines in the current tag when we cannot know
                            // if it is bond to the following text (tag after a white space)
    size_t position=0; // position in the input stream;
    enum RetVal {SUCCESS, INVALID_OPENING_TAG_CHAR, INVALID_CLOSING_TAG_CHAR,
                    DUPLICATED_OPENING_TAG_CHAR, DUPLICATED_CLOSING_TAG_CHAR,
                    UNCLOSED_OPENING_TAG_CHAR};
    RetVal retVal = SUCCESS;
    
    enum Etat {TEXT, DEBCOL, FINCOL, BLANC, DEBBLANC, FINBLANC, BEGENTITY, ENTITY};
    Etat etat = BLANC;

    char carLu;
    char carLu2; 
    std::string s;
    
    std::ostringstream txt;
    std::ostringstream tag;
    std::ostringstream tagValue;
    std::ostringstream entity;
    
    while (input.good())
    {
        input.get(carLu);
        LDEBUG << carLu;
        if (input.eof()) continue;
        switch (etat)
        {
            case TEXT:
                switch (carLu)
                {
                    case '<':
                        output << txt.str();
                        txt.str("");
                        tag << '_';
                        tag << ' ';
                        tagValue << carLu;
                        LDEBUG << "TEXT-> DEBCOL" << LENDL;
                        etat = DEBCOL;
                    break;
                    case '>':
                        txt << carLu;
                        status << "Invalid '>' character at " << position << std::endl;
                        retVal = INVALID_CLOSING_TAG_CHAR;
                    break;
                    case '&':
                        output << txt.str();
                        txt.str("");
                        entity << carLu;
                        LDEBUG << "TEXT -> BEGENTITY;" << LENDL;
                        etat = BEGENTITY;
                    break;
                    case ' ':case '\t':case '\n':
                        output << txt.str();;
                        output << carLu;
                        txt.str("");
                        LDEBUG << "TEXT-> BLANC" << LENDL;
                        etat = BLANC;
                    break;
                    default:
                        txt << carLu;
                    break;
                }
            break;
            case BEGENTITY:
                switch (carLu)
                {
                    case 'A':;case 'B':;case 'C':;case 'D':;case 'E':;case 'F':;case 'G':;
                    case 'H':;case 'I':;case 'J':;case 'K':;case 'L':;case 'M':;case 'N':;
                    case 'O':;case 'P':;case 'Q':;case 'R':;case 'S':;case 'T':;case 'U':;
                    case 'V':;case 'W':;case 'X':;case 'Y':;case 'Z':;
                    case 'a':;case 'b':;case 'c':;case 'd':;case 'e':;case 'f':;case 'g':;
                    case 'h':;case 'i':;case 'j':;case 'k':;case 'l':;case 'm':;case 'n':;
                    case 'o':;case 'p':;case 'q':;case 'r':;case 's':;case 't':;case 'u':;
                    case 'v':;case 'w':;case 'x':;case 'y':;case 'z':
                        entity << carLu;
                        LDEBUG << "BEGENTITY-> ENTITY" << LENDL;
                        etat = ENTITY;
                    break;
                    case '<':
                        output.put('_');
                        output.put(' ');
                        entity.str("");
                        tag << '_';
                        tag << ' ';
                        LDEBUG << "BEGENTITY-> DEBCOL" << LENDL;
                        etat = DEBCOL;
                    break;
                    case ' ':case '\t':case '\n':
//                        output.put('_');
                        output.put(' ');
                        output << carLu;
                        entity.str("");
                        LDEBUG << "BEGENTITY-> BLANC" << LENDL;
                        etat = BLANC;
                    break;
                    default:
//                        output.put('_');
                        output.put(' ');
                        output << carLu;
                        entity.str("");
                        LDEBUG << "BEGENTITY-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                }
            break;
            case ENTITY:
                switch (carLu)
                {
                    case 'A':;case 'B':;case 'C':;case 'D':;case 'E':;case 'F':;case 'G':;
                    case 'H':;case 'I':;case 'J':;case 'K':;case 'L':;case 'M':;case 'N':;
                    case 'O':;case 'P':;case 'Q':;case 'R':;case 'S':;case 'T':;case 'U':;
                    case 'V':;case 'W':;case 'X':;case 'Y':;case 'Z':;
                    case 'a':;case 'b':;case 'c':;case 'd':;case 'e':;case 'f':;case 'g':;
                    case 'h':;case 'i':;case 'j':;case 'k':;case 'l':;case 'm':;case 'n':;
                    case 'o':;case 'p':;case 'q':;case 'r':;case 's':;case 't':;case 'u':;
                    case 'v':;case 'w':;case 'x':;case 'y':;case 'z':
                        entity << carLu;
                    break;
                    case '<':
                        for (uint64_t i = 0; i < entity.str().size(); i++)
                        {
//                            output << '_';
                            output << ' ';
                        }
                        entity.str("");
//                        tag << '_';
                        tag << ' ';
                        LDEBUG << "ENTITY-> DEBCOL" << LENDL;
                        etat = DEBCOL;
                    break;
                    case ' ':case '\t':case '\n':
                        for (uint64_t i = 0; i < entity.str().size(); i++)
                        {
//                            output << '_'; 
                            output << ' '; 
                        }
                        output << carLu;
                        entity.str("");
                        LDEBUG << "ENTITY-> BLANC" << LENDL;
                        etat = BLANC;
                    break;
                    case ';':
                        for (uint64_t i = 0; i < entity.str().size()+1; i++)
                        {
//                            output << '_'; 
                            output << ' '; 
                        }
                        entity.str("");
                        LDEBUG << "ENTITY-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                    default:
                        for (uint64_t i = 0; i < entity.str().size(); i++)
                        {
//                            output << '_'; 
                            output << ' '; 
                        }
                        output << carLu;
                        entity.str("");
                        LDEBUG << "ENTITY-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                }
            break;
            case DEBCOL:
                tagValue << carLu;
                switch (carLu)
                {
                    case '<':
//                        tag << '_';
                        tag << ' ';
                        status << "Invalid '<' character at " << position << std::endl;
                        retVal = DUPLICATED_OPENING_TAG_CHAR;
                    break;
                    case '>':
//                        tag << '_';
                        tag << ' ';
                        LDEBUG << "DEBCOL-> FINCOL" << LENDL;
                        etat = FINCOL;
                    break;
                    case ' ':case '\t':case '\n':
                        tag << carLu;
                    break;
                    default:
                        LDEBUG << "Looking at " << carLu << LENDL;
                        char buf[MB_LEN_MAX];
                        buf[0] = carLu;
                        input.rdbuf()-> sgetn(buf+1, 9);
                        wchar_t mbc;
                        int transRes = mbtowc(&mbc, buf, MB_LEN_MAX);
                        LDEBUG << "transres value is " << transRes << LENDL;
                        if (transRes > 1)
                        {
                            LDEBUG << "Got a multibyte char inside tag: " << mbc << LENDL;
                            for (int i = 1; i < transRes; i++)
                            {
                                input.get(carLu);
                            }
                        }
//                        tag << '_';
                        tag << ' ';
                    break;
                }
            break;
            case FINCOL:
                switch (carLu)
                {
                    case '<':
//                        tag << '_';
                        tag << ' ';
                        tagValue << carLu;
                        LDEBUG << "FINCOL-> DEBCOL" << LENDL;
                        etat = DEBCOL;
                    break;
                    case '>':
//                        tag << '_';
                        tag << ' ';
                        tagValue << carLu;
                        status << "Invalid '>' character at " << position << std::endl;
                        retVal = DUPLICATED_CLOSING_TAG_CHAR;
                    break;
                    case ' ':case '\t':case '\n':
                        putTag(status, output, wide, endSentenceTag, tag, tagValue);
                        output << carLu;
                        LDEBUG << "FINCOL-> BLANC" << LENDL;
                        etat = BLANC;
                    break;
                    case '&':
                        putTag(status, output, wide, endSentenceTag, tag, tagValue);
                        entity << carLu;
                        LDEBUG << "FINCOL -> BEGENTITY;" << LENDL;
                        etat = BEGENTITY;
                    break;
                    default:
                        putTag(status, output, wide, endSentenceTag, tag, tagValue);
                        txt << carLu;
                        tagValue << carLu;
                        LDEBUG << "FINCOL-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                }
            break;
            case BLANC:
                switch (carLu)
                {
                    case '&':
                        entity << carLu;
                        LDEBUG << "BLANC -> BEGENTITY;" << LENDL;
                        etat = BEGENTITY;
                    break;
                    case '<':
                        nb = 1;
                        nbNewLines = 0;
                        tagValue << carLu;
                        LDEBUG << "BLANC-> DEBBLANC" << LENDL;
                        etat = DEBBLANC;
                    break;
                    case '>':
                        output << '>';
                        status << "Invalid '>' character at " << position << std::endl;
                        retVal = INVALID_CLOSING_TAG_CHAR;
                        LDEBUG << "BLANC-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                    case ' ':case '\t':case '\n':
                        output << carLu;
                    break;
                    default:
                        txt << carLu;
                        LDEBUG << "BLANC-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                }
            break;
            case DEBBLANC:
                tagValue << carLu;
                switch (carLu)
                {
                    case '<':
                        nb++;
                        status << "Duplicated '<' character at " << position << std::endl;
                        retVal = DUPLICATED_OPENING_TAG_CHAR;
                    break;
                    case '>':
                        nb++;
                        LDEBUG << "DEBBLANC-> FINBLANC" << LENDL;
                        etat = FINBLANC;
                    break;
                    case '\n':
                        nbNewLines++;
                    break;
                    default:
                        LDEBUG << "Looking at " << carLu << LENDL;
                        char buf[MB_LEN_MAX];
                        buf[0] = carLu;
                        std::streamsize got = input.rdbuf()-> sgetn(buf+1, 9);
                        for (std::streamsize i = 0; i < got ; i++)
                            input.rdbuf()-> sungetc();
                        for (uint64_t i = 0; i<MB_LEN_MAX; i++)
                            LDEBUG << buf[i];
                        LDEBUG << LENDL;
                        wchar_t mbc;
                        int transRes = mbtowc(&mbc, buf, MB_LEN_MAX);
                        LDEBUG << "transres  is " << transRes << LENDL;
                        if (transRes > 1)
                        {
                            LDEBUG << "Got a multibyte char inside tag: " << mbc << LENDL;
                            for (int i = 1; i < transRes; i++)
                            {
                                input.get(carLu);
                            }
                        }
                        nb++;
                    break;
                }
            break;
            case FINBLANC:
                switch (carLu)
                {
                    case '<':
                        nb++;
                        tagValue << carLu;
                        LDEBUG << "FINBLANC-> DEBBLANC" << LENDL;
                        etat = DEBBLANC;
                    break;
                    case '>':
                        status << "Duplicated '>' character at " << position << std::endl;
                        retVal = DUPLICATED_CLOSING_TAG_CHAR;
                        putWhites(status, output, wide,endSentenceTag, tagValue,
                                output, carLu, ' ', nb, nbNewLines);
                        LDEBUG << "FINBLANC-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                    case ' ':case '\t':case '\n':
                        putWhites(status, output, wide,endSentenceTag, tagValue,
                                output, carLu, ' ', nb, nbNewLines);
                        LDEBUG << "FINBLANC-> BLANC" << LENDL;
                        etat = BLANC;
                    break;
                    case '&':
//                        putWhites(status, output, wide,endSentenceTag, tagValue,
//                                entity, carLu, '_', nb, nbNewLines);
                        putWhites(status, output, wide,endSentenceTag, tagValue,
                                entity, carLu, ' ', nb, nbNewLines);
                        LDEBUG << "FINBLANC -> BEGENTITY;" << LENDL;
                        etat = BEGENTITY;
                    break;
                    default:
//                        putWhites(status, output, wide,endSentenceTag, tagValue,
//                                txt, carLu, '_', nb, nbNewLines);
                        putWhites(status, output, wide,endSentenceTag, tagValue,
                                txt, carLu, ' ', nb, nbNewLines);
                        LDEBUG << "FINBLANC-> TEXT" << LENDL;
                        etat = TEXT;
                    break;
                }
            break;
            default:
                throw std::runtime_error((std::string("unknown state %d.\n", int(etat))).c_str());
        }
        ++position;
    }
    if ( (etat == DEBCOL) || (etat == DEBBLANC) )
    {
        status << "Unclosed tag at EOF (" << position << ")" << std::endl;
        retVal = UNCLOSED_OPENING_TAG_CHAR;
        if (etat == DEBCOL) 
        {
          output << tag.str();
        }
        else
        {
//                s = std::string(nb/2, '_');
            s = std::string(nb/2, ' ');
            s.append(nbNewLines, '\n');
//                if (nb%2 == 0) s.append(nb/2, '_');
            if (nb%2 == 0) s.append(nb/2, ' ');
//                else s.append(nb/2 + 1, '_');
            else s.append(nb/2 + 1, ' ');
            output << s;
            nb = 0;
            nbNewLines = 0;
        }
    }

    else if ((etat == FINCOL) || (etat == FINBLANC))
    {
      output << tag.str();
    }

    else if (etat == TEXT)
    {
      output << txt.str();
    }
    else {} // BLANC nothing to do

    return int(retVal);
}
void MeshData::read_unv_implementation (std::istream& in_file)
{
  /*
   * This is the actual implementation of
   * reading in UNV format.  This enables
   * to read either through the conventional
   * C++ stream, or through a stream that
   * allows to read .gz'ed files.
   */
  if ( !in_file.good() )
    {
      libMesh::err << "ERROR: Input file not good."
		    << std::endl;
      libmesh_error();
    }

  const std::string _label_dataset_mesh_data = "2414";

  /*
   * locate the beginning of data set
   * and read it.
   */
  {
    std::string olds, news;

    while (true)
    {
      in_file >> olds >> news;

      /*
       * Yes, really dirty:
       *
       * When we found a dataset, and the user does
       * not want this dataset, we jump back here
       */
    go_and_find_the_next_dataset:

      /*
       * a "-1" followed by a number means the beginning of a dataset
       * stop combing at the end of the file
       */
      while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() )
	{
	  olds = news;
	  in_file >> news;
	}

      if(in_file.eof())
	break;

      /*
       * if beginning of dataset
       */
      if (news == _label_dataset_mesh_data)
        {

	  /*
	   * Now read the data of interest.
	   * Start with the header.  For
	   * explanation of the variable
	   * dataset_location, see below.
	   */
	  unsigned int dataset_location;

	  /*
	   * the type of data (complex, real,
	   * float, double etc, see below)
	   */
	  unsigned int data_type;

	  /*
	   * the number of floating-point values per entity
	   */
	  unsigned int NVALDC;


	  /*
	   * If there is no MeshDataUnvHeader object
	   * attached
	   */
	  if (_unv_header==NULL)
	    {
	      /*
	       * Ignore the first lines that stand for
	       * analysis dataset label and name.
	       */
	      for(unsigned int i=0; i<3; i++)
		in_file.ignore(256,'\n');

	      /*
	       * Read the dataset location, where
	       * 1: Data at nodes
	       * 2: Data on elements
	       * other sets are currently not supported.
	       */
	      in_file >> dataset_location;

	      /*
	       * Ignore five ID lines.
	       */
	      for(unsigned int i=0; i<6; i++)
		in_file.ignore(256,'\n');

	      /*
	       * These data are all of no interest to us...
	       */
	      unsigned int model_type,
		  analysis_type,
		  data_characteristic,
		  result_type;

	      /*
	       * Read record 9.
	       */
	      in_file >> model_type           // not used here
		      >> analysis_type        // not used here
		      >> data_characteristic  // not used here
		      >> result_type          // not used here
		      >> data_type
		      >> NVALDC;


	      /*
	       * Ignore record 10 and 11
	       * (Integer analysis type specific data).
	       */
	      for (unsigned int i=0; i<3; i++)
		in_file.ignore(256,'\n');

	      /*
	       * Ignore record 12 and record 13.  Since there
	       * exist UNV files with 'D' instead of 'e' as
	       * 10th-power char, it is safer to use a string
	       * to read the dummy reals.
	       */
	      {
	        std::string dummy_Real;
		for (unsigned int i=0; i<12; i++)
		    in_file >> dummy_Real;
	      }

	    }
	  else
	    {

	      /*
	       * the read() method returns false when
	       * the user wanted a special header, and
	       * when the current header is _not_ the correct
	       * header
	       */
	      if (_unv_header->read(in_file))
	        {
		  dataset_location = _unv_header->dataset_location;
		  NVALDC = _unv_header->nvaldc;
		  data_type = _unv_header->data_type;
		}
	      else
	        {
		  /*
		   * This is not the correct header.  Go
		   * and find the next.  For this to
		   * work correctly, shift to the
		   * next line, so that the "-1"
		   * disappears from olds
		   */
		  olds = news;
		  in_file >> news;

		  /*
		   * No good style, i know...
		   */
		  goto go_and_find_the_next_dataset;
		}

	    }

	  /*
	   * Check the location of the dataset.
	   */
	  if (dataset_location != 1)
	    {
	      libMesh::err << "ERROR: Currently only Data at nodes is supported."
			    << std::endl;
	      libmesh_error();
	    }


	  /*
	   * Now get the foreign node id number and the respective nodal data.
	   */
	  int f_n_id;
	  std::vector<Number> values;

	  while(true)
	    {
	      in_file >> f_n_id;

	      /*
	       * if node_nr = -1 then we have reached the end of the dataset.
	       */
	      if (f_n_id==-1)
		  break;

	      /*
	       * Resize the values vector (usually data in three
	       * principle directions, i.e. NVALDC = 3).
	       */
	      values.resize(NVALDC);

	      /*
	       * Read the meshdata for the respective node.
	       */
	      for (unsigned int data_cnt=0; data_cnt<NVALDC; data_cnt++)
		{
		  /*
		   * Check what data type we are reading.
		   * 2,4: Real
		   * 5,6: Complex
		   * other data types are not supported yet.
		   * As again, these floats may also be written
		   * using a 'D' instead of an 'e'.
		   */
		  if (data_type == 2 || data_type == 4)
		    {
		      std::string buf;
		      in_file >> buf;
		      MeshDataUnvHeader::need_D_to_e(buf);
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
		      values[data_cnt] = Complex(std::atof(buf.c_str()), 0.);
#else
		      values[data_cnt] = std::atof(buf.c_str());
#endif
		    }

		  else if(data_type == 5 || data_type == 6)

		    {
#ifdef LIBMESH_USE_COMPLEX_NUMBERS
		      Real re_val, im_val;

		      std::string buf;
		      in_file >> buf;

		      if (MeshDataUnvHeader::need_D_to_e(buf))
		        {
			  re_val = std::atof(buf.c_str());
			  in_file >> buf;
			  MeshDataUnvHeader::need_D_to_e(buf);
			  im_val = std::atof(buf.c_str());
			}
		      else
		        {
			  re_val = std::atof(buf.c_str());
			  in_file >> im_val;
			}

		      values[data_cnt] = Complex(re_val,im_val);
#else

		      libMesh::err << "ERROR: Complex data only supported" << std::endl
				    << "when libMesh is configured with --enable-complex!"
				    << std::endl;
		      libmesh_error();
#endif
		    }
Beispiel #29
0
 uv::uv(std::istream &stream_, uint32_t version = 68) {
     stream_.read((char *)&uv_scale, sizeof(float) * 4);
     data = compressed<float>(stream_, true, true, version);
 }
Beispiel #30
0
bool demo_header_read(std::istream& is, demo_header& header) {
    is.read(reinterpret_cast<char*>(&header.magic), sizeof(header.magic));
    is.read(reinterpret_cast<char*>(&header.demo_protocol), sizeof(header.demo_protocol));
    is.read(reinterpret_cast<char*>(&header.network_protocol), sizeof(header.network_protocol));
    is.read(reinterpret_cast<char*>(&header.server_name), sizeof(header.server_name));
    is.read(reinterpret_cast<char*>(&header.client_name), sizeof(header.client_name));
    is.read(reinterpret_cast<char*>(&header.map_name), sizeof(header.map_name));
    is.read(reinterpret_cast<char*>(&header.game_directory), sizeof(header.game_directory));
    is.read(reinterpret_cast<char*>(&header.playback_time), sizeof(header.playback_time));
    is.read(reinterpret_cast<char*>(&header.playback_ticks), sizeof(header.playback_ticks));
    is.read(reinterpret_cast<char*>(&header.playback_frames), sizeof(header.playback_frames));
    is.read(reinterpret_cast<char*>(&header.signonlength), sizeof(header.signonlength));

    return is.good();
}