Example #1
0
void GUI_Button::readAttributes(TiXmlElement* p_element)
{
	TiXmlElement* e = p_element->FirstChildElement("Title");
	if(e)
	{
		const char* p_title = e->GetText();
		setTitle(p_title ? p_title : "");
	}

	e = p_element->FirstChildElement("Image");
	if(e)
	{
		const char* p_imageFilename = e->GetText();
		if(p_imageFilename) setImageFilename(localizeString(p_imageFilename));

		e->QueryIntAttribute("u", &positionOnTexture.x);
		e->QueryIntAttribute("v", &positionOnTexture.y);

		e->QueryIntAttribute("u2", &clickedPositionOnTexture.x);
		e->QueryIntAttribute("v2", &clickedPositionOnTexture.y);
	}

	e = p_element->FirstChildElement("ExtendedStyle");
	if(e) style = 1;
}
Example #2
0
bool CSPropExcitation::ReadFromXML(TiXmlNode &root)
{
	if (CSProperties::ReadFromXML(root)==false) return false;

	TiXmlElement *prop = root.ToElement();
	if (prop==NULL) return false;

	int iHelp;
	if (prop->QueryIntAttribute("Number",&iHelp)!=TIXML_SUCCESS) uiNumber=0;
	else uiNumber=(unsigned int)iHelp;

	if (prop->QueryIntAttribute("Type",&iExcitType)!=TIXML_SUCCESS) return false;

	if (ReadVectorTerm(Excitation,*prop,"Excite",0.0)==false) return false;

	ReadTerm(m_Frequency,*prop,"Frequency");
	ReadTerm(Delay,*prop,"Delay");

	TiXmlElement *weight = prop->FirstChildElement("Weight");
	if (weight!=NULL)
	{
		ReadTerm(WeightFct[0],*weight,"X");
		ReadTerm(WeightFct[1],*weight,"Y");
		ReadTerm(WeightFct[2],*weight,"Z");
	}

	ReadVectorTerm(PropagationDir,*prop,"PropDir",0.0);

	return true;
}
Example #3
0
void ClassifierSVM::loadCache(TiXmlElement* settings, boost::filesystem::path file){
	clearData();

	svm = svm_load_model(file.c_str());

	TiXmlElement* pScales = settings->FirstChildElement("scales");
	if(!pScales){
		throw "Bad cache file - no scales";
	}
	pScales->QueryIntAttribute("desc_len", &descLen);
	scalesSub = new double[descLen];
	scalesDiv = new double[descLen];
	TiXmlElement* pValue = pScales->FirstChildElement("value");
	while(pValue){
		int d = -1;
		pValue->QueryIntAttribute("idx", &d);
		if(d == -1){
			throw "Bad cache file - no idx for value";
		}
		pValue->QueryDoubleAttribute("sub", &scalesSub[d]);
		pValue->QueryDoubleAttribute("div", &scalesDiv[d]);

		pValue = pValue->NextSiblingElement();
	}

	TiXmlElement* pLabels = settings->FirstChildElement("labels");
	if(!pLabels){
		throw "Bad cache file - no labels";
	}
	pLabels->QueryIntAttribute("num", &numLabels);
}
//网络返回数据 刷新内存
void CMGetNewContent::OnSessionCmd(unsigned int nCmdID, unsigned int nCode, TiXmlDocument *pDoc)
{
    if (nCode == MER_OK)
    {
        TiXmlElement* pItem = pDoc->RootElement();
        
        if (pItem)
        {
            INT32 nCmdID = 0;
            
            pItem->QueryIntAttribute("no", &nCmdID);
            
            INT32 nErr = 0;
            
            if (pItem->QueryIntAttribute("errno", &nErr) == TIXML_SUCCESS)
            {
                if (nErr == 0)
                {
                    if (nCmdID == SERVICE_GETNEWCONTENT || nCmdID == SERVICE_GETRECOMMEND)
                    {
						if(!pItem->NoChildren())
                        {
                            TiXmlElement* pHeadItemList = pItem->FirstChildElement("largeimage");
                            if(pHeadItemList)
                                DoHeadItemList(pHeadItemList);
                            DoItemList(pItem);
                        }

                        if (m_lstItem && m_lstItem->size() > 0)
                        {
                        	if(m_pListener)
                        		m_pListener->OnUpdateDataFinish(m_pUserData, TResult::ESuccess);
                            return ;
                        }
                        else
                        {
                        	if(m_pListener)
                        		m_pListener->OnUpdateDataFinish(m_pUserData, TResult::ENothing);
                            return ;
                        }
                    }
                }
            }
        }
    }
    if(m_pListener)
    	m_pListener->OnUpdateDataFinish(m_pUserData, TResult::EUnknownError);
}
	logic::CScenario* CScenariosXmlDao::read(int id){
		// Vamos a recuperar las rutas donde se encuentran las definiciones de los escenarios

		logic::CScenario* scenario = 0;

		TiXmlElement* pScenarioPathElement = _hRoot.FirstChild("scenario").Element();

		while(pScenarioPathElement){
			int idscenario = 0;
			pScenarioPathElement->QueryIntAttribute("id", &idscenario);
			string folder = pScenarioPathElement->Attribute("folder");
			string path = "./data/scenarios/";
			string scenariopath = path+folder+(string)"/gfx.xml";
			//cout<<"[CScenariosXmlDao::read] Escenario: "<<idscenario<<" en "<<scenariopath<<"\n";

			if(idscenario == id){
				_cameraDAO = CDaoServer::instance().getCameraDAO(scenariopath);
				std::vector<gui::CAbstractCamera*> cameras = _cameraDAO->read();
				scenario = readScenario(scenariopath);
				scenario->setCameras(cameras);
			}


			pScenarioPathElement = pScenarioPathElement->NextSiblingElement("scenario");
		}

		return scenario;

	}
Example #6
0
void File::parse(){

	// Make sure we can parse the file
	TiXmlDocument doc(simFile);
	if(!doc.LoadFile()){
		string exp_str = "Invalid simulation file: ";
		exp_str += simFile;

		throw(Exception(exp_str));
	}

	// Get root node and check
	TiXmlHandle hDoc = TiXmlHandle(&doc);
	TiXmlElement *pParent = hDoc.FirstChild("simulation").ToElement();
	if(!pParent) throw(Exception("Invalid root"));
	pParent->QueryIntAttribute("runs",&numRuns);
	pParent->QueryIntAttribute("seed",&seed);

	TiXmlNode* pChild;
	for(pChild = pParent->FirstChild(); pChild!=NULL; pChild = pChild->NextSibling()){

		// Ignore comments
		if(pChild->Type() == TiXmlNode::TINYXML_COMMENT){
			continue;
		}

		// Devicelist
		if(strcmp(pChild->Value(),"devicelist") == 0){
			parseDevices(pChild);
		}

		// Strategylist
		else if(strcmp(pChild->Value(),"strategylist") == 0){
			parseStrategies(pChild);
		}

		// Targetlist
		else if(strcmp(pChild->Value(),"targetlist") == 0){
			parseTargets(pChild);
		}

		// Outputlist
		else if(strcmp(pChild->Value(),"outputlist") == 0){
			parseOutputs(pChild);
		}
	}
}
Example #7
0
bool CSProperties::ReadFromXML(TiXmlNode &root)
{
	TiXmlElement* prop = root.ToElement();
	if (prop==NULL) return false;

	int help;
	if (prop->QueryIntAttribute("ID",&help)==TIXML_SUCCESS)
		uiID=help;

	const char* cHelp=prop->Attribute("Name");
	if (cHelp!=NULL) sName=std::string(cHelp);
	else sName.clear();

	TiXmlElement* FC = root.FirstChildElement("FillColor");
	if (FC!=NULL)
	{
		if (FC->QueryIntAttribute("R",&help)==TIXML_SUCCESS)
			FillColor.R=(unsigned char) help;
		if (FC->QueryIntAttribute("G",&help)==TIXML_SUCCESS)
			FillColor.G=(unsigned char) help;
		if (FC->QueryIntAttribute("B",&help)==TIXML_SUCCESS)
			FillColor.B=(unsigned char) help;
		if (FC->QueryIntAttribute("a",&help)==TIXML_SUCCESS)
			FillColor.a=(unsigned char) help;
	}

	TiXmlElement* EC = root.FirstChildElement("EdgeColor");
	if (EC!=NULL)
	{
		if (EC->QueryIntAttribute("R",&help)==TIXML_SUCCESS)
			EdgeColor.R=(unsigned char) help;
		if (EC->QueryIntAttribute("G",&help)==TIXML_SUCCESS)
			EdgeColor.G=(unsigned char) help;
		if (EC->QueryIntAttribute("B",&help)==TIXML_SUCCESS)
			EdgeColor.B=(unsigned char) help;
		if (EC->QueryIntAttribute("a",&help)==TIXML_SUCCESS)
			EdgeColor.a=(unsigned char) help;
	}

	TiXmlElement* att_root = root.FirstChildElement("Attributes");
	if (att_root)
	{
		TiXmlAttribute* att = att_root->FirstAttribute();
		while (att)
		{
			AddAttribute(att->Name(),att->Value());
			att = att->Next();
		}
	}

	return true;
}
Example #8
0
		SCSerror SCSanimation::OpenAnimation (const SCSstring& rsFilename)
		{
			TiXmlDocument kXmlFile(rsFilename);
			TiXmlHandle hkRoot(0);
			TiXmlElement* pkElement;
			TiXmlHandle hkXml(0);
			SCSint iPosX, iPosY;
			SCSint iSizeX, iSizeY;
			SCSint iRepeat;
			SCSfloat fDuration;

			Init();

			if (!kXmlFile.LoadFile()) return scsHandleError(SCS_ERROR_GRAPHICS | SCS_ERROR_OPEN | SCS_ERROR_ANIMATION);
			hkXml = TiXmlHandle(&kXmlFile);
			pkElement = hkXml.FirstChild("animation").Element();
			if (!pkElement) return scsHandleError(SCS_ERROR_GRAPHICS | SCS_ERROR_OPEN | SCS_ERROR_ANIMATION | SCS_ERROR_NULL);
			hkRoot = TiXmlHandle(pkElement);

			SCSstring sTexture = pkElement->Attribute("resource");
			pkElement->QueryIntAttribute("width", &iSizeX);
			pkElement->QueryIntAttribute("height", &iSizeY);
			pkElement->QueryIntAttribute("repeat", &iRepeat);

			m_pkTexture = SCStextures::Singleton()->GetTexture(sTexture);
			if (!m_pkTexture) return scsHandleError(SCS_ERROR_GRAPHICS | SCS_ERROR_GET | SCS_ERROR_TEXTURE | SCS_ERROR_NULL);
			m_kFrameSize = SCSvector2(iSizeX, iSizeY);
			m_iRepeat = iRepeat;

			pkElement = hkRoot.FirstChild("frame").Element();
			while (pkElement) {
				// load frame
				pkElement->QueryIntAttribute("x", &iPosX);
				pkElement->QueryIntAttribute("y", &iPosY);
				pkElement->QueryFloatAttribute("duration", &fDuration);
				AddFrame(SCSvector2(iPosX, iPosY), fDuration);
				// find next element
				pkElement = pkElement->NextSiblingElement("frame");
			}
			return SCS_ERROR_NONE;
		}
Example #9
0
TileMap tilemapFromXML(TiXmlDocument* doc) {
	TileMap tilemap;
	
	// Get top level attributes for source tilemap
	TiXmlElement* tilemapElement = doc->FirstChild()->ToElement();
//	int totalWidth, totalHeight, inputTileWidth, inputTileHeight;
	assert(TIXML_SUCCESS == tilemapElement->QueryIntAttribute("width", &tilemap.totalWidth));
	assert(TIXML_SUCCESS == tilemapElement->QueryIntAttribute("height", &tilemap.totalHeight));
	assert(TIXML_SUCCESS == tilemapElement->QueryIntAttribute("tileWidth", &tilemap.tileWidth));
	assert(TIXML_SUCCESS == tilemapElement->QueryIntAttribute("tileHeight", &tilemap.tileHeight));
	
	tilemap.highestIndex = 0;
	
	// CREATE ORIGINAL TILEMAP (and find number of atlases)
	for (TiXmlNode* child = doc->FirstChild()->FirstChild(); child != 0; child = child->NextSibling()) {
		TiXmlElement* element = child->ToElement();
		
		if(0 == strcmp(element->Value(), "row")) {
			string rowText = element->GetText();
			vector<int> inputRow = parseRow(rowText);
			tilemap.tilemap.push_back(inputRow);
		}
		else if(0 == strcmp(element->Value(), "atlas")) {
			int atlasWidth, atlasHeight;
			
			assert(TIXML_SUCCESS == element->QueryIntAttribute("width", &atlasWidth));
			assert(TIXML_SUCCESS == element->QueryIntAttribute("height", &atlasHeight));
			
			tilemap.highestIndex += (atlasWidth / tilemap.tileWidth) * (atlasHeight / tilemap.tileHeight);
		}
	}
	
	return tilemap;
}
Example #10
0
/**
 *	@method PigManager::loadLevel()
 *	@desc   parse the current level xml and instantiate the pigs in it
 */
void PigManager::loadLevel(TiXmlElement* levelPigElement)
{
	if (numPigs > 0)
	{
		shutdown();
	}

	numPigs = 0;
	TiXmlElement* levelPig = levelPigElement->FirstChildElement();
	while (levelPig != NULL)
	{
		numPigs++;
		levelPig = levelPig->NextSiblingElement();
	}

	pigList = new EnemyPig*[numPigs];
	int i = 0;
	int x, y;
	float wid, ht;

	levelPig = levelPigElement->FirstChildElement();
	ObjectData currentPigData;

	while (levelPig != NULL)
	{
		const char* currentBlockType = levelPig->Attribute("type");
		int j;
		for (j = 0; j < totalPossiblePigs; j++)
		{
			if (strcmp(currentBlockType, allPigsData[j].objectType) == 0)
			{
				currentPigData = allPigsData[j];
				break;
			}
		}
		assert(j < totalPossiblePigs);

		levelPig->QueryIntAttribute("x", &x);
		levelPig->QueryIntAttribute("y", &y);
		levelPig->QueryFloatAttribute("wid", &wid);
		levelPig->QueryFloatAttribute("ht", &ht);

		pigList[i] = new EnemyPig();
		pigList[i]->init(x, y, wid, currentPigData);

		levelPig = levelPig->NextSiblingElement();
		i++;
	}

	CGame::GetInstance()->setPigCount(numPigs);

}
void ProjectConfiguration::XmlLoad(TiXmlElement* Node,cbProject* Project)
{
    m_GlobalUsedLibs.Clear();
    m_TargetsUsedLibs.clear();
    m_DisableAuto = false;

    TiXmlElement* LibFinder = Node->FirstChildElement("lib_finder");
    if ( !LibFinder ) return;

    int noauto = 0;
    if ( (LibFinder->QueryIntAttribute("disable_auto",&noauto) == TIXML_SUCCESS) && noauto )
    {
        m_DisableAuto = true;
    }

    for ( TiXmlElement* Elem = LibFinder->FirstChildElement("lib");
            Elem;
            Elem = Elem->NextSiblingElement("lib") )
    {
        wxString LibName = cbC2U(Elem->Attribute("name"));
        if ( !LibName.IsEmpty() && m_GlobalUsedLibs.Index(LibName)==wxNOT_FOUND )
        {
            m_GlobalUsedLibs.Add(LibName);
        }
    }

    for ( TiXmlElement* Elem = LibFinder->FirstChildElement("target");
            Elem;
            Elem = Elem->NextSiblingElement("target") )
    {
        wxString TargetName = cbC2U(Elem->Attribute("name"));
        if ( !Project->GetBuildTarget(TargetName) ) continue;

        wxArrayString& Libs = m_TargetsUsedLibs[TargetName];
        for ( TiXmlElement* LibElem = Elem->FirstChildElement("lib");
                LibElem;
                LibElem = LibElem->NextSiblingElement("lib") )
        {
            wxString LibName = cbC2U(LibElem->Attribute("name"));
            if ( !LibName.IsEmpty() && Libs.Index(LibName)==wxNOT_FOUND )
            {
                Libs.Add(LibName);
            }
        }
    }

    // TODO: Invoke library settings check
}
void cConversationManager::Init(const string &lacConversationFile)
{
	TiXmlDocument doc(lacConversationFile);
	bool lbLoadOk = doc.LoadFile();
	if ( lbLoadOk )
	{
	
		TiXmlHandle lpRoot( &doc ); // Buscamos el Handle del Documento
		TiXmlElement *lpElem; 
	//	TiXmlAttribute* pAttrib; // Con estos punteros accedemos Elementos y Atributos
		lpRoot = lpRoot.FirstChildElement().Element(); //Nos posicionamos en la etiqueta "Conversations"

	// Read all the Characters (los Personajes,no los Chars)
		lpElem = lpRoot.FirstChild( "Characters" ).FirstChild().Element();
		for (lpElem; lpElem; lpElem = lpElem->NextSiblingElement())
		{			
			cCharacterSpeaker lCharacter;
			//Character ID
			lpElem->QueryIntAttribute("speakerId", &lCharacter.miCharacterId );
			assert(lCharacter.miCharacterId >= 0);

			// Character Name
			const char * lacName = lpElem->GetText();

			assert(lacName);
			lCharacter.macCharacterName = lacName;

			// Add the character to the Vector
			mSpeakers.push_back( lCharacter );
		}

	// Read all the conversations 
		lpElem = lpRoot.FirstChild( "Conversation" ).Element();
		for( lpElem; lpElem; lpElem = lpElem->NextSiblingElement("Conversation"))
		{			
			ParseConversation( lpElem );
		}

	}
}
Example #13
0
const std::string CScraperParser::Parse(const std::string& strTag,
                                       CScraper* scraper)
{
  TiXmlElement* pChildElement = m_pRootElement->FirstChildElement(strTag.c_str());
  if(pChildElement == NULL)
  {
    CLog::Log(LOGERROR,"%s: Could not find scraper function %s",__FUNCTION__,strTag.c_str());
    return "";
  }
  int iResult = 1; // default to param 1
  pChildElement->QueryIntAttribute("dest",&iResult);
  TiXmlElement* pChildStart = FirstChildScraperElement(pChildElement);
  m_scraper = scraper;
  ParseNext(pChildStart);
  std::string tmp = m_param[iResult-1];

  const char* szClearBuffers = pChildElement->Attribute("clearbuffers");
  if (!szClearBuffers || stricmp(szClearBuffers,"no") != 0)
    ClearBuffers();

  return tmp;
}
int WindowParams::LoadParamsFromXML(char fileName[])
{		
	TiXmlDocument doc(fileName);
	if (!doc.LoadFile()) return -1;

	TiXmlHandle hDoc(&doc);
	TiXmlElement* pElem;
	TiXmlHandle hRoot(0);
	
	pElem = hDoc.FirstChildElement().Element();
	if (!pElem) return -1;
	hRoot = TiXmlHandle(pElem);	
	
	pElem = hRoot.FirstChild("HOGParams").Element();
	if (pElem)
	{
		pElem->QueryIntAttribute("cell_width", &m_DetectionParams.m_HOG_Params.m_cell.width);
		pElem->QueryIntAttribute("cell_height", &m_DetectionParams.m_HOG_Params.m_cell.height);
		pElem->QueryIntAttribute("block_width", &m_DetectionParams.m_HOG_Params.m_block.width);
		pElem->QueryIntAttribute("block_height", &m_DetectionParams.m_HOG_Params.m_block.height);
		pElem->QueryIntAttribute("total_bin", &m_DetectionParams.m_HOG_Params.m_inBin);
		pElem->QueryFloatAttribute("overlap", &m_DetectionParams.m_HOG_Params.m_fStepOverlap);
	}
		
	pElem = hRoot.FirstChild("SVMParams").Element();
	if (pElem)
	{
		pElem->QueryFloatAttribute("confidence_score", &m_DetectionParams.m_SVM_Params.m_fConfidenceScore);
	}
	
	pElem = hRoot.FirstChild("GaussianParams").Element();
	if (pElem)
	{		
		pElem->QueryFloatAttribute("threshold", &m_DetectionParams.m_Gaussian_Params.m_fThreshold);
	}

	pElem = hRoot.FirstChild("HeadParams").Element();
	if (pElem)
	{		
		pElem->QueryIntAttribute("min_area", &m_DetectionParams.m_Head_Params.m_iMinHeadArea);
		pElem->QueryIntAttribute("max_area", &m_DetectionParams.m_Head_Params.m_iMaxHeadArea);
		pElem->QueryIntAttribute("relative_width_height", &m_DetectionParams.m_Head_Params.m_iRelative_Width_Height);
		pElem->QueryIntAttribute("relative_height_width", &m_DetectionParams.m_Head_Params.m_iRelative_Height_Width);
		pElem->QueryIntAttribute("max_width", &m_DetectionParams.m_Head_Params.m_iMaxWidth);
		pElem->QueryIntAttribute("min_width", &m_DetectionParams.m_Head_Params.m_iMinWidth);
		pElem->QueryIntAttribute("max_head_area_top", &m_DetectionParams.m_Head_Params.m_iMaxHeadAreaTop);
		pElem->QueryIntAttribute("min_head_area_bottom", &m_DetectionParams.m_Head_Params.m_iMinHeadAreaBottom);
	}

	const char* tmp;
	pElem = hRoot.FirstChild("ModelSVM").Element();
	if (pElem)
	{		
		tmp = pElem->GetText();
		m_modelSVMPath = new char[strlen(tmp)];
		strcpy(m_modelSVMPath,pElem->GetText());
	}
	
	pElem = hRoot.FirstChild("ModelGauss").Element();
	if (pElem)
	{	
		tmp = pElem->GetText();
		m_modelGaussPath = new char[strlen(tmp)];
		strcpy( m_modelGaussPath, pElem->GetText());
	}	
	return 0;
}
Example #15
0
/**
 *	@method PigManager::init()
 *	@desc   initializes the pig renderer and stores the properties of all possible types of pigs like the UV coordinates of the sprite states and physics properties
 */
void PigManager::init(TiXmlElement* pigsElement, TiXmlElement* poofElement)
{
	numPigs = 0;
	totalPossiblePigs = 0;
	int totalSpriteCount = 0;

	TiXmlElement* pigElement = pigsElement->FirstChildElement();
	while (pigElement != NULL)
	{
		totalPossiblePigs++;
		pigElement = pigElement->NextSiblingElement();
	}

	allPigsData = (ObjectData *)malloc(totalPossiblePigs * sizeof(ObjectData));
	pigElement = pigsElement->FirstChildElement();
	int i = 0, j = 0;
	while (pigElement != NULL)
	{
		allPigsData[i].objectType = pigElement->Attribute("type");

		TiXmlElement* physicsElement = pigElement->FirstChildElement();
		physicsElement->QueryFloatAttribute("density", &allPigsData[i].density);
		physicsElement->QueryFloatAttribute("restitution", &allPigsData[i].restitution);
		physicsElement->QueryFloatAttribute("friction", &allPigsData[i].friction);
		physicsElement->QueryIntAttribute("health", &allPigsData[i].health);

		TiXmlElement* spritesParentElement = physicsElement->NextSiblingElement();
		int spriteStateCount = 0;
		TiXmlElement* spriteElement = spritesParentElement->FirstChildElement();
		while (spriteElement != NULL)
		{
			spriteStateCount++;
			spriteElement = spriteElement->NextSiblingElement();
		}

		totalSpriteCount += spriteStateCount;

		allPigsData[i].spriteData = (SpriteStateData *)malloc(spriteStateCount * sizeof(SpriteStateData));
		allPigsData[i].numSprites = spriteStateCount;
		j = 0;
		spriteElement = spritesParentElement->FirstChildElement();
		while (spriteElement != NULL)
		{
			allPigsData[i].spriteData[j].spriteState = spriteElement->Attribute("state");
			spriteElement->QueryFloatAttribute("xPosLeft", &allPigsData[i].spriteData[j].uLeft);
			spriteElement->QueryFloatAttribute("xPosRight", &allPigsData[i].spriteData[j].uRight);
			spriteElement->QueryFloatAttribute("yPosTop", &allPigsData[i].spriteData[j].vTop);
			spriteElement->QueryFloatAttribute("yPosBottom", &allPigsData[i].spriteData[j].vBottom);

			spriteElement = spriteElement->NextSiblingElement();
			j++;
		}

		pigElement = pigElement->NextSiblingElement();
		i++;
	}

	/**************************/

	int totalPoofFrames = 0;
	TiXmlElement* poofSprite = poofElement->FirstChildElement()->FirstChildElement();
	while (poofSprite != NULL)
	{
		poofSprite = poofSprite->NextSiblingElement();
		totalPoofFrames++;
	}

	poofData.numSprites = totalPoofFrames;
	poofData.spriteData = (SpriteStateData *)malloc(poofData.numSprites * sizeof(SpriteStateData));

	j = 0;
	poofSprite = poofElement->FirstChildElement()->FirstChildElement();
	while (poofSprite != NULL)
	{
		poofData.spriteData[j].spriteState = poofSprite->Attribute("state");
		poofSprite->QueryFloatAttribute("xPosLeft", &poofData.spriteData[j].uLeft);
		poofSprite->QueryFloatAttribute("xPosRight", &poofData.spriteData[j].uRight);
		poofSprite->QueryFloatAttribute("yPosTop", &poofData.spriteData[j].vTop);
		poofSprite->QueryFloatAttribute("yPosBottom", &poofData.spriteData[j].vBottom);

		//pigRenderer->setUTextureLeft(k, poofData.spriteData[j].uLeft);
		//pigRenderer->setUTextureRight(k, poofData.spriteData[j].uRight);
		//pigRenderer->setVTextureTop(k, poofData.spriteData[j].vTop);
		//pigRenderer->setVTextureBottom(k, poofData.spriteData[j].vBottom);

		//poofData.spriteData[j].rendererIndex = k;

		//k++;

		poofSprite = poofSprite->NextSiblingElement();
		j++;
	}

	totalSpriteCount += totalPoofFrames;
	
	/*************************/

	float imageWidth, imageHeight;
	pigsElement->QueryFloatAttribute("imageWidth", &imageWidth);
	pigsElement->QueryFloatAttribute("imageHeight", &imageHeight);

	pigRenderer = new Renderer();
	pigRenderer->init(pigsElement->Attribute("src"), totalSpriteCount, imageWidth, imageHeight);

	int k = 0;

	for (i = 0; i < totalPossiblePigs; i++)
	{
		for (j = 0; j < allPigsData[i].numSprites; j++)
		{
			pigRenderer->setUTextureLeft(k, allPigsData[i].spriteData[j].uLeft);
			pigRenderer->setUTextureRight(k, allPigsData[i].spriteData[j].uRight);
			pigRenderer->setVTextureTop(k, allPigsData[i].spriteData[j].vTop);
			pigRenderer->setVTextureBottom(k, allPigsData[i].spriteData[j].vBottom);

			allPigsData[i].spriteData[j].rendererIndex = k;

			k++;
		}
	}

	/********Poofing*********/
	j = 0;
	poofSprite = poofElement->FirstChildElement()->FirstChildElement();
	while (poofSprite != NULL)
	{
		pigRenderer->setUTextureLeft(k, poofData.spriteData[j].uLeft);
		pigRenderer->setUTextureRight(k, poofData.spriteData[j].uRight);
		pigRenderer->setVTextureTop(k, poofData.spriteData[j].vTop);
		pigRenderer->setVTextureBottom(k, poofData.spriteData[j].vBottom);

		poofData.spriteData[j].rendererIndex = k;

		k++;

		poofSprite = poofSprite->NextSiblingElement();
		j++;
	}

}
Example #16
0
void StyleManager::Init( wxString fromPath )
{
    TiXmlDocument doc;

    if( !wxDir::Exists( fromPath ) ) {
        wxString msg = _T("No styles found at: ");
        msg << fromPath;
        wxLogMessage( msg );
        return;
    }

    wxDir dir( fromPath );
    if( !dir.IsOpened() ) return;

    wxString filename;

    // We allow any number of styles to load from files called style<something>.xml

    bool more = dir.GetFirst( &filename, _T("style*.xml"), wxDIR_FILES );

    if( !more ) {
        wxString msg = _T("No styles found at: ");
        msg << fromPath;
        wxLogMessage( msg );
        return;
    }

    bool firstFile = true;
    while( more ) {
        wxString name, extension;

        if( !firstFile ) more = dir.GetNext( &filename );
        if( !more ) break;
        firstFile = false;

        wxString fullFilePath = fromPath + filename;

        if( !doc.LoadFile( (const char*) fullFilePath.mb_str() ) ) {
            wxString msg( _T("Attempt to load styles from this file failed: ") );
            msg += fullFilePath;
            wxLogMessage( msg );
            continue;
        }

        wxString msg( _T("Styles loading from ") );
        msg += fullFilePath;
        wxLogMessage( msg );

        TiXmlHandle hRoot( doc.RootElement() );

        wxString root = wxString( doc.RootElement()->Value(), wxConvUTF8 );
        if( root != _T("styles" ) ) {
            wxLogMessage( _T("    StyleManager: Expected XML Root <styles> not found.") );
            continue;
        }

        TiXmlElement* styleElem = hRoot.FirstChild().Element();

        for( ; styleElem; styleElem = styleElem->NextSiblingElement() ) {

            if( wxString( styleElem->Value(), wxConvUTF8 ) == _T("style") ) {

                Style* style = new Style();
                styles.Add( style );

                style->name = wxString( styleElem->Attribute( "name" ), wxConvUTF8 );
                style->myConfigFileDir = fromPath;

                TiXmlElement* subNode = styleElem->FirstChild()->ToElement();

                for( ; subNode; subNode = subNode->NextSiblingElement() ) {
                    wxString nodeType( subNode->Value(), wxConvUTF8 );

                    if( nodeType == _T("description") ) {
                        style->description = wxString( subNode->GetText(), wxConvUTF8 );
                        continue;
                    }
                    if( nodeType == _T("chart-status-icon") ) {
                        int w = 0;
                        subNode->QueryIntAttribute( "width", &w );
                        style->chartStatusIconWidth = w;
                        continue;
                    }
                    if( nodeType == _T("chart-status-window") ) {
                        style->chartStatusWindowTransparent = wxString(
                                subNode->Attribute( "transparent" ), wxConvUTF8 ).Lower().IsSameAs(
                                        _T("true") );
                        continue;
                    }
                    if( nodeType == _T("embossed-indicators") ) {
                        style->embossFont = wxString( subNode->Attribute( "font" ), wxConvUTF8 );
                        subNode->QueryIntAttribute( "size", &(style->embossHeight) );
                        continue;
                    }
                    if( nodeType == _T("graphics-file") ) {
                        style->graphicsFile = wxString( subNode->Attribute( "name" ), wxConvUTF8 );
                        isOK = true; // If we got this far we are at least partially OK...
                        continue;
                    }
                    if( nodeType == _T("active-route") ) {
                        TiXmlHandle handle( subNode );
                        TiXmlElement* tag = handle.Child( "font-color", 0 ).ToElement();
                        if( tag ) {
                            int r, g, b;
                            tag->QueryIntAttribute( "r", &r );
                            tag->QueryIntAttribute( "g", &g );
                            tag->QueryIntAttribute( "b", &b );
                            style->consoleFontColor = wxColour( r, g, b );
                        }
                        tag = handle.Child( "text-background-location", 0 ).ToElement();
                        if( tag ) {
                            int x, y, w, h;
                            tag->QueryIntAttribute( "x", &x );
                            tag->QueryIntAttribute( "y", &y );
                            tag->QueryIntAttribute( "width", &w );
                            tag->QueryIntAttribute( "height", &h );
                            style->consoleTextBackgroundLoc = wxPoint( x, y );
                            style->consoleTextBackgroundSize = wxSize( w, h );
                        }
                        continue;
                    }
                    if( nodeType == _T("icons") ) {
                        TiXmlElement* iconNode = subNode->FirstChild()->ToElement();

                        for( ; iconNode; iconNode = iconNode->NextSiblingElement() ) {
                            wxString nodeType( iconNode->Value(), wxConvUTF8 );
                            if( nodeType == _T("icon") ) {
                                Icon* icon = new Icon();
                                style->icons.Add( icon );
                                icon->name = wxString( iconNode->Attribute( "name" ), wxConvUTF8 );
                                style->iconIndex[icon->name] = style->icons.Count() - 1;
                                TiXmlHandle handle( iconNode );
                                TiXmlElement* tag = handle.Child( "icon-location", 0 ).ToElement();
                                if( tag ) {
                                    int x, y;
                                    tag->QueryIntAttribute( "x", &x );
                                    tag->QueryIntAttribute( "y", &y );
                                    icon->iconLoc = wxPoint( x, y );
                                }
                                tag = handle.Child( "size", 0 ).ToElement();
                                if( tag ) {
                                    int x, y;
                                    tag->QueryIntAttribute( "x", &x );
                                    tag->QueryIntAttribute( "y", &y );
                                    icon->size = wxSize( x, y );
                                }
                            }
                        }
                    }
                    if( nodeType == _T("tools") ) {
                        TiXmlElement* toolNode = subNode->FirstChild()->ToElement();

                        for( ; toolNode; toolNode = toolNode->NextSiblingElement() ) {
                            wxString nodeType( toolNode->Value(), wxConvUTF8 );

                            if( nodeType == _T("horizontal") || nodeType == _T("vertical") ) {
                                int orientation = 0;
                                if( nodeType == _T("vertical") ) orientation = 1;

                                TiXmlElement* attrNode = toolNode->FirstChild()->ToElement();
                                for( ; attrNode; attrNode = attrNode->NextSiblingElement() ) {
                                    wxString nodeType( attrNode->Value(), wxConvUTF8 );
                                    if( nodeType == _T("separation") ) {
                                        attrNode->QueryIntAttribute( "distance",
                                                                     &style->toolSeparation[orientation] );
                                        continue;
                                    }
                                    if( nodeType == _T("margin") ) {
                                        attrNode->QueryIntAttribute( "top",
                                                                     &style->toolMarginTop[orientation] );
                                        attrNode->QueryIntAttribute( "right",
                                                                     &style->toolMarginRight[orientation] );
                                        attrNode->QueryIntAttribute( "bottom",
                                                                     &style->toolMarginBottom[orientation] );
                                        attrNode->QueryIntAttribute( "left",
                                                                     &style->toolMarginLeft[orientation] );
                                        wxString invis = wxString(
                                                             attrNode->Attribute( "invisible" ), wxConvUTF8 );
                                        style->marginsInvisible = ( invis.Lower() == _T("true") );
                                        continue;;
                                    }
                                    if( nodeType == _T("toggled-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toggledBGlocation[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toggledBGSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-start") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolbarStartLoc[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toolbarStartSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-end") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolbarEndLoc[orientation] = wxPoint( x, y );
                                        x = 0;
                                        y = 0;
                                        attrNode->QueryIntAttribute( "width", &x );
                                        attrNode->QueryIntAttribute( "height", &y );
                                        style->toolbarEndSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("toolbar-corners") ) {
                                        int r;
                                        attrNode->QueryIntAttribute( "radius", &r );
                                        style->cornerRadius[orientation] = r;
                                        continue;
                                    }
                                    if( nodeType == _T("background-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->normalBGlocation[orientation] = wxPoint( x, y );
                                        style->HasBackground( true );
                                        continue;
                                    }
                                    if( nodeType == _T("active-location") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->activeBGlocation[orientation] = wxPoint( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("size") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->toolSize[orientation] = wxSize( x, y );
                                        continue;
                                    }
                                    if( nodeType == _T("icon-offset") ) {
                                        int x, y;
                                        attrNode->QueryIntAttribute( "x", &x );
                                        attrNode->QueryIntAttribute( "y", &y );
                                        style->verticalIconOffset = wxSize( x, y );
                                        continue;
                                    }
                                }
                                continue;
                            }
                            if( nodeType == _T("compass") ) {

                                TiXmlElement* attrNode = toolNode->FirstChild()->ToElement();
                                for( ; attrNode; attrNode = attrNode->NextSiblingElement() ) {
                                    wxString nodeType( attrNode->Value(), wxConvUTF8 );
                                    if( nodeType == _T("margin") ) {
                                        attrNode->QueryIntAttribute( "top",
                                                                     &style->compassMarginTop );
                                        attrNode->QueryIntAttribute( "right",
                                                                     &style->compassMarginRight );
                                        attrNode->QueryIntAttribute( "bottom",
                                                                     &style->compassMarginBottom );
                                        attrNode->QueryIntAttribute( "left",
                                                                     &style->compassMarginLeft );
                                        continue;
                                    }
                                    if( nodeType == _T("compass-corners") ) {
                                        int r;
                                        attrNode->QueryIntAttribute( "radius", &r );
                                        style->compasscornerRadius = r;
                                        continue;
                                    }
                                    if( nodeType == _T("offset") ) {
                                        attrNode->QueryIntAttribute( "x",
                                                                     &style->compassXoffset );
                                        attrNode->QueryIntAttribute( "y",
                                                                     &style->compassYoffset );
                                        continue;
                                    }
                                }
                            }

                            if( nodeType == _T("tool") ) {
                                Tool* tool = new Tool();
                                style->tools.Add( tool );
                                tool->name = wxString( toolNode->Attribute( "name" ), wxConvUTF8 );
                                style->toolIndex[tool->name] = style->tools.Count() - 1;
                                TiXmlHandle toolHandle( toolNode );
                                TiXmlElement* toolTag =
                                    toolHandle.Child( "icon-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->iconLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "rollover-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->rolloverLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "disabled-location", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->disabledLoc = wxPoint( x, y );
                                }
                                toolTag = toolHandle.Child( "size", 0 ).ToElement();
                                if( toolTag ) {
                                    int x, y;
                                    toolTag->QueryIntAttribute( "x", &x );
                                    toolTag->QueryIntAttribute( "y", &y );
                                    tool->customSize = wxSize( x, y );
                                }
                                continue;
                            }
                        }
                        continue;
                    }
                }
            }
        }
    }
}
Example #17
0
void YafFile::processGraph(TiXmlElement* graphElement)
{
    string rootid=graphElement->Attribute("rootid");
    TiXmlElement* nodeElement = graphElement->FirstChildElement("node");
    sceneGraph = new Graph();
    sceneGraph->setRootId(rootid);
    while(nodeElement!=NULL)
    {
        Node* node = new Node(nodeElement->Attribute("id"));
        bool displaylist=false;
        nodeElement->QueryBoolAttribute("displaylist",&displaylist);
        if(displaylist!=NULL)
            node->setDisplayList(displaylist);

        string animID;
        TiXmlElement* animationsN = nodeElement->FirstChildElement("animationref");
        if(animationsN!=NULL)
            animID=animationsN->Attribute("id");


        TiXmlElement* transformations = nodeElement->FirstChildElement("transforms");
        TiXmlElement* transformation=transformations->FirstChildElement();

        while(transformation!=NULL)
        {
            if(transformation->Attribute("axis")!=NULL)
            {
                string axis=transformation->Attribute("axis");
                float angle;
                transformation->QueryFloatAttribute("angle",&angle);
                Transformation* rot = new Rotation(axis,angle);
                node->addTransformation(rot);
            }
            else if (transformation->Attribute("to")!=NULL)
            {
                float translation[3];
                read3Float("to",transformation,translation[0],translation[1],translation[2]);
                Transformation* translationElement = new Translation(translation[0],translation[1],translation[2]);
                node->addTransformation(translationElement);
            }

            else if (transformation->Attribute("factor")!=NULL)
            {
                float factor[3];
                read3Float("factor",transformation,factor[0],factor[1],factor[2]);
                Transformation* scaling = new Scaling(factor[0],factor[1],factor[2]);
                node->addTransformation(scaling);
            }

            transformation = transformation->NextSiblingElement();
        }

        TiXmlElement* appearanceRef = nodeElement->FirstChildElement("appearanceref");
        if(appearanceRef!=NULL)
        {

            node->setNodeAppearance(make_pair(appearanceRef->Attribute("id"),appearances[appearanceRef->Attribute("id")]));
        }
        else
        {
            node->setNodeAppearance(make_pair("",new Appearance()));
        }
        TiXmlElement* children = nodeElement->FirstChildElement("children");
        TiXmlElement* childrenAnalyzer = children->FirstChildElement();
        while(childrenAnalyzer!=NULL)
        {
            if(childrenAnalyzer->Attribute("xy1")!=NULL)
            {
                float xy1[2],xy2[2];
                read2Float("xy1",childrenAnalyzer,xy1[0],xy1[1]);
                read2Float("xy2",childrenAnalyzer,xy2[0],xy2[1]);
                SceneObject* rectangle = new SceneRectangle(xy1[0],xy1[1],xy2[0],xy2[1]);
                node->addObject(rectangle);
            }

            else if(childrenAnalyzer->Attribute("xyz1")!=NULL)
            {
                float xyz1[3],xyz2[3],xyz3[3];
                read3Float("xyz1",childrenAnalyzer,xyz1[0],xyz1[1],xyz1[2]);
                read3Float("xyz2",childrenAnalyzer,xyz2[0],xyz2[1],xyz2[2]);
                read3Float("xyz3",childrenAnalyzer,xyz3[0],xyz3[1],xyz3[2]);
                SceneObject* triangle = new SceneTriangle(xyz1,xyz2,xyz3);
                node->addObject(triangle);
            }

            else if(childrenAnalyzer->Attribute("base")!=NULL)
            {
                float base,top,height;
                int slices,stacks;
                childrenAnalyzer->QueryFloatAttribute("base",&base);
                childrenAnalyzer->QueryFloatAttribute("top",&top);
                childrenAnalyzer->QueryFloatAttribute("height",&height);
                childrenAnalyzer->QueryIntAttribute("slices",&slices);
                childrenAnalyzer->QueryIntAttribute("stacks",&stacks);
                SceneObject* cylinder = new SceneCylinder(base,top,height,slices,stacks);
                node->addObject(cylinder);
            }
            else if(childrenAnalyzer->Attribute("radius")!=NULL)
            {
                float radius;
                int slices,stacks;
                childrenAnalyzer->QueryFloatAttribute("radius",&radius);
                childrenAnalyzer->QueryIntAttribute("slices",&slices);
                childrenAnalyzer->QueryIntAttribute("stacks",&stacks);
                SceneObject* sphere = new SceneSphere(radius,slices,stacks);
                node->addObject(sphere);
            }
            else if(childrenAnalyzer->Attribute("inner")!=NULL)
            {
                float inner,outer;
                int slices,loops;
                childrenAnalyzer->QueryFloatAttribute("inner",&inner);
                childrenAnalyzer->QueryFloatAttribute("outer",&outer);
                childrenAnalyzer->QueryIntAttribute("slices",&slices);
                childrenAnalyzer->QueryIntAttribute("loops",&loops);
                SceneObject* thorus = new SceneTorus(inner,outer,slices,loops);
                node->addObject(thorus);
            }
            else if(childrenAnalyzer->Attribute("parts")!=NULL)
            {
                int parts;
                childrenAnalyzer->QueryIntAttribute("parts",&parts);
                SceneObject* plane = new ScenePlane(parts);
                node->addObject(plane);
            }
            else if(strcmp(childrenAnalyzer->Value(),"patch")==0)
            {
                int order,partsU,partsV;
                float x,y,z;
                string compute;

                childrenAnalyzer->QueryIntAttribute("order",&order);
                childrenAnalyzer->QueryIntAttribute("partsU",&partsU);
                childrenAnalyzer->QueryIntAttribute("partsV",&partsV);
                compute=childrenAnalyzer->Attribute("compute");

                ScenePatch* patch = new ScenePatch(order,partsU,partsV,compute);

                TiXmlElement* points = childrenAnalyzer->FirstChildElement("controlpoint");

                while(points!=NULL)
                {
                    points->QueryFloatAttribute("x",&x);
                    points->QueryFloatAttribute("y",&y);
                    points->QueryFloatAttribute("z",&z);

                    cout<<x<<","<<y<<","<<z<<endl;
                    patch->addCntrPoint(x,y,z);

                    points = points->NextSiblingElement("controlpoint");
                }
                node->addObject(patch);

            }

            else if(strcmp(childrenAnalyzer->Value(),"vehicle")==0)
            {
                SceneObject* vehicle = new SceneVehicle();
                node->addObject(vehicle);
            }

            else if(childrenAnalyzer->Attribute("heightmap")!=NULL)
            {
                string heightMap,textureMap,fragmentShader,vertexShader;
                heightMap=childrenAnalyzer->Attribute("heightmap");
                textureMap=childrenAnalyzer->Attribute("texturemap");
                fragmentShader=childrenAnalyzer->Attribute("fragmentshader");
                vertexShader=childrenAnalyzer->Attribute("vertexshader");

                SceneObject* shader = new SceneShader(heightMap,textureMap,fragmentShader,vertexShader);
                node->addObject(shader);
            }


            else if (childrenAnalyzer->Attribute("id")!=NULL)
            {
                node->addchildId(childrenAnalyzer->Attribute("id"));
            }
            childrenAnalyzer=childrenAnalyzer->NextSiblingElement();
        }
        //set animation
        Animation* anime=animations[animID];

        if(anime!=NULL)
        {
            node->setAnimation(anime);
        }
        sceneGraph->addNode(node);
        nodeElement=nodeElement->NextSiblingElement("node");
    }
    sceneGraph->createSonNodes();
}
void CScriptManager::LoadScript( std::string szFilename, SCRIPT_TYPE eScript )
{
	if (eScript == ST_LEVEL)
	{
		// Load!
		TiXmlDocument doc;
		if (doc.LoadFile(szFilename.c_str()) == true)
		{
			TiXmlElement* pRoot = doc.RootElement();

			if (pRoot == nullptr)
				return;


			int nAIPlayer;
			pRoot->QueryIntAttribute("AIEnemy", &nAIPlayer);

			if (nAIPlayer==1)
			{
				CGameManager::GetInstance()->SetPlayerAsAI(1);
			}

			if (nAIPlayer==2)
			{
				CGameManager::GetInstance()->SetPlayerAsAI(1);
				CGameManager::GetInstance()->SetPlayerAsAI(0);
			}
			TiXmlElement* pSpawns = pRoot->FirstChildElement("UnitSpawns");
			int nNumSpawns;
			pSpawns->QueryIntAttribute("numSpawns", &nNumSpawns);
			TiXmlElement* pSpawn = pSpawns->FirstChildElement("UnitSpawn");

			for (int i = 0; i < nNumSpawns; ++i)
			{
				ScriptedSpawn s;
				ScriptSpawnData scriptData;

				int nType;
				pSpawn->QueryIntAttribute("unitType", &nType);
				scriptData.eType = (UNIT_TYPE)nType;
				int nFacing;
				pSpawn->QueryIntAttribute("facing", &nFacing);
				scriptData.nFacing = nFacing;
				int posX;
				int posY;
				pSpawn->QueryIntAttribute("posX", &posX);
				pSpawn->QueryIntAttribute("posY", &posY);
				scriptData.sPos.nPosX = posX;
				scriptData.sPos.nPosY = posY;
				int nPlayerID;
				pSpawn->QueryIntAttribute("playerID", &nPlayerID);
				scriptData.nPlayerID = nPlayerID;
				pSpawn->QueryIntAttribute("TurnToSpawn", &s.first);
				s.second = scriptData;
				CGameManager::GetInstance()->AddScriptSpawn(s);

				pSpawn = pSpawn->NextSiblingElement();
			}
		}
	}
}
// IMPORTANT! We have to be careful of what to unicode and what not to.
// TinyXML must use NON-unicode strings!
// ----------------------------------------------------------------------------
bool BrowseTrackerLayout::Open(const wxString& filename, FileBrowse_MarksHash& m_FileBrowse_MarksArchive )
// ----------------------------------------------------------------------------
{
    TiXmlDocument doc;
    if (!TinyXML::LoadDocument(filename, &doc))
        return false;

    ProjectManager* pMan = Manager::Get()->GetProjectManager();
    LogManager* pMsg = Manager::Get()->GetLogManager();
    if (!pMan || !pMsg)
        return false;

    TiXmlElement* root;
    TiXmlElement* elem;
    wxString fname;
    ProjectFile* pf;


    root = doc.FirstChildElement("BrowseTracker_layout_file");
    if (!root)
    {
        // old tag
        root = doc.FirstChildElement("BrowseTracker_layout_file");
        if (!root)
        {
            pMsg->DebugLog(_T("Not a valid BrowseTracker layout file..."));
            return false;
        }
    }

    elem = root->FirstChildElement("ActiveTarget");
    if (elem)
    {
        if (elem->Attribute("name"))
        {
            ;//m_pProject->SetActiveBuildTarget(cbC2U(elem->Attribute("name")));
        }
    }

    elem = root->FirstChildElement("File");
    if (!elem)
    {
        //pMsg->DebugLog(_T("No 'File' element in file..."));
        return false;
    }

    while (elem)
    {
        //pMsg->DebugLog(elem->Value());
        fname = cbC2U(elem->Attribute("name"));
        if (fname.IsEmpty())
        {
            //pMsg->DebugLog(_T("'File' node exists, but no filename?!?"));
            pf = 0L;
        }
        else
            pf = m_pProject->GetFileByFilename(fname);

        if (pf)
        {
            //pf->editorOpen = false;
            //pf->editorPos = 0;
            //pf->editorTopLine = 0;
            int open = 0;
            int top = 0;
            int tabpos = 0;
            if (elem->QueryIntAttribute("open", &open) == TIXML_SUCCESS)
            {
                ;//pf->editorOpen = open != 0;
            }
            if (elem->QueryIntAttribute("top", &top) == TIXML_SUCCESS)
            {
                if(top)
                    m_TopProjectFile = pf;
            }
            if (elem->QueryIntAttribute("tabpos", &tabpos) == TIXML_SUCCESS)
            {
                ;//pf->editorTabPos = tabpos;
            }

            TiXmlElement* cursor = elem->FirstChildElement();
            if (cursor)
            {
                int pos = 0;
                int topline = 0;
                if (cursor->QueryIntAttribute("position", &pos) == TIXML_SUCCESS)
                {
                    ;//pf->editorPos = pos;
                }
                if (cursor->QueryIntAttribute("topLine", &topline) == TIXML_SUCCESS)
                {
                    ;//pf->editorTopLine = topline;
                }
            }

            #if defined(LOGGING)
            ///LOGIT( _T("Open Layout processing for[%s]"),fname.c_str() );
            #endif

            TiXmlElement* browsemarks = cursor->NextSiblingElement("BrowseMarks");
            //if (not browsemarks)
            //    LOGIT( _T("OPEN LAYOUT failed for BrowseMarks") );
            if (browsemarks)
            {
                wxString marksString = cbC2U(browsemarks->Attribute("positions"));
                #if defined(LOGGING)
                //LOGIT( _T("OPEN_LAYOUT BROWSEMarksStrng[%s][%s]"), fname.c_str(), marksString.c_str() );
                #endif
                ParseBrowse_MarksString( fname, marksString, m_FileBrowse_MarksArchive );
            }
        }

        elem = elem->NextSiblingElement();
    }

    return true;
}//Open
// A font is specified by two files: a TGA file with the rendered 
// chars for the font, and a XML file which contains global info 
// about the font and the texture coordinates and width of each char
// The parameter fontName is the filename without extension. 
// It is assumed that the files are "fontName.xml" and "fontName.tga"
bool
VSFontLib::load(std::string fontName) 
{
	// Test if image file exists
	FILE *fp;
	std::string s;
	errno_t err = -1;

	s = fontName + ".tga";
	err = fopen_s(&fp, s.c_str(), "r");
	if (fp == NULL || err == -1)
	{
		printf("Unable to find font texture: %s", s.c_str());
		return false;
	}
	
	mFontTex = loadRGBATexture(s, true, false, GL_LINEAR, GL_REPEAT);

	s = fontName + ".xml";
	TiXmlDocument doc(s.c_str());
	bool loadOK = doc.LoadFile();

	if (!loadOK) {
		printf("Problem reading the XML font definition file: %s", s.c_str());
		return false;
	}
	TiXmlHandle hDoc(&doc);
	TiXmlHandle hRoot(0);
	TiXmlElement *pElem;

	pElem = hDoc.FirstChildElement().Element();
	if (0 == pElem)
		return false;

	hRoot = TiXmlHandle(pElem);
	
	pElem->QueryIntAttribute("numchars",&mNumChars);

	if (mNumChars == 0)
		return false;

	hRoot = hRoot.FirstChild("characters");
	pElem = hRoot.FirstChild("chardata").Element();
	if (pElem)
		pElem->QueryIntAttribute("hgt",&mHeight);
	VSFLChar aChar;
	int charCode, numChars = 0;
	for(; 0 != pElem; pElem = pElem->NextSiblingElement(), ++numChars) {

		pElem->QueryIntAttribute("char",&charCode);
		pElem->QueryIntAttribute("wid",&(aChar.width));
		pElem->QueryFloatAttribute("X1", &(aChar.x1));
		pElem->QueryFloatAttribute("X2", &(aChar.x2));
		pElem->QueryFloatAttribute("Y1", &(aChar.y1));
		pElem->QueryFloatAttribute("Y2", &(aChar.y2));
		pElem->QueryIntAttribute("A", &(aChar.A));
		pElem->QueryIntAttribute("C", &(aChar.C));
		mChars[(unsigned char)charCode] = aChar;
	}
	printf("Font has %d chars", numChars);
	return true;
}
Example #21
0
int CDBServiceConfig::LoadXmlByFileName(const string& sFileName)
{
	SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());

	TiXmlDocument m_xmlDoc;
    TiXmlElement *pService;
	
	if(!m_xmlDoc.LoadFile(sFileName.c_str()))
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Load File Error,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());
		return -1;
	}
		
	if((pService=m_xmlDoc.RootElement())==NULL)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No RootElement,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());
		return -1;
	}

	SServiceDesc serviceDesc;
	
	char szName[64] = {0};
	int nRet = pService->QueryValueAttribute("name", &szName);
	if(nRet != TIXML_SUCCESS)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Service Name,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());
		return -1;
	}
	serviceDesc.sServiceName = szName;
	boost::to_lower(serviceDesc.sServiceName);
	
	serviceDesc.bReadOnly = false;
	
	char szReadOnly[64]={0};
	nRet = pService->QueryValueAttribute("queryonly", &szReadOnly);
	if(nRet == TIXML_SUCCESS)
	{
		if (strncmp(szReadOnly,"true",4)==0)
		{
			serviceDesc.bReadOnly = true;
		}		
	}
	
	int nServiceId = 0;
	nRet = pService->QueryIntAttribute("id", (int *)&nServiceId);
	if(nRet != TIXML_SUCCESS)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get ServiceId Error\n",__FUNCTION__);
    	return -1;
	}
	serviceDesc.nServiceId = nServiceId;

	/* get types */
	TiXmlElement * pConfigType = NULL;
	if((pConfigType=pService->FirstChildElement("type"))==NULL)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Type,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());
		return -1; 
	}
	else
	{	
		SServiceType serviceType;
		if(LoadServiceTypes(pConfigType,serviceType)<0)
		{
			return -1;
		}

		serviceDesc.mapServiceType.insert(make_pair(serviceType.sTypeName,serviceType));
	}
	while((pConfigType=pConfigType->NextSiblingElement("type"))!=NULL)
	{
		SServiceType serviceType;
		if(LoadServiceTypes(pConfigType,serviceType)<0)
		{
			return -1;
		}
		serviceDesc.mapServiceType.insert(make_pair(serviceType.sTypeName,serviceType));
	}

	PostProcessServiceTypes(serviceDesc.mapServiceType);

	//get message attribute
	TiXmlElement * pMsgAttri = NULL;
	if((pMsgAttri=pService->FirstChildElement("message"))==NULL)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Message,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());
		return -1;
	}
	else
	{
		SMsgAttri sMsgAttri;
		if(LoadServiceMessage(pMsgAttri,sMsgAttri)<0)
		{
			return -1;
		}
		SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,OperType=[%d]\n",__FUNCTION__,sMsgAttri.eOperType);
		serviceDesc.mapMsgAttri.insert(make_pair(sMsgAttri.nMsgId,sMsgAttri));
	}

	while((pMsgAttri=pMsgAttri->NextSiblingElement("message"))!=NULL)
	{
		SMsgAttri sMsgAttri;
		if(LoadServiceMessage(pMsgAttri,sMsgAttri)<0)
		{
			return -1;
		}
		SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,OperType=[%d]\n",__FUNCTION__,sMsgAttri.eOperType);
		serviceDesc.mapMsgAttri.insert(make_pair(sMsgAttri.nMsgId,sMsgAttri));
	}

	PostProcessMsgAttri(serviceDesc.mapMsgAttri,serviceDesc.mapServiceType);

	mapServiceConfig.insert(make_pair(serviceDesc.nServiceId,serviceDesc));

	return 0;
	
}
Example #22
0
/**
 * @brief Read in the XML Data File.
 * @return
 */
bool SurfaceManager::readFontSets()
{
    FontSet font_set;
    std::string path = getProgramPath();
    path.append("fontsets.xml");

    TiXmlDocument doc(path.c_str());
    if(!doc.LoadFile())
    {
        std::cout << "readFontSets() Error Reading: " << path << std::endl;
        return false;
    }
    TiXmlHandle hDoc(&doc);
    TiXmlElement* pElem;
    TiXmlHandle hRoot(0);

    // If vector already populated then clear to refresh it.
    if(m_fontSet.size() > 0)
    {
        m_fontSet.clear();
        std::vector<FontSet>().swap(m_fontSet);
    }
    // block: EtherTerm
    {
        std::cout << "readFontConfiguration - FirstChildElement" << std::endl;
        pElem=hDoc.FirstChildElement().Element();
        // should always have a valid root but handle gracefully if it does
        if(!pElem)
        {
            std::cout << "readFontConfiguration - EtherTerm Element not found!" << std::endl;
            return false;
        }
        std::cout << "Root Value: " << pElem->Value() << std::endl;
        // save this for later
        hRoot=TiXmlHandle(pElem);
    }
    // block: Fontset
    {
        //std::cout << "readDialDirectory - Phonebook" << std::endl;
        pElem=hRoot.FirstChild("Fontset").Element();
        std::cout << "Fontset Version: " << pElem->Attribute("version") << std::endl;
    }
    // block: Font
    {
        //std::cout << "readDialDirectory - BBS" << std::endl;
        pElem=hRoot.FirstChild("Fontset").FirstChild().Element();
        for(; pElem; pElem=pElem->NextSiblingElement())
        {
            font_set.name = pElem->Attribute("name");
            font_set.type = pElem->Attribute("type");
            pElem->QueryIntAttribute("width", &font_set.width);
            pElem->QueryIntAttribute("height", &font_set.height);
            font_set.filename = pElem->Attribute("filename");
            font_set.sequence = pElem->Attribute("sequence");

            // Add to Vector so we can parse
            m_fontSet.push_back(font_set);
        }
    }
    std::cout << "readFontConfiguration - Done" << std::endl;
    return true;
}
bool WorkspaceLoader::Open(const wxString& filename, wxString& Title)
{
    TiXmlDocument doc;
    if (!TinyXML::LoadDocument(filename, &doc))
        return false;

//    ProjectManager* pMan = Manager::Get()->GetProjectManager();
//    LogManager* pMsg = Manager::Get()->GetLogManager();

    if (!GetpMan() || !GetpMsg())
        return false;

    // BUG: Race condition. to be fixed by Rick.
    // If I click close AFTER pMan and pMsg are calculated,
    // I get a segfault.
    // I modified classes projectmanager and logmanager,
    // so that when self==NULL, they do nothing
    // (constructors, destructors and static functions excempted from this)
    // This way, we'll use the *manager::Get() functions to check for nulls.

    TiXmlElement* root = doc.FirstChildElement("CodeBlocks_workspace_file");
    if (!root)
    {
        // old tag
        root = doc.FirstChildElement("Code::Blocks_workspace_file");
        if (!root)
        {
            GetpMsg()->DebugLog(_T("Not a valid Code::Blocks workspace file..."));
            return false;
        }
    }
    TiXmlElement* wksp = root->FirstChildElement("Workspace");
    if (!wksp)
    {
        GetpMsg()->DebugLog(_T("No 'Workspace' element in file..."));
        return false;
    }

    Title = cbC2U(wksp->Attribute("title")); // Conversion to unicode is automatic (see wxString::operator= )

    TiXmlElement* proj = wksp->FirstChildElement("Project");
    if (!proj)
    {
        GetpMsg()->DebugLog(_T("Workspace file contains no projects..."));
        return false;
    }

    // first loop to load projects
    while (proj)
    {
        if(Manager::isappShuttingDown() || !GetpMan() || !GetpMsg())
            return false;
        wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename")));
        if (projectFilename.IsEmpty())
        {
            GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?"));
        }
        else
        {
            wxFileName fname(projectFilename);
            wxFileName wfname(filename);
            fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
            int active = 0;
            int ret = proj->QueryIntAttribute("active", &active);
            switch (ret)
            {
                case TIXML_SUCCESS:
                    if (active == 1)
					{
						cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), true); // activate it
						if(!pProject)
						{
							cbMessageBox(_("Unable to open ") + projectFilename,
							 _("Opening WorkSpace") + filename, wxICON_WARNING);
						}
					}
                    break;
                case TIXML_WRONG_TYPE:
                    GetpMsg()->DebugLog(F(_T("Error %s: %s"), doc.Value(), doc.ErrorDesc()));
                    GetpMsg()->DebugLog(_T("Wrong attribute type (expected 'int')"));
                    break;
                default:
					cbProject* pProject = GetpMan()->LoadProject(fname.GetFullPath(), false); // don't activate it
					if(!pProject)
					{
						cbMessageBox(_("Unable to open ") + projectFilename,
						 _("Opening WorkSpace") + filename, wxICON_WARNING);
					}
                    break;
            }
        }
        proj = proj->NextSiblingElement("Project");
    }

    // second loop to setup dependencies
    proj = wksp->FirstChildElement("Project");
    while (proj)
    {
        cbProject* thisprj = 0;
        wxString projectFilename = UnixFilename(cbC2U(proj->Attribute("filename")));
        if (projectFilename.IsEmpty())
        {
            GetpMsg()->DebugLog(_T("'Project' node exists, but no filename?!?"));
            thisprj = 0;
        }
        else
        {
            wxFileName fname(projectFilename);
            wxFileName wfname(filename);
            fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
            thisprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath());
        }

        if (thisprj)
        {
            TiXmlElement* dep = proj->FirstChildElement("Depends");
            while (dep)
            {
                wxFileName fname(UnixFilename(cbC2U(dep->Attribute("filename"))));
                wxFileName wfname(filename);
                fname.MakeAbsolute(wfname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR));
                cbProject* depprj = Manager::Get()->GetProjectManager()->IsOpen(fname.GetFullPath());
                if (depprj)
                    Manager::Get()->GetProjectManager()->AddProjectDependency(thisprj, depprj);
                dep = dep->NextSiblingElement("Depends");
            }
        }
        proj = proj->NextSiblingElement("Project");
    }

    return true;
}
Example #24
0
int main()
{

    //
    // We start with the 'demoStart' todo list. Process it. And
    // should hopefully end up with the todo list as illustrated.
    //
    const char* demoStart =
        "<?xml version=\"1.0\"  standalone='no' >\n"
        "<!-- Our to do list data -->"
        "<ToDo>\n"
        "<!-- Do I need a secure PDA? -->\n"
        "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
        "<Item priority=\"2\" distance='none'> Do bills   </Item>"
        "<Item priority=\"2\" distance='far &amp; back'> Look for Evil Dinosaurs! </Item>"
        "</ToDo>";

    {

#ifdef TIXML_USE_STL
        //	What the todo list should look like after processing.
        // In stream (no formatting) representation.
        const char* demoEnd =
            "<?xml version=\"1.0\" standalone=\"no\" ?>"
            "<!-- Our to do list data -->"
            "<ToDo>"
            "<!-- Do I need a secure PDA? -->"
            "<Item priority=\"2\" distance=\"close\">Go to the"
            "<bold>Toy store!"
            "</bold>"
            "</Item>"
            "<Item priority=\"1\" distance=\"far\">Talk to:"
            "<Meeting where=\"School\">"
            "<Attendee name=\"Marple\" position=\"teacher\" />"
            "<Attendee name=\"Voel\" position=\"counselor\" />"
            "</Meeting>"
            "<Meeting where=\"Lunch\" />"
            "</Item>"
            "<Item priority=\"2\" distance=\"here\">Do bills"
            "</Item>"
            "</ToDo>";
#endif

        // The example parses from the character string (above):
#if defined( WIN32 ) && defined( TUNE )
        _CrtMemCheckpoint( &startMemState );
#endif

        {
            // Write to a file and read it back, to check file I/O.

            TiXmlDocument doc( "demotest.xml" );
            doc.Parse( demoStart );

            if ( doc.Error() )
            {
                printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
                exit( 1 );
            }
            doc.SaveFile();
        }

        TiXmlDocument doc( "demotest.xml" );
        bool loadOkay = doc.LoadFile();

        if ( !loadOkay )
        {
            printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
            exit( 1 );
        }

        printf( "** Demo doc read from disk: ** \n\n" );
        printf( "** Printing via doc.Print **\n" );
        doc.Print( stdout );

        {
            printf( "** Printing via TiXmlPrinter **\n" );
            TiXmlPrinter printer;
            doc.Accept( &printer );
            fprintf( stdout, "%s", printer.CStr() );
        }
#ifdef TIXML_USE_STL
        {
            printf( "** Printing via operator<< **\n" );
            std::cout << doc;
        }
#endif
        TiXmlNode* node = 0;
        TiXmlElement* todoElement = 0;
        TiXmlElement* itemElement = 0;


        // --------------------------------------------------------
        // An example of changing existing attributes, and removing
        // an element from the document.
        // --------------------------------------------------------

        // Get the "ToDo" element.
        // It is a child of the document, and can be selected by name.
        node = doc.FirstChild( "ToDo" );
        assert( node );
        todoElement = node->ToElement();
        assert( todoElement  );

        // Going to the toy store is now our second priority...
        // So set the "priority" attribute of the first item in the list.
        node = todoElement->FirstChildElement();	// This skips the "PDA" comment.
        assert( node );
        itemElement = node->ToElement();
        assert( itemElement  );
        itemElement->SetAttribute( "priority", 2 );

        // Change the distance to "doing bills" from
        // "none" to "here". It's the next sibling element.
        itemElement = itemElement->NextSiblingElement();
        assert( itemElement );
        itemElement->SetAttribute( "distance", "here" );

        // Remove the "Look for Evil Dinosaurs!" item.
        // It is 1 more sibling away. We ask the parent to remove
        // a particular child.
        itemElement = itemElement->NextSiblingElement();
        todoElement->RemoveChild( itemElement );

        itemElement = 0;

        // --------------------------------------------------------
        // What follows is an example of created elements and text
        // nodes and adding them to the document.
        // --------------------------------------------------------

        // Add some meetings.
        TiXmlElement item( "Item" );
        item.SetAttribute( "priority", "1" );
        item.SetAttribute( "distance", "far" );

        TiXmlText text( "Talk to:" );

        TiXmlElement meeting1( "Meeting" );
        meeting1.SetAttribute( "where", "School" );

        TiXmlElement meeting2( "Meeting" );
        meeting2.SetAttribute( "where", "Lunch" );

        TiXmlElement attendee1( "Attendee" );
        attendee1.SetAttribute( "name", "Marple" );
        attendee1.SetAttribute( "position", "teacher" );

        TiXmlElement attendee2( "Attendee" );
        attendee2.SetAttribute( "name", "Voel" );
        attendee2.SetAttribute( "position", "counselor" );

        // Assemble the nodes we've created:
        meeting1.InsertEndChild( attendee1 );
        meeting1.InsertEndChild( attendee2 );

        item.InsertEndChild( text );
        item.InsertEndChild( meeting1 );
        item.InsertEndChild( meeting2 );

        // And add the node to the existing list after the first child.
        node = todoElement->FirstChild( "Item" );
        assert( node );
        itemElement = node->ToElement();
        assert( itemElement );

        todoElement->InsertAfterChild( itemElement, item );

        printf( "\n** Demo doc processed: ** \n\n" );
        doc.Print( stdout );


#ifdef TIXML_USE_STL
        printf( "** Demo doc processed to stream: ** \n\n" );
        cout << doc << endl << endl;
#endif

        // --------------------------------------------------------
        // Different tests...do we have what we expect?
        // --------------------------------------------------------

        int count = 0;
        TiXmlElement*	element;

        //////////////////////////////////////////////////////

#ifdef TIXML_USE_STL
        cout << "** Basic structure. **\n";
        ostringstream outputStream( ostringstream::out );
        outputStream << doc;
        XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
                 outputStream.str().c_str(), true );
#endif

        node = doc.RootElement();
        assert( node );
        XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) );
        XmlTest ( "Root element value is 'ToDo'.", "ToDo",  node->Value());

        node = node->FirstChild();
        XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) );
        node = node->NextSibling();
        XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) );
        XmlTest ( "Value is 'Item'.", "Item", node->Value() );

        node = node->FirstChild();
        XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) );
        XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() );


        //////////////////////////////////////////////////////
        printf ("\n** Iterators. **\n");

        // Walk all the top level nodes of the document.
        count = 0;
        for( node = doc.FirstChild();
                node;
                node = node->NextSibling() )
        {
            count++;
        }
        XmlTest( "Top level nodes, using First / Next.", 3, count );

        count = 0;
        for( node = doc.LastChild();
                node;
                node = node->PreviousSibling() )
        {
            count++;
        }
        XmlTest( "Top level nodes, using Last / Previous.", 3, count );

        // Walk all the top level nodes of the document,
        // using a different syntax.
        count = 0;
        for( node = doc.IterateChildren( 0 );
                node;
                node = doc.IterateChildren( node ) )
        {
            count++;
        }
        XmlTest( "Top level nodes, using IterateChildren.", 3, count );

        // Walk all the elements in a node.
        count = 0;
        for( element = todoElement->FirstChildElement();
                element;
                element = element->NextSiblingElement() )
        {
            count++;
        }
        XmlTest( "Children of the 'ToDo' element, using First / Next.",
                 3, count );

        // Walk all the elements in a node by value.
        count = 0;
        for( node = todoElement->FirstChild( "Item" );
                node;
                node = node->NextSibling( "Item" ) )
        {
            count++;
        }
        XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count );

        count = 0;
        for( node = todoElement->LastChild( "Item" );
                node;
                node = node->PreviousSibling( "Item" ) )
        {
            count++;
        }
        XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count );

#ifdef TIXML_USE_STL
        {
            cout << "\n** Parsing. **\n";
            istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '&gt;' />" );
            TiXmlElement element0( "default" );
            parse0 >> element0;

            XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() );
            XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" ));
            XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) );
            XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) );
        }
#endif

        {
            const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
                                "<passages count=\"006\" formatversion=\"20020620\">\n"
                                "    <wrong error>\n"
                                "</passages>";

            TiXmlDocument docTest;
            docTest.Parse( error );
            XmlTest( "Error row", docTest.ErrorRow(), 3 );
            XmlTest( "Error column", docTest.ErrorCol(), 17 );
            //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );

        }

#ifdef TIXML_USE_STL
        {
            //////////////////////////////////////////////////////
            cout << "\n** Streaming. **\n";

            // Round trip check: stream in, then stream back out to verify. The stream
            // out has already been checked, above. We use the output

            istringstream inputStringStream( outputStream.str() );
            TiXmlDocument document0;

            inputStringStream >> document0;

            ostringstream outputStream0( ostringstream::out );
            outputStream0 << document0;

            XmlTest( "Stream round trip correct.",	string( demoEnd ).c_str(),
                     outputStream0.str().c_str(), true );

            std::string str;
            str << document0;

            XmlTest( "String printing correct.", string( demoEnd ).c_str(),
                     str.c_str(), true );
        }
#endif
    }

    {
        const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlElement* ele = doc.FirstChildElement();

        int iVal, result;
        double dVal;

        result = ele->QueryDoubleAttribute( "attr0", &dVal );
        XmlTest( "Query attribute: int as double", result, TIXML_SUCCESS );
        XmlTest( "Query attribute: int as double", (int)dVal, 1 );
        result = ele->QueryDoubleAttribute( "attr1", &dVal );
        XmlTest( "Query attribute: double as double", (int)dVal, 2 );
        result = ele->QueryIntAttribute( "attr1", &iVal );
        XmlTest( "Query attribute: double as int", result, TIXML_SUCCESS );
        XmlTest( "Query attribute: double as int", iVal, 2 );
        result = ele->QueryIntAttribute( "attr2", &iVal );
        XmlTest( "Query attribute: not a number", result, TIXML_WRONG_TYPE );
        result = ele->QueryIntAttribute( "bar", &iVal );
        XmlTest( "Query attribute: does not exist", result, TIXML_NO_ATTRIBUTE );
    }

    {
        const char* str = "<doc/>";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlElement* ele = doc.FirstChildElement();

        int iVal;
        double dVal;

        ele->SetAttribute( "str", "strValue" );
        ele->SetAttribute( "int", 1 );
        ele->SetDoubleAttribute( "double", -1.0 );

        const char* cStr = ele->Attribute( "str" );
        ele->QueryIntAttribute( "int", &iVal );
        ele->QueryDoubleAttribute( "double", &dVal );

        XmlTest( "Attribute round trip. c-string.", "strValue", cStr );
        XmlTest( "Attribute round trip. int.", 1, iVal );
        XmlTest( "Attribute round trip. double.", -1, (int)dVal );
    }

    {
        const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
                            "</room>";

        TiXmlDocument doc;
        doc.SetTabSize( 8 );
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );

        assert( docHandle.Node() );
        assert( roomHandle.Element() );

        TiXmlElement* room = roomHandle.Element();
        assert( room );
        TiXmlAttribute* doors = room->FirstAttribute();
        assert( doors );

        XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 );
        XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 );
        XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 );
        XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 );
    }

    {
        const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
                            "  <!-- Silly example -->\n"
                            "    <door wall='north'>A great door!</door>\n"
                            "\t<door wall='east'/>"
                            "</room>";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );
        TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild();
        TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild();
        TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 );
        TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 );

        assert( docHandle.Node() );
        assert( roomHandle.Element() );
        assert( commentHandle.Node() );
        assert( textHandle.Text() );
        assert( door0Handle.Element() );
        assert( door1Handle.Element() );

        TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration();
        assert( declaration );
        TiXmlElement* room = roomHandle.Element();
        assert( room );
        TiXmlAttribute* doors = room->FirstAttribute();
        assert( doors );
        TiXmlText* text = textHandle.Text();
        TiXmlComment* comment = commentHandle.Node()->ToComment();
        assert( comment );
        TiXmlElement* door0 = door0Handle.Element();
        TiXmlElement* door1 = door1Handle.Element();

        XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 );
        XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 );
        XmlTest( "Location tracking: room row", room->Row(), 1 );
        XmlTest( "Location tracking: room col", room->Column(), 45 );
        XmlTest( "Location tracking: doors row", doors->Row(), 1 );
        XmlTest( "Location tracking: doors col", doors->Column(), 51 );
        XmlTest( "Location tracking: Comment row", comment->Row(), 2 );
        XmlTest( "Location tracking: Comment col", comment->Column(), 3 );
        XmlTest( "Location tracking: text row", text->Row(), 3 );
        XmlTest( "Location tracking: text col", text->Column(), 24 );
        XmlTest( "Location tracking: door0 row", door0->Row(), 3 );
        XmlTest( "Location tracking: door0 col", door0->Column(), 5 );
        XmlTest( "Location tracking: door1 row", door1->Row(), 4 );
        XmlTest( "Location tracking: door1 col", door1->Column(), 5 );
    }


    // --------------------------------------------------------
    // UTF-8 testing. It is important to test:
    //	1. Making sure name, value, and text read correctly
    //	2. Row, Col functionality
    //	3. Correct output
    // --------------------------------------------------------
    printf ("\n** UTF-8 **\n");
    {
        TiXmlDocument doc( "utf8test.xml" );
        doc.LoadFile();
        if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) {
            printf( "WARNING: File 'utf8test.xml' not found.\n"
                    "(Are you running the test from the wrong directory?)\n"
                    "Could not test UTF-8 functionality.\n" );
        }
        else
        {
            TiXmlHandle docH( &doc );
            // Get the attribute "value" from the "Russian" element and check it.
            TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element();
            const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
                                                    0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0
                                                 };

            XmlTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ), true );
            XmlTest( "UTF-8: Russian value row.", 4, element->Row() );
            XmlTest( "UTF-8: Russian value column.", 5, element->Column() );

            const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
                                                            0xd1U, 0x81U, 0xd1U, 0x81U,
                                                            0xd0U, 0xbaU, 0xd0U, 0xb8U,
                                                            0xd0U, 0xb9U, 0
                                                       };
            const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

            TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text();
            XmlTest( "UTF-8: Browsing russian element name.",
                     russianText,
                     text->Value(),
                     true );
            XmlTest( "UTF-8: Russian element name row.", 7, text->Row() );
            XmlTest( "UTF-8: Russian element name column.", 47, text->Column() );

            TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration();
            XmlTest( "UTF-8: Declaration column.", 1, dec->Column() );
            XmlTest( "UTF-8: Document column.", 1, doc.Column() );

            // Now try for a round trip.
            doc.SaveFile( "utf8testout.xml" );

            // Check the round trip.
            char savedBuf[256];
            char verifyBuf[256];
            int okay = 1;

            FILE* saved  = fopen( "utf8testout.xml", "r" );
            FILE* verify = fopen( "utf8testverify.xml", "r" );

            //bool firstLineBOM=true;
            if ( saved && verify )
            {
                while ( fgets( verifyBuf, 256, verify ) )
                {
                    fgets( savedBuf, 256, saved );
                    NullLineEndings( verifyBuf );
                    NullLineEndings( savedBuf );

                    if ( /*!firstLineBOM && */ strcmp( verifyBuf, savedBuf ) )
                    {
                        printf( "verify:%s<\n", verifyBuf );
                        printf( "saved :%s<\n", savedBuf );
                        okay = 0;
                        break;
                    }
                    //firstLineBOM = false;
                }
            }
            if ( saved )
                fclose( saved );
            if ( verify )
                fclose( verify );
            XmlTest( "UTF-8: Verified multi-language round trip.", 1, okay );

            // On most Western machines, this is an element that contains
            // the word "resume" with the correct accents, in a latin encoding.
            // It will be something else completely on non-wester machines,
            // which is why TinyXml is switching to UTF-8.
            const char latin[] = "<element>r\x82sum\x82</element>";

            TiXmlDocument latinDoc;
            latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY );

            text = latinDoc.FirstChildElement()->FirstChild()->ToText();
            XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() );
        }
    }

    //////////////////////
    // Copy and assignment
    //////////////////////
    printf ("\n** Copy and Assignment **\n");
    {
        TiXmlElement element( "foo" );
        element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN );

        TiXmlElement elementCopy( element );
        TiXmlElement elementAssign( "foo" );
        elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN );
        elementAssign = element;

        XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() );
        XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) );
        XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() );
        XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) );
        XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) );

        TiXmlComment comment;
        comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlComment commentCopy( comment );
        TiXmlComment commentAssign;
        commentAssign = commentCopy;
        XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() );
        XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() );

        TiXmlUnknown unknown;
        unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlUnknown unknownCopy( unknown );
        TiXmlUnknown unknownAssign;
        unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN );
        unknownAssign = unknownCopy;
        XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() );
        XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() );

        TiXmlText text( "TextNode" );
        TiXmlText textCopy( text );
        TiXmlText textAssign( "incorrect" );
        textAssign = text;
        XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() );
        XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() );

        TiXmlDeclaration dec;
        dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlDeclaration decCopy( dec );
        TiXmlDeclaration decAssign;
        decAssign = dec;

        XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() );
        XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() );

        TiXmlDocument doc;
        elementCopy.InsertEndChild( textCopy );
        doc.InsertEndChild( decAssign );
        doc.InsertEndChild( elementCopy );
        doc.InsertEndChild( unknownAssign );

        TiXmlDocument docCopy( doc );
        TiXmlDocument docAssign;
        docAssign = docCopy;

#ifdef TIXML_USE_STL
        std::string original, copy, assign;
        original << doc;
        copy << docCopy;
        assign << docAssign;
        XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true );
        XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true );

#endif
    }

    //////////////////////////////////////////////////////
#ifdef TIXML_USE_STL
    printf ("\n** Parsing, no Condense Whitespace **\n");
    TiXmlBase::SetCondenseWhiteSpace( false );
    {
        istringstream parse1( "<start>This  is    \ntext</start>" );
        TiXmlElement text1( "text" );
        parse1 >> text1;

        XmlTest ( "Condense white space OFF.", "This  is    \ntext",
                  text1.FirstChild()->Value(),
                  true );
    }
    TiXmlBase::SetCondenseWhiteSpace( true );
#endif

    //////////////////////////////////////////////////////
    // GetText();
    {
        const char* str = "<foo>This is text</foo>";
        TiXmlDocument doc;
        doc.Parse( str );
        const TiXmlElement* element = doc.RootElement();

        XmlTest( "GetText() normal use.", "This is text", element->GetText() );

        str = "<foo><b>This is text</b></foo>";
        doc.Clear();
        doc.Parse( str );
        element = doc.RootElement();

        XmlTest( "GetText() contained element.", element->GetText() == 0, true );

        str = "<foo>This is <b>text</b></foo>";
        doc.Clear();
        TiXmlBase::SetCondenseWhiteSpace( false );
        doc.Parse( str );
        TiXmlBase::SetCondenseWhiteSpace( true );
        element = doc.RootElement();

        XmlTest( "GetText() partial.", "This is ", element->GetText() );
    }


    //////////////////////////////////////////////////////
    // CDATA
    {
        const char* str =	"<xmlElement>"
                            "<![CDATA["
                            "I am > the rules!\n"
                            "...since I make symbolic puns"
                            "]]>"
                            "</xmlElement>";
        TiXmlDocument doc;
        doc.Parse( str );
        doc.Print();

        XmlTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(),
                 "I am > the rules!\n...since I make symbolic puns",
                 true );

#ifdef TIXML_USE_STL
        //cout << doc << '\n';

        doc.Clear();

        istringstream parse0( str );
        parse0 >> doc;
        //cout << doc << '\n';

        XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(),
                 "I am > the rules!\n...since I make symbolic puns",
                 true );
#endif

        TiXmlDocument doc1 = doc;
        //doc.Print();

        XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(),
                 "I am > the rules!\n...since I make symbolic puns",
                 true );
    }
    {
        // [ 1482728 ] Wrong wide char parsing
        char buf[256];
        buf[255] = 0;
        for( int i=0; i<255; ++i ) {
            buf[i] = (char)((i>=32) ? i : 32);
        }
        TIXML_STRING str( "<xmlElement><![CDATA[" );
        str += buf;
        str += "]]></xmlElement>";

        TiXmlDocument doc;
        doc.Parse( str.c_str() );

        TiXmlPrinter printer;
        printer.SetStreamPrinting();
        doc.Accept( &printer );

        XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true );

#ifdef TIXML_USE_STL
        doc.Clear();
        istringstream iss( printer.Str() );
        iss >> doc;
        std::string out;
        out << doc;
        XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true );
#endif
    }
    {
        // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags
        // CDATA streaming had a couple of bugs, that this tests for.
        const char* str =	"<xmlElement>"
                            "<![CDATA["
                            "<b>I am > the rules!</b>\n"
                            "...since I make symbolic puns"
                            "]]>"
                            "</xmlElement>";
        TiXmlDocument doc;
        doc.Parse( str );
        doc.Print();

        XmlTest( "CDATA parse. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
                 "<b>I am > the rules!</b>\n...since I make symbolic puns",
                 true );

#ifdef TIXML_USE_STL

        doc.Clear();

        istringstream parse0( str );
        parse0 >> doc;

        XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
                 "<b>I am > the rules!</b>\n...since I make symbolic puns",
                 true );
#endif

        TiXmlDocument doc1 = doc;
        //doc.Print();

        XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(),
                 "<b>I am > the rules!</b>\n...since I make symbolic puns",
                 true );
    }
    //////////////////////////////////////////////////////
    // Visit()



    //////////////////////////////////////////////////////
    printf( "\n** Fuzzing... **\n" );

    const int FUZZ_ITERATION = 300;

    // The only goal is not to crash on bad input.
    int len = (int) strlen( demoStart );
    for( int i=0; i<FUZZ_ITERATION; ++i )
    {
        char* demoCopy = new char[ len+1 ];
        strcpy( demoCopy, demoStart );

        demoCopy[ i%len ] = (char)((i+1)*3);
        demoCopy[ (i*7)%len ] = '>';
        demoCopy[ (i*11)%len ] = '<';

        TiXmlDocument xml;
        xml.Parse( demoCopy );

        delete [] demoCopy;
    }
    printf( "** Fuzzing Complete. **\n" );

    //////////////////////////////////////////////////////
    printf ("\n** Bug regression tests **\n");

    // InsertBeforeChild and InsertAfterChild causes crash.
    {
        TiXmlElement parent( "Parent" );
        TiXmlElement childText0( "childText0" );
        TiXmlElement childText1( "childText1" );
        TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
        TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 );

        XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true );
    }

    {
        // InsertBeforeChild and InsertAfterChild causes crash.
        TiXmlElement parent( "Parent" );
        TiXmlElement childText0( "childText0" );
        TiXmlElement childText1( "childText1" );
        TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
        TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 );

        XmlTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent.LastChild() ), true );
    }

    // Reports of missing constructors, irregular string problems.
    {
        // Missing constructor implementation. No test -- just compiles.
        TiXmlText text( "Missing" );

#ifdef TIXML_USE_STL
        // Missing implementation:
        TiXmlDocument doc;
        string name = "missing";
        doc.LoadFile( name );

        TiXmlText textSTL( name );
#else
        // verifying some basic string functions:
        TiXmlString a;
        TiXmlString b( "Hello" );
        TiXmlString c( "ooga" );

        c = " World!";
        a = b;
        a += c;
        a = a;

        XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() );
#endif
    }

    // Long filenames crashing STL version
    {
        TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" );
        bool loadOkay = doc.LoadFile();
        loadOkay = true;	// get rid of compiler warning.
        // Won't pass on non-dev systems. Just a "no crash" check.
        //XmlTest( "Long filename. ", true, loadOkay );
    }

    {
        // Entities not being written correctly.
        // From Lynn Allen

        const char* passages =
            "<?xml version=\"1.0\" standalone=\"no\" ?>"
            "<passages count=\"006\" formatversion=\"20020620\">"
            "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
            " It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
            "</passages>";

        TiXmlDocument doc( "passages.xml" );
        doc.Parse( passages );
        TiXmlElement* psg = doc.RootElement()->FirstChildElement();
        const char* context = psg->Attribute( "context" );
        const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

        XmlTest( "Entity transformation: read. ", expected, context, true );

        FILE* textfile = fopen( "textfile.txt", "w" );
        if ( textfile )
        {
            psg->Print( textfile, 0 );
            fclose( textfile );
        }
        textfile = fopen( "textfile.txt", "r" );
        assert( textfile );
        if ( textfile )
        {
            char buf[ 1024 ];
            fgets( buf, 1024, textfile );
            XmlTest( "Entity transformation: write. ",
                     "<psg context=\'Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
                     " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.' />",
                     buf,
                     true );
        }
        fclose( textfile );
    }

    {
        FILE* textfile = fopen( "test5.xml", "w" );
        if ( textfile )
        {
            fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile);
            fclose(textfile);

            TiXmlDocument doc;
            doc.LoadFile( "test5.xml" );
            XmlTest( "dot in element attributes and names", doc.Error(), 0);
        }
    }

    {
        FILE* textfile = fopen( "test6.xml", "w" );
        if ( textfile )
        {
            fputs("<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>", textfile );
            fclose(textfile);

            TiXmlDocument doc;
            bool result = doc.LoadFile( "test6.xml" );
            XmlTest( "Entity with one digit.", result, true );

            TiXmlText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
            XmlTest( "Entity with one digit.",
                     text->Value(), "1.1 Start easy ignore fin thickness\n" );
        }
    }

    {
        // DOCTYPE not preserved (950171)
        //
        const char* doctype =
            "<?xml version=\"1.0\" ?>"
            "<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
            "<!ELEMENT title (#PCDATA)>"
            "<!ELEMENT books (title,authors)>"
            "<element />";

        TiXmlDocument doc;
        doc.Parse( doctype );
        doc.SaveFile( "test7.xml" );
        doc.Clear();
        doc.LoadFile( "test7.xml" );

        TiXmlHandle docH( &doc );
        TiXmlUnknown* unknown = docH.Child( 1 ).Unknown();
        XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() );
#ifdef TIXML_USE_STL
        TiXmlNode* node = docH.Child( 2 ).Node();
        std::string str;
        str << (*node);
        XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() );
#endif
    }

    {
        // [ 791411 ] Formatting bug
        // Comments do not stream out correctly.
        const char* doctype =
            "<!-- Somewhat<evil> -->";
        TiXmlDocument doc;
        doc.Parse( doctype );

        TiXmlHandle docH( &doc );
        TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment();

        XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
#ifdef TIXML_USE_STL
        std::string str;
        str << (*comment);
        XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() );
#endif
    }

    {
        // [ 870502 ] White space issues
        TiXmlDocument doc;
        TiXmlText* text;
        TiXmlHandle docH( &doc );

        const char* doctype0 = "<element> This has leading and trailing space </element>";
        const char* doctype1 = "<element>This has  internal space</element>";
        const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

        TiXmlBase::SetCondenseWhiteSpace( false );
        doc.Clear();
        doc.Parse( doctype0 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() );

        doc.Clear();
        doc.Parse( doctype1 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", "This has  internal space", text->Value() );

        doc.Clear();
        doc.Parse( doctype2 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", " This has leading, trailing, and  internal space ", text->Value() );

        TiXmlBase::SetCondenseWhiteSpace( true );
        doc.Clear();
        doc.Parse( doctype0 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() );

        doc.Clear();
        doc.Parse( doctype1 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has internal space", text->Value() );

        doc.Clear();
        doc.Parse( doctype2 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() );
    }

    {
        // Double attributes
        const char* doctype = "<element attr='red' attr='blue' />";

        TiXmlDocument doc;
        doc.Parse( doctype );

        XmlTest( "Parsing repeated attributes.", true, doc.Error() );	// is an  error to tinyxml (didn't use to be, but caused issues)
        //XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) );
    }

    {
        // Embedded null in stream.
        const char* doctype = "<element att\0r='red' attr='blue' />";

        TiXmlDocument doc;
        doc.Parse( doctype );
        XmlTest( "Embedded null throws error.", true, doc.Error() );

#ifdef TIXML_USE_STL
        istringstream strm( doctype );
        doc.Clear();
        doc.ClearError();
        strm >> doc;
        XmlTest( "Embedded null throws error.", true, doc.Error() );
#endif
    }

    {
        // Legacy mode test. (This test may only pass on a western system)
        const char* str =
            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
            "<ä>"
            "CöntäntßäöüÄÖÜ"
            "</ä>";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" );
        TiXmlHandle tHandle = aHandle.Child( 0 );
        assert( aHandle.Element() );
        assert( tHandle.Text() );
        XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() );
    }

    {
        // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717
        const char* str = "    ";
        TiXmlDocument doc;
        doc.Parse( str );
        XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() );
    }
#ifndef TIXML_USE_STL
    {
        // String equality. [ 1006409 ] string operator==/!= no worky in all cases
        TiXmlString temp;
        XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true );

        TiXmlString    foo;
        TiXmlString    bar( "" );
        XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true );
    }

#endif
    {
        // Bug [ 1195696 ] from marlonism
        TiXmlBase::SetCondenseWhiteSpace(false);
        TiXmlDocument xml;
        xml.Parse("<text><break/>This hangs</text>");
        XmlTest( "Test safe error return.", xml.Error(), false );
    }

    {
        // Bug [ 1243992 ] - another infinite loop
        TiXmlDocument doc;
        doc.SetCondenseWhiteSpace(false);
        doc.Parse("<p><pb></pb>test</p>");
    }
    {
        // Low entities
        TiXmlDocument xml;
        xml.Parse( "<test>&#x0e;</test>" );
        const char result[] = { 0x0e, 0 };
        XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result );
        xml.Print();
    }
    {
        // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly
        TiXmlDocument xml;
        xml.Parse( "<foo attribute=bar\" />" );
        XmlTest( "Throw error with bad end quotes.", xml.Error(), true );
    }
#ifdef TIXML_USE_STL
    {
        // Bug [ 1449463 ] Consider generic query
        TiXmlDocument xml;
        xml.Parse( "<foo bar='3' barStr='a string'/>" );

        TiXmlElement* ele = xml.FirstChildElement();
        double d;
        int i;
        float f;
        bool b;
        std::string str;

        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS );

        XmlTest( "QueryValueAttribute", (d==3.0), true );
        XmlTest( "QueryValueAttribute", (i==3), true );
        XmlTest( "QueryValueAttribute", (f==3.0f), true );
        XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true );
    }
#endif

#ifdef TIXML_USE_STL
    {
        // [ 1505267 ] redundant malloc in TiXmlElement::Attribute
        TiXmlDocument xml;
        xml.Parse( "<foo bar='3' />" );
        TiXmlElement* ele = xml.FirstChildElement();
        double d;
        int i;

        std::string bar = "bar";

        const std::string* atrrib = ele->Attribute( bar );
        ele->Attribute( bar, &d );
        ele->Attribute( bar, &i );

        XmlTest( "Attribute", atrrib->empty(), false );
        XmlTest( "Attribute", (d==3.0), true );
        XmlTest( "Attribute", (i==3), true );
    }
#endif

    {
        // [ 1356059 ] Allow TiXMLDocument to only be at the top level
        TiXmlDocument xml, xml2;
        xml.InsertEndChild( xml2 );
        XmlTest( "Document only at top level.", xml.Error(), true );
        XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY );
    }

    {
        // [ 1663758 ] Failure to report error on bad XML
        TiXmlDocument xml;
        xml.Parse("<x>");
        XmlTest("Missing end tag at end of input", xml.Error(), true);
        xml.Parse("<x> ");
        XmlTest("Missing end tag with trailing whitespace", xml.Error(), true);
    }

    {
        // [ 1635701 ] fail to parse files with a tag separated into two lines
        // I'm not sure this is a bug. Marked 'pending' for feedback.
        TiXmlDocument xml;
        xml.Parse( "<title><p>text</p\n><title>" );
        //xml.Print();
        //XmlTest( "Tag split by newline", xml.Error(), false );
    }

#ifdef TIXML_USE_STL
    {
        // [ 1475201 ] TinyXML parses entities in comments
        TiXmlDocument xml;
        istringstream parse1( "<!-- declarations for <head> & <body> -->"
                              "<!-- far &amp; away -->" );
        parse1 >> xml;

        TiXmlNode* e0 = xml.FirstChild();
        TiXmlNode* e1 = e0->NextSibling();
        TiXmlComment* c0 = e0->ToComment();
        TiXmlComment* c1 = e1->ToComment();

        XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
        XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
    }
#endif

    {
        // [ 1475201 ] TinyXML parses entities in comments
        TiXmlDocument xml;
        xml.Parse("<!-- declarations for <head> & <body> -->"
                  "<!-- far &amp; away -->" );

        TiXmlNode* e0 = xml.FirstChild();
        TiXmlNode* e1 = e0->NextSibling();
        TiXmlComment* c0 = e0->ToComment();
        TiXmlComment* c1 = e1->ToComment();

        XmlTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
        XmlTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
    }

    {
        TiXmlDocument xml;
        xml.Parse( "<Parent>"
                   "<child1 att=''/>"
                   "<!-- With this comment, child2 will not be parsed! -->"
                   "<child2 att=''/>"
                   "</Parent>" );
        int count = 0;

        TiXmlNode* ele = 0;
        while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) {
            ++count;
        }
        XmlTest( "Comments iterate correctly.", 3, count );
    }

    {
        // trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
        unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
        buf[60] = 239;
        buf[61] = 0;

        TiXmlDocument doc;
        doc.Parse( (const char*)buf);
    }


    {
        // bug 1827248 Error while parsing a little bit malformed file
        // Actually not malformed - should work.
        TiXmlDocument xml;
        xml.Parse( "<attributelist> </attributelist >" );
        XmlTest( "Handle end tag whitespace", false, xml.Error() );
    }

    {
        // This one must not result in an infinite loop
        TiXmlDocument xml;
        xml.Parse( "<infinite>loop" );
        XmlTest( "Infinite loop test.", true, true );
    }

    {
        // 1709904 - can not repro the crash
        {
            TiXmlDocument xml;
            xml.Parse( "<tag>/</tag>" );
            XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" );
        }
        /* Could not repro. {
        	TiXmlDocument xml;
        	xml.LoadFile( "EQUI_Inventory.xml" );
        	//XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" );
        	TiXmlPrinter printer;
        	xml.Accept( &printer );
        	fprintf( stdout, "%s", printer.CStr() );
        }*/
    }

    /*  1417717 experiment
    {
    	TiXmlDocument xml;
    	xml.Parse("<text>Dan & Tracie</text>");
    	xml.Print(stdout);
    }
    {
    	TiXmlDocument xml;
    	xml.Parse("<text>Dan &foo; Tracie</text>");
    	xml.Print(stdout);
    }
    */

#if defined( WIN32 ) && defined( TUNE )
    _CrtMemCheckpoint( &endMemState );
    //_CrtMemDumpStatistics( &endMemState );

    _CrtMemState diffMemState;
    _CrtMemDifference( &diffMemState, &startMemState, &endMemState );
    _CrtMemDumpStatistics( &diffMemState );
#endif

    printf ("\nPass %d, Fail %d\n", gPass, gFail);
    return gFail;
}
Example #25
0
bool JAnimator::Load(const char* scriptFile)
{

    JFileSystem *fileSystem = JFileSystem::GetInstance();
    if (fileSystem == NULL) return false;

    if (!fileSystem->OpenFile(scriptFile)) return false;

    int size = fileSystem->GetFileSize();
    char *xmlBuffer = new char[size];
    fileSystem->ReadFile(xmlBuffer, size);

    TiXmlDocument doc;
    doc.Parse(xmlBuffer);

    TiXmlNode* script = 0;
    TiXmlNode* frame = 0;
    TiXmlNode* obj = 0;
    TiXmlNode* param = 0;
    TiXmlElement* element = 0;

    float defaultTime = 0.033f;

    script = doc.FirstChild("script");
    if (script)
    {
        element = script->ToElement();
        printf("---- Loading %s:%s\n", element->Value(), element->Attribute("name"));

        char *type[] =
        {
            "ANIMATION_TYPE_LOOPING",
            "ANIMATION_TYPE_ONCE_AND_STAY",
            "ANIMATION_TYPE_ONCE_AND_BACK",
            "ANIMATION_TYPE_ONCE_AND_GONE",
            "ANIMATION_TYPE_PINGPONG"
        };

        const char* aniType = element->Attribute("type");
        for (int i=0; i<5; i++)
            if (strcmp(type[i], aniType)==0)
            {
                SetAnimationType(i);
                break;
            }

        float fps;
        if (element->QueryFloatAttribute("framerate", &fps) != TIXML_SUCCESS)
            fps = 30.0f;

        defaultTime = 1/fps;

        for (frame = script->FirstChild("frame"); frame; frame = frame->NextSibling())
        {
            JAnimatorFrame *aniFrame = new JAnimatorFrame(this);

            float duration;
            element = frame->ToElement();
            if (element->QueryFloatAttribute("time", &duration) != TIXML_SUCCESS)
                duration = defaultTime;
            aniFrame->SetFrameTime(duration);

            for (obj = frame->FirstChild(); obj; obj = obj->NextSibling())
            {
                for (param = obj->FirstChild(); param; param = param->NextSibling())
                {

                    element = param->ToElement();
                    if (element != NULL)
                    {
                        if (strcmp(element->Value(), "settings")==0)
                        {
                            const char* quadName = element->Attribute("quad");
                            JQuad* quad = mResource->GetQuad(quadName);

                            float x, y;
                            float vsize, hsize;
                            float angle;
                            int a, r, g, b;
                            int value;
                            bool flipped = false;

                            if (element->QueryFloatAttribute("x", &x) != TIXML_SUCCESS)
                                x = 0.0f;

                            if (element->QueryFloatAttribute("y", &y) != TIXML_SUCCESS)
                                y = 0.0f;

                            if (element->QueryFloatAttribute("hsize", &hsize) != TIXML_SUCCESS)
                                hsize = 1.0f;

                            if (element->QueryFloatAttribute("vsize", &vsize) != TIXML_SUCCESS)
                                vsize = 1.0f;

                            if (element->QueryFloatAttribute("rotation", &angle) != TIXML_SUCCESS)
                                angle = 0.0f;

                            if (element->QueryIntAttribute("a", &a) != TIXML_SUCCESS)
                                a = 255;

                            if (element->QueryIntAttribute("r", &r) != TIXML_SUCCESS)
                                r = 255;

                            if (element->QueryIntAttribute("g", &g) != TIXML_SUCCESS)
                                g = 255;

                            if (element->QueryIntAttribute("b", &b) != TIXML_SUCCESS)
                                b = 255;

                            if (element->QueryIntAttribute("flip", &value) == TIXML_SUCCESS)
                                flipped = (value==1);


                            JAnimatorObject *object = new JAnimatorObject();
                            object->SetQuad(quad);
                            object->SetPosition(x, y);
                            object->SetHScale(hsize);
                            object->SetVScale(vsize);
                            object->SetRotation(angle);
                            object->SetColor(ARGB(a,r,g,b));
                            object->SetFlip(flipped);

                            aniFrame->AddObject(object);

                        }
                    }
                }

            }

            mFrames.push_back(aniFrame);
        }

    }

    fileSystem->CloseFile();
    delete[] xmlBuffer;

    return true;

}
Example #26
0
bool ETHEntityProperties::ReadFromXMLFile(TiXmlElement *pElement)
{
	pElement->QueryIntAttribute(GS_L("type"), (int*)&type);

	int nStaticEntity = static_cast<int>(staticEntity);
	pElement->QueryIntAttribute(GS_L("static"), &nStaticEntity);
	staticEntity = static_cast<ETH_BOOL>(nStaticEntity);

	int nApplyLight = static_cast<int>(applyLight);
	pElement->QueryIntAttribute(GS_L("applyLight"), &nApplyLight);
	applyLight = static_cast<ETH_BOOL>(nApplyLight);

	int nCastShadow = static_cast<int>(castShadow);
	pElement->QueryIntAttribute(GS_L("castShadow"), &nCastShadow);
	castShadow = static_cast<ETH_BOOL>(nCastShadow);

	int nHideFromSceneEditor = static_cast<int>(hideFromSceneEditor);
	pElement->QueryIntAttribute(GS_L("hideFromSceneEditor"), &nHideFromSceneEditor);
	hideFromSceneEditor = static_cast<ETH_BOOL>(nHideFromSceneEditor);

	pElement->QueryIntAttribute(GS_L("shape"), (int*)&shape);
	pElement->QueryIntAttribute(GS_L("blendMode"), (int*)&blendMode);
	pElement->QueryFloatAttribute(GS_L("layerDepth"), &layerDepth);
	pElement->QueryFloatAttribute(GS_L("soundVolume"), &soundVolume);
	pElement->QueryFloatAttribute(GS_L("parallaxIntensity"), &parallaxIntensity);

	if (applyLight)
	{
		pElement->QueryFloatAttribute(GS_L("specularPower"), &specularPower);
		pElement->QueryFloatAttribute(GS_L("specularBrightness"), &specularBrightness);
	}

	if (castShadow)
	{
		pElement->QueryFloatAttribute(GS_L("shadowScale"), &shadowScale);
		pElement->QueryFloatAttribute(GS_L("shadowLengthScale"), &shadowLengthScale);
		pElement->QueryFloatAttribute(GS_L("shadowOpacity"), &shadowOpacity);
	}

	if (shape != BS_NONE)
	{
		int nSensor = static_cast<int>(sensor);
		pElement->QueryIntAttribute(GS_L("sensor"), &nSensor);
		sensor = static_cast<ETH_BOOL>(nSensor);

		int nFixedRotation = static_cast<int>(fixedRotation);
		pElement->QueryIntAttribute(GS_L("fixedRotation"), &nFixedRotation);
		fixedRotation = static_cast<ETH_BOOL>(nFixedRotation);

		int nBullet = static_cast<int>(bullet);
		pElement->QueryIntAttribute(GS_L("bullet"), &nBullet);
		bullet = static_cast<ETH_BOOL>(nBullet);

		pElement->QueryFloatAttribute(GS_L("friction"), &friction);
		pElement->QueryFloatAttribute(GS_L("density"), &density);
		pElement->QueryFloatAttribute(GS_L("gravityScale"), &gravityScale);
		pElement->QueryFloatAttribute(GS_L("restitution"), &restitution);
	}

	TiXmlElement *pIter;
	TiXmlNode *pNode;

	pNode = pElement->FirstChild(GS_L("EmissiveColor"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("r"), &emissiveColor.x);
			pIter->QueryFloatAttribute(GS_L("g"), &emissiveColor.y);
			pIter->QueryFloatAttribute(GS_L("b"), &emissiveColor.z);
			pIter->QueryFloatAttribute(GS_L("a"), &emissiveColor.w);
		}
	}

	pNode = pElement->FirstChild(GS_L("SpriteCut"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryIntAttribute(GS_L("x"), &spriteCut.x);
			pIter->QueryIntAttribute(GS_L("y"), &spriteCut.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("Scale"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("x"), &scale.x);
			pIter->QueryFloatAttribute(GS_L("y"), &scale.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("PivotAdjust"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			pIter->QueryFloatAttribute(GS_L("x"), &pivotAdjust.x);
			pIter->QueryFloatAttribute(GS_L("y"), &pivotAdjust.y);
		}
	}

	pNode = pElement->FirstChild(GS_L("Sprite"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			spriteFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Normal"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			normalFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Gloss"));
	if (pNode)
	{
		pIter = pNode->ToElement();
		if (pIter)
		{
			glossFile = pIter->GetText();
		}
	}

	pNode = pElement->FirstChild(GS_L("Particles"));
	if (pNode)
	{
		TiXmlElement *pParticles = pNode->ToElement();
		if (pParticles)
		{
			pNode = pParticles->FirstChild(GS_L("ParticleSystem"));
			if (pNode)
			{
				TiXmlElement *pParticleIter = pNode->ToElement();
				if (pParticleIter)
				{
					// TODO: use unlimited amount of systems 
					for (std::size_t t = 0; t < ETH_MAX_PARTICLE_SYS_PER_ENTITY; t++)
					{
						if (pParticleIter)
						{
							boost::shared_ptr<ETHParticleSystem> newSystem = boost::shared_ptr<ETHParticleSystem>(new ETHParticleSystem);
							newSystem->ReadFromXMLFile(pParticleIter);
							if (newSystem->nParticles > 0)
							{
								particleSystems.push_back(newSystem);
							}
							pParticleIter = pParticleIter->NextSiblingElement();
						}
					}
				}
			}
		}
	}

	pNode = pElement->FirstChild(GS_L("Light"));
	if (pNode)
	{
		TiXmlElement *pLight = pNode->ToElement();
		if (pLight)
		{
			boost::shared_ptr<ETHLight> newLight = boost::shared_ptr<ETHLight>(new ETHLight(true));
			newLight->ReadFromXMLFile(pLight);
			if (newLight->IsActive() && newLight->range > 0.0f)
			{
				light = newLight;
				// forces the light 'static' flag to be the same as its owner's
				light->staticLight = staticEntity;
			}
		}
	}

	{
		int nCollidable = 1;
		const int r = pElement->QueryIntAttribute(GS_L("collidable"), &nCollidable);
		if (nCollidable || r == TIXML_NO_ATTRIBUTE)
		{
			pNode = pElement->FirstChild(GS_L("Collision"));
			if (pNode)
			{
				collision = boost::shared_ptr<ETHCollisionBox>(new ETHCollisionBox);
				TiXmlElement *pCollision = pNode->ToElement();
				if (pCollision)
				{
					collision->ReadFromXMLFile(pCollision);
				}

				// if it's a legacy entity, it may have a collision body in its XML even though it is not collidable
				if (collision->size == Vector3(0, 0, 0))
				{
					collision.reset();
				}
				
				{
					TiXmlNode *pPolygonNode = pNode->FirstChild(GS_L("Polygon"));
					if (pPolygonNode)
					{
						pIter = pPolygonNode->ToElement();
						if (pIter)
						{
							polygon = ETHPolygonPtr(new ETHPolygon(pIter->GetText()));
						}
					}
					else
					{
						TiXmlNode *pCompoundNode = pNode->FirstChild(GS_L("Compound"));
						if (pCompoundNode)
						{
							pIter = pCompoundNode->ToElement();
							if (pIter)
							{
								compoundShape = ETHCompoundShapePtr(new ETHCompoundShape(pIter->GetText()));
							}
						}
					}
				}
				{
					TiXmlNode *pJointsNode = pNode->FirstChild(GS_L("Joints"));
					if (pJointsNode)
					{
						pIter = pJointsNode->ToElement();
						if (pIter)
						{
							enmlJointDefinitions = pIter->GetText();
						}
					}

				}
			}
		}
	}
	ReadDataFromXMLFile(pElement);
	return true;
}
bool Brothel::LoadBrothelXML( TiXmlHandle hBrothel )
{
    //no need to init this, we just created it
    TiXmlElement* pBrothel = hBrothel.ToElement();
    
    if( pBrothel == nullptr )
    {
        return false;
    }
    
    if( pBrothel->Attribute( "Name" ) )
    {
        m_Name = pBrothel->Attribute( "Name" );
    }
    
    int tempInt = 0;
    
    std::string message = "Loading brothel: ";
    message += m_Name;
    g_LogFile.write( message );
    
    // load variables for sex restrictions
    pBrothel->QueryValueAttribute<bool>( "RestrictAnal", &m_RestrictAnal );
    pBrothel->QueryValueAttribute<bool>( "RestrictBDSM", &m_RestrictBDSM );
    pBrothel->QueryValueAttribute<bool>( "RestrictBeast", &m_RestrictBeast );
    pBrothel->QueryValueAttribute<bool>( "RestrictGroup", &m_RestrictGroup );
    pBrothel->QueryValueAttribute<bool>( "RestrictNormal", &m_RestrictNormal );
    pBrothel->QueryValueAttribute<bool>( "RestrictLesbian", &m_RestrictLesbian );
    
    pBrothel->QueryValueAttribute<unsigned short>( "AdvertisingBudget", &m_AdvertisingBudget );
    pBrothel->QueryIntAttribute( "Bar", &tempInt );
    m_Bar = tempInt;
    tempInt = 0;
    pBrothel->QueryIntAttribute( "Fame", &tempInt );
    m_Fame = tempInt;
    tempInt = 0;
    pBrothel->QueryIntAttribute( "GamblingHall", &tempInt );
    m_GamblingHall = tempInt;
    tempInt = 0;
    pBrothel->QueryValueAttribute<unsigned short>( "Happiness", &m_Happiness );
    pBrothel->QueryIntAttribute( "HasBarStaff", &tempInt );
    m_HasBarStaff = tempInt;
    tempInt = 0;
    pBrothel->QueryIntAttribute( "id", &m_id );
    pBrothel->QueryIntAttribute( "HasGambStaff", &tempInt );
    m_HasGambStaff = tempInt;
    tempInt = 0;
    pBrothel->QueryIntAttribute( "NumRooms", &tempInt );
    m_NumRooms = tempInt;
    tempInt = 0;
    pBrothel->QueryIntAttribute( "Filthiness", &m_Filthiness );
    pBrothel->QueryIntAttribute( "SecurityLevel", &m_SecurityLevel );
    
    m_Finance.loadGoldXML( hBrothel.FirstChild( "Gold" ) );
    
    // Load girls
    m_NumGirls = 0;
    TiXmlElement* pGirls = pBrothel->FirstChildElement( "Girls" );
    
    if( pGirls )
    {
        for( TiXmlElement* pGirl = pGirls->FirstChildElement( "Girl" );
                pGirl != nullptr;
                pGirl = pGirl->NextSiblingElement( "Girl" ) ) // load each girl and add her
        {
            Girl* girl = new Girl();
            bool success = girl->LoadGirlXML( TiXmlHandle( pGirl ) );
            
            if( success == true )
            {
                AddGirl( girl );
            }
            else
            {
                delete girl;
                continue;
            }
        }
    }
    
    //commented out before the conversion to XML
    //building.load(ifs);
    return true;
}
Example #28
0
void CScraperParser::ParseExpression(const std::string& input, std::string& dest, TiXmlElement* element, bool bAppend)
{
  std::string strOutput = XMLUtils::GetAttribute(element, "output");

  TiXmlElement* pExpression = element->FirstChildElement("expression");
  if (pExpression)
  {
    bool bInsensitive=true;
    const char* sensitive = pExpression->Attribute("cs");
    if (sensitive)
      if (stricmp(sensitive,"yes") == 0)
        bInsensitive=false; // match case sensitive

    CRegExp::utf8Mode eUtf8 = CRegExp::autoUtf8;
    const char* const strUtf8 = pExpression->Attribute("utf8");
    if (strUtf8)
    {
      if (stricmp(strUtf8, "yes") == 0)
        eUtf8 = CRegExp::forceUtf8;
      else if (stricmp(strUtf8, "no") == 0)
        eUtf8 = CRegExp::asciiOnly;
      else if (stricmp(strUtf8, "auto") == 0)
        eUtf8 = CRegExp::autoUtf8;
    }

    CRegExp reg(bInsensitive, eUtf8);
    std::string strExpression;
    if (pExpression->FirstChild())
      strExpression = pExpression->FirstChild()->Value();
    else
      strExpression = "(.*)";
    ReplaceBuffers(strExpression);
    ReplaceBuffers(strOutput);

    if (!reg.RegComp(strExpression.c_str()))
    {
      return;
    }

    bool bRepeat = false;
    const char* szRepeat = pExpression->Attribute("repeat");
    if (szRepeat)
      if (stricmp(szRepeat,"yes") == 0)
        bRepeat = true;

    const char* szClear = pExpression->Attribute("clear");
    if (szClear)
      if (stricmp(szClear,"yes") == 0)
        dest=""; // clear no matter if regexp fails

    bool bClean[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bClean,pExpression->Attribute("noclean"),true);

    bool bTrim[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bTrim,pExpression->Attribute("trim"),false);

    bool bFixChars[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bFixChars,pExpression->Attribute("fixchars"),false);

    bool bEncode[MAX_SCRAPER_BUFFERS];
    GetBufferParams(bEncode,pExpression->Attribute("encode"),false);

    int iOptional = -1;
    pExpression->QueryIntAttribute("optional",&iOptional);

    int iCompare = -1;
    pExpression->QueryIntAttribute("compare",&iCompare);
    if (iCompare > -1)
      StringUtils::ToLower(m_param[iCompare-1]);
    std::string curInput = input;
    for (int iBuf=0;iBuf<MAX_SCRAPER_BUFFERS;++iBuf)
    {
      if (bClean[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!CLEAN!!!");
      if (bTrim[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!TRIM!!!");
      if (bFixChars[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!FIXCHARS!!!");
      if (bEncode[iBuf])
        InsertToken(strOutput,iBuf+1,"!!!ENCODE!!!");
    }
    int i = reg.RegFind(curInput.c_str());
    while (i > -1 && (i < (int)curInput.size() || curInput.empty()))
    {
      if (!bAppend)
      {
        dest = "";
        bAppend = true;
      }
      std::string strCurOutput=strOutput;

      if (iOptional > -1) // check that required param is there
      {
        char temp[12];
        sprintf(temp,"\\%i",iOptional);
        std::string szParam = reg.GetReplaceString(temp);
        CRegExp reg2;
        reg2.RegComp("(.*)(\\\\\\(.*\\\\2.*)\\\\\\)(.*)");
        int i2=reg2.RegFind(strCurOutput.c_str());
        while (i2 > -1)
        {
          std::string szRemove(reg2.GetMatch(2));
          int iRemove = szRemove.size();
          int i3 = strCurOutput.find(szRemove);
          if (!szParam.empty())
          {
            strCurOutput.erase(i3+iRemove,2);
            strCurOutput.erase(i3,2);
          }
          else
            strCurOutput.replace(strCurOutput.begin()+i3,strCurOutput.begin()+i3+iRemove+2,"");

          i2 = reg2.RegFind(strCurOutput.c_str());
        }
      }

      int iLen = reg.GetFindLen();
      // nasty hack #1 - & means \0 in a replace string
      StringUtils::Replace(strCurOutput, "&","!!!AMPAMP!!!");
      std::string result = reg.GetReplaceString(strCurOutput.c_str());
      if (!result.empty())
      {
        std::string strResult(result);
        StringUtils::Replace(strResult, "!!!AMPAMP!!!","&");
        Clean(strResult);
        ReplaceBuffers(strResult);
        if (iCompare > -1)
        {
          std::string strResultNoCase = strResult;
          StringUtils::ToLower(strResultNoCase);
          if (strResultNoCase.find(m_param[iCompare-1]) != std::string::npos)
            dest += strResult;
        }
        else
          dest += strResult;
      }
      if (bRepeat && iLen > 0)
      {
        curInput.erase(0,i+iLen>(int)curInput.size()?curInput.size():i+iLen);
        i = reg.RegFind(curInput.c_str());
      }
      else
        i = -1;
    }
  }
}