Example #1
0
/**
	createResolutionData
	Create Android resolution file as follow imported resolution file
*/
int CreateResolutionData(RESOLUTION* resolutionResult, int index, TiXmlElement* pSubElement, char* directory) {
	/** Get node */
	TiXmlHandle hRoot(0);
	TiXmlElement* pElement = pSubElement;
	TiXmlAttribute* pAttribute = NULL;

	/** Set current dept node to root node */
	hRoot = TiXmlHandle(pElement);
	/** Check has child root */
	pElement = hRoot.FirstChildElement().Element();

	/** Set xml properties and root node for save file */
	TiXmlDocument docArray[RESOLUTION_TYPE_COUNT];
	TiXmlDeclaration* dec[RESOLUTION_TYPE_COUNT] = { ENCODING, ENCODING, ENCODING, ENCODING };
	for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
		docArray[i].LinkEndChild(dec[i]);
	}

	/** Add root node */
	TiXmlElement* pRoot[RESOLUTION_TYPE_COUNT] = { FIRST_NODE, FIRST_NODE, FIRST_NODE, FIRST_NODE };
	for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
		docArray[i].LinkEndChild(pRoot[i]);
	}

	/** Add child node */
	TiXmlElement* pElementArray[RESOLUTION_TYPE_COUNT];

	/** If has child */
	if (pElement) {
		char* pszNode = NULL;			/** For save node */
		char* pszAttributeValue = NULL;	/** For save attribute's name (key) */
		char* pszAttributeName = NULL;	/** for save attribute's name (value) */

		/** Repeat if has child node */
		while (pElement) {
			/** Get node */
			pszNode = (char*)pElement->Value();

			/** Get attribute */
			pAttribute = pElement->FirstAttribute();

			/** If has attribute */
			while (pAttribute) {
				pszAttributeValue = (char*)pAttribute->Name();
				pszAttributeName = (char*)pAttribute->Value();
				pAttribute = pAttribute->Next();
			}

			/** Get resoultion unit info */
			char* pszText = (char*)pElement->GetText();

			/** Calculete resolution size */
			struct RESOLUTION result;
			result = ConvertResolution(pszAttributeName, strtod(pszText, NULL), RESOLUTION_HDPI); //It's HDPI type unconditionally in prototype
			resolutionResult[index++] = result;
			double resolution_value[RESOLUTION_TYPE_COUNT] = { result.ldpi, result.mdpi, result.hdpi, result.xhdpi };

			char temp[100];
			for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
				/** For create new resolution file */
				sprintf_s(temp, sizeof(temp), "%.2lfdp", resolution_value[i]);
				pElementArray[i] = new TiXmlElement("dimen");
				pElementArray[i]->LinkEndChild(new TiXmlText(temp));
				pRoot[i]->LinkEndChild(pElementArray[i]);
				pElementArray[i]->SetAttribute("name", pszAttributeName);
			}

			/** Call self recursively for search child node of current node */
			CreateResolutionData(resolutionResult, index, pElement, NULL);
			pElement = pElement->NextSiblingElement();
		}
	}

	/** Save file */
	if (directory != NULL) {
		char savepath[RESOLUTION_TYPE_COUNT][100] = { "_ldpi.xml", "_mdpi.xml",  "_hdpi.xml", "_xhdpi.xml" };

		for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
			char filepath[100] = "";

			strncpy_s(filepath, directory, sizeof(filepath));
			strcat_s(filepath, sizeof(filepath), savepath[i]);
			docArray[i].SaveFile(filepath);
		}

		AfxMessageBox(_T("Save successfully!"));
	}

	return index;
}
bool CGetResultListBG::ParseResultListXml(const CStdString& strHtml, CFileItemList& items)
{
  TiXmlDocument xmlDoc;
  xmlDoc.Parse(strHtml);

  TiXmlElement *pRootElement = xmlDoc.RootElement();
  if (!pRootElement)
    return false;

  if (strcmpi(pRootElement->Value(), "search") != 0)
  {
    CLog::Log(LOGERROR, "CGetResultListBG::ParseResultListXml, could not parse manual resolution results (manual)");
    return false;
  }

  const TiXmlNode* pTag = 0;
  while ((pTag = pRootElement->IterateChildren(pTag)))
  {
    if (pTag->ValueStr() == "title")
    {
      const TiXmlNode *pValue = pTag->FirstChild();
      CStdString strValue = pValue->ValueStr();

      // Find the id attribute, we do not know its name but we know that there are two attributes and it's not the one called 'year'
      CStdString idAttributeName;
      CStdString idAttributeValue;

      TiXmlAttribute* attribute = ((TiXmlElement*)pTag)->FirstAttribute();
      while (attribute)
      {
        if ((strcmpi(attribute->Name(), "year") != 0) && (strcmpi(attribute->Name(), "type") != 0))
        {
          idAttributeName = attribute->Name();
          idAttributeValue = attribute->Value();
        }
        attribute = attribute->Next();
      }

      if (idAttributeName.IsEmpty() || idAttributeValue.IsEmpty())
      {
        // this should not happen, each search result should have an id
        CLog::Log(LOGERROR, "CGetResultListBG::ParseResultListXml, search result without id, value = %s (manual)", strValue.c_str());
        continue;
      }

      // Get the year
      CStdString strYear = ((TiXmlElement*)pTag)->Attribute("year");

      CStdString strType = ((TiXmlElement*)pTag)->Attribute("type");

      bool bIsMovie = false;
      if (strType == "movie")
      {
        bIsMovie = true;
      }
      else if (strType == "tv")
      {
        bIsMovie = false;
      }
      else
      {
        CLog::Log(LOGERROR, "CGetResultListBG::ParseResultListXml, invalid type = %s (manual)", strType.c_str());
        continue;
      }

      CStdString strMovieTypeLabel = "Movie";
      CStdString strTvTypeLabel = "TV";

      // Format label and create file item
      CStdString strLabel;
      if (strYear.IsEmpty())
        strLabel.Format("%s (%s)", strValue.c_str(), bIsMovie ? strMovieTypeLabel.c_str() : strTvTypeLabel.c_str());
      else
        strLabel.Format("%s (%s) (%s)", strValue.c_str(), strYear.c_str(), bIsMovie ? strMovieTypeLabel.c_str() : strTvTypeLabel.c_str());

      CFileItemPtr resultItem (new CFileItem(strLabel));
      resultItem->SetProperty("type", "msearch");
      resultItem->SetProperty("manualresolve::Title", strValue);
      resultItem->SetProperty("manualresolve::Year", strYear);
      resultItem->SetProperty("manualresolve::idName", idAttributeName);
      resultItem->SetProperty("manualresolve::idValue", idAttributeValue);
      resultItem->SetProperty("manualresolve::isMovie", bIsMovie);
      items.Add(resultItem);

      CLog::Log(LOGDEBUG, "CGetResultListBG::ParseResultListXml, added item, title = %s, type = %s, year = %s, idName = %s, idValue = %s (manual)",
          strValue.c_str(), bIsMovie ? "movie" : "tv", strYear.c_str(), idAttributeName.c_str(), idAttributeValue.c_str());
    }
  }

  return items.Size() > 0;
}
Example #3
0
const char* TiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
	p = SkipWhiteSpace( p, encoding );
	TiXmlDocument* document = GetDocument();

	if ( !p || !*p )
	{
		if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding );
		return 0;
	}

//	TiXmlParsingData data( p, prevData );
	if ( data )
	{
		data->Stamp( p, encoding );
		location = data->Cursor();
	}

	if ( *p != '<' )
	{
		if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding );
		return 0;
	}

	p = SkipWhiteSpace( p+1, encoding );

	// Read the name.
	const char* pErr = p;

    p = ReadName( p, &value, encoding );
	if ( !p || !*p )
	{
		if ( document )	document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding );
		return 0;
	}

    TIXML_STRING endTag ("</");
	endTag += value;
	endTag += ">";

	// Check for and read attributes. Also look for an empty
	// tag or an end tag.
	while ( p && *p )
	{
		pErr = p;
		p = SkipWhiteSpace( p, encoding );
		if ( !p || !*p )
		{
			if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding );
			return 0;
		}
		if ( *p == '/' )
		{
			++p;
			// Empty tag.
			if ( *p  != '>' )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding );		
				return 0;
			}
			return (p+1);
		}
		else if ( *p == '>' )
		{
			// Done with attributes (if there were any.)
			// Read the value -- which can include other
			// elements -- read the end tag, and return.
			++p;
			p = ReadValue( p, data, encoding );		// Note this is an Element method, and will set the error if one happens.
			if ( !p || !*p ) {
				// We were looking for the end tag, but found nothing.
				// Fix for [ 1663758 ] Failure to report error on bad XML
				if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
				return 0;
			}

			// We should find the end tag now
			if ( StringEqual( p, endTag.c_str(), false, encoding ) )
			{
				p += endTag.length();
				return p;
			}
			else
			{
				if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
				return 0;
			}
		}
		else
		{
			// Try to read an attribute:
			TiXmlAttribute* attrib = new TiXmlAttribute();
			if ( !attrib )
			{
				if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, pErr, data, encoding );
				return 0;
			}

			attrib->SetDocument( document );
			const char* pErr = p;
			p = attrib->Parse( p, data, encoding );

			if ( !p || !*p )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding );
				delete attrib;
				return 0;
			}

			// Handle the strange case of double attributes:
			TiXmlAttribute* node = attributeSet.Find( attrib->Name() );
			if ( node )
			{
				node->SetValue( attrib->Value() );
				delete attrib;
				return 0;
			}

			attributeSet.Add( attrib );
		}
	}
	return p;
}
bool CGmObjShapeStaticItem::ReadXML( TiXmlNode* poParent, unsigned int uiCounter )
{
	if( !poParent )
		return false;
	
	static char acTxt_[256];
	if( uiCounter == 0 )
	{
	}
	
	switch ( poParent->Type() )
	{
	case TiXmlNode::DOCUMENT:
		LOG( "XML: Document" );
	break;
	case TiXmlNode::ELEMENT:
	{
		const char *pcName = poParent->Value();
		//LOG( "name: %s\n", pcName );
		if( !strcmp( pcName, "item" ) )
		{
			LOG( "item:\n" );
			
			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_oName = acTxt_;
					}
					if( !strcmp( pcName, "type" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						if( !strcmp( acTxt_, "weapon" ) )
							m_eType = TYPE_WEAPON;
						else if( !strcmp( acTxt_, "energy" ) )
							m_eType = TYPE_ENERGY;
						else if( !strcmp( acTxt_, "ammo" ) )
							m_eType = TYPE_AMMO;
						else if( !strcmp( acTxt_, "key" ) )
							m_eType = TYPE_KEY;
						else
							m_eType = TYPE_UNDEFINED;
					}
					if( !strcmp( pcName, "cycle_duration" ) )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							if( dVal >= 0.0 )
								m_iTickDurCycle = int( dVal / m_dTInteractionInterval_ );
							else
								m_iTickDurCycle = -1;
						}
					}
					if( !strcmp( pcName, "rotation_y_speed" ) )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							m_fRotationYSpeed = float( dVal * 360.0 );
						}
					}
					if( !strcmp( pcName, "weapon_name" )
					 && ( m_eType == TYPE_WEAPON || m_eType == TYPE_AMMO ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_oWeaponName = acTxt_;
					}
					if( !strcmp( pcName, "energy" ) && m_eType == TYPE_ENERGY )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							m_fEnergy = float( dVal );
						}
					}
					if( !strcmp( pcName, "ammo" )
					 && ( m_eType == TYPE_WEAPON || m_eType == TYPE_AMMO ) )
					{
						int iVal;
						if( poAttrib->QueryIntValue( &iVal ) == TIXML_SUCCESS
						 && iVal > 0 )
						{
							LOG( "%s: %d\n", poAttrib->Name(), iVal );
							m_uiAmmo = iVal;
						}
					}
					if( !strcmp( pcName, "key" ) && m_eType == TYPE_ENERGY )
					{
						int iVal;
						if( poAttrib->QueryIntValue( &iVal ) == TIXML_SUCCESS
						 && iVal > 0 )
						{
							LOG( "%s: %d\n", poAttrib->Name(), iVal );
							m_uiKey = iVal;
						}
					}
					poAttrib = poAttrib->Next();
				}
			}
		}
		if( !strcmp( pcName, "animation" ) )
		{
			LOG( "animation:\n" );
			
			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "file_name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_poAnim = m_poResMan_->NewAnim3( CStr( "item/" ) + acTxt_ );
					}
					poAttrib = poAttrib->Next();
				}
			}
		}
		// Gleich wie in GmObjShapeDynamicEnemy.cpp.
		if( !strcmp( pcName, "mesh" ) )
		{
			LOG( "mesh:\n" );

			CStr oFileName, oSubDir;

			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "sub_dir" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						oSubDir = acTxt_;
					}
					else if( !strcmp( pcName, "file_name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						oFileName = acTxt_;
					}
					poAttrib = poAttrib->Next();
				}
			}
			if( oFileName.GetSize() )
			{
				CGMesh * poMesh( m_poResMan_->NewMeshObj( oSubDir, oFileName ) ); //, false, false ) );
				if( poMesh )
				{
					m_oLstMesh.Append( poMesh );
				}
			}
		}
	}
	break;
	case TiXmlNode::COMMENT:
		//LOG( "XML: Comment: [%s]", poParent->Value());
	break;
	case TiXmlNode::UNKNOWN:
		//LOG( "XML: Unknown" );
	break;
	case TiXmlNode::TEXT:
		//LOG( "XML: Text: [%s]", poParent->ToText()->Value() );
	break;
	case TiXmlNode::DECLARATION:
		//LOG( "XML: Declaration" );
	break;
	default:
	break;
	}
	LOG( "\n" );

	++uiCounter;

	for( TiXmlNode* poChild = poParent->FirstChild(); poChild != 0; poChild = poChild->NextSibling() )
	{
		ReadXML( poChild, uiCounter );
	}
	
	// Ganz am Schluss...
	if( uiCounter == 1 )
	{
	}
	return true;
}
void HoOrionModelParser::ParseRouter(TiXmlNode* pParent) {
	double TmpDouble;
	int TmpInt;
	string Type;
	stringstream Energy;
	stringstream Area;
	int MaxIn = 0;
	int MaxOut = 0;
	TiXmlAttribute* Attribute = ( pParent->ToElement())->FirstAttribute() ;
	while (Attribute ) {
		if (string(Attribute->Name() ) == "type") {
			Type = string(Attribute->Value() ) ;
		} else if (string(Attribute->Name() ) == "maxin") {
			Attribute->QueryIntValue(&TmpInt) ;
			MaxIn = TmpInt ;
		} else if (string(Attribute->Name() ) == "maxout") {
			Attribute->QueryIntValue(&TmpInt) ;
			MaxOut = TmpInt ;
		} else if (string(Attribute->Name() ) == "maxbw") {
			Attribute->QueryDoubleValue(&TmpDouble) ;
			//mModel->RouterMaxBw = TmpDouble ;
		} else if (string(Attribute->Name() ) == "energy") {
			Energy << Attribute->ValueStr() ;
		} else if (string(Attribute->Name() ) == "area") {
			Area << Attribute->ValueStr() ;
		} else {
			cout << "Unknown attribute "<< Attribute->Name() << " for wire"
					<< endl ;
		}
		Attribute = Attribute->Next() ;
	}

	mMaxIn = MaxIn ;
	mMaxOut = MaxOut ;

	if (Type == "r1ch32") {
		mArouter1ch32.resize(MaxIn + 1) ;
		mErouter1ch32.resize(MaxIn + 1) ;
		mErouterLeak1ch32.resize(MaxIn + 1) ;
		mArouter1ch32[0].resize(MaxOut + 1) ;
		mErouter1ch32[0].resize(MaxOut + 1) ;
		mErouterLeak1ch32[0].resize(MaxOut + 1) ;
		for (int i = 1; i <= MaxIn ; i++) {
			mArouter1ch32[i].resize(MaxOut + 1) ;
			mErouter1ch32[i].resize(MaxOut + 1) ;
			mErouterLeak1ch32[i].resize(MaxOut + 1) ;
			for (int j = 1; j <= MaxOut ; j++) {
				Area >> mArouter1ch32[i][j];
				mArouter1ch32[i][j] = mArouter1ch32[i][j]*1e-12;
				Energy >> mErouter1ch32[i][j];
				Energy >> mErouterLeak1ch32[i][j];
			}
		}

		//handle first rows nad first column
		for (int j = 0; j <= MaxOut ; j++) {
			mArouter1ch32[0][j] = 0;
			mErouter1ch32[0][j] = 0;
			mErouterLeak1ch32[0][j] = 0;
		}
		for (int i = 0; i <= MaxIn ; i++) {
			mArouter1ch32[i][0] = 0;
			mErouter1ch32[i][0] = 0;
			mErouterLeak1ch32[i][0] = 0;
		}

	} else if (Type == "r4ch32") {
int LibraryDetectionManager::LoadXmlDoc( TiXmlDocument& Doc )
{
    int loaded = 0;
    for ( TiXmlElement* Elem = Doc.FirstChildElement("library");
          Elem;
          Elem = Elem->NextSiblingElement("library") )
    {
        // Load the version of this set
        int version = 0;
        if ( Elem->QueryIntAttribute( "version", &version ) != TIXML_SUCCESS )
            version = 0;

        // Load shortcode
        wxString ShortCode = wxString(Elem->Attribute("short_code"),wxConvUTF8);
        if ( ShortCode.IsEmpty() )
            continue;

        // Load name
        wxString Name = wxString( Elem->Attribute("name"), wxConvUTF8 );
        if ( Name.IsEmpty() )
            continue;

        // Check if we already have setting of this library
        // I'm to lazy to firbid const_cast here ;)
        LibraryDetectionConfigSet* OldSet = const_cast< LibraryDetectionConfigSet* > ( GetLibrary( ShortCode ) );
        LibraryDetectionConfigSet* NewSet = 0;

        if ( OldSet )
        {
            // There are detection settings yet, we override only when there's newer
            // or same version already
            if ( OldSet->Version > version )
                continue; // We do not upgrade

            OldSet->Categories.Clear();
            OldSet->Configurations.clear();
            OldSet->LibraryName.Clear();
            NewSet = OldSet;
        }
        else
        {
            NewSet = new LibraryDetectionConfigSet;
            Libraries.Add( NewSet );
        }

        // Setup configuration set
        NewSet->ShortCode = ShortCode;
        NewSet->Version = version;
        NewSet->LibraryName = Name;

        // Read categories of library
        for ( TiXmlAttribute* attr = Elem->FirstAttribute();
              attr;
              attr = attr->Next() )
        {
//            if ( !strncasecmp(attr->Name(),"category",8) )
            if ( !strncmp(attr->Name(),"category",8) )
                NewSet->Categories.Add( wxString( attr->Value(),wxConvUTF8 ) );
        }

        // Check if there's corresponding pkg-config entry
        if ( IsPkgConfigEntry(ShortCode) )
        {
            LibraryDetectionConfig Config;
            Config.PkgConfigVar = ShortCode;
            Config.Description = NewSet->LibraryName + _T(" (pkg-config)");
            LibraryDetectionFilter Filter;
            Filter.Type = LibraryDetectionFilter::PkgConfig;
            Filter.Value = ShortCode;
            Config.Filters.push_back(Filter);
            loaded += AddConfig(Config,NewSet) ? 1 : 0;
        }

        // Load libraries
        LibraryDetectionConfig Initial;
        loaded += LoadXml( Elem, Initial, NewSet );
    }
    return loaded;
}
Example #7
0
bool StoryDataCenter::ReadOneXmlItem(TiXmlElement* pElement)
{
	if (pElement == 0)
	{
		return false;
	}

	unsigned int taskID = 0;
	StroyData storyData;

	// Note: Parse TaskID
	TiXmlAttribute* pAttribute = pElement->FirstAttribute();
	while(pAttribute)
	{
		std::string strName(pAttribute->Name());
		std::string content = pElement->Attribute(strName.c_str());
		if (strName == "task_ID")
		{
			unsigned int task_id = atoi(content.c_str());
			taskID = task_id;
			storyData.setTaskId(task_id);
		}
		else if (strName == "instance_ID")
		{
			unsigned int task_id = atoi(content.c_str());
			taskID = task_id;
			storyData.setTaskId(task_id);
		}
		else if (strName == "map_ID")
		{
			unsigned int map_id = atoi(content.c_str());
			storyData.setMapId(map_id);
		}
		else if (strName == "camera")
		{
			float posx = 0;
			float posy = 0;
			if (SplitPosFromContent(content,posx,posy))
			{
				storyData.setCameraPos(ccp(posx,posy));
			}
		}
		else if (strName == "end_frame")
		{
			int endFrame = atoi(content.c_str());
			storyData.setEndFrame(endFrame);
		}
		else if (strName == "when")
		{
			int nWhen = atoi(content.c_str());
			storyData.setHappendAtWhen(nWhen);
		}
		else if (std::string::npos != strName.find("set_role_position_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				std::vector<std::string> vecContent;
				SplitContent(content,vecContent);
				size_t vecSize = vecContent.size();
				for (size_t index = 0;index<vecSize;index++)
				{
					unsigned int frameIndex = 0;
					float posx = 0;
					float posy = 0;
					if(SplitFrameAndPosFromContent(vecContent[index],frameIndex,posx,posy))
					{
						storyData.InsertRolePosAtFrame(roleIndex,frameIndex,ccp(posx,posy));
					}
				}
			}	
		}
		else if (std::string::npos != strName.find("set_role_act_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				std::vector<std::string> vecContent;
				SplitContent(content,vecContent);
				size_t vecSize = vecContent.size();
				for (size_t index = 0;index<vecSize;index++)
				{
					unsigned int frameIndex = 0;
					int actorId = 0;
					if (SplitFrameAndActorIdFromContent(vecContent[index],frameIndex,actorId))
					{
						storyData.InsertRoleActorAtFrame(roleIndex,frameIndex,actorId);
					}	
				}			
			}
		}
		else if (std::string::npos != strName.find("role_dialog_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				std::vector<unsigned int> vecFrameIndex;
				std::vector<std::string> vecTextId;
				if (SplitFrameAndTextIdFromContent(content,vecFrameIndex,vecTextId))
				{
					size_t count = vecFrameIndex.size();
					for (size_t index = 0;index<count;index++)
					{
						storyData.InsertDialogTextIdAtFrame(roleIndex,vecFrameIndex[index],vecTextId[index]);
					}
				}
			}
		}
		else if (std::string::npos != strName.find("set_role_flip_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				std::vector<std::string> vecContent;
				SplitContent(content,vecContent);
				size_t vecSize = vecContent.size();
				for (size_t index = 0;index<vecSize;index++)
				{
					unsigned int nFrame = 0;
					int nFlip = 0;

					if (SplitFrameAndActorIdFromContent(vecContent[index],nFrame,nFlip))
					{
						storyData.InsertIsFlipAtFrame(roleIndex,nFrame,nFlip);
					}
				}
			}
		}
		else if (std::string::npos != strName.find("set_role_icon_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				storyData.SetRoleLeftIcon(roleIndex,content);
			}
		}
		else if (std::string::npos != strName.find("role_"))
		{
			unsigned int roleIndex = 0;
			if (SplitRoleID(strName,roleIndex))
			{
				unsigned int roleId = 0;
				roleId = atoi(content.c_str());
				//if (roleId == 0)
				//{
				//	roleId = UserData::Get()->getUserId();
				//}
				storyData.SetRoleIdAtIndex(roleIndex,roleId);
			}
		}
		else
		{
			CCError("StoryDataCenter::ReadOneXmlItem() %s attribute undefined ",strName.c_str());
		}

		pAttribute = pAttribute->Next();
	}	

	if (taskID != 0)
	{
		mVecTaskIdAndStoryData.push_back(storyData);

		//bool bHasSameId = false;
		//for (std::vector<StroyData>::iterator iter = mVecTaskIdAndStoryData.begin();
		//	 iter != mVecTaskIdAndStoryData.end(); iter++)
		//{
		//	unsigned int id = (*iter).getTaskId();
		//	if (id == taskID)
		//	{
		//		bHasSameId = true;
		//		break;
		//	}
		//}
		//if (false == bHasSameId)
		//{
		//	mVecTaskIdAndStoryData.push_back(storyData);
		//}
		//else
		//{
		//	CCError("ERROR: mVecTaskIdAndStoryData repeat key %d",taskID);
		//}
	}

	return true;
}
const char* TiXmlElement::Parse( const char* p )
{
	p = SkipWhiteSpace( p );
	TiXmlDocument* document = GetDocument();

	if ( !p || !*p || *p != '<' )
	{
		if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT );
		return false;
	}

	p = SkipWhiteSpace( p+1 );

	// Read the name.
	p = ReadName( p, &value );
	if ( !p || !*p )
	{
		if ( document )	document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME );
		return false;
	}

	string endTag = "</";
	endTag += value;
	endTag += ">";

	// Check for and read attributes. Also look for an empty
	// tag or an end tag.
	while ( p && *p )
	{
		p = SkipWhiteSpace( p );
		if ( !p || !*p )
		{
			if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES );
			return 0;
		}
		if ( *p == '/' )
		{
			++p;
			// Empty tag.
			if ( *p  != '>' )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY );		
				return 0;
			}
			return (p+1);
		}
		else if ( *p == '>' )
		{
			// Done with attributes (if there were any.)
			// Read the value -- which can include other
			// elements -- read the end tag, and return.
			++p;
			p = ReadValue( p );		// Note this is an Element method, and will set the error if one happens.
			if ( !p || !*p )
				return 0;

			// We should find the end tag now
			if ( StringEqual( p, endTag.c_str(), false ) )
			{
				p += endTag.length();
				return p;
			}
			else
			{
				if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG );
				return 0;
			}
		}
		else
		{
			// Try to read an element:
			TiXmlAttribute attrib;
			attrib.SetDocument( document );
			p = attrib.Parse( p );

			if ( !p || !*p )
			{
				if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT );
				return 0;
			}
			SetAttribute( attrib.Name(), attrib.Value() );
		}
	}
	return p;
}
bool XMLControlInterface::Load(const char * filepath)
{
	try
	{

			m_configure = new TiXmlDocument(filepath);
			m_configure->LoadFile();
			TiXmlElement *l_root = m_configure->RootElement();

			//------------------------------------------------
			TiXmlElement* l_LeftElement = NULL;
			TiXmlElement* l_IndexitemElement = NULL;

			

			SERVER_INFO_ svrinfo_;

			string strTxt,strVal;
			strVal=l_root->Value();
			//strVal=l_root->GetText();
			if(!l_root || strcmp(l_root->Value(), "I_hosts")) 
				return false;

			/*if(const TiXmlElement *updates=l_root->FirstChildElement("address")) 
			{
				//GetChild(updates, "ip",strTxt);

				TiXmlAttribute *IDAttribute = (TiXmlAttribute *)updates->FirstAttribute();
				strTxt=IDAttribute->Value();
				for (TiXmlAttribute * nextID=IDAttribute->Next();nextID;)
				{
					strTxt=nextID->Value();
					nextID=nextID->Next();
				}

			}*/
			for( l_LeftElement = l_root->FirstChildElement();
				l_LeftElement!=NULL;
				l_LeftElement = l_LeftElement->NextSiblingElement() )	
			{	
				strTxt=l_LeftElement->Value();

				//for( l_IndexitemElement = l_LeftElement->FirstChildElement();
					//l_IndexitemElement!=NULL;
					//l_IndexitemElement = l_IndexitemElement->NextSiblingElement() )	
				//{
				TiXmlAttribute *IDAttribute = (TiXmlAttribute *)l_LeftElement->FirstAttribute();
				
				for (;IDAttribute;IDAttribute=IDAttribute->Next())
				{
					strTxt=IDAttribute->Name();
					if( 0 == strncmp( "ip" ,IDAttribute->Name(), 2 ) )
					{
						svrinfo_._ip=IDAttribute->Value();
					}

					else if(0 == strncmp( "port" ,IDAttribute->Name(), 4 ))
					{
						svrinfo_._port=IDAttribute->Value();
					}
					else if(0 == strncmp( "root" ,IDAttribute->Name() , 4 ))
					{
						svrinfo_._root =IDAttribute->Value();


					}
					else if(0 == strncmp( "redirect" ,IDAttribute->Name() , 8 ))
					{
						svrinfo_._redirect=IDAttribute->Value();

					}
				}
				
					/*strTxt=nextID->Value();
					nextID=nextID->Next();
				
					strTxt=l_IndexitemElement->Value();
					strVal=l_IndexitemElement->GetText();
					if( 0 == strncmp( "ip" , l_IndexitemElement->Value() , 2 ) )
					{
						svrinfo_._ip= l_IndexitemElement->GetText();
					}
					else if(0 == strncmp( "port" , l_IndexitemElement->Value() , 2 ))
					{
						svrinfo_._port= l_IndexitemElement->GetText();
					}
					else if(0 == strncmp( "root" , l_IndexitemElement->Value() , 3 ))
					{
						svrinfo_._root =l_IndexitemElement->GetText();


					}
					else if(0 == strncmp( "redirect" , l_IndexitemElement->Value() , 8 ))
					{
						svrinfo_._redirect= l_IndexitemElement->GetText();

					}*/

				//}

				m_serList.push_back( svrinfo_);

				
			}
			if( NULL != m_configure )
				delete m_configure;
	}

	catch (...)
	{
		if( NULL != m_configure )
			delete m_configure;
	}
	return m_serList.empty();

}
Example #10
0
// static
HeeksObj* HDimension::ReadFromXMLElement(TiXmlElement* pElem)
{
	double m[16];
	wxString text;
	HeeksColor c;
	double p0[3] = {0, 0, 0};
	double p1[3] = {0, 0, 0};
	double p2[3] = {0, 0, 0};
	double scale=1;

	DimensionMode mode = TwoPointsDimensionMode;
	DimensionUnits units = DimensionUnitsGlobal;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "col"){c = HeeksColor((long)(a->IntValue()));}
		else if(name == "m0"){m[0] = a->DoubleValue();}
		else if(name == "m1"){m[1] = a->DoubleValue();}
		else if(name == "m2"){m[2] = a->DoubleValue();}
		else if(name == "m3"){m[3] = a->DoubleValue();}
		else if(name == "m4"){m[4] = a->DoubleValue();}
		else if(name == "m5"){m[5] = a->DoubleValue();}
		else if(name == "m6"){m[6] = a->DoubleValue();}
		else if(name == "m7"){m[7] = a->DoubleValue();}
		else if(name == "m8"){m[8] = a->DoubleValue();}
		else if(name == "m9"){m[9] = a->DoubleValue();}
		else if(name == "ma"){m[10]= a->DoubleValue();}
		else if(name == "mb"){m[11]= a->DoubleValue();}
		else if(name == "scale"){scale= a->DoubleValue();}
		else if(name == "mode"){mode = (DimensionMode)(a->IntValue());}
		else if(name == "units"){
			const char* str = a->Value();
			switch(str[0])
			{
			case 'm':
				units = DimensionUnitsMM;
				break;
			case 'i':
				units = DimensionUnitsInches;
				break;
			}
		}
	}

	HDimension* new_object = new HDimension(make_matrix(m), make_point(p0), make_point(p1), make_point(p2), mode, units, &c);
	new_object->ReadBaseXML(pElem);
	new_object->m_scale = scale;

	if(new_object->GetNumChildren()>3)
	{
		//This is a new style line, with children points
		new_object->Remove(new_object->A);
		new_object->Remove(new_object->B);
		new_object->Remove(new_object->m_p2);
		delete new_object->A;
		delete new_object->B;
		delete new_object->m_p2;
		new_object->A = (HPoint*)new_object->GetFirstChild();
		new_object->B = (HPoint*)new_object->GetNextChild();
		new_object->m_p2 = (HPoint*)new_object->GetNextChild();
		new_object->A->m_draw_unselected = false;
		new_object->B->m_draw_unselected = false;
		new_object->m_p2->m_draw_unselected = false;
		new_object->A->SetSkipForUndo(true);
		new_object->B->SetSkipForUndo(true);
		new_object->m_p2->SetSkipForUndo(true);
	}


	return new_object;
}
Example #11
0
void XMLParser::navigateChildren (int depth, XMLElement *parent, TiXmlElement *element)
{
	#ifdef defAPI_TINY_XML
		TiXmlElement *xeElm = element;
		xeElm = xeElm->FirstChildElement ();

		while (xeElm != 0)
		{
			XMLElement *xmlElment = new XMLElement ();
			const char *cParentValue = (const char *)element->Value ();
			const char *cValue = (const char *)xeElm->Value ();
			const char *cContent = 0;
			std::string strParentValue = "";
			std::string strValue = "";
			std::string strContent = "";

			if (xeElm->NoChildren () == false)
			{
				TiXmlNode *xeChild = xeElm->FirstChild ();

				if (xeChild != 0)
					cContent = xeChild->Value ();
			}

			if (cParentValue != 0)
				strParentValue = cParentValue;

			if (cValue != 0)
				strValue = cValue;

			if (cContent != 0)
				strContent = cContent;

			std::vector<std::string> aryAttributeNames;
			std::vector<std::string> aryAttributeValues;
			TiXmlAttribute *xaAtt = xeElm->FirstAttribute ();

			while (xaAtt != 0)
			{
				const char *cAttributeName = (const char *)xaAtt->Name ();
				std::string strAttributeName = "";
				const char *cAttributeValue = (const char *)xaAtt->Value ();
				std::string strAttributeValue = "";

				if (cAttributeName != 0)
					strAttributeName = cAttributeName;

				if (cAttributeValue != 0)
					strAttributeValue = cAttributeValue;

				aryAttributeNames.push_back (strAttributeName);
				aryAttributeValues.push_back (strAttributeValue);

				xaAtt = xaAtt->Next ();
			}

			xmlElment->parent = parent;
			xmlElment->tag = strValue;

			for (unsigned int iIdx = 0; iIdx < aryAttributeNames.size (); iIdx++)
				xmlElment->aryAttributeNames.push_back (aryAttributeNames.at (iIdx));

			for (unsigned int iIdx = 0; iIdx < aryAttributeValues.size (); iIdx++)
				xmlElment->aryAttributeValues.push_back (aryAttributeValues.at (iIdx));

			xmlElment->content = strContent;
			xmlElment->parentParser = this;

			if (parent == 0)
				aryElements->push_back (xmlElment);
			else
				parent->children->push_back (xmlElment);

			if (xeElm->NoChildren () == false)
				navigateChildren (depth++, xmlElment, xeElm);

			xeElm = xeElm->NextSiblingElement ();
		}
	#endif
}
Example #12
0
void CGUIIncludes::ResolveIncludesForNode(TiXmlElement *node, std::map<int, bool>* xmlIncludeConditions /* = NULL */)
{
  // we have a node, find any <include file="fileName">tagName</include> tags and replace
  // recursively with their real includes
  if (!node) return;

  // First add the defaults if this is for a control
  CStdString type;
  if (node->ValueStr() == "control")
  {
    type = node->Attribute("type");
    map<CStdString, TiXmlElement>::const_iterator it = m_defaults.find(type);
    if (it != m_defaults.end())
    {
      const TiXmlElement &element = (*it).second;
      const TiXmlElement *tag = element.FirstChildElement();
      while (tag)
      {
        // we insert at the end of block
        node->InsertEndChild(*tag);
        tag = tag->NextSiblingElement();
      }
    }
  }

  TiXmlElement *include = node->FirstChildElement("include");
  while (include && include->FirstChild())
  {
    // have an include tag - grab it's tag name and replace it with the real tag contents
    const char *file = include->Attribute("file");
    if (file)
    { // we need to load this include from the alternative file
      LoadIncludes(g_SkinInfo->GetSkinPath(file));
    }
    const char *condition = include->Attribute("condition");
    if (condition)
    { // check this condition
      int conditionID = g_infoManager.Register(condition);
      bool value = g_infoManager.GetBoolValue(conditionID);

      if (xmlIncludeConditions)
        (*xmlIncludeConditions)[conditionID] = value;

      if (!value)
      {
        include = include->NextSiblingElement("include");
        continue;
      }
    }
    CStdString tagName = include->FirstChild()->Value();
    map<CStdString, TiXmlElement>::const_iterator it = m_includes.find(tagName);
    if (it != m_includes.end())
    { // found the tag(s) to include - let's replace it
      const TiXmlElement &element = (*it).second;
      const TiXmlElement *tag = element.FirstChildElement();
      while (tag)
      {
        // we insert before the <include> element to keep the correct
        // order (we render in the order given in the xml file)
        node->InsertBeforeChild(include, *tag);
        tag = tag->NextSiblingElement();
      }
      // remove the <include>tagName</include> element
      node->RemoveChild(include);
      include = node->FirstChildElement("include");
    }
    else
    { // invalid include
      CLog::Log(LOGWARNING, "Skin has invalid include: %s", tagName.c_str());
      include = include->NextSiblingElement("include");
    }
  }

  // run through this element's attributes, resolving any constants
  TiXmlAttribute *attribute = node->FirstAttribute();
  while (attribute)
  { // check the attribute against our set
    if (m_constantAttributes.count(attribute->Name()))
      attribute->SetValue(ResolveConstant(attribute->ValueStr()));
    attribute = attribute->Next();
  }
  // also do the value
  if (node->FirstChild() && node->FirstChild()->Type() == TiXmlNode::TINYXML_TEXT && m_constantNodes.count(node->ValueStr()))
    node->FirstChild()->SetValue(ResolveConstant(node->FirstChild()->ValueStr()));
}
Example #13
0
/*!
    \brief Load / save project hook.

    When CodeBlocks loads and saves a file, we hook into the process here and load or save
    our parameters.

    \param project CodeBlocks project instance.
    \param elem XML element of root node.
    \param loading Flag set whether load / save, true = loading, false = saving.
*/
void OpenOCDDriver::OnProjectLoadingHook(cbProject* project, TiXmlElement* elem, bool loading)
{
    if (loading) {
        TiXmlElement* node = elem->FirstChildElement("gdbremote");
        if (node) {

            TiXmlElement *device = node->FirstChildElement("hardware");

            m_Interface = cbC2U(device->Attribute("interface"));
            m_Option = cbC2U(device->Attribute("option"));
            m_JTAGSpeed = cbC2U(device->Attribute("jtagspeed"));
            m_GDBPort = atoi(device->Attribute("gdbport"));
            m_ConfigFile = cbC2U(device->Attribute("configfile"));
            wxString strAuto = cbC2U(device->Attribute("auto"));
            m_TelnetPort = atoi(device->Attribute("telnetport"));
            m_TCLPort = atoi(device->Attribute("tclport"));
            if (strAuto == _T("true"))
                m_Auto = true;
            else
                m_Auto = false;

            // Now get advanced options.
            TiXmlElement *advopts = node->FirstChildElement("advintopts");
            if (advopts) {

                TiXmlAttribute *attr = advopts->FirstAttribute();
                while (attr) {

                    // Populate hash map with attributes.
                    wxString key = cbC2U(attr->Name());
                    wxString value = cbC2U(attr->Value());

                    m_AdvOpts[key] = value;

                    attr = attr->Next();
                }
            }

        } else {
            m_Interface = _T("parport");
            m_Option = _T("wiggler");
            m_JTAGSpeed = _T("0");
            m_ConfigFile = _T("openocd.cfg");
            m_Auto = true;
            m_TelnetPort = 4444;
            m_GDBPort = 2000;
            m_TCLPort = 6666;
            m_AdvOpts.clear();

        }
    } else {

        TiXmlElement* node = elem->FirstChildElement("gdbremote");
        if (!node)
            node = elem->InsertEndChild(TiXmlElement("gdbremote"))->ToElement();
        node->Clear();

        TiXmlElement *device = node->InsertEndChild(TiXmlElement("hardware"))->ToElement();

        device->SetAttribute("interface", cbU2C(m_Interface));
        device->SetAttribute("option", cbU2C(m_Option));
        device->SetAttribute("jtagspeed", cbU2C(m_JTAGSpeed));
        device->SetAttribute("gdbport", m_GDBPort);
        device->SetAttribute("configfile", cbU2C(m_ConfigFile));
        if (m_Auto == true)
            device->SetAttribute("auto", "true");
        else
            device->SetAttribute("auto", "false");
        device->SetAttribute("telnetport", m_TelnetPort);
        device->SetAttribute("tclport", m_TCLPort);

        // Write advanced options
        TiXmlElement *advopts = node->InsertEndChild(TiXmlElement("advintopts"))->ToElement();

        AdvOptsHash::iterator it;
        for( it = m_AdvOpts.begin(); it != m_AdvOpts.end(); ++it )
        {
            wxString key = it->first, value = it->second;
            // do something useful with key and value

            advopts->SetAttribute(cbU2C(key), cbU2C(value));
        }

    }
}
Example #14
0
static int _Decode( sqbind::CSqMulti *out, TiXmlElement *in, int bIndexed, int nDepth = 0 )
{_STT();

	// Sanity check
	if ( !out || !in || nDepth > CSqXml::eMaxParseDepth )
		return 0;

	int nDecoded = 0;
	int nIdx = 0;

	// Add child elements
	do
	{
		// Only element types
		if ( in->Type() != TiXmlNode::TINYXML_ELEMENT )
			continue;

		// Apply some sane limit
		int nMax = CSqXml::eMaxParseElements;

		// Grab the tag name
		const char *pName = in->Value();
		sqbind::stdString sName;
		if ( pName && *pName )
			sName = oexMbToStrPtr( pName );

		sqbind::CSqMulti *r = oexNULL;
		if ( bIndexed )
		{
			// Use numeric index
			r = &(*out)[ oexMks( nIdx++ ).Ptr() ];

			// Save name if valid
			if ( sName.length() )
				(*r)[ oexT( "$" ) ].set( oexMbToStrPtr( pName ) );

		} // end if

		else
		{
			// Ensure valid name and that it exists
			if ( !sName.length() || (*out).isset( sName ) )
				continue;

			// Use name as index
			r = &(*out)[ sName ];

		} // end else

		if ( !r )
			continue;

		// First add the attributes
		TiXmlAttribute *pAttrib = in->FirstAttribute();
		while ( nMax-- && pAttrib )
		{
			// Get name and value
			const char *pAtt = pAttrib->Name();
			const char *pValue = pAttrib->Value();
			if ( pAtt && *pAtt && pValue && *pValue )
			{	sqbind::stdString sAtt = oexMbToStrPtr( pAtt );
				if ( !r->isset( sAtt ) )
					nDecoded++, (*r)[ sAtt ].set( oexMbToStrPtr( pValue ) );
			} // end if

			// Next attribute
			pAttrib = pAttrib->Next();

		} // end while

		// Default value?
		const char *pText = in->GetText();
		if ( pText && *pText )
		{	nDecoded++;
			r->set( oexMbToStrPtr( pText ) );
		} // end if

		// Child elements?
		if ( in->FirstChildElement() )
			nDecoded += _Decode( r, in->FirstChildElement(), bIndexed, nDepth + 1 );

	} while ( ( in = in->NextSiblingElement() ) );

	return nDecoded;
}
Example #15
0
void searchXMLData(TiXmlElement* pElem, vector<no> &objects, string &file, string &path)  
{  
	TiXmlHandle hRoot(0);  
	TiXmlElement* pSubElem = pElem;  
	TiXmlAttribute* pAttrib = NULL;  


	//Set current node to root node and determine childe node is exist or not  
	hRoot = TiXmlHandle(pSubElem);  
	pSubElem = hRoot.FirstChildElement().Element();  
	if (!pSubElem) return;  

	char* pszNode = NULL;  
	char* pszAttrib = NULL;  
	char* pszText = NULL;  
	
	while (pSubElem)  
	{  
		//node  
		pszNode = (char*)pSubElem->Value();  
		//Attribute  
		pAttrib = pSubElem->FirstAttribute();  
		no buffer;
		if(!strcmp(pszNode,"rect"))buffer.nome += "rect";
		else if(!strcmp(pszNode,"circle"))buffer.nome += "circle";
		bool flag = false;
		while (pAttrib)  
		{  
			char* pszAttrib = (char*)pAttrib->Name();
			char* pszText = (char*)pAttrib->Value();

			if(buffer.nome == "rect" || buffer.nome == "circle")
			{
				flag = true;
				if(!strcmp(pszAttrib,"x") || !strcmp(pszAttrib,"cx"))
				{
					buffer.x = atoi(pszText);
				}
				else
				if(!strcmp(pszAttrib,"y") || !strcmp(pszAttrib,"cy"))
				{
					buffer.y = atoi(pszText);
				}
				else
				
				if(!strcmp(pszAttrib,"fill"))
				{
					buffer.fill += pszText;
				}
				else
				if(!strcmp(pszAttrib,"id"))
				{
					buffer.id += pszText;
				}
			}
			
			if(buffer.nome == "rect")
			{
				if(!strcmp(pszAttrib,"width"))
				{
					buffer.width = atoi(pszText);
				}
				else
				if(!strcmp(pszAttrib,"height"))
				{
					buffer.height = atoi(pszText);
				}
				else
				if(!strcmp(pszAttrib,"stroke-width"))
				{
					buffer.stroke_width = atoi(pszText);
				}
				else
				if(!strcmp(pszAttrib,"stroke"))
				{
					buffer.stroke += pszText;
				}
			}
			else
			{
				if(buffer.nome == "circle")
				{
					if(!strcmp(pszAttrib,"r"))buffer.r = atoi(pszText);
				}
			}
			
  			if(!strcmp(pszNode,"arquivoDaArena"))
			{
				if(!strcmp(pszAttrib,"nome"))
				{
					file += pszText;
				}
				else
				{			
					if(!strcmp(pszAttrib,"tipo") && !file.empty())
					{
						file+='.';
						file+=pszText;
					}
					else
					{
						if(!strcmp(pszAttrib,"caminho"))
						{
							path+=pszText;
						}
					}
				}
			}

			pAttrib = pAttrib->Next();  
		}  
		if(flag)objects.push_back(buffer);
		//Data  
		pszText = (char*)pSubElem->GetText();   

		// Recursive call for searching child node based current node  
		searchXMLData(pSubElem, objects, file, path);  
		pSubElem = pSubElem->NextSiblingElement();  
	}  
}  
Example #16
0
		bool SimXMLLoader::loadFromXML( const std::string & filename, AgentInitializer * agentInit, bool verbose ) {
			// COnfirms file is
			//	a) available for reading
			//	b) valid xml
			//	c) An "Experiment"
			if ( verbose ) logger << Logger::INFO_MSG << "Loading from xml: " << filename << ".";
			TiXmlDocument xml( filename );
			bool loadOkay = xml.LoadFile();

			if ( !loadOkay ) {	// load xml file
				logger << Logger::ERR_MSG << "Could not load simulation configuration xml (" << filename << ") due to xml syntax errors.\n";
				logger << "\t" << xml.ErrorDesc();
				return false;
			}

			TiXmlElement* experimentNode = xml.RootElement();	
			if( ! experimentNode ) {
				logger << Logger::ERR_MSG << "Scene configuration (" << filename << ") does not contain a root element.";
				return false;
			}

			if( experimentNode->ValueStr () != "Experiment" ) {
				logger << Logger::ERR_MSG << "Scene configuration (" << filename << ")'s root element is not \"Experiment\".";
				return false;
			}

			std::string absPath;
			os::path::absPath( filename, absPath );
			std::string junk;
			os::path::split( absPath, _sceneFldr, junk );
			logger << Logger::INFO_MSG << "Scene root: " << _sceneFldr << ".";		

			bool commonDone = false;	// common experiment parameters parsed
			bool targetDone = !_sim->hasExpTarget();	// target experiment parameters parsed
			bool spatialQueryDone = false;	// spatial query must be finished before obstacles and agents can be created

			// Tags I'm not ready to parse - only parse agent sets and obstacles AFTER experiment
			//	parameters
			std::list< TiXmlElement * > tagQueue;
			
			TiXmlElement* child;
			for( child = experimentNode->FirstChildElement(); child; child = child->NextSiblingElement()) {
				if ( child->ValueStr() == "Common" ) {
					// Currently the only "common" experiment parameter is the time step
					TiXmlAttribute * attr;
					for ( attr = child->FirstAttribute(); attr; attr = attr->Next() ) {
						try {
							if ( !_sim->setExpParam( attr->Name(), attr->ValueStr() ) ) {
								logger << Logger::WARN_MSG << "Unrecognized parameter in the global \"Common\" parameters (" << attr->Name() << ") on line " << child->Row() << "\n";
							}
						} catch ( XMLParamException e ) {
							logger << Logger::ERR_MSG << e.what();
							return false;
						}
					}
					commonDone = true;
				} else if ( child->ValueStr() == "AgentProfile" ) {
					if ( !parseAgentProfile( child, agentInit ) ) {
						return false;
					}
				} else if ( child->ValueStr() == "AgentGroup" ) {
					if ( ! ( commonDone || targetDone || spatialQueryDone ) ) {
						tagQueue.push_back( child );
					} else {
						if ( !parseAgentGroup( child, agentInit ) ) {
							return false;
						}
					}
				} else if ( child->ValueStr() == "ObstacleSet" ) {
					if ( ! ( commonDone || targetDone || spatialQueryDone) ) {
						tagQueue.push_back( child );
					} else {
						if ( ! parseObstacleSet( child ) ) {
							return false;
						}
					}
				} else if ( child->ValueStr() == "Elevation" ) {
					if ( _sim->hasElevation() ) {
						logger << Logger::ERR_MSG << "More than one elevation has been specified.  Found redundant elevation specification on line " << child->Row() << ".";
						return false;
					}
					Elevation * elevation = ElevationDB::getInstance( child, _sceneFldr );
					if ( elevation == 0x0 ) {
						logger << Logger::ERR_MSG << "Unable to instantiate elevation specifcation on line " << child->Row() << ".";
						return false;
					} else {
						_sim->setElevationInstance( elevation );
					}
					Menge::ELEVATION = elevation;
				} else if ( child->ValueStr() == "SpatialQuery" ) {
					if ( _sim->hasSpatialQuery() ) {
						logger << Logger::ERR_MSG << "More than one spatial query implementation has been specified.  Found redundant spatial query specification on line " << child->Row() << ".";
						return false;
					}
					SpatialQuery * spQuery = SpatialQueryDB::getInstance( child, _sceneFldr );
					if ( spQuery == 0x0 ) {
						logger << Logger::ERR_MSG << "Unable to instantiate spatial query specifcation on line " << child->Row() << ".";
						return false;
					} else {
						_sim->setSpatialQuery( spQuery );
						spatialQueryDone = true;
					}
				} else {	// target parameter 
					if ( !targetDone && _sim->isExpTarget( child->ValueStr() ) ) {
						// Parse the target
						TiXmlAttribute * attr;
						for ( attr = child->FirstAttribute(); attr; attr = attr->Next() ) {
							try {
								if ( ! _sim->setExpParam( attr->Name(), attr->ValueStr() ) ) {
									logger << Logger::WARN_MSG << "Unrecognized parameter in the global \"" << child->ValueStr() << "\" parameters (" << attr->Name() << ") on line " << child->Row() << "\n";
								}
							} catch ( XMLParamException e ) {
								logger << Logger::ERR_MSG << e.what() << " (on line " << child->Row() << ")";
								return false;
							}
						}
						targetDone = true;
					}
				} 
			}
			if ( !targetDone || !commonDone || !spatialQueryDone) {
				logger << Logger::ERR_MSG << "Missing required experiment parameters: \n";
				if ( !targetDone ) logger << "\tmodel simulation parameters ";
				if ( !commonDone ) logger << "\tcommon simulation parameters ";
				if ( !spatialQueryDone ) logger << "\tSpatial Query ";
				return false;
			}
			// Now parse any of the tags that were skipped while waiting for experiment configuration
			std::list< TiXmlElement * >::iterator tagItr = tagQueue.begin();
			for ( ; tagItr != tagQueue.end(); ++tagItr ) {
				TiXmlElement * child = *tagItr;
				if ( child->ValueStr() == "AgentGroup" ) {
					if ( !parseAgentGroup( child, agentInit ) ) {
						return false;
					}
				} else if ( child->ValueStr() == "ObstacleSet" ) {
					if ( ! parseObstacleSet( child ) ) {
							return false;
						}
				} else {
					logger << Logger::ERR_MSG << "XML contains an invalid tag: " << child->ValueStr() << " on line " << child->Row() << ".";
					return false;
				}
			}

			if ( _agtCount == 0 ) {
				// TODO: Change this test when agent sources are introduced
				//	in this case, it is possible to start with no agents and then add them
				//	w.r.t. time.
				logger << Logger::ERR_MSG << "No agents defined in simulation.";
				return false;
			}

			// free up the profiles
			//	TODO: I'll need to save these when I have AgentSources.
			for ( HASH_MAP< std::string, AgentInitializer * >::iterator itr = _profiles.begin();
				itr != _profiles.end();
				++itr ) 
			{
				delete itr->second;
			}
			_profiles.clear();

			return _sim->initSpatialQuery();
		}
Example #17
0
// pRoot의 모든 스킬을 읽는다.
XSkillDat* XESkillMng::LoadSkill( TiXmlElement *pRoot, 
							XSkillDat *pParentDat,
							EFFECT *pParentEffect )
{
	XSkillDat *pSkillDat = NULL;
	EFFECT *pEffect = NULL;
	//////////////////////////////////////////////////////////////////////////
	// 먼저 Attribute(폴더가 아닌것)가 있는지 살펴본다.
	TiXmlAttribute *pAttr = pRoot->FirstAttribute();
	if( pAttr )
	{
		const char *cAttrName = pAttr->Name();
		if( cAttrName )
		{
			// 속성이 하나라도 있으면 skillDat객체를 생성한다.
			// Attribute가 있으면 일단 스킬로 인식하고 Dat객체를 생성한다.
			pSkillDat = CreateSkillDat();
			if( pParentDat )
			{
				ID idSkill = pSkillDat->GetidSkill();
				*pSkillDat = *pParentDat;		// 부모의 데이타를 상속받는다.
				pSkillDat->SetidSkill( idSkill );
				_tstring strIdentifier = U82SZ( pRoot->Value() );
				pSkillDat->SetstrIdentifier( strIdentifier );
			}
			// 디폴트 이펙트버퍼도 하나 받는다.
			pEffect = new EFFECT;		
			if( pParentEffect )
				*pEffect = *pParentEffect;
			// 루프 시작
			do 
			{
				const char *cAttrName = pAttr->Name();
				const char *cParam = pAttr->Value();
				if( cAttrName && cAttrName[ 0 ] != '_' )
				{
					XU8LOG( cAttrName );
					XU8LOG( cParam );
					// 변수명과 값을 파싱해서 pSkillDat에 넣는다.
					ParsingAttr( pAttr, cAttrName, cParam, pSkillDat, pEffect );
				}
			} while (( pAttr = pAttr->Next() ));
		}
	}
	
	// pRoot에 폴더가 있는지 찾는다.
	TiXmlElement *pElemChild = pRoot->FirstChildElement();
	if( pElemChild  )
	{
		do 
		{
			// pRoot하의 모든 폴더를 하나씩 꺼낸다.
			const char *cFolderName = pElemChild->Value();
			if( cFolderName && cFolderName[0] != '_' ) {
				XU8LOG( cFolderName );
				//////////////////////////////////////////////////////////////////////////
				// "효과"블럭은 따로 처리
				if( XSAME( pElemChild->Value(), 96 ) ||
					XSAME( pElemChild->Value(), 226 ) )	{ // 효과/발동효과
					if( pSkillDat == NULL ) {
						pSkillDat = CreateSkillDat();
						if( pParentDat ) {
							ID idSkill = pSkillDat->GetidSkill();
							*pSkillDat = *pParentDat;		// 부모의 데이타를 상속받는다.
							pSkillDat->SetidSkill( idSkill );
							_tstring strIdentifier = U82SZ( pRoot->Value() );
							pSkillDat->SetstrIdentifier( strIdentifier );
						}
					}
					EFFECT *pEffBlock = new EFFECT;
					if( pEffect )
						*pEffBlock = *pEffect;	// 하위상속을 위해 내용 복사.
					else
						*pEffBlock = *pParentEffect;		// 스킬블럭에 디폴트 파라메터가 없으면 부모것을 디폴트로 쓴다.

					int numAttr = LoadEffect( pElemChild, pSkillDat, pEffBlock );
					// 효과블럭안에 아무것도 없었으면 지운다.
					if( numAttr == 0 )
						SAFE_DELETE( pEffBlock );
					if( pEffBlock )
						pSkillDat->AddEffect( pEffBlock );
				} else
				if( XSAME( pElemChild->Value(), 235 ) )	{	// 발동조건
					if( pEffect == nullptr ) {
						pEffect = new EFFECT;
						if( pParentEffect )
							*pEffect = *pParentEffect;
					}
					LoadCond( pElemChild, pEffect );
				} else
					if( cFolderName[0] != '_' )		// 스킬이름이 _로 시작되면 읽지 않는다.
					{
						// 그외 폴더는 일단 스킬로 인식한다.
						XSkillDat* pNewSkillDat = NULL;
						pNewSkillDat = LoadSkill( pElemChild,
							( pSkillDat ) ? pSkillDat : pParentDat,
							( pEffect ) ? pEffect : pParentEffect );
						if( pNewSkillDat ) {
							Add( pNewSkillDat );
						}
					}
			}
		} while (( pElemChild = pElemChild->NextSiblingElement() ));
	}
	if( pSkillDat )	{
		// "효과"블럭이 추가된게 있었으면 디폴트용으로 생성되었던 이펙트 블럭은 필요없으므로 지운다.
		if( pSkillDat->GetNumEffect() > 0 ) {
			SAFE_DELETE( pEffect );
		}
		else
		// 효과폴더가 없고 발동파라메터가 지정되지 않은 폴더는 스킬이 아니라고 보고 지운다.
		if( pSkillDat->GetNumEffect() == 0 ) {
			if( pEffect->invokeParameter == 0 && 
				pEffect->invokeState == 0 &&
				pEffect->strInvokeSkill.empty() && 
				pEffect->idInvokeSkill == 0 &&
				pEffect->invokeAbilityMin.size() == 0 &&
				pEffect->invokeJuncture != 99 )	{	// 발동시점:하드코딩
				SAFE_RELEASE_REF( pSkillDat );
				SAFE_DELETE( pEffect );
			} else
				// "효과"블럭으로 추가된게 없고 발동파라메터는 지정되었으면 디폴트 이펙트를 이펙트로 추가한다.
				pSkillDat->AddEffect( pEffect );
		} else {
			XBREAK(1);
		}
		if( pSkillDat )
		{
			XBREAK( pSkillDat->GetTargetEff().IsHave() && pSkillDat->GetTargetEff().m_Loop == xAL_LOOP );
			if( pSkillDat->m_strShootObj.empty() == false && pSkillDat->m_idShootObj == 0 )
				pSkillDat->m_idShootObj = 1;
			// 파라메터 보정
			for( const auto pEffect : pSkillDat->GetlistEffects() ) {
				// 지속시간이 있는데 발동시점이 지정안되면 디폴트로 persist동작을 하도록 수정.(버프라도 지속시간계속 발동하는게 있고 버프받는최초에만 적용되는게 있다, 버프끝날때 발동되는것도 있고.
				if( pEffect->IsDuration() && pEffect->invokeJuncture == xJC_NONE ) {
						pEffect->invokeJuncture = xJC_PERSIST;
				}
				LCONSOLE( !pEffect->IsDuration() && pEffect->invokeJuncture == xJC_PERSIST
						 , "%s", _T("지속시간이 없는스킬인데 지속발동으로 지정되어 있음.") );
				// 발동시점스킬이 지정되어 있다면 발동시점은 무조건 스킬발동시가 된다.
				if( pEffect->strInvokeTimeSkill.empty() == false ) {
					pEffect->invokeJuncture = xJC_INVOKE_SKILL;	// 이걸하지않으면 지속형 스킬이 되어버림.
				}
				// 발동대상우호가 지정되지 않았으면 시전대상우호를 가져다 쓴다.
				if( pEffect->invokefiltFriendship == xfNONESHIP )
					pEffect->invokefiltFriendship = pEffect->castfiltFriendship;
				// 시전거리는 정해졌는데 시전범위타입이 지정되지 않았으면 디폴트로 원형이 됨
				if( pEffect->castSize.w > 0.f && pEffect->castSize.h > 0.f &&
					pEffect->castTargetRange == xTR_ONE )
					pEffect->castTargetRange = xTR_LINE;
				if( pEffect->castSize.w > 0.f && 
					pEffect->castTargetRange == xTR_ONE )
					pEffect->castTargetRange = xTR_CIRCLE;
				if( pEffect->invokeTarget == xIVT_NONE )
					pEffect->invokeTarget = xIVT_CAST_TARGET;
				if( pEffect->invokeTarget == xIVT_CAST_TARGET_RADIUS 
						|| pEffect->invokeTarget == xIVT_CAST_TARGET_SURROUND ) {
					if( pEffect->IsHaveInvokeSize() == false )
						XALERT("스킬\"%s\":발동범위가 지정되지 않음", pSkillDat->GetstrIdentifier().c_str() );
				}
				// 지속시간스킬이면서 발동스킬이 있는건 에러(매프레임 스킬을 발동시키게 됨)
				XBREAK( pEffect->IsDuration() 
								&& pEffect->secInvokeDOT == 0 
								&& pEffect->invokeJuncture == xJC_PERSIST
								&& !pEffect->strInvokeSkill.empty() );
				XBREAK( pEffect->castTarget == xCST_BASE_TARGET_POS			// 시전대상이 좌표형
								&& pEffect->IsDuration()												// 지속시간형
								&& pEffect->m_PersistEff.IsEmpty() );						// 일때 지속효과 spr이 없으면 안됨.(투명 객체됨)
				AdjustEffectParam( pSkillDat, pEffect );	// virtual
			} // for effect
		}
	} else {
		SAFE_DELETE( pEffect );
	}
	return pSkillDat;
}
Example #18
0
//----------------------------------------------------------------//
void MOAIXmlParser::Parse ( MOAILuaState& state, TiXmlNode* node ) {

    if ( !node ) return;

    TiXmlElement* element = node->ToElement();
    if ( element ) {

        lua_newtable ( state );

        // element name
        lua_pushstring ( state, element->Value ());
        lua_setfield ( state, -2, "type" );

        // parse attributes

        TiXmlAttribute* attribute = element->FirstAttribute ();
        if ( attribute ) {
            lua_newtable ( state );
            for ( ; attribute; attribute = attribute->Next ()) {
                lua_pushstring ( state, attribute->Value ());
                lua_setfield ( state, -2, attribute->Name ());
            }
            lua_setfield ( state, -2, "attributes" );
        }

        // round up the children
        STLSet < string > children;
        TiXmlElement* childElement = node->FirstChildElement ();
        for ( ; childElement; childElement = childElement->NextSiblingElement ()) {
            children.affirm ( childElement->Value ());
        }

        if ( children.size ()) {
            lua_newtable ( state );
            STLSet < string >::iterator childrenIt = children.begin ();
            for ( ; childrenIt != children.end (); ++childrenIt ) {

                string name = *childrenIt;
                lua_newtable ( state );

                childElement = node->FirstChildElement ( name );
                for ( u32 count = 1; childElement; childElement = childElement->NextSiblingElement ( name ), ++count ) {
                    MOAIXmlParser::Parse ( state, childElement );
                    lua_rawseti ( state, -2, count );
                }
                lua_setfield ( state, -2, name.c_str ());
            }
            lua_setfield ( state, -2, "children" );
        }

        // handle text children
        TiXmlNode* child = node->FirstChild ();
        if ( child ) {
            TiXmlText* text = child->ToText ();
            if ( text ) {
                lua_pushstring ( state, text->Value ());
                lua_setfield ( state, -2, "value" );
            }
        }
    }
}
Example #19
0
int CSkeleton::CBone::ReadXMLAttrib( TiXmlElement* poElement )
{
	if( !poElement )
		return 0;
	
	TiXmlAttribute* poAttrib = poElement->FirstAttribute();
	int i = 0;
	int iVal;
	double dVal;
	static char acName_[256];
	
	while( poAttrib )
	{
		const char *pcName = poAttrib->Name();
		if( !strcmp( pcName, "name" ) )
		{
			SKELETON_STR_COPY( acName_, sizeof(acName_), poAttrib->Value() );
			SKELETON_LOG( "name: %s\n", acName_ );
			m_oName = acName_;
		}
		else if( !strcmp( pcName, "parent_index" ) )
		{
			if( poAttrib->QueryIntValue( &iVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %d\n", poAttrib->Name(), iVal );
				m_iIndexParent = iVal;
			}
		}
		else if( !strcmp( pcName, "head_x" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oHead[0] = float( dVal );
			}
		}
		else if( !strcmp( pcName, "head_y" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oHead[1] = float( dVal );
			}
		}
		else if( !strcmp( pcName, "head_z" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oHead[2] = float( dVal );
			}
		}
		else if( !strcmp( pcName, "tail_x" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oTail[0] = float( dVal );
			}
		}
		else if( !strcmp( pcName, "tail_y" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oTail[1] = float( dVal );
			}
		}
		else if( !strcmp( pcName, "tail_z" ) )
		{
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
			{
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
				m_oTail[2] = float( dVal );
			}
		}
#define CHECK_M( i, j ) \
		else if( !strcmp( pcName, "m" #i #j ) ) \
		{ \
			if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS ) \
			{ \
				SKELETON_LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) ); \
				m_oTransform( i, j ) = float( dVal ); \
			} \
		}
		CHECK_M( 0, 0 )
		CHECK_M( 1, 0 )
		CHECK_M( 2, 0 )
		CHECK_M( 3, 0 )
		CHECK_M( 0, 1 )
		CHECK_M( 1, 1 )
		CHECK_M( 2, 1 )
		CHECK_M( 3, 1 )
		CHECK_M( 0, 2 )
		CHECK_M( 1, 2 )
		CHECK_M( 2, 2 )
		CHECK_M( 3, 2 )
		CHECK_M( 0, 3 )
		CHECK_M( 1, 3 )
		CHECK_M( 2, 3 )
		CHECK_M( 3, 3 )
#undef CHECK_M
		else
		{
			//m_bError = true;
			SKELETON_ERR( "undefined attribute, %s\n", pcName );
		}
		i++;
		poAttrib = poAttrib->Next();
	}
	return i;
}
Example #20
0
TiXmlNode * readXMLConfig::selectChildNode(TiXmlNode * pNode,string nodeName,string nodeAttrName,string nodeAttrValue)  
{  
    if(pNode == NULL)  
    {  
        return NULL;  
    }  
    TiXmlNode * pSelectedNode = NULL;  
    TiXmlNode * pChildNode = NULL;  
    int t = pNode->Type();  
    switch (t)  
    {  
    case TiXmlText::TINYXML_DOCUMENT:  
    case TiXmlText::TINYXML_DECLARATION:  
    case TiXmlText::TINYXML_TEXT:  
    case TiXmlText::TINYXML_UNKNOWN:  
    case TiXmlText::TINYXML_COMMENT:  
        break;  
    case TiXmlText::TINYXML_ELEMENT:  
    if(pNode->Value() == nodeName)  
    {  
        //cout << pNode->Value() << endl;  
        if(!nodeAttrName.empty() && !nodeAttrValue.empty())  
        {  
            TiXmlElement * pElement = pNode->ToElement();  

            TiXmlAttribute * pAttr = pElement->FirstAttribute();  
            TiXmlAttribute * pNextAttr =NULL;  
            if(pAttr != NULL)  
            {    
                do  
                {                            
                    if(pAttr->Name()==nodeAttrName&&pAttr->Value()== nodeAttrValue)  
                    {  
                        //cout << pAttr->Value() << endl;  
                        return pNode;  
                    }  
                }while(pAttr = pAttr->Next());  
            }  
        }  
        else  
        {  
            return pNode;  
        }  
             
    }  
    else  
    {  
        //循环访问它的每一个元素  
        for(pChildNode=pNode->FirstChild();  
            pChildNode!=0;  
            pChildNode = pChildNode->NextSibling())  
        {  
            pSelectedNode = selectChildNode(  
                                pChildNode,  
                                nodeName,  
                                nodeAttrName,  
                                nodeAttrValue);  
            if(pSelectedNode)  
            {  
                return pSelectedNode;  
            }  
        }  
    }  
 
    default:break;  
    }  
    return NULL;  
}
Example #21
0
void CPacketDlg::OnBnClickedButton6()
{
	m_pBaseDataLogic->ClearRandomPacket();

	//读取XML文件
	TiXmlDocument * pDocument = new TiXmlDocument(PACKETDATA_FILENAME);//tstl可以为文件路径或文件名
	pDocument->LoadFile();

	if(NULL == pDocument)
	{
		MessageBox(_T("读取顺序数据包xml文件失败"), _T("提示信息"), MB_OK);
		return;
	}

	TiXmlElement *Root = pDocument->RootElement();//获取根节点<Particls>
	TiXmlElement *Particl = NULL;

	int nLen        = 0;
	int nType       = 0;
	int nRecvLength = 0;

	for(Particl = Root->FirstChildElement();Particl != NULL;Particl = Particl->NextSiblingElement())
	{
		//得到文档内容
		const char *sztext = Particl->GetText();

		//得到文档属性
		TiXmlAttribute* pAddrAttr = Particl->FirstAttribute();
		if(strcmp(pAddrAttr->Name(), "Len") == 0)
		{
			nLen = atoi(pAddrAttr->Value());
		}
		else if(strcmp(pAddrAttr->Name(), "Type") == 0)
		{
			nType = atoi(pAddrAttr->Value());
		}
		else
		{
			nRecvLength = atoi(pAddrAttr->Value());
		}

		TiXmlAttribute *pAttr1 = pAddrAttr->Next();
		if(strcmp(pAttr1->Name(), "Len") == 0)
		{
			nLen = atoi(pAttr1->Value());
		}
		else if(strcmp(pAttr1->Name(), "Type") == 0)
		{
			nType = atoi(pAttr1->Value());
		}
		else
		{
			nRecvLength = atoi(pAttr1->Value());
		}

		TiXmlAttribute * pAttr2 = pAttr1->Next();
		if(strcmp(pAttr2->Name(), "Len") == 0)
		{
			nLen = atoi(pAttr2->Value());
		}
		else if(strcmp(pAttr2->Name(), "Type") == 0)
		{
			nType = atoi(pAttr2->Value());
		}
		else
		{
			nRecvLength = atoi(pAttr2->Value());
		}

		//添加类型
		m_pBaseDataLogic->InsertRandomPacket(sztext, nLen, nRecvLength, nType);
	}

	ShowPacketList();

	delete pDocument;
}
Example #22
0
void ResultMap::LoadPredefinedResultFromFile(const wxString& FileName)
{
    TiXmlDocument Doc;

    if ( !Doc.LoadFile(FileName.mb_str(wxConvFile)) ) return;

    wxString CBBase = ConfigManager::GetFolder(sdBase) + wxFileName::GetPathSeparator();

    for ( TiXmlElement* RootElem = Doc.FirstChildElement("predefined_library");
          RootElem;
          RootElem = RootElem->NextSiblingElement("predefined_library") )
    {
        for ( TiXmlElement* Elem = RootElem->FirstChildElement();
              Elem;
              Elem = Elem->NextSiblingElement() )
        {
            LibraryResult* Result = new LibraryResult();
            Result->Type         = rtPredefined;
            Result->LibraryName  = wxString(Elem->Attribute("name")      ,wxConvUTF8);
            Result->ShortCode    = wxString(Elem->Attribute("short_code"),wxConvUTF8);
            Result->BasePath     = wxString(Elem->Attribute("base_path") ,wxConvUTF8);
            Result->PkgConfigVar = wxString(Elem->Attribute("pkg_config"),wxConvUTF8);
            if ( TiXmlElement* Sub = Elem->FirstChildElement("description") )
            {
                Result->Description  = wxString(Sub->GetText(),wxConvUTF8);
            }

            for ( TiXmlAttribute* Attr = Elem->FirstAttribute(); Attr; Attr=Attr->Next() )
            {
//                if ( !strncasecmp(Attr->Name(),"category",8) )
                if ( !strncmp(Attr->Name(),"category",8) )
                {
                    Result->Categories.Add(wxString(Attr->Value(),wxConvUTF8));
                }
            }

            for ( TiXmlElement* Sub = Elem->FirstChildElement(); Sub; Sub=Sub->NextSiblingElement() )
            {
                wxString Name = wxString(Sub->Value(),wxConvUTF8).Lower();

                if ( Name == _T("path") )
                {
                    wxString Include = wxString(Sub->Attribute("include"),wxConvUTF8);
                    wxString Lib     = wxString(Sub->Attribute("lib"),wxConvUTF8);
                    wxString Obj     = wxString(Sub->Attribute("obj"),wxConvUTF8);

                    if ( !Include.IsEmpty() )
                    {
                        Result->IncludePath.Add(wxFileName(Include).IsRelative() ? CBBase + Include : Include);
                    }

                    if ( !Lib.IsEmpty() )
                    {
                        Result->LibPath.Add(wxFileName(Lib).IsRelative() ? CBBase + Lib : Lib);
                    }

                    if ( !Obj.IsEmpty() )
                    {
                        Result->ObjPath.Add(wxFileName(Obj).IsRelative() ? CBBase + Obj : Obj);
                    }
                }

                if ( Name == _T("add") )
                {
                    wxString Lib = wxString(Sub->Attribute("lib"),wxConvUTF8);
                    wxString Define = wxString(Sub->Attribute("define"),wxConvUTF8);
                    wxString CFlags = wxString(Sub->Attribute("cflags"),wxConvUTF8);
                    wxString LFlags = wxString(Sub->Attribute("lflags"),wxConvUTF8);

                    if ( !Lib.IsEmpty() ) Result->Libs.Add(Lib);
                    if ( !Define.IsEmpty() ) Result->Defines.Add(Define);
                    if ( !CFlags.IsEmpty() ) Result->CFlags.Add(CFlags);
                    if ( !LFlags.IsEmpty() ) Result->LFlags.Add(LFlags);
                }

                if ( Name == _T("compiler") )
                {
                    Result->Compilers.Add(wxString(Sub->Attribute("name"),wxConvUTF8));
                }

                if ( Name == _T("header") )
                {
                    Result->Headers.Add(wxString(Sub->Attribute("file"),wxConvUTF8));
                }

                if ( Name == _T("require") )
                {
                    Result->Require.Add(wxString(Sub->Attribute("library"),wxConvUTF8));
                }
            }

            if ( Result->LibraryName.IsEmpty() ||
                 Result->ShortCode.IsEmpty() )
            {
                delete Result;
                continue;
            }

            GetShortCode(Result->ShortCode).Add(Result);
        }
    }
}
Example #23
0
bool CGmObjAnim3::ReadXML( TiXmlNode* poParent, unsigned int uiCounter )
{
	if( !poParent )
		return false;
	
	static char acTxt_[256];
	if( uiCounter == 0 )
	{
	}
	
	switch ( poParent->Type() )
	{
	case TiXmlNode::DOCUMENT:
		LOG( "XML: Document" );
	break;
	case TiXmlNode::ELEMENT:
	{
		const char *pcName = poParent->Value();
		//LOG( "name: %s\n", pcName );
		if( !strcmp( pcName, "animation" ) )
		{
			LOG( "animation:\n" );
			
			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				int iIdx;
				CStr oMeshFileName;
				CArray<CStr> oArrAnimFileName;
				
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "mesh" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						oMeshFileName = acTxt_;
					}
					else if( SSCANF( pcName, "anim_%d", &iIdx ) == 1 )
					{
						LOG( "%s: %d\n", poAttrib->Name(), iIdx );
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						if( iIdx >= int( oArrAnimFileName.GetSize() ) )
							oArrAnimFileName.Resize( iIdx + 1 );
						oArrAnimFileName[iIdx] = acTxt_;
						
					}
					poAttrib = poAttrib->Next();
				}
				
				if( oMeshFileName.GetSize() )
				{
					// Model.
					m_poModel = m_poResMan_->NewModelMD5( oMeshFileName, oArrAnimFileName, false );
					
					const unsigned int uiFrameCountTotal = m_poModel->GetFrameCountTotal();
					const unsigned int uiMeshCount = m_poModel->GetMeshCount();
					const unsigned int uiAnimCount = m_poModel->GetAnimCount();
					
					m_oArrAnim.Resize( uiAnimCount );
					m_oArrAnim.Fill( 0 );
					
					m_poData->SetFrameCount( uiFrameCountTotal );
					unsigned int uiFrameIdx = 0;
					
					for( unsigned int uiAnim=0; uiAnim<uiAnimCount; ++uiAnim )
					{
						//m_poModel->SetAnim( uiAnim );	
						const unsigned int uiFrameCount = m_poModel->GetFrameCount( uiAnim );
						
						CAnim * poAnim = new CAnim;
						m_oArrAnim[uiAnim] = poAnim;
						
						poAnim->SetFrameRate( m_poModel->GetFrameRate( uiAnim ) );
						poAnim->SetFrameCount( uiFrameCount );
						
						for( unsigned int uiFrame=0; uiFrame<uiFrameCount; ++uiFrame )
						{
							CFrame * poFrame = new CFrame;
							m_poData->SetFrame( uiFrameIdx, poFrame );
							poAnim->SetFrameIndex( uiFrame, uiFrameIdx );
							++uiFrameIdx;
							
							poFrame->SetMeshCount( uiMeshCount );

							for( unsigned int uiMesh=0; uiMesh<uiMeshCount; ++uiMesh )
							{
								CGMeshMD5 * poMesh = m_poModel->GetPrecalcMesh( uiMesh, uiFrame, uiAnim );
								ASSERT( poMesh );
								poFrame->SetMesh( uiMesh, poMesh );
							}
						}

						poAnim->Init();
					}
					ASSERT( uiFrameIdx == uiFrameCountTotal );
				}
			}
		}
		else if( m_poModel )
		{
			if( !strcmp( pcName, "action" ) )
			{
				LOG( "action:\n" );
				
				TiXmlElement * poElement = poParent->ToElement();
				if( poElement )
				{
					CAction *poAction = 0;
					
					TiXmlAttribute* poAttrib = poElement->FirstAttribute();
					while( poAttrib )
					{
						const char *pcName = poAttrib->Name();
						if( !strcmp( pcName, "name" ) )
						{
							STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
							LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
							
							poAction = new CAction;
							poAction->m_oName = acTxt_;
							poAction->m_uiIndex = m_oArrAction.GetSize();
							m_oArrAction.Append( poAction );
						}
						else if( !strcmp( pcName, "anim" ) )
						{
							STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
							LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
							
							CStr oIdxSeq( acTxt_ );
							if( oIdxSeq.GetSize() && poAction )
							{
								static const char cDelim_ = ',';
								
								unsigned int i = 0;
								while( true )
								{
									int iIdx;
									if( SSCANF( oIdxSeq.GetData() + i, "%d", &iIdx ) == 1 )
									{
										LOG( "index: %d\n", iIdx );
										poAction->AppendAnimIndex( iIdx );
									}
									const int c = oIdxSeq.Find( i, cDelim_ );
									if( c < 0 )
										break;
									i = c + 1;
								}
								
							}
						}
						else if( !strcmp( pcName, "sound" ) )
						{
							STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
							LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
							
							TWav * poWav = m_poResMan_->NewWav( acTxt_ );
							if( poWav )
							{
								poAction->SetSoundStart( poWav );
							}
						}
						poAttrib = poAttrib->Next();
					}

					poAction->Init();
				}
			}
			/*
			else if( !strcmp( pcName, "joint_tracker" ) )
			{
				LOG( "joint_tracker:\n" );
				
				TiXmlElement * poElement = poParent->ToElement();
				if( poElement )
				{
					CJointTracker *poJointTracker = 0;
					
					TiXmlAttribute* poAttrib = poElement->FirstAttribute();
					while( poAttrib )
					{
						const char *pcName = poAttrib->Name();
						if( !strcmp( pcName, "name" ) )
						{
							STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
							LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
							
							poJointTracker = GetJointTracker( acTxt_ );
							if( !poJointTracker )
							{
								poJointTracker = new CJointTracker;
								poJointTracker->m_oName = acTxt_;
								m_oLstJointTracker.Append( poJointTracker );
							}
						}
						else if( !strcmp( pcName, "joint" ) && poJointTracker )
						{
							STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
							LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
							
							const int iJoint = m_poModel->GetJointIndex( acTxt_ );
							if( iJoint >= 0 )
								poJointTracker->New( iJoint );
						}
						poAttrib = poAttrib->Next();
					}
				}
			}
			*/
		}
	}
	break;
	case TiXmlNode::COMMENT:
		//LOG( "XML: Comment: [%s]", poParent->Value());
	break;
	case TiXmlNode::UNKNOWN:
		//LOG( "XML: Unknown" );
	break;
	case TiXmlNode::TEXT:
		//LOG( "XML: Text: [%s]", poParent->ToText()->Value() );
	break;
	case TiXmlNode::DECLARATION:
		//LOG( "XML: Declaration" );
	break;
	default:
	break;
	}
	LOG( "\n" );
	
	++uiCounter;
	
	for( TiXmlNode* poChild = poParent->FirstChild(); poChild != 0; poChild = poChild->NextSibling() ) 
	{
		ReadXML( poChild, uiCounter );
	}
	
	// Ganz am Schluss...
	if( uiCounter == 1 )
	{
	}
	return true;
}
Example #24
0
HeeksObj* Constraint::ReadFromXMLElement(TiXmlElement* pElem)
{
	const char* type=0;
	EnumConstraintType etype=(EnumConstraintType)0;
	const char* angle=0;
	EnumAbsoluteAngle eangle=(EnumAbsoluteAngle)0;
	double length=0;
	int obj1_id=0;
	int obj2_id=0;
	int obj1_type=0;
	int obj2_type=0;
	ConstrainedObject* obj1=0;
	ConstrainedObject* obj2=0;
	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "type"){type = a->Value();}
		else if(name == "angle"){angle = a->Value();}
		else if(name == "length"){length = a->DoubleValue();}
		else if(name == "obj1_id"){obj1_id = a->IntValue();}
		else if(name == "obj1_type"){obj1_type = a->IntValue();}
		else if(name == "obj2_id"){obj2_id = a->IntValue();}
		else if(name == "obj2_type"){obj2_type = a->IntValue();}
	}

	//Ugh, we need to convert the strings back into types
	for(unsigned i=0; i < sizeof(ConstraintTypes); i++)
	{
		if(strcmp(ConstraintTypes[i].c_str(),type)==0)
		{
			etype = (EnumConstraintType)i;
			break;
		}
	}

	for(unsigned i=0; i < sizeof(AbsoluteAngle); i++)
	{
		if(strcmp(AbsoluteAngle[i].c_str(),angle)==0)
		{
			eangle = (EnumAbsoluteAngle)i;
			break;
		}
	}


	//JT
	//Ok.. There is a problem here.. Further up stream there a conditions where the xml has been written out for obj1_id, obj2_id != 0 for objects that don't exist
	//This is a huge pain, since the error is being introduced on the file save, and doesn't show up, until you load the file.
	// Sometimes you get a segmentation fault right at load... Or when you're really lucky it shows up when solvesketch kicks in and you have no clue whats going on.
    // At this point,until these critters get irridicated CheckforValidConstraint basically tries to see if the constraint makes sense
    // I hope to install this at both ends when constraints are being written out or read in my attempt to identify, isolate and irradicate these most annoying
    // critters

#ifdef CHECK_FOR_INVALID_CONSTRAINT
    bool blockConstraint =false;
    blockConstraint =  checkForInvalidConstraint(type,etype,angle,eangle,length,obj1_id,obj2_id,obj1_type,obj2_type);
    if (blockConstraint)
	{
      return NULL;
    }
#endif

	//Get real pointers to the objects
	obj1 = (ConstrainedObject*)wxGetApp().GetIDObject(obj1_type,obj1_id);
	obj2 = (ConstrainedObject*)wxGetApp().GetIDObject(obj2_type,obj2_id);

	Constraint *c = new Constraint(etype,eangle,length,obj1,obj2);

	unsigned int len;
	char *str = new char[512];
	char *cstr = str;

	printf("Searched for: 0x%X:0x%X, 0x%X:0x%X\n", obj1_type, obj1_id, obj2_type, obj2_id);
	if(obj1)
	{
		obj1->constraints.push_back(c);
		obj1->ToString(str,&len,512);
		cstr = str+len;
	}
	if(obj2)
	{
		obj2->constraints.push_back(c);
		obj2->ToString(cstr,&len,512);
		cstr = cstr+len;
	}
	printf("%s",str);

	//Don't let the xml reader try to insert us in the tree
	return NULL;
}
Example #25
0
void CAttachOp::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element = heeksCAD->NewXMLElement( "AttachOp" );
	heeksCAD->LinkXMLEndChild( root,  element );

	element->SetDoubleAttribute( "tolerance", m_tolerance);
	element->SetDoubleAttribute( "minz", m_min_z);
	element->SetDoubleAttribute( "material_allowance", m_material_allowance);

	// write solid ids
#ifdef OP_SKETCHES_AS_CHILDREN
	for (HeeksObj *object = GetFirstChild(); object != NULL; object = GetNextChild())
	{
		if (object->GetIDGroupType() != SolidType)continue;
		int solid = object->GetID();
#else
	for (std::list<int>::iterator It = m_solids.begin(); It != m_solids.end(); It++)
    {
		int solid = *It;
#endif
		TiXmlElement * solid_element = heeksCAD->NewXMLElement( "solid" );
		heeksCAD->LinkXMLEndChild( element, solid_element );
		solid_element->SetAttribute("id", solid);
	}

	COp::WriteBaseXML(element);
}

// static member function
HeeksObj* CAttachOp::ReadFromXMLElement(TiXmlElement* element)
{
	CAttachOp* new_object = new CAttachOp;

	element->Attribute("tolerance", &new_object->m_tolerance);
	element->Attribute("minz", &new_object->m_min_z);
	element->Attribute("material_allowance", &new_object->m_material_allowance);

	std::list<TiXmlElement *> elements_to_remove;

	// read solid ids
	for(TiXmlElement* pElem = heeksCAD->FirstXMLChildElement( element ) ; pElem; pElem = pElem->NextSiblingElement())
	{
		std::string name(pElem->Value());
		if(name == "solid"){
			for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
			{
				std::string name(a->Name());
				if(name == "id"){
					int id = a->IntValue();
					new_object->m_solids.push_back(id);
				}
			}
			elements_to_remove.push_back(pElem);
		}
	}

	for (std::list<TiXmlElement*>::iterator itElem = elements_to_remove.begin(); itElem != elements_to_remove.end(); itElem++)
	{
		heeksCAD->RemoveXMLChild( element, *itElem);
	}

	new_object->ReadBaseXML(element);

	return new_object;
}
Example #26
0
bool MainLandManager::LoadData()
{
	// Note: 避免数据重复加载
	if (false == mIsDataLoad)
	{
		mIsDataLoad = true;
	}
	else
	{
		return true;
	}

	std::string xmlFilePath = "Data/CityBasicInformation.xml";
	std::string fullFilePath = GameResourceManager::sharedManager()->storedFullPathFromRelativePath(xmlFilePath.c_str());

	unsigned long	_size;
	char			*_pFileContent = (char*)CCFileUtils::sharedFileUtils()->getFileData(fullFilePath.c_str() , "r", &_size);
	TiXmlDocument	*_document = new TiXmlDocument();
	_document->Parse(_pFileContent, 0, TIXML_ENCODING_UTF8);

	CC_SAFE_DELETE_ARRAY(_pFileContent);

	TiXmlElement *RootElement = _document->RootElement();
	if (RootElement)
	{
		TiXmlElement *childElement = RootElement->FirstChildElement();
		while(childElement)
		{
			CityBasicInfo *cityBasicInfo = new CityBasicInfo();

			unsigned int city_id = 0;
			TiXmlAttribute* pAttribute = childElement->FirstAttribute();
			while(pAttribute)
			{
				std::string strName(pAttribute->Name());
				if (strName == "CityID")
				{
					const char* city_id_str = childElement->Attribute("CityID");
					city_id = atoi(city_id_str);
				}
				else if (strName == "MapID")
				{
					std::string mapIdStr(childElement->Attribute("MapID"));
					cityBasicInfo->map_id = atoi(mapIdStr.c_str());
				}
				else if (strName == "CityName")
				{
					cityBasicInfo->city_name = childElement->Attribute("CityName");
				}
				else if (strName == "HeroBornCoordinate")
				{
					cityBasicInfo->heroBornPoint = getPointAttribute(childElement, "HeroBornCoordinate");
				}
				else if (strName == "NormalRaidTransmissionGate")
				{
					cityBasicInfo->normalRaidTransmissionGate = getPointAttribute(childElement, "NormalRaidTransmissionGate");
				}
				else if (strName == "NormalRaidTransmissionGate")
				{
					cityBasicInfo->normalRaidTransmissionGate = getPointAttribute(childElement, "NormalRaidTransmissionGate");
				}
				else if (strName == "EliteRaidTransmissionGate")
				{
					cityBasicInfo->eliteRaidTransmissionGate = getPointAttribute(childElement, "EliteRaidTransmissionGate");
				}
				else if (strName == "BGMID")
				{
					const char* city_bgm = childElement->Attribute("BGMID");
					cityBasicInfo->backgroundMusicID = atoi(city_bgm);
				}
				else
				{
					int pos = strName.find("TaskNPC");
					if (std::string::npos != pos)
					{
						pos = pos + 6;
						int endPos = strName.rfind("ID");
						int firstNpcId = atoi(strName.substr(pos+1,endPos-pos-1).c_str());

						char buffer[100];
						memset(buffer,0,sizeof(buffer)/sizeof(char));
						sprintf(buffer,"TaskNPC%dID",firstNpcId);
						int npc_id = atoi(childElement->Attribute(buffer));

						NpcBasicInfo npcBasicInfo;

						memset(buffer,0,sizeof(buffer)/sizeof(char));
						sprintf(buffer,"TaskNPC%dposition",firstNpcId);

						std::string npc_pos_str(childElement->Attribute(buffer));
						int midPos = npc_pos_str.find("/");
						float posX = atoi(npc_pos_str.substr(0,midPos).c_str()) * 16;
						float posY = atoi(npc_pos_str.substr(midPos+1,npc_pos_str.length()-midPos-1).c_str()) * 16;

						npcBasicInfo.pos.x = posX;
						npcBasicInfo.pos.y = posY;				

						memset(buffer,0,sizeof(buffer)/sizeof(char));
						sprintf(buffer,"TaskNPC%dflip",firstNpcId);
						const char* bFlip_str = childElement->Attribute(buffer);
						if (bFlip_str != 0)
						{
							int value = atoi(bFlip_str);
							if (value == 1)
							{
								npcBasicInfo.bFlip = true;
							}
						}

						cityBasicInfo->mapNpcIdAndPos->insert(std::make_pair(npc_id,npcBasicInfo));
					}
				}

				pAttribute = pAttribute->Next();
			}
			
			mapCityIdAndBasicInfo->insert(std::make_pair(city_id,cityBasicInfo));

			childElement = childElement->NextSiblingElement();
		}
	}

	delete _document;

	return true;
}
Example #27
0
bool WorldDB::load_object_attributes(WorldObject *object, TiXmlElement *elmt)
{
    bool result = true;

    TiXmlAttribute *attr = elmt->FirstAttribute();
    while (attr) {
        if (strcmp(attr->Name(), "id") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "location_x") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "location_y") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "location") == 0) {
            object->m_location = std::string(attr->Value());
        }
        else if (strcmp(attr->Name(), "type") == 0) {
            if (strcmp(attr->Value(), "item") == 0) {
                object->m_object_type = Object::TypeItem;
            }
            else if (strcmp(attr->Value(), "collectable") == 0) {
                object->m_object_type = Object::TypeCollectable;
            }
            else if (strcmp(attr->Value(), "curse") == 0) {
                object->m_object_type = Object::TypeCurse;
            }
            else if (strcmp(attr->Value(), "event") == 0) {
                object->m_object_type = Object::TypeEvent;
            }
            else {
                result = false;
                break;
            }
        }
        else if (strcmp(attr->Name(), "name") == 0) {
            object->m_strings[std::string(attr->Name())] =
                std::string(attr->Value());
        }
        else if (strcmp(attr->Name(), "player") == 0) {
            object->m_strings[std::string(attr->Name())] =
                std::string(attr->Value());
        }
        else if (strcmp(attr->Name(), "destination") == 0) {
            object->m_strings[std::string(attr->Name())] =
                std::string(attr->Value());
        }
        else if (strcmp(attr->Name(), "start_x") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "start_y") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "event_type") == 0) {
            if (strcmp(attr->Value(), "area") == 0) {
                object->m_strings[std::string(attr->Name())] =
                    std::string(attr->Value());
            }
            else {
                result = false;
                break;
            }
        }
        else if (strcmp(attr->Name(), "event") == 0) {
            object->m_strings[std::string(attr->Name())] =
                std::string(attr->Value());
        }
        else if (strcmp(attr->Name(), "x") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "y") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "width") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "height") == 0) {
            object->m_integers[std::string(attr->Name())] = atoi(attr->Value());
        }
        else if (strcmp(attr->Name(), "area_type") == 0) {
            object->m_strings[std::string(attr->Name())] =
                std::string(attr->Value());
        }
        else {
            result = false;
            break;
        }

        attr = attr->Next();
    }

    return result;
}
Example #28
0
CConverToMK::CConverToMK(const char* pszXMLFile):
m_bIsInit(false),
m_pszMKFile(0),
m_pszHelpFile(0),
m_pszConfigFile(0),
m_uiKeyStringPosition(0)
{
	m_pszMKFile = new char[255];
	m_pszHelpFile = new char[255];
	m_pszConfigFile = new char[255];

	memset(m_pszHelpFile,0,sizeof(char) * 255);
	memset(m_pszMKFile,0,sizeof(char) * 255);
	memset(m_pszConfigFile,0,sizeof(char) * 255);

	TiXmlDocument kDocument(pszXMLFile);

	if (!kDocument.LoadFile())
	{
		return;
	}

	TiXmlElement* pkConfElement = kDocument.RootElement();

	if (0 == pkConfElement)
	{
		return;
	}

	TiXmlElement* pkSubElement = pkConfElement->FirstChildElement("module");

	do
	{
		TiXmlAttribute* pkNameAttribute = pkSubElement->FirstAttribute();
		string strName = pkNameAttribute->Name();
		string strData;

		if (strcmp("name",strName.c_str()) != 0)
		{
			continue;
		}

		strData = pkNameAttribute->Value();
		ModuleInfo kInfo = {0};
		strcpy_s(kInfo.szModuleName,255,strData.c_str());

		TiXmlElement* pkVCProjectPath = pkSubElement->FirstChildElement("VCProjectPath");

		if (0 == pkVCProjectPath)
		{
			continue;
		}

		string strVCPath = pkVCProjectPath->GetText();

		strcpy_s(kInfo.szVCProjFile,255,strVCPath.c_str());

		crc_32_type kCrc32;
		kCrc32.process_bytes(kInfo.szModuleName,strlen(kInfo.szModuleName));
		unsigned int uiID = kCrc32.checksum();

		m_kModuleInfoMap.insert(make_pair(uiID,kInfo));
	} while (pkSubElement = pkSubElement->NextSiblingElement("module"));

	TiXmlElement* pkPathElement = pkConfElement->FirstChildElement("path");

	if (0 == pkPathElement)
	{
		return;
	}

	TiXmlElement* pkMKFilePath = pkPathElement->FirstChildElement("MKFilePath");
	TiXmlElement* pkHelpFilePath = pkPathElement->FirstChildElement("HelpFilePath");

	string strHelpFile = pkHelpFilePath->GetText();
	string strMKFile = pkMKFilePath->GetText();

	TiXmlElement* pkFilterElement = pkConfElement->FirstChildElement("filter");

	if (pkFilterElement)
	{
		TiXmlElement* pkSrcFileElement = pkFilterElement->FirstChildElement("SrcFile");

		do 
		{
			string strTemp = pkSrcFileElement->GetText();
			m_kFilterWord.push_back(strTemp);
		} while (pkSrcFileElement = pkSrcFileElement->NextSiblingElement("SrcFile"));
	}

	if (strHelpFile.length() != 0)
	{
		strcpy_s(m_pszHelpFile,255,strHelpFile.c_str());

		if (!InitialiseHelp())
		{
			return;
		}
	}

	if (0 == strMKFile.c_str())
	{
		return;
	}

	strcpy_s(m_pszMKFile,255,strMKFile.c_str());

	if (!ParseVCProjectFile())
	{
		return;
	}

	if (!ParseMKFile())
	{
		return;
	}

	m_bIsInit = true;
}
Example #29
0
bool CPlayListASX::LoadData(istream& stream)
{
  CLog::Log(LOGNOTICE, "Parsing ASX");

  if(stream.peek() == '[')
  {
    return LoadAsxIniInfo(stream);
  }
  else
  {
    CXBMCTinyXML xmlDoc;
    stream >> xmlDoc;

    if (xmlDoc.Error())
    {
      CLog::Log(LOGERROR, "Unable to parse ASX info Error: %s", xmlDoc.ErrorDesc());
      return false;
    }

    TiXmlElement *pRootElement = xmlDoc.RootElement();

    // lowercase every element
    TiXmlNode *pNode = pRootElement;
    TiXmlNode *pChild = NULL;
    std::string value;
    value = pNode->Value();
    StringUtils::ToLower(value);
    pNode->SetValue(value);
    while(pNode)
    {
      pChild = pNode->IterateChildren(pChild);
      if(pChild)
      {
        if (pChild->Type() == TiXmlNode::TINYXML_ELEMENT)
        {
          value = pChild->Value();
          StringUtils::ToLower(value);
          pChild->SetValue(value);

          TiXmlAttribute* pAttr = pChild->ToElement()->FirstAttribute();
          while(pAttr)
          {
            value = pAttr->Name();
            StringUtils::ToLower(value);
            pAttr->SetName(value);
            pAttr = pAttr->Next();
          }
        }

        pNode = pChild;
        pChild = NULL;
        continue;
      }

      pChild = pNode;
      pNode = pNode->Parent();
    }
    std::string roottitle;
    TiXmlElement *pElement = pRootElement->FirstChildElement();
    while (pElement)
    {
      value = pElement->Value();
      if (value == "title" && !pElement->NoChildren())
      {
        roottitle = pElement->FirstChild()->ValueStr();
      }
      else if (value == "entry")
      {
        std::string title(roottitle);

        TiXmlElement *pRef = pElement->FirstChildElement("ref");
        TiXmlElement *pTitle = pElement->FirstChildElement("title");

        if(pTitle && !pTitle->NoChildren())
          title = pTitle->FirstChild()->ValueStr();

        while (pRef)
        { // multiple references may apear for one entry
          // duration may exist on this level too
          value = XMLUtils::GetAttribute(pRef, "href");
          if (!value.empty())
          {
            if(title.empty())
              title = value;

            CLog::Log(LOGINFO, "Adding element %s, %s", title.c_str(), value.c_str());
            CFileItemPtr newItem(new CFileItem(title));
            newItem->SetPath(value);
            Add(newItem);
          }
          pRef = pRef->NextSiblingElement("ref");
        }
      }
      else if (value == "entryref")
      {
        value = XMLUtils::GetAttribute(pElement, "href");
        if (!value.empty())
        { // found an entryref, let's try loading that url
          auto_ptr<CPlayList> playlist(CPlayListFactory::Create(value));
          if (NULL != playlist.get())
            if (playlist->Load(value))
              Add(*playlist);
        }
      }
      pElement = pElement->NextSiblingElement();
    }
  }

  return true;
}
Example #30
0
void ConvertElemToObj( IdCollection* ids, TiXmlElement* pElem, MathObj* obj ) {
	for( pElem; pElem; pElem = pElem->NextSiblingElement() ) //пробегаемся по всем элементам одного слоя
	{
		const std::string pKey = pElem->Value(); //получаем тэг текущей вершины
		const char *pText = pElem->GetText(); //получаем содержание тега, если оно есть, иначе NULL

		//Если корень
		if( pKey == "OMOBJ" ) 
		{
			ConvertElemToObj( ids, pElem->FirstChildElement(), obj );
		}

		//Если переменная
		else if( pKey == "OMV" ) 
		{
			TiXmlAttribute* pAttrib = pElem->FirstAttribute();
			ParamObj* node = new ParamObj( pAttrib->Value() );
            static_cast<FormulaObj*>( obj )->params.push_back( node );
		}

		//Если целое число
		else if( pKey == "OMI" ) 
		{
			ParamObj* node = new ParamObj( pElem->GetText() );
            static_cast<FormulaObj*>( obj )->params.push_back( node );
		}

        //Если десятичное число
        else if( pKey == "OMF" )
        {
            TiXmlAttribute* pAttrib = pElem->FirstAttribute();
            ParamObj* node = new ParamObj( pAttrib->Value( ) );
            static_cast<FormulaObj*>( obj )->params.push_back( node );

        }
		//Если конструкция, содержащая массив операций
		else if( pKey == "OMA" ) 
		{
			FormulaObj* node = new FormulaObj();
            static_cast<FormulaObj*>( obj )->params.push_back( node );
			ConvertElemToObj( ids, pElem->FirstChildElement(), node );
		}

		//Если операнд
		else if( pKey == "OMS" ) 
		{
			TiXmlAttribute* pAttrib = pElem->FirstAttribute();
			std::string name = pAttrib->Name(); // Тип атрибута

            //Находим атрибут, отвечающий за название словаря, содержащего наш атрибут
            while( name != "cd" )
            {
                pAttrib = pAttrib->Next( );
                name = pAttrib->Name( );
            }

            std::string cd = pAttrib->Value(); // получаем требуемый словарь

			//Находим атрибут, отвечающий за тип операнда
			while( name != "name" ) 
			{
				pAttrib = pAttrib->Next();
				name = pAttrib->Name();
			}

			std::string operand = pAttrib->Value(); // Получаем тип операнда
            SetFormulaObjType( ids, static_cast<FormulaObj*>( obj ), &cd, &operand );
		}
	}

}