Esempio n. 1
0
void XmlExcel::guardar_archivo(TiXmlDocument doc,char archivo[]){
	doc.SaveFile(archivo);
}
Esempio n. 2
0
	void Puppet::Save(Entity *entity)
	{
		// save to filename
		TiXmlDocument xmlDoc;

		/// TextureAtlas
		if (textureAtlas)
		{
			textureAtlas->Save(&xmlDoc);
		}

		/// Parts
		//TiXmlElement *xmlParts = xmlDoc.FirstChildElement("Parts");
		TiXmlElement xmlParts("Parts");
		SaveParts(&xmlParts, entity);
		xmlDoc.InsertEndChild(xmlParts);


		/// Animations
		TiXmlElement xmlAnimations("Animations");
		{
			/// Animation
			for (std::list<Animation>::iterator i = animations.begin(); i != animations.end(); ++i)
			{
				TiXmlElement xmlAnimation("Animation");

				Animation *animation = &(*i);
                
                XMLFileNode xmlFileNodeKeyFrameAnim(&xmlAnimation);
				animation->Save(&xmlFileNodeKeyFrameAnim);

				/// PartKeyFrames
				for (std::list<Part*>::iterator j = parts.begin(); j != parts.end(); ++j)
				{
					PartKeyFrames *partKeyFrames = animation->GetPartKeyFrames(*j);
					if (partKeyFrames)
					{
						TiXmlElement xmlPartKeyFrames("PartKeyFrames");
						XMLFileNode xmlFileNodePartKeyFrames(&xmlPartKeyFrames);

						partKeyFrames->Save(&xmlFileNodePartKeyFrames);

						/// KeyFrame
					
						std::list<KeyFrame> *keyFrames = partKeyFrames->GetKeyFrames();
						for (std::list<KeyFrame>::iterator i = keyFrames->begin(); i != keyFrames->end(); ++i)
						{
							KeyFrame *keyFrame = &(*i);

							TiXmlElement xmlKeyFrame("KeyFrame");
							XMLFileNode xmlFileNodeKeyFrame(&xmlKeyFrame);

							keyFrame->Save(&xmlFileNodeKeyFrame);

							xmlPartKeyFrames.InsertEndChild(xmlKeyFrame);
						}

						xmlAnimation.InsertEndChild(xmlPartKeyFrames);
					}
				}

				xmlAnimations.InsertEndChild(xmlAnimation);
			}
		}
		xmlDoc.InsertEndChild(xmlAnimations);

		xmlDoc.SaveFile(Assets::GetContentPath() + filename);
	}
Esempio n. 3
0
OsStatus
CallerAliasDB::store()
{
   UtlString fileName = DbName + ".xml";
   UtlString pathName = SipXecsService::Path(SipXecsService::DatabaseDirType,
                                             fileName.data());

   // Create an empty document
   TiXmlDocument document;

   // Create a hard coded standalone declaration section
   document.Parse ("<?xml version=\"1.0\" standalone=\"yes\"?>");

   // Create the root node container
   TiXmlElement itemsElement ( "items" );
   itemsElement.SetAttribute( "type", sType.data() );
   itemsElement.SetAttribute( "xmlns", sXmlNamespace.data() );

   // Critical Section while actually opening and using the database
   {
      OsLock lock( sLockMutex );

      if ( mpFastDB != NULL ) 
      {
         // Thread Local Storage
         mpFastDB->attach();

         // Search our memory for rows
         dbCursor< CallerAliasRow > cursor;

         // Select everything in the IMDB and add as item elements if present
         int rowNumber;
         int rows;
         for (rowNumber = 0, rows = cursor.select();
              rowNumber < rows;
              rowNumber++, cursor.next()
              )
         {
            // Create an item container
            TiXmlElement itemElement ("item");

            if ( *cursor->identity )
            {
               // Add an identity element and put the value in it
               TiXmlElement identityElement(IdentityKey.data());
               TiXmlText    identityValue(cursor->identity);
               identityElement.InsertEndChild(identityValue);
               itemElement.InsertEndChild(identityElement);
            }
         
            // add the domain element and put the value in it
            TiXmlElement domainElement(DomainKey.data());
            TiXmlText    domainValue(cursor->domain);
            domainElement.InsertEndChild(domainValue);
            itemElement.InsertEndChild(domainElement);

            // add the alias element and put the value in it
            TiXmlElement aliasElement(AliasKey.data());
            TiXmlText    aliasValue(cursor->alias);
            aliasElement.InsertEndChild(aliasValue);
            itemElement.InsertEndChild(aliasElement);
            
            // add this item (row) to the parent items container
            itemsElement.InsertEndChild ( itemElement );
         }

         // Commit rows to memory - multiprocess workaround
         mpFastDB->detach(0);
         mTableLoaded = true;
      }
   } // release mutex around database use
   
   // Attach the root node to the document
   document.InsertEndChild ( itemsElement );
   document.SaveFile ( pathName );

   return OS_SUCCESS;
}
Esempio n. 4
0
bool SaveXmlFile(const wxFileName& file, TiXmlNode* node, wxString* error /*=0*/, bool move /*=false*/)
{
	if (!node)
		return true;

	const wxString& fullPath = file.GetFullPath();

	TiXmlDocument* pDocument = node->GetDocument();

	bool exists = false;

	bool isLink = false;
	int flags = 0;
	if (CLocalFileSystem::GetFileInfo( fullPath, isLink, 0, 0, &flags ) == CLocalFileSystem::file)
	{
#ifdef __WXMSW__
		if (flags & FILE_ATTRIBUTE_HIDDEN)
			SetFileAttributes(fullPath, flags & ~FILE_ATTRIBUTE_HIDDEN);
#endif

		exists = true;
		bool res;
		if (!move)
		{
			wxLogNull null;
			res = wxCopyFile(fullPath, fullPath + _T("~"));
		}
		else
		{
			wxLogNull null;
			res = wxRenameFile(fullPath, fullPath + _T("~"));
		}
		if (!res)
		{
			const wxString msg = _("Failed to create backup copy of xml file");
			if (error)
				*error = msg;
			else
				wxMessageBoxEx(msg);
			return false;
		}
	}

	wxFFile f(fullPath, _T("w"));
	if (!f.IsOpened() || !pDocument->SaveFile(f.fp()))
	{
		wxRemoveFile(fullPath);
		if (exists)
		{
			wxLogNull null;
			wxRenameFile(fullPath + _T("~"), fullPath);
		}
		const wxString msg = _("Failed to write xml file");
		if (error)
			*error = msg;
		else
			wxMessageBoxEx(msg);
		return false;
	}

	if (exists)
		wxRemoveFile(fullPath + _T("~"));

	return true;
}
// 子类实现父类的函数
bool XMLNetworkFileLoader::saveFile()
{
    mutex.lock();

    //生成xml文件
    TiXmlDocument *doc = new TiXmlDocument();
    TiXmlDeclaration dec("1.0","gb2312","yes");
    doc->InsertEndChild(dec);
    TiXmlElement *my_root1 = new TiXmlElement("network_config");
    doc->LinkEndChild(my_root1);
    my_root1->SetAttribute("calibration_file", NetworkConfigList::getNetworkConfigListInstance()->getCalibrationFile().c_str());
    my_root1->SetAttribute("master_ip", NetworkConfigList::getNetworkConfigListInstance()->getMasterIP().toLocal8Bit().constData());
    my_root1->SetAttribute("master_backup_nasip", NetworkConfigList::getNetworkConfigListInstance()->getMasterBackupNasIP().toLocal8Bit().constData());
    my_root1->SetAttribute("db_server_ip", NetworkConfigList::getNetworkConfigListInstance()->getDBServerIP().toLocal8Bit().constData());

    // string slaveip[9]={"10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210","10.13.29.210"};
    for (int i = 0; i <= NetworkConfigList::getNetworkConfigListInstance()->listsnid()->size(); i++)
    {
        SlaveModel slavemodel = NetworkConfigList::getNetworkConfigListInstance()->listsnid()->at(0);
        TiXmlElement *my_root2 = new TiXmlElement("slave");
        my_root2->SetAttribute("slaveid", slavemodel.getIndex());
        //my_root2->SetAttribute("ip", "10.13.29.217");
        my_root2->SetAttribute("ip", slavemodel.getHostAddress().c_str());
        my_root2->SetAttribute("port",slavemodel.getPort());
        my_root2->SetAttribute("is_rt_slave", slavemodel.getIsRT());
        my_root2->SetAttribute("backup_nasip", slavemodel.getBackupNasIP().c_str());

        for (int j = 0; j <= 1; j++)
        {
            CameraPair x;
            switch (j)
            {
                case 0: x = slavemodel.box1;
                    break;
                case 1: x = slavemodel.box2;
                    break;
                default: break;
            }
            TiXmlElement *my_root3 =new TiXmlElement("camera_pair");
            my_root3->SetAttribute("index", x.boxindex);
            my_root3->SetAttribute("camera_calib_file", x.box_camera_calib_file.c_str());
            my_root3->SetAttribute("index", x.box_fenzhong_calib_file.c_str());

            {
                TiXmlElement *my_root4 =new TiXmlElement("camera_ref");
                my_root4->SetAttribute("cameraid", x.camera_ref.c_str());
                my_root4->SetAttribute("sn", x.camera_ref_sn.c_str());
                my_root4->SetAttribute("paramfile", x.camera_ref_file.c_str());
                my_root3->LinkEndChild(my_root4);
                TiXmlElement *my_root5 =new TiXmlElement("camera");
                my_root5->SetAttribute("cameraid", x.camera.c_str());
                my_root5->SetAttribute("sn", x.camera_sn.c_str());
                my_root5->SetAttribute("calibration_file", x.camera_file.c_str());
                my_root3->LinkEndChild(my_root5);
            }
            my_root2->LinkEndChild(my_root3);
        }
        my_root1->LinkEndChild(my_root2);
    }
    // 【注意!】QString转cchar不能用QString().toStdString().c_str(),否则可能会出问题
    QByteArray tempstr = getFilename().toAscii();
    bool ret = doc->SaveFile(tempstr.constData());
    mutex.unlock();
    return ret;
}
Esempio n. 6
0
// save map actors into memory
void MapInfoXmlWriter::SaveActors(const std::string &Filename, std::map<long, Actor *> * vec)
{
	TiXmlDocument doc;
 	TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "UTF8", "" );
	doc.LinkEndChild( decl );

	TiXmlElement * root = new TiXmlElement("actors");
	doc.LinkEndChild( root );

	std::map<long, Actor *>::const_iterator it = vec->begin();
	std::map<long, Actor *>::const_iterator end = vec->end();
	for(; it != end; ++it)
	{
		TiXmlElement * act = new TiXmlElement( "actor" );
		root->LinkEndChild(act);
		act->SetAttribute("id", it->second->GetId());
		act->SetAttribute("type", it->second->GetType());
		act->SetDoubleAttribute("posX", it->second->GetPosX());
		act->SetDoubleAttribute("posY", it->second->GetPosY());
		act->SetDoubleAttribute("posZ", it->second->GetPosZ());
		act->SetDoubleAttribute("sizeX", it->second->GetSizeX());
		act->SetDoubleAttribute("sizeY", it->second->GetSizeY());
		act->SetDoubleAttribute("sizeZ", it->second->GetSizeZ());
		act->SetDoubleAttribute("offsetsizeY", it->second->GetOffsetSizeY());
		act->SetDoubleAttribute("rotation", it->second->GetRotation());
		act->SetAttribute("passable", it->second->IsPassable());
		act->SetAttribute("depthmask", it->second->IsDepthMask());
		act->SetAttribute("movable", it->second->IsMovable());
		act->SetAttribute("outputsignal", it->second->GetSignal());
		act->SetAttribute("attachedsound", it->second->GetAttachedSound());
		act->SetAttribute("collidable", it->second->GetCollidable());
		act->SetAttribute("actif", it->second->GetActif());
		act->SetAttribute("allowfreemove", it->second->GetAllowFreeMove());

		{
			std::vector<long> vect = it->second->GetTargets();
			std::stringstream str;
			if(vect.size() > 0)
				str<<vect[0];

			for(size_t i=1; i<vect.size(); ++i)
				str<<","<<vect[i];

			act->SetAttribute("signaltargets", str.str());
		}

		if(it->second->GetRenderer() != NULL)
		{
			act->SetAttribute("renderertype", it->second->GetRendererType());

			std::vector<long> vect = it->second->GetRendererTarget();
			std::stringstream str;
			if(vect.size() > 0)
				str<<vect[0];

			for(size_t i=1; i<vect.size(); ++i)
				str<<","<<vect[i];
			act->SetAttribute("renderertarget", str.str());
		}


		switch(it->second->GetType())
		{
			case 1:	//text actor class
			{
				{
					TextActor * tmpa = static_cast<TextActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetAttribute("textid", tmpa->GetTextId());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;

			case 2:	//ladder actor class
			{
				{
					LadderActor * tmpa = static_cast<LadderActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetDoubleAttribute("deltaX", tmpa->GetDX());
					act->SetDoubleAttribute("deltaY", tmpa->GetDY());
					act->SetDoubleAttribute("deltaZ", tmpa->GetDZ());
					act->SetAttribute("direction", tmpa->GetDir());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;

			case 3:	//exit actor class
			{
				{
					ExitActor * tmpa = static_cast<ExitActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetDoubleAttribute("deltaX", tmpa->GetDX());
					act->SetDoubleAttribute("deltaY", tmpa->GetDY());
					act->SetDoubleAttribute("deltaZ", tmpa->GetDZ());
					act->SetAttribute("direction", tmpa->GetDir());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;

			case 4:	//door actor class
			{
				{
					DoorActor * tmpa = static_cast<DoorActor *>(it->second);
					act->SetDoubleAttribute("zoneSizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zoneSizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zoneSizeZ", tmpa->GetZoneZ());
					act->SetAttribute("locked", tmpa->GetLocked());
					act->SetAttribute("keyid", tmpa->GetKeyId());
					act->SetAttribute("hide", tmpa->GetHide());
					act->SetAttribute("destroykey", tmpa->GetDesKey());

					act->SetDoubleAttribute("OpenTransX", tmpa->GetOpenTransX());
					act->SetDoubleAttribute("OpenTransY", tmpa->GetOpenTransY());
					act->SetDoubleAttribute("OpenTransZ", tmpa->GetOpenTransZ());
					act->SetDoubleAttribute("OpenTransSpeedX", tmpa->GetOpenTransSpeedX());
					act->SetDoubleAttribute("OpenTransSpeedY", tmpa->GetOpenTransSpeedY());
					act->SetDoubleAttribute("OpenTransSpeedZ", tmpa->GetOpenTransSpeedZ());
				}
			}
			break;

			case 5:	//container actor class
			{
				{
					ContainerActor * tmpa = static_cast<ContainerActor *>(it->second);
					act->SetDoubleAttribute("zonesizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zonesizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zonesizeZ", tmpa->GetZoneZ());
					act->SetAttribute("activationtype", tmpa->GetActivationType());

					const std::vector<ItemGroup> & lootlist = tmpa->GetLootList();
					for(size_t cci=0; cci<lootlist.size(); ++cci)
					{
						TiXmlElement * grit = new TiXmlElement( "itemgroup" );
						grit->SetDoubleAttribute("respawnTimeInMs", lootlist[cci].RespawningTime);
						act->LinkEndChild(grit);

						for(size_t ccj=0; ccj<lootlist[cci].groupelements.size(); ++ccj)
						{
							TiXmlElement * grelem = new TiXmlElement( "item" );
							grelem->SetDoubleAttribute("id", lootlist[cci].groupelements[ccj].id);
							grelem->SetDoubleAttribute("number", lootlist[cci].groupelements[ccj].number);
							grelem->SetDoubleAttribute("probability", lootlist[cci].groupelements[ccj].probability);
							grit->LinkEndChild(grelem);
						}
					}
				}
			}
			break;

			case 6:	//up exit actor class
			{
				{
					UpExitActor * tmpa = static_cast<UpExitActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetAttribute("direction", tmpa->GetDir());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;

			case 7:	//switch actor class
			{
				{
					SwitchActor * tmpa = static_cast<SwitchActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;

			case 8:	//area switch actor class
			{
				{
					AreaSwitch * tmpa = static_cast<AreaSwitch *>(it->second);
					act->SetDoubleAttribute("zonesizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zonesizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zonesizeZ", tmpa->GetZoneZ());
					act->SetAttribute("QuestToTriggerEnd", tmpa->GetQuestToTriggerEnd());
				}
			}
			break;

			case 9:	//floor switch actor class
			{
				{
					FloorSwitch * tmpa = static_cast<FloorSwitch *>(it->second);
					act->SetDoubleAttribute("zonesizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zonesizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zonesizeZ", tmpa->GetZoneZ());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;


			case 10:	//lift actor class
			{
				{
					ScriptableActor * tmpa = static_cast<ScriptableActor *>(it->second);
					act->SetAttribute("autoattach", tmpa->GetAutoAttach());		
					
					const std::vector<PlayerScriptPart> & scriptsV = tmpa->GetScripts();
					if(scriptsV.size() > 0)
					{
						TiXmlElement * scripts = new TiXmlElement( "scripts" );
						act->LinkEndChild(scripts);

						for(size_t cci=0; cci<scriptsV.size(); ++cci)
						{
							TiXmlElement * script = new TiXmlElement( "script" );
							scripts->LinkEndChild(script);

							script->SetAttribute("type", scriptsV[cci].Type);
							script->SetDoubleAttribute("ValueA", scriptsV[cci].ValueA);
							script->SetDoubleAttribute("ValueB", scriptsV[cci].ValueB);
							script->SetDoubleAttribute("ValueC", scriptsV[cci].ValueC);
							script->SetDoubleAttribute("Speed", scriptsV[cci].Speed);
							script->SetAttribute("Sound", scriptsV[cci].Sound);
							script->SetAttribute("SoundNum", scriptsV[cci].SoundNum);
							script->SetAttribute("Animation", scriptsV[cci].Animation);
							script->SetAttribute("Flag", scriptsV[cci].Flag);
						}
					}
				}
			}
			break;

			case 11:	//hurt area class
			{
				{
					HurtArea * tmpa = static_cast<HurtArea *>(it->second);
					act->SetDoubleAttribute("zonesizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zonesizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zonesizeZ", tmpa->GetZoneZ());
					act->SetDoubleAttribute("lifetaken", tmpa->GetLifeTaken());
				}
			}
			break;


			case 12:	//NPC actor class
			{
				{
					NPCActor * tmpa = static_cast<NPCActor *>(it->second);
					act->SetAttribute("NPCType", tmpa->GetNPCType());
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetAttribute("Name", tmpa->GetName());
					
					const std::vector<PlayerScriptPart> & scriptsV = tmpa->GetScripts();
					if(scriptsV.size() > 0)
					{
						TiXmlElement * scripts = new TiXmlElement( "scripts" );
						act->LinkEndChild(scripts);

						for(size_t cci=0; cci<scriptsV.size(); ++cci)
						{
							TiXmlElement * script = new TiXmlElement( "script" );
							scripts->LinkEndChild(script);

							script->SetAttribute("type", scriptsV[cci].Type);
							script->SetDoubleAttribute("ValueA", scriptsV[cci].ValueA);
							script->SetDoubleAttribute("ValueB", scriptsV[cci].ValueB);
							script->SetDoubleAttribute("ValueC", scriptsV[cci].ValueC);
							script->SetDoubleAttribute("Speed", scriptsV[cci].Speed);
							script->SetAttribute("Sound", scriptsV[cci].Sound);
							script->SetAttribute("SoundNum", scriptsV[cci].SoundNum);
							script->SetAttribute("Animation", scriptsV[cci].Animation);
							script->SetAttribute("Flag", scriptsV[cci].Flag);
						}
					}
				}
			}
			break;


			case 13:	//scripted zone actor
			{
				{
					ScriptedZoneActor * tmpa = static_cast<ScriptedZoneActor *>(it->second);
					act->SetDoubleAttribute("zonesizeX", tmpa->GetZoneX());
					act->SetDoubleAttribute("zonesizeY", tmpa->GetZoneY());
					act->SetDoubleAttribute("zonesizeZ", tmpa->GetZoneZ());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
					act->SetAttribute("neededitem", tmpa->GetNeededItemId());
					act->SetAttribute("destroyitem", tmpa->GetDesItem());
					act->SetAttribute("abortedmessage", tmpa->GetAbortedMessage());

					TiXmlElement * scripts = new TiXmlElement( "scripts" );
					act->LinkEndChild(scripts);
					const std::vector<PlayerScriptPart> & scriptsV = tmpa->GetScripts();
					for(size_t cci=0; cci<scriptsV.size(); ++cci)
					{
						TiXmlElement * script = new TiXmlElement( "script" );
						scripts->LinkEndChild(script);

						script->SetAttribute("type", scriptsV[cci].Type);
						script->SetDoubleAttribute("ValueA", scriptsV[cci].ValueA);
						script->SetDoubleAttribute("ValueB", scriptsV[cci].ValueB);
						script->SetDoubleAttribute("ValueC", scriptsV[cci].ValueC);
						script->SetDoubleAttribute("Speed", scriptsV[cci].Speed);
						script->SetAttribute("Sound", scriptsV[cci].Sound);
						script->SetAttribute("SoundNum", scriptsV[cci].SoundNum);
						script->SetAttribute("Animation", scriptsV[cci].Animation);
						script->SetAttribute("Flag", scriptsV[cci].Flag);

						script->SetAttribute("newMap", scriptsV[cci].NewMap);
						script->SetAttribute("spawning", scriptsV[cci].Spawning);
					}
				}
			}
			break;

			case 14:	//mailbox class
			{
				{
					MailboxActor * tmpa = static_cast<MailboxActor *>(it->second);
					act->SetDoubleAttribute("activationdistance", tmpa->GetActivationDistance());
					act->SetAttribute("activationtype", tmpa->GetActivationType());
				}
			}
			break;
		}
	}


	doc.SaveFile(Filename);
}
Esempio n. 7
0
// save all sprites info
void MapInfoXmlWriter::SaveSprites(const std::string &Filename, std::map<long, SpriteInfo> *vec)
{
	TiXmlDocument doc;
 	TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "UTF8", "" );
	doc.LinkEndChild( decl );

	TiXmlElement * root = new TiXmlElement("sprites");
	doc.LinkEndChild( root );

	std::map<long, SpriteInfo>::const_iterator it = vec->begin();
	std::map<long, SpriteInfo>::const_iterator end = vec->end();
	for(; it != end; ++it)
	{
		TiXmlElement * act = new TiXmlElement( "sprite" );
		root->LinkEndChild(act);
		act->SetAttribute("id", it->first);
		act->SetAttribute("filename", it->second.filename);

		std::vector<QuadImageInfo>::const_iterator itq = it->second.quadsInfo.begin();
		std::vector<QuadImageInfo>::const_iterator endq = it->second.quadsInfo.end();
		for(; itq != endq; ++itq)
		{
			TiXmlElement * quad = new TiXmlElement( "textpart" );
			act->LinkEndChild(quad);
			quad->SetAttribute("UseFullImage", itq->UseFullImage);

			quad->SetDoubleAttribute("BottomLeftCornerX", itq->BottomLeftCornerX);
			quad->SetDoubleAttribute("BottomLeftCornerY", itq->BottomLeftCornerY);
			quad->SetDoubleAttribute("BottomLeftCornerZ", itq->BottomLeftCornerZ);
			quad->SetDoubleAttribute("TopRightCornerX", itq->TopRightCornerX);
			quad->SetDoubleAttribute("TopRightCornerY", itq->TopRightCornerY);
			quad->SetDoubleAttribute("TopRightCornerZ", itq->TopRightCornerZ);

			quad->SetDoubleAttribute("BottomRightCornerX", itq->BottomRightCornerX);
			quad->SetDoubleAttribute("BottomRightCornerY", itq->BottomRightCornerY);
			quad->SetDoubleAttribute("BottomRightCornerZ", itq->BottomRightCornerZ);
			quad->SetDoubleAttribute("TopLeftCornerX", itq->TopLeftCornerX);
			quad->SetDoubleAttribute("TopLeftCornerY", itq->TopLeftCornerY);
			quad->SetDoubleAttribute("TopLeftCornerZ", itq->TopLeftCornerZ);

			//quad->SetDoubleAttribute("BottomRightCornerX",itq->TopRightCornerX);//itq->BottomRightCornerX);
			//quad->SetDoubleAttribute("BottomRightCornerY",itq->BottomLeftCornerY);//itq->BottomRightCornerY);
			//quad->SetDoubleAttribute("BottomRightCornerZ",itq->TopRightCornerZ);//itq->BottomRightCornerZ);
			//quad->SetDoubleAttribute("TopLeftCornerX",itq->BottomLeftCornerX);//itq->TopLeftCornerX);
			//quad->SetDoubleAttribute("TopLeftCornerY",itq->TopRightCornerY);//itq->TopLeftCornerY);
			//quad->SetDoubleAttribute("TopLeftCornerZ",itq->BottomLeftCornerZ);//itq->TopLeftCornerZ);

			quad->SetAttribute("BottomLeftTextcoordX", itq->BottomLeftTextcoordX);
			quad->SetAttribute("BottomLeftTextcoordY", itq->BottomLeftTextcoordY);

			quad->SetAttribute("BottomRightTextcoordX", itq->BottomRightTextcoordX);
			quad->SetAttribute("BottomRightTextcoordY", itq->BottomRightTextcoordY);

			quad->SetAttribute("TopLeftTextcoordX", itq->TopLeftTextcoordX);
			quad->SetAttribute("TopLeftTextcoordY", itq->TopLeftTextcoordY);

			quad->SetAttribute("TopRightTextcoordX", itq->TopRightTextcoordX);
			quad->SetAttribute("TopRightTextcoordY", itq->TopRightTextcoordY);
		}
	}


	doc.SaveFile(Filename);
}
Esempio n. 8
0
OsStatus
UserLocationDB::store()
{
    // Critical Section here
    OsLock lock( sLockMutex );
    OsStatus result = OS_SUCCESS;

    if ( m_pFastDB != NULL )
    {
        UtlString fileName = mDatabaseName + ".xml";
        UtlString pathName = SipXecsService::Path(SipXecsService::DatabaseDirType,
                                                  fileName.data());

        // Create an empty document
        TiXmlDocument document;

        // Create a hard coded standalone declaration section
        document.Parse ("<?xml version=\"1.0\" standalone=\"yes\"?>");

        // Create the root node container
        TiXmlElement itemsElement ( "items" );
        itemsElement.SetAttribute( "type", sType.data() );
        itemsElement.SetAttribute( "xmlns", sXmlNamespace.data() );

        // Thread Local Storage
        m_pFastDB->attach();

        // Search our memory for rows
        dbCursor< UserLocationRow > cursor;

        // Select everything in the IMDB and add as item elements if present
        if ( cursor.select() > 0 )
        {
            // metadata contains column names
            dbTableDescriptor* pTableMetaData = &UserLocationRow::dbDescriptor;

            do {
                // Create an item container
                TiXmlElement itemElement ("item");

                byte* base = (byte*)cursor.get();

                // Add the column name value pairs
                for ( dbFieldDescriptor* fd = pTableMetaData->getFirstField();
                      fd != NULL; fd = fd->nextField ) 
                {
                    // if the column name does not contain the 
                    // np_prefix we must_presist it
                    if ( strstr( fd->name, "np_" ) == NULL )
                    {
                        // Create the a column element named after the IMDB column name
                        TiXmlElement element (fd->name );

                        // See if the IMDB has the predefined SPECIAL_NULL_VALUE
                        UtlString textValue;
                        SIPDBManager::getFieldValue(base, fd, textValue);

                        // If the value is not null append a text child element
                        if ( textValue != SPECIAL_IMDB_NULL_VALUE ) 
                        {
                            // Text type assumed here... @todo change this
                            TiXmlText value ( textValue.data() );
                            // Store the column value in the element making this
                            // <colname>coltextvalue</colname>
                            element.InsertEndChild  ( value );
                        }

                        // Store this in the item tag as follows
                        // <item>
                        // .. <col1name>col1textvalue</col1name>
                        // .. <col2name>col2textvalue</col2name>
                        // .... etc
                        itemElement.InsertEndChild  ( element );
                    }
                }
                // add the line to the element
                itemsElement.InsertEndChild ( itemElement );
            } while ( cursor.next() );
        }  
        // Attach the root node to the document
        document.InsertEndChild ( itemsElement );
        document.SaveFile ( pathName );
        // Commit rows to memory - multiprocess workaround
        m_pFastDB->detach(0);
        mTableLoaded = true;
    } else
    {
        result = OS_FAILED;
    }
    return result;
}
Esempio n. 9
0
void ConfigFile::updateConfig(ConfigState myConfigState)
{

	boost::recursive_mutex::scoped_lock lock(m_configMutex);

	size_t i;

	if(myConfigState == NONEXISTING) {

		//Create a new ConfigFile!
		TiXmlDocument doc;
		TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "");
		doc.LinkEndChild( decl );

		TiXmlElement * root = new TiXmlElement( "PokerTH" );
		doc.LinkEndChild( root );

		TiXmlElement * config;
		config = new TiXmlElement( "Configuration" );
		root->LinkEndChild( config );

		for (i=0; i<configList.size(); i++) {
			TiXmlElement *tmpElement = new TiXmlElement(configList[i].name);
			config->LinkEndChild( tmpElement );
			tmpElement->SetAttribute("value", myQtToolsInterface->stringToUtf8(configList[i].defaultValue));

			if(configList[i].type == CONFIG_TYPE_INT_LIST || configBufferList[i].type == CONFIG_TYPE_STRING_LIST) {

				tmpElement->SetAttribute("type", "list");
				list<string> tempList = configList[i].defaultListValue;
				list<string>::iterator it;
				for(it = tempList.begin(); it != tempList.end(); ++it) {

					TiXmlElement *tmpSubElement = new TiXmlElement(configList[i].defaultValue);
					tmpElement->LinkEndChild( tmpSubElement );
					tmpSubElement->SetAttribute("value", *it);
				}
			}
		}
		doc.SaveFile( configFileName );
	}

	if(myConfigState == OLD) {

		TiXmlDocument oldDoc(configFileName);

		//load the old one
		if(oldDoc.LoadFile()) {

			string tempString1("");
			string tempString2("");

			TiXmlDocument newDoc;

			//Create the new one
			TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "");
			newDoc.LinkEndChild( decl );

			TiXmlElement * root = new TiXmlElement( "PokerTH" );
			newDoc.LinkEndChild( root );

			TiXmlElement * config;
			config = new TiXmlElement( "Configuration" );
			root->LinkEndChild( config );

			//change configRev and AppDataPath
			std::list<std::string> noUpdateElemtsList;

			TiXmlElement * confElement0 = new TiXmlElement( "ConfigRevision" );
			config->LinkEndChild( confElement0 );
			confElement0->SetAttribute("value", configRev);
			noUpdateElemtsList.push_back("ConfigRevision");

			TiXmlElement * confElement1 = new TiXmlElement( "AppDataDir" );
			config->LinkEndChild( confElement1 );
			confElement1->SetAttribute("value", myQtToolsInterface->stringToUtf8(myQtToolsInterface->getDataPathStdString(myArgv0)));
			noUpdateElemtsList.push_back("AppDataDir");

			///////// VERSION HACK SECTION ///////////////////////
			//this is the right place for special version depending config hacks:
			//0.9.1 - log interval needs to be set to 1 instead of 0
			if (configRev >= 95 && configRev <= 98) { // this means 0.9.1 or 0.9.2 or 1.0
				TiXmlElement * confElement2 = new TiXmlElement( "LogInterval" );
				config->LinkEndChild( confElement2 );
				confElement2->SetAttribute("value", 1);
				noUpdateElemtsList.push_back("LogInterval");
			}

			if (configRev == 98) { // this means 1.0
				TiXmlElement * confElement3 = new TiXmlElement( "CurrentCardDeckStyle" );
				config->LinkEndChild( confElement3 );
				confElement3->SetAttribute("value", "");
				noUpdateElemtsList.push_back("CurrentCardDeckStyle");
			}
			///////// VERSION HACK SECTION ///////////////////////

			TiXmlHandle oldDocHandle( &oldDoc );

			for (i=0; i<configList.size(); i++) {

				TiXmlElement* oldConf = oldDocHandle.FirstChild( "PokerTH" ).FirstChild( "Configuration" ).FirstChild( configList[i].name ).ToElement();

				if ( oldConf ) { // if element is already there --> take over the saved values

					// dont update ConfigRevision and AppDataDir AND possible hacked Config-Elements becaus it was already set ^^
					if(count(noUpdateElemtsList.begin(), noUpdateElemtsList.end(), configList[i].name) == 0) {

						TiXmlElement *tmpElement = new TiXmlElement(configList[i].name);
						config->LinkEndChild( tmpElement );

						const char *tmpStr1 = oldConf->Attribute("value");
						if (tmpStr1) tempString1 = tmpStr1;
						tmpElement->SetAttribute("value", tempString1);

						//for lists copy elements
						const char *tmpStr2 = oldConf->Attribute("type");
						if (tmpStr2) {
							tempString2 = tmpStr2;
							if(tempString2 == "list") {

								list<string> tempStringList2;

								TiXmlElement* oldConfList = oldDocHandle.FirstChild( "PokerTH" ).FirstChild( "Configuration" ).FirstChild( configList[i].name ).FirstChild().ToElement();

								for( ; oldConfList; oldConfList=oldConfList->NextSiblingElement()) {
									tempStringList2.push_back(oldConfList->Attribute("value"));
								}

								tmpElement->SetAttribute("type", "list");
								list<string> tempList = tempStringList2;
								list<string>::iterator it;
								for(it = tempList.begin(); it != tempList.end(); ++it) {

									TiXmlElement *tmpSubElement = new TiXmlElement(tempString1);
									tmpElement->LinkEndChild( tmpSubElement );
									tmpSubElement->SetAttribute("value", *it);
								}
							}
						}
					}
				} else {
					// if element is not there --> set it with defaultValue
					TiXmlElement *tmpElement = new TiXmlElement(configList[i].name);
					config->LinkEndChild( tmpElement );
					tmpElement->SetAttribute("value", myQtToolsInterface->stringToUtf8(configList[i].defaultValue));

					if(configList[i].type == CONFIG_TYPE_INT_LIST || configBufferList[i].type == CONFIG_TYPE_STRING_LIST) {

						tmpElement->SetAttribute("type", "list");
						list<string> tempList = configList[i].defaultListValue;
						list<string>::iterator it;
						for(it = tempList.begin(); it != tempList.end(); ++it) {

							TiXmlElement *tmpSubElement = new TiXmlElement(configList[i].defaultValue);
							tmpElement->LinkEndChild( tmpSubElement );
							tmpSubElement->SetAttribute("value", *it);
						}
					}
				}
			}
			newDoc.SaveFile( configFileName );
		} else {
			LOG_ERROR("Cannot update config file: Unable to load configuration.");
		}


	}
}
Esempio n. 10
0
BOOL CStubbornFiles::_SaveToFile()
{
    BOOL retval = FALSE;
    CDataFileLoader dataLoader;
    TiXmlDocument xmlDoc;
    TiXmlElement* pXmlItem = NULL;
    TiXmlElement* pXmlTime = NULL;
    TiXmlElement* pXmlItems = NULL;
    TiXmlText* pXmlText = NULL;
    TCHAR szConfPathTemp[MAX_PATH] = { 0 };
    TCHAR szConfPath[MAX_PATH] = { 0 };
    TiXmlDeclaration *pXmlDecl = new TiXmlDeclaration("1.0", "utf-8", "yes");
    POSITION pos = NULL;
    CStringW strPathUtf16;
    CStringA strPathUtf8;
    CString strXmlUtf16;
    CStringA strXmlAnsi;
    LARGE_INTEGER ver;
    BOOL fRetCode;
    FILE* pFile = NULL;
    SYSTEMTIME sysTime = { 0 };
    CStringA strTime;

    GetModuleFileName(NULL, szConfPath, MAX_PATH);
    PathRemoveFileSpec(szConfPath);
    _tcscpy_s(szConfPathTemp, MAX_PATH, szConfPath);
    PathAppend(szConfPathTemp, _T("data\\~strash.dat"));
    PathAppend(szConfPath, _T("data\\strash.dat"));

    xmlDoc.LinkEndChild(pXmlDecl);

    pXmlItems = new TiXmlElement("items");
    if (!pXmlItems)
        goto clean0;

    pos = m_fileList.GetHeadPosition();
    while (pos)
    {
        strPathUtf16 = m_fileList.GetNext(pos);
        strPathUtf8 = KUTF16_To_UTF8(strPathUtf16);

        pXmlText = new TiXmlText(strPathUtf8);
        if (!pXmlText)
            goto clean0;

        pXmlItem = new TiXmlElement("item");
        if (!pXmlItem)
            goto clean0;

        pXmlItem->LinkEndChild(pXmlText);
        pXmlItems->LinkEndChild(pXmlItem);
    }
    xmlDoc.LinkEndChild(pXmlItems);

    GetLocalTime(&sysTime);
    strTime.Format("%d.%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay);
    pXmlTime = new TiXmlElement("time");
    if (!pXmlTime)
        goto clean0;

    pXmlText = new TiXmlText(strTime);
    if (!pXmlText)
        goto clean0;

    pXmlTime->LinkEndChild(pXmlText);

    xmlDoc.LinkEndChild(pXmlTime);

    if (!xmlDoc.SaveFile(KUTF16_To_ANSI(szConfPathTemp)))
        goto clean0;

    pFile = _wfopen(szConfPathTemp, L"r");
    if (!pFile)
        goto clean0;

    {
        fseek(pFile, 0, SEEK_END);
        int nSize = ftell(pFile);
        fseek(pFile, 0, SEEK_SET);
        char* pXml = strXmlAnsi.GetBuffer(nSize + 1);
        memset(pXml, 0, nSize + 1);
        fread(pXml, 1, nSize, pFile);
        fclose(pFile);
        pFile = NULL;
        strXmlAnsi.ReleaseBuffer();
        strXmlUtf16 = KANSI_TO_UTF16(strXmlAnsi);
    }

    {
        ver.QuadPart = 1;
        fRetCode = dataLoader.Save(
                       szConfPath, BkDatLibEncodeParam2(enumLibTypePlugine, ver, strXmlUtf16, 1).GetEncodeParam()
                   );
    }

    if (!fRetCode)
        goto clean0;

    retval = TRUE;

clean0:
    if (pFile)
    {
        fclose(pFile);
        pFile = NULL;
    }

    if (GetFileAttributes(szConfPathTemp) != INVALID_FILE_ATTRIBUTES)
    {
        ::DeleteFile(szConfPathTemp);
    }

    return retval;
}
Esempio n. 11
0
void Dlg::Calculate( wxCommandEvent& event, bool write_file, int Pattern  ){
   if(OpenXML()){
  
	bool error_occured=false;
   // double dist, fwdAz, revAz;


    double lat1,lon1;
   // if(!this->m_Lat1->GetValue().ToDouble(&lat1)){ lat1=0.0;}
   // if(!this->m_Lon1->GetValue().ToDouble(&lon1)){ lon1=0.0;}
	int num_hours;

	num_hours = this->m_Nship->GetSelection();
	
	// wxString str_countPts =  wxString::Format(wxT("%d"), (int)num_hours);
    // wxMessageBox(str_countPts,_T("count_hours"));

	lat1 = 0.0;
	lon1 = 0.0;
    //if (error_occured) wxMessageBox(_T("error in conversion of input coordinates"));

    //error_occured=false;
    wxString s;
    if (write_file){
        wxFileDialog dlg(this, _("Export DR Positions in GPX file as"), wxEmptyString, wxEmptyString, _T("GPX files (*.gpx)|*.gpx|All files (*.*)|*.*"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT);
        if (dlg.ShowModal() == wxID_CANCEL){
            error_occured=true;     // the user changed idea...
		    return;
		}
			
		//dlg.ShowModal();
        s=dlg.GetPath();
        //  std::cout<<s<< std::endl;
        if (dlg.GetPath() == wxEmptyString){ error_occured=true; if (dbg) printf("Empty Path\n");}
    }

    //Validate input ranges
    if (!error_occured){
        if (std::abs(lat1)>90){ error_occured=true; }
        if (std::abs(lon1)>180){ error_occured=true; }
        if (error_occured) wxMessageBox(_("error in input range validation"));
    }

    //Start GPX
    TiXmlDocument doc;
    TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "utf-8", "" );
    doc.LinkEndChild( decl );
    TiXmlElement * root = new TiXmlElement( "gpx" );
    TiXmlElement * Route = new TiXmlElement( "rte" );
    TiXmlElement * RouteName = new TiXmlElement( "name" );
    TiXmlText * text4 = new TiXmlText( this->m_Route->GetValue().ToUTF8() );

    if (write_file){
        doc.LinkEndChild( root );
        root->SetAttribute("version", "0.1");
        root->SetAttribute("creator", "DR_pi by Rasbats");
        root->SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root->SetAttribute("xmlns:gpxx","http://www.garmin.com/xmlschemas/GpxExtensions/v3" );
        root->SetAttribute("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd");
        root->SetAttribute("xmlns:opencpn","http://www.opencpn.org");
        Route->LinkEndChild( RouteName );
        RouteName->LinkEndChild( text4 );


        TiXmlElement * Extensions = new TiXmlElement( "extensions" );

        TiXmlElement * StartN = new TiXmlElement( "opencpn:start" );
        TiXmlText * text5 = new TiXmlText( "Start" );
        Extensions->LinkEndChild( StartN );
        StartN->LinkEndChild( text5 );

        TiXmlElement * EndN = new TiXmlElement( "opencpn:end" );
        TiXmlText * text6 = new TiXmlText( "End" );
        Extensions->LinkEndChild( EndN );
        EndN->LinkEndChild( text6 );

        Route->LinkEndChild( Extensions );
    }

    switch ( Pattern ) {
    case 1:
        {		
        if (dbg) cout<<"DR Calculation\n";      
        double speed=0;
		int    interval=1;
        		
		if(!this->m_Speed_PS->GetValue().ToDouble(&speed)){ speed=5.0;} // 5 kts default speed
		interval = m_Nship->GetCurrentSelection();//S=1

		speed = speed*interval;

        int n=0;
        //int multiplier=1;
        double lati, loni;
        double latN[100], lonN[100];
		double latF, lonF;
		
		Position my_point;		
       
		double value, value1;
		
		for(std::vector<Position>::iterator it = my_positions.begin();  it != my_positions.end(); it++){
       
			if(!(*it).lat.ToDouble(&value)){ /* error! */ }
				lati = value;
			if(!(*it).lon.ToDouble(&value1)){ /* error! */ }
				loni = value1;

		latN[n] = lati;
		lonN[n] = loni;

		n++;//0,1,2,3
		}
		
		my_positions.clear();

		n--;//n = 2,  0,1,2
		int routepoints = n+1; //3
		
		
		double myDist, myBrng, myDistForBrng;
		int count_pts;
		double remaining_dist, myLast, route_dist;
		remaining_dist = 0;
		route_dist= 0;
		myLast = 0;
		myDistForBrng =0;
		double total_dist = 0;
		int i,c;
		bool skip = false;
		bool inloop = false;
		bool setF = false;

		latF = latN[0];
		lonF = lonN[0];
		// Start of new logic
		//
		//
		for (i=0; i<n; i++){			

			// save the routepoint
			my_point.lat = wxString::Format(wxT("%f"),latN[i]);
			my_point.lon = wxString::Format(wxT("%f"),lonN[i]);
			my_point.routepoint = 1;
			my_point.wpt_num =  wxString::Format(wxT("%d"),(int)i);
			my_points.push_back(my_point);	
            			
			if (i==0){ // First F is a routepoint
				latF = latN[i];
				lonF = lonN[i];
				}

			distRhumb(latF, lonF, latN[i+1], lonN[i+1], &myDist, &myBrng);						
			total_dist = total_dist + myDist;

				if (total_dist > speed){	
						// DR point after route point
				        //
						route_dist = total_dist - myDist; //305						
						remaining_dist = speed - route_dist;
												
						distRhumb(latN[i], lonN[i], latN[i+1], lonN[i+1], &myLast, &myBrng);		
						destRhumb(latN[i], lonN[i], myBrng,remaining_dist, &lati, &loni);

						// Put in DR after many route points
						my_point.lat = wxString::Format(wxT("%f"),lati);
						my_point.lon = wxString::Format(wxT("%f"),loni);
						my_point.routepoint = 0;			
						my_points.push_back(my_point);
			            
						latF = lati;
						lonF = loni;

						total_dist = 0;
			    
						// 
				        // End of  speed
					
				distRhumb(latF, lonF, latN[i+1], lonN[i+1], &myDistForBrng, &myBrng);	
				if (myDistForBrng > speed){
													
						// put in the DR positions
						//
						count_pts = (int)floor(myDistForBrng/speed);
						//
						remaining_dist = myDistForBrng - (count_pts*speed);
						//
						distRhumb(latF, lonF, latN[i+1], lonN[i+1], &myDistForBrng, &myBrng);	

						for (c = 1; c <= count_pts ; c++){
								    					
							destRhumb(latF, lonF, myBrng,speed*c, &lati, &loni);					
							// print mid points
							my_point.lat = wxString::Format(wxT("%f"),lati);
							my_point.lon = wxString::Format(wxT("%f"),loni);
							my_point.routepoint = 0;
							my_points.push_back(my_point);
							//	End of prints					
							}													
						
						latF = lati;
						lonF = loni;
						
						total_dist = 0; 
						//
						//
						// All the DR positions inserted
						}
			
				if (total_dist == 0){
					distRhumb(latF, lonF, latN[i+1], lonN[i+1], &myDistForBrng, &myBrng);	
					total_dist = myDistForBrng;
					latF = latN[i+1];
					lonF = lonN[i+1];
					}
			
			}															
			else{
				//
				latF = latN[i+1];
				lonF = lonN[i+1];
				//
				//
				//
				//
			}   //			

	}
		// End of new logic
		// print the last routepoint
		my_point.lat = wxString::Format(wxT("%f"),latN[i]);
		my_point.lon = wxString::Format(wxT("%f"),lonN[i]);
		my_point.routepoint = 1;
		my_point.wpt_num =  wxString::Format(wxT("%d"),(int)i);
		my_points.push_back(my_point);
		//


		for(std::vector<Position>::iterator itOut = my_points.begin();  itOut != my_points.end(); itOut++){
			//wxMessageBox((*it).lat, _T("*it.lat"));
		
        double value, value1;
		if(!(*itOut).lat.ToDouble(&value)){ /* error! */ }
			lati = value;
		if(!(*itOut).lon.ToDouble(&value1)){ /* error! */ }
			loni = value1;
		
		if ((*itOut).routepoint == 1){
			if (write_file){Addpoint(Route, wxString::Format(wxT("%f"),lati), wxString::Format(wxT("%f"),loni), (*itOut).wpt_num ,_T("diamond"),_T("WPT"));}
		}
		else{
			if ((*itOut).routepoint == 0){
				if (write_file){Addpoint(Route, wxString::Format(wxT("%f"),lati), wxString::Format(wxT("%f"),loni), _T("DR") ,_T("square"),_T("WPT"));}			
			}
		}
        
		}
		
		my_points.clear();		
        break;
		
		}

    
      default:
      {            // Note the colon, not a semicolon
        cout<<"Error, bad input, quitting\n";
        break;
      }
    }

       if (write_file){
            root->LinkEndChild( Route );
            // check if string ends with .gpx or .GPX
            if (!wxFileExists(s)){
                 s = s + _T(".gpx");
            }
            wxCharBuffer buffer=s.ToUTF8();
            if (dbg) std::cout<< buffer.data()<<std::endl;
            doc.SaveFile( buffer.data() );}
    //} //end of if no error occured

    if (error_occured==true)  {
        wxLogMessage(_("Error in calculation. Please check input!") );
        wxMessageBox(_("Error in calculation. Please check input!") );
    }
  }
}
Esempio n. 12
0
void CCreateDefmaDlg::OnSave()
{
	BOOL queryRet = TRUE;
	UpdateData(TRUE); //Interface -> Variable

	if(m_tag.IsEmpty()){
		AfxMessageBox("请输入标签描述\n");
		return;
	}

	CString fileName,folderName,fullPathName;
	if(m_bNewFile) {
		//(1) Add new record to database
		DefMADataSet *pNewSet = new DefMADataSet();
		pNewSet->Open();
		pNewSet->AddNew();
		pNewSet->m_Mode = this->m_thickMode;
		pNewSet->m_Tag  = this->m_tag;
		pNewSet->Update();
		Sleep(200);

		//(2) Query last 
		pNewSet->m_strSort=_T("ID DESC");
		if(!pNewSet->Requery()){
			AfxMessageBox(_T("CCreateDefmaDlg::OnSave(), Requery failed!"));
			queryRet = FALSE;
		}
		int index = pNewSet->m_ID; // default new file name
		pNewSet->Close();
		delete pNewSet;
		
		if(queryRet){
			//(3) Save defMA to 00xx.xma
			SaveDataToPtr();
			fileName.Format("%04d",index);
			fullPathName = ((CTMeterApp*)AfxGetApp())->m_AppWorkDirectory + "\\DefineMA\\" + fileName + ".xma";
			
			TiXmlDocument doc;
			m_pDefMa->XMLSerialize(TRUE,&doc);
			if(!doc.SaveFile((LPTSTR)(LPCTSTR)fullPathName))
			{
				CString text;
				text.Format("%s 保存失败",fullPathName);
				AfxMessageBox(text);
				return;
			}
		}
	} 
	else 
	{
		// for debugging watch, delete the codes when release
		OneLayerDefine* pOneLayer;
		CClassicalElement* pElem;
		CString eleName; double content; BOOL active;
		int winLeft,winRight;
		int nLayers = m_pDefMa->m_layerArray.GetSize();
		for(int m=0;m<nLayers;m++)
		{
			pOneLayer = m_pDefMa->m_layerArray.GetAt(m);
			int nEle = pOneLayer->m_elementList.GetSize();
			for(int n=0;n<nEle;n++)
			{
				pElem = pOneLayer->m_elementList.GetAt(n);
				eleName = pElem->Name;    //watch
				content = pElem->Content; //watch
				active = pElem->beActive; //watch
				winLeft = pElem->WinLeft;
				winRight = pElem->WinRight;
			}
		}
		// end : debugging watch

		// Rewrite defMA to 00xx.xma
		SaveDataToPtr();
		folderName.Format("%04d",m_pWz->GetDirIndex());
		fullPathName = ((CTMeterApp*)AfxGetApp())->m_AppWorkDirectory + "\\DefineFP\\" + folderName + "\\analysis.xma"; 
		
		TiXmlDocument doc;
		m_pDefMa->XMLSerialize(TRUE,&doc);
		if(!doc.SaveFile((LPTSTR)(LPCTSTR)fullPathName))
		{
			CString text;
			text.Format("%s 保存失败",fullPathName);
			AfxMessageBox(text);
			return;
		}

	}
	
	CDialog::EndDialog(TRUE);
	
}
//----------------------------------------------------------------------------------------
int CDotSceneSerializer::Export(bool SaveAs)
{
    OgitorsRoot *ogRoot = OgitorsRoot::getSingletonPtr();
    OgitorsSystem *mSystem = OgitorsSystem::getSingletonPtr();

    PROJECTOPTIONS *pOpt = ogRoot->GetProjectOptions();
    Ogre::String fileName = pOpt->ProjectName;

    PROJECTOPTIONS tmpOPT = *pOpt;

    UTFStringVector extlist;
    extlist.push_back(OTR("DotScene File"));
    extlist.push_back("*.scene");
    extlist.push_back(OTR("DotScene File"));
    extlist.push_back("*.xml");
    fileName = mSystem->DisplaySaveDialog(OTR("Export DotScene File"),extlist);
    if(fileName == "") 
        return SCF_CANCEL;

    Ogre::String oldProjDir = pOpt->ProjectDir;
    Ogre::String oldProjName = pOpt->ProjectName;

    pOpt->ProjectName = OgitorsUtils::ExtractFileName(fileName);
    pOpt->ProjectDir = OgitorsUtils::ExtractFilePath(fileName);

    ogRoot->AdjustUserResourceDirectories(oldProjDir);

    Ogre::String newDir = pOpt->ProjectDir;

    mSystem->MakeDirectory(newDir);
    mSystem->CopyFilesEx(oldProjDir + "*", newDir);

    pOpt->ProjectName = oldProjName;
    pOpt->ProjectDir = oldProjDir;

    //TODO: figure out how to make Ogitor link to the active project file again (ogscene)

    TiXmlDocument *pXMLDoc = new TiXmlDocument();
    pXMLDoc->InsertEndChild(TiXmlDeclaration( "1.0", "UTF-8", ""));
    pXMLDoc->InsertEndChild(TiXmlElement("scene"));

    // export basic info
    TiXmlElement *pRoot = pXMLDoc->RootElement();
    pRoot->SetAttribute("formatVersion", "1.0.0");
    pRoot->SetAttribute("generator", Ogre::String(Ogre::String("Ogitor SceneBuilder ") + Ogre::String(OGITOR_VERSION)).c_str());

    // export resource locations
    TiXmlElement *pResourceLocations = pRoot->InsertEndChild(TiXmlElement("resourceLocations"))->ToElement();
    
    for(unsigned int r = 0;r < pOpt->ResourceDirectories.size();r++)
    {
        TiXmlElement *pResourceLocation = pResourceLocations->InsertEndChild(TiXmlElement("resourceLocation"))->ToElement();
        Ogre::String loc = pOpt->ResourceDirectories[r];
        loc.erase(0,3);
        if(pOpt->ResourceDirectories[r].substr(0,2) == "ZP")
            pResourceLocation->SetAttribute("type", "Zip");
        else
            pResourceLocation->SetAttribute("type", "FileSystem");

        std::replace(loc.begin(),loc.end(),'\\','/');
        pResourceLocation->SetAttribute("name", loc.c_str());
    }

    //TODO: do we need all those object id's ?

    TiXmlElement *pEnvironment = pRoot->InsertEndChild(TiXmlElement("environment"))->ToElement();

    // export octree scenemanagers
    NameObjectPairList smList = ogRoot->GetObjectsByTypeName("OctreeSceneManager");
    NameObjectPairList::const_iterator smIt = smList.begin();
    while(smIt != smList.end())
    {
        smIt->second->exportDotScene(pEnvironment);
        smIt++;
    }

    // export viewports
    NameObjectPairList vpList = ogRoot->GetObjectsByTypeName("Viewport Object");
    NameObjectPairList::const_iterator vpIt = vpList.begin();
    while(vpIt != vpList.end())
    {
        vpIt->second->exportDotScene(pEnvironment);
        vpIt++;
    }

    // export terrains
    NameObjectPairList terrainList = ogRoot->GetObjectsByType(ETYPE_TERRAIN_MANAGER);
    NameObjectPairList::const_iterator tlIt = terrainList.begin();
    while(tlIt != terrainList.end())
    {
        tlIt->second->exportDotScene(pRoot);
        tlIt++;
    }

    NameObjectPairList items = ogRoot->GetSceneManagerEditor()->getChildren();
   
    // export lights
    NameObjectPairList::const_iterator nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if(nodeIt->second->getEditorType() == ETYPE_LIGHT)
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pRoot);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    // export cameras
    nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if(nodeIt->second->getEditorType() == ETYPE_CAMERA)
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pRoot);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    // export nodes
    TiXmlElement *pNodes = pRoot->InsertEndChild(TiXmlElement("nodes"))->ToElement();
    nodeIt = items.begin();

    while(nodeIt != items.end())
    {
        if( nodeIt->second->getEditorType() != ETYPE_TERRAIN_MANAGER &&
            nodeIt->second->getEditorType() != ETYPE_LIGHT &&
            nodeIt->second->getEditorType() != ETYPE_CAMERA )
        {
            TiXmlElement *result = nodeIt->second->exportDotScene(pNodes);
            saveUserData(nodeIt->second->getCustomProperties(), result);
        }
        nodeIt++;
    }

    if (pXMLDoc->SaveFile(fileName.c_str()))
    {
        OgitorsSystem::getSingletonPtr()->DisplayMessageDialog(OTR("Scene has been exported succesfully"), DLGTYPE_OK);
        delete pXMLDoc;
    }
    else
        OgitorsSystem::getSingletonPtr()->DisplayMessageDialog(OTR("An error occured during export.. :("), DLGTYPE_OK);

    *pOpt = tmpOPT;


    return SCF_OK;
}
Esempio n. 14
0
TiXmlDocument * ConfigManager::createNewConfiguration() {
    if (Log::enabledDbg()) Log::dbg("Creating new initial configuration");
    createdNew = true;
    string homeDir = getenv ("HOME");
    string storagePath = homeDir + "/.config";
    struct stat st;
    if(stat(storagePath.c_str(),&st) == 0) {
        // directory exists
        storagePath += "/garminplugin";
        if(stat(storagePath.c_str(),&st) == 0) {
            // directory already exists
            storagePath += "/";
        } else {
            if(mkdir(storagePath.c_str(), 0755) == -1)
            {
                if (Log::enabledErr()) Log::err("Failed to create directory "+storagePath);
                storagePath = homeDir+"/.";
            } else {
                storagePath += "/";
            }
        }
    } else {
        storagePath = homeDir+"/.";
    }

    string configFile = storagePath + "garminplugin.xml";

    TiXmlDocument * doc = new TiXmlDocument();

    TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "no" );
    doc->LinkEndChild( decl );

/*  <GarminPlugin logfile="" level="ERROR">
      <Devices>
        <Device enabled="false">
          <Name>My Oregon 300</Name>
          <StoragePath>/tmp</StoragePath>
          <StorageCommand></StorageCommand>
          <FitnessDataPath></FitnessDataPath>
          <GpxDataPath></GpxDataPath>
        </Device>
      </Devices>
    </GarminPlugin> */
	TiXmlElement * plugin = new TiXmlElement( "GarminPlugin" );
	plugin->SetAttribute("logfile", "");
	plugin->SetAttribute("level", "ERROR");
	doc->LinkEndChild( plugin );

	TiXmlElement * devices = new TiXmlElement( "Devices" );
	plugin->LinkEndChild( devices );

	TiXmlElement * device = new TiXmlElement( "Device" );
	device->SetAttribute("enabled", "false");
	devices->LinkEndChild( device );

	TiXmlElement * name = new TiXmlElement( "Name" );
	name->LinkEndChild(new TiXmlText("Home Directory "+homeDir));
	device->LinkEndChild( name );

	TiXmlElement * storePath = new TiXmlElement( "StoragePath" );
	storePath->LinkEndChild(new TiXmlText(homeDir));
	device->LinkEndChild( storePath );

	TiXmlElement * storageCmd = new TiXmlElement( "StorageCommand" );
	storageCmd->LinkEndChild(new TiXmlText(""));
	device->LinkEndChild( storageCmd );

	TiXmlElement * fitnessPath = new TiXmlElement( "FitnessDataPath" );
	fitnessPath->LinkEndChild(new TiXmlText(""));
	device->LinkEndChild( fitnessPath );

	TiXmlElement * gpxPath = new TiXmlElement( "GpxDataPath" );
	gpxPath->LinkEndChild(new TiXmlText(""));
	device->LinkEndChild( gpxPath );

/*
    <Settings>
        <ForerunnerTools enabled ="true"/>
    </Settings>
*/
    TiXmlElement * settings = new TiXmlElement( "Settings" );
	plugin->LinkEndChild( settings );

    TiXmlElement * forerunnertools = new TiXmlElement( "ForerunnerTools" );
	settings->LinkEndChild( forerunnertools );

	forerunnertools->SetAttribute("enabled", "true");

    doc->SaveFile(configFile);
    configurationFile = configFile;

    return doc;
}
Esempio n. 15
0
void WriteXmlToFile(IXMLDataBound* aXml, std::string aFileName)
{	
		TiXmlDocument doc;
		aXml->toXml(&doc, true, true);
		if(!doc.SaveFile(aFileName)) throw Exception(LOCATION, "Unspecified error while saving");
}
Esempio n. 16
0
void WeatherRouting::SaveXML(wxString filename)
{
    TiXmlDocument doc;
    TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "utf-8", "" );
    doc.LinkEndChild( decl );

    TiXmlElement * root = new TiXmlElement( "OpenCPNWeatherRoutingConfiguration" );
    doc.LinkEndChild( root );

    char version[24];
    sprintf(version, "%d.%d", PLUGIN_VERSION_MAJOR, PLUGIN_VERSION_MINOR);
    root->SetAttribute("version", version);
    root->SetAttribute("creator", "Opencpn Weather Routing plugin");

    for(std::list<RouteMapPosition>::iterator it = RouteMap::Positions.begin();
        it != RouteMap::Positions.end(); it++)
    {
        TiXmlElement *c = new TiXmlElement( "Position" );

        c->SetAttribute("Name", (*it).Name.mb_str());
        c->SetAttribute("Latitude", wxString::Format(_T("%.5f"), (*it).lat).mb_str());
        c->SetAttribute("Longitude", wxString::Format(_T("%.5f"), (*it).lon).mb_str());

        root->LinkEndChild(c);
    }

    for(std::list<WeatherRoute*>::iterator it = m_WeatherRoutes.begin();
        it != m_WeatherRoutes.end(); it++)
    {
        TiXmlElement *c = new TiXmlElement( "Configuration" );

        RouteMapConfiguration configuration =
            (*it)->routemapoverlay->GetConfiguration();

        c->SetAttribute("Start", configuration.Start.mb_str());
        c->SetAttribute("StartDate", configuration.StartTime.FormatDate().mb_str());
        c->SetAttribute("StartTime", configuration.StartTime.FormatTime().mb_str());
        c->SetAttribute("End", configuration.End.mb_str());
        c->SetAttribute("dt", configuration.dt);

        c->SetAttribute("Boat", configuration.boatFileName.ToUTF8());

        c->SetAttribute("MaxDivertedCourse", configuration.MaxDivertedCourse);
        c->SetAttribute("MaxWindKnots", configuration.MaxWindKnots);
        c->SetAttribute("MaxSwellMeters", configuration.MaxSwellMeters);
        c->SetAttribute("MaxLatitude", configuration.MaxLatitude);
        c->SetAttribute("MaxTacks", configuration.MaxTacks);
        c->SetAttribute("TackingTime", configuration.TackingTime);

        c->SetAttribute("UseGrib", configuration.UseGrib);
        c->SetAttribute("UseClimatology", configuration.UseClimatology);
        c->SetAttribute("AllowDataDeficient", configuration.AllowDataDeficient);
        c->SetAttribute("DetectLand", configuration.DetectLand);
        c->SetAttribute("Currents", configuration.Currents);
        c->SetAttribute("InvertedRegions", configuration.InvertedRegions);
        c->SetAttribute("Anchoring", configuration.Anchoring);

        wxString degreesteps;
        for(std::list<double>::iterator it = configuration.DegreeSteps.begin();
            it != configuration.DegreeSteps.end(); it++)
            degreesteps += wxString::Format(_T("%.1f;"), *it);
        c->SetAttribute("DegreeSteps", degreesteps.mb_str());

        root->LinkEndChild(c);
    }

    if(!doc.SaveFile(filename.mb_str()))
    {
        wxMessageDialog mdlg(this, _("Failed to save xml file: ") + filename,
                             _("Weather Routing"), wxOK | wxICON_ERROR);
        mdlg.ShowModal();
    }
}
Esempio n. 17
0
void Saver::save(CEGUI::String filename)
{
	TiXmlDocument doc;

	TiXmlElement * scene = new TiXmlElement( "scene" );
	//scene attrib setup
	if (!author.empty()) 
		scene->SetAttribute("author",author.c_str());
	scene->SetAttribute("formatVersion",MAXVERSION);
	//environment entry
	TiXmlElement *environment = new TiXmlElement( "environment" ); //TiXmlText * text = new TiXmlText( "World" ); //environment->LinkEndChild( text );
		TiXmlElement *skybox = new TiXmlElement( "skyBox" );
	TiXmlElement *fog = new TiXmlElement( "fog" ); 
		fog->SetAttribute("mode","none");
		skybox->SetAttribute("material","Examples/MorningSkyBox");
		environment->LinkEndChild(skybox);
		environment->LinkEndChild(fog);
		if (assign)
		{
			TiXmlElement *el = new TiXmlElement("colourAmbient");
			el->SetAttribute("r","0.2980392");
			el->SetAttribute("g","0.2980392");
			el->SetAttribute("b","0.2980392");
			environment->LinkEndChild(el);
			el = new TiXmlElement("newtonWorld");
			el->SetAttribute("x1","-100000");
			el->SetAttribute("y1","-100000");
			el->SetAttribute("z1","-100000");	
			el->SetAttribute("x2","100000");
			el->SetAttribute("y2","100000");
			el->SetAttribute("z2","100000");	
			environment->LinkEndChild(el);
			el = new TiXmlElement("player");
			el->SetAttribute("x","0");
			el->SetAttribute("y","100");
			el->SetAttribute("z","0");	
			/*el->SetAttribute("x2","100000");
			el->SetAttribute("y2","100000");
			el->SetAttribute("z2","100000");*/	
			environment->LinkEndChild(el);
			el = new TiXmlElement("fade");
			el->SetAttribute("speed","0.5");
			el->SetAttribute("duration","3");
			el->SetAttribute("overlay","Overlays/FadeInOut");	
			el->SetAttribute("material","Materials/OverlayMaterial");
			el->SetAttribute("startFade","true");	
			environment->LinkEndChild(el);
		}
	scene->LinkEndChild(environment);
	//nodes entry
	TiXmlElement *nodes = new TiXmlElement( "nodes" );
	for (i=0; i!=StObjs_s.size(); i++)
	{
		TiXmlElement *node = new TiXmlElement( "node" );
		node->SetAttribute("name",StObjs_s[i]->getName().c_str());
		node->SetAttribute("id",rand() % 1000 + 1);
			//pos orient scale and what contains
			TiXmlElement *pos = new TiXmlElement( "position" );
			TiXmlElement *quat = new TiXmlElement( "rotation" );
			TiXmlElement *scale = new TiXmlElement( "scale" );
			TiXmlElement *entity;
			if (StObjs[i]->type!="")
			{
			entity	= new TiXmlElement( StObjs[i]->type.c_str() );
			}
			else
			{
				entity=new TiXmlElement("entity");
			}
			pos->SetAttribute("x",Ogre::StringConverter::toString(StObjs_s[i]->getPosition().x*mScaler).c_str());
				pos->SetAttribute("y",Ogre::StringConverter::toString(StObjs_s[i]->getPosition().y*mScaler).c_str());
				pos->SetAttribute("z",Ogre::StringConverter::toString(StObjs_s[i]->getPosition().z*mScaler).c_str());
				quat->SetAttribute("qw",Ogre::StringConverter::toString(StObjs_s[i]->getOrientation().w).c_str());
				quat->SetAttribute("qx",Ogre::StringConverter::toString(StObjs_s[i]->getOrientation().x).c_str());
				quat->SetAttribute("qy",Ogre::StringConverter::toString(StObjs_s[i]->getOrientation().y).c_str());
				quat->SetAttribute("qz",Ogre::StringConverter::toString(StObjs_s[i]->getOrientation().z).c_str());
				scale->SetAttribute("x",Ogre::StringConverter::toString(StObjs_s[i]->getScale().x*mScaler).c_str());
				scale->SetAttribute("y",Ogre::StringConverter::toString(StObjs_s[i]->getScale().y*mScaler).c_str());
				scale->SetAttribute("z",Ogre::StringConverter::toString(StObjs_s[i]->getScale().z*mScaler).c_str());
				entity->SetAttribute("name",StObjs[i]->ent->getName().c_str());
				entity->SetAttribute("meshFile",StObjs[i]->ent->getMesh()->getName().c_str());
				entity->SetAttribute("castShadows","true");
				if (!St_mats[i].empty())
				{
				entity->SetAttribute("materialFile",St_mats[i].c_str());
				entity->SetAttribute("scaleU",Ogre::StringConverter::toString(scaleU[i]).c_str());
				entity->SetAttribute("scaleV",Ogre::StringConverter::toString(scaleV[i]).c_str());
				entity->SetAttribute("scrollU",Ogre::StringConverter::toString(scrollU[i]).c_str());
				entity->SetAttribute("scrollV",Ogre::StringConverter::toString(scrollV[i]).c_str());
				}
		node->LinkEndChild(pos);
		//if (!(StObjs_s[i]->getOrientation()==Quaternion::IDENTITY))
		//{
		node->LinkEndChild(quat);
		//}
		//if (!(StObjs_s[i]->getScale()==Vector3(1,1,1)))
		//{
		node->LinkEndChild(scale);
		//}
		node->LinkEndChild(entity);
		//already made nodes put into <nodes>
		nodes->LinkEndChild(node);
	}

	for (i=0; i!=PhysObjs.size(); i++)
	{
		TiXmlElement *node = new TiXmlElement( "node" );
		node->SetAttribute("name",PhysObjs[i]->node->getName().c_str());
		node->SetAttribute("id",rand() % 1000 + 1);
			//pos orient scale and what contains
			TiXmlElement *pos = new TiXmlElement( "position" );
			TiXmlElement *quat = new TiXmlElement( "rotation" );
			TiXmlElement *scale = new TiXmlElement( "scale" );
			TiXmlElement *entity = new TiXmlElement( "phys" );
			SceneNode* n = PhysObjs[i]->node;
			pos->SetAttribute("x",Ogre::StringConverter::toString(n->getPosition().x*mScaler).c_str());
				pos->SetAttribute("y",Ogre::StringConverter::toString(n->getPosition().y*mScaler).c_str());
				pos->SetAttribute("z",Ogre::StringConverter::toString(n->getPosition().z*mScaler).c_str());
				quat->SetAttribute("qw",Ogre::StringConverter::toString(n->getOrientation().w).c_str());
				quat->SetAttribute("qx",Ogre::StringConverter::toString(n->getOrientation().x).c_str());
				quat->SetAttribute("qy",Ogre::StringConverter::toString(n->getOrientation().y).c_str());
				quat->SetAttribute("qz",Ogre::StringConverter::toString(n->getOrientation().z).c_str());
				scale->SetAttribute("x",Ogre::StringConverter::toString(n->getScale().x*mScaler).c_str());
				scale->SetAttribute("y",Ogre::StringConverter::toString(n->getScale().y*mScaler).c_str());
				scale->SetAttribute("z",Ogre::StringConverter::toString(n->getScale().z*mScaler).c_str());
				entity->SetAttribute("name",PhysObjs[i]->ent->getName().c_str());
				entity->SetAttribute("meshFile",PhysObjs[i]->ent->getMesh()->getName().c_str());
				entity->SetAttribute("castShadows","true");
		node->LinkEndChild(pos);
		//if (!(n->getOrientation()==Quaternion::IDENTITY))
		//{
		node->LinkEndChild(quat);
		//}
		//if (!(n->getScale()==Vector3(1,1,1)))
		//{
		node->LinkEndChild(scale);
		//}
		node->LinkEndChild(entity);
		//already made nodes put into <nodes>
		nodes->LinkEndChild(node);
	}

	for (i=0; i!=lights.size(); i++)
	{
		TiXmlElement *node = new TiXmlElement( "node" );
		node->SetAttribute("name",lights[i]->getName().c_str());
		node->SetAttribute("id",rand() % 1000 + 1);
			//pos orient scale and what contains
			TiXmlElement *pos = new TiXmlElement( "position" );
			TiXmlElement *quat = new TiXmlElement( "rotation" );
			TiXmlElement *scale = new TiXmlElement( "scale" );
			TiXmlElement *light = new TiXmlElement( "light" );
			SceneNode* n = lights[i];
			Light* l = (Ogre::Light*)n->getAttachedObject(0);
			pos->SetAttribute("x",Ogre::StringConverter::toString(n->getPosition().x*mScaler).c_str());
				pos->SetAttribute("y",Ogre::StringConverter::toString(n->getPosition().y*mScaler).c_str());
				pos->SetAttribute("z",Ogre::StringConverter::toString(n->getPosition().z*mScaler).c_str());
				quat->SetAttribute("qw",Ogre::StringConverter::toString(n->getOrientation().w).c_str());
				quat->SetAttribute("qx",Ogre::StringConverter::toString(n->getOrientation().x).c_str());
				quat->SetAttribute("qy",Ogre::StringConverter::toString(n->getOrientation().y).c_str());
				quat->SetAttribute("qz",Ogre::StringConverter::toString(n->getOrientation().z).c_str());
				scale->SetAttribute("x",Ogre::StringConverter::toString(n->getScale().x*mScaler).c_str());
				scale->SetAttribute("y",Ogre::StringConverter::toString(n->getScale().y*mScaler).c_str());
				scale->SetAttribute("z",Ogre::StringConverter::toString(n->getScale().z*mScaler).c_str());
				light->SetAttribute("name",l->getName().c_str());
				light->SetAttribute("castShadows","true");
				light->SetAttribute("type","spot");
				TiXmlElement *light1 = new TiXmlElement( "colourDiffuse" );
				TiXmlElement *light2 = new TiXmlElement( "colourSpecular" );
				TiXmlElement *light3 = new TiXmlElement( "normal" );
				TiXmlElement *light4 = new TiXmlElement( "lightAttenuation" );
				TiXmlElement *light5 = new TiXmlElement( "lightRange" );
				
				light1->SetAttribute("r",StringConverter::toString(l->getDiffuseColour().r).c_str());
				light1->SetAttribute("g",StringConverter::toString(l->getDiffuseColour().g).c_str());
				light1->SetAttribute("b",StringConverter::toString(l->getDiffuseColour().b).c_str());
				
				light2->SetAttribute("r",StringConverter::toString(l->getSpecularColour().r).c_str());
				light2->SetAttribute("g",StringConverter::toString(l->getSpecularColour().g).c_str());
				light2->SetAttribute("b",StringConverter::toString(l->getSpecularColour().b).c_str());

				light3->SetAttribute("x",StringConverter::toString(l->getDirection().x).c_str());
				light3->SetAttribute("y",StringConverter::toString(l->getDirection().y).c_str());
				light3->SetAttribute("z",StringConverter::toString(l->getDirection().z).c_str());

				light4->SetAttribute("range",StringConverter::toString(l->getAttenuationRange()).c_str());
				light5->SetAttribute("inner",StringConverter::toString(l->getSpotlightInnerAngle()).c_str());
				light5->SetAttribute("outer",StringConverter::toString(l->getSpotlightOuterAngle()).c_str());
				
				light->LinkEndChild(light1);
				light->LinkEndChild(light2);
				light->LinkEndChild(light3);
				light->LinkEndChild(light4);
				light->LinkEndChild(light5);
		node->LinkEndChild(pos);
		//if (!(n->getOrientation()==Quaternion::IDENTITY))
		//{
		node->LinkEndChild(quat);
		//}
		//if (!(n->getScale()==Vector3(1,1,1)))
		//{
		node->LinkEndChild(scale);
		//}
		node->LinkEndChild(light);
		//already made nodes put into <nodes>
		nodes->LinkEndChild(node);
	}
TiXmlElement *ainodes = new TiXmlElement( "aiNodes" );
	for (i=0; i!=npcNodes.size(); i++)
	{
		TiXmlElement *npcnode = new TiXmlElement( "npcnode" );
		npcnode->SetAttribute("x",StringConverter::toString(npcNodes[i]->getPosition().x*mScaler).c_str());
		npcnode->SetAttribute("y",StringConverter::toString(npcNodes[i]->getPosition().y*mScaler).c_str());
		npcnode->SetAttribute("z",StringConverter::toString(npcNodes[i]->getPosition().z*mScaler).c_str());
		ainodes->LinkEndChild(npcnode);
	}
	//put nodes to <scene>
	scene->LinkEndChild(nodes);
	scene->LinkEndChild(ainodes);
	//bind it and save
	doc.LinkEndChild( scene );
	doc.SaveFile( filename.c_str() );
}
Esempio n. 18
0
void do_savexml(FILE * filehandle)
{
    int masterkey = 0;
    int i;
    for (i = 0; i < (signed)gChip.size(); i++)
        masterkey ^= gChip[i]->mKey;
    for (i = 0; i < (signed)gWire.size(); i++)
        masterkey ^= gWire[i]->mKey;

    TiXmlDocument doc;
    TiXmlDeclaration * decl = new TiXmlDeclaration("1.0","","");
    TiXmlElement * topelement = new TiXmlElement("Atanua");
    {
        char temp[512];
        sprintf(temp, "%s - %s", TITLE, gConfig.mUserInfo);
        topelement->SetAttribute("Version",temp);
    }

	int chipcount = 0;
	int wirecount = 0;
	for (i = 0; i < (signed)gChip.size(); i++)
		if (gChip[i]->mBox == 0)
			chipcount++;

	for (i = 0; i < (signed)gWire.size(); i++)
		if (gWire[i]->mBox == 0)
			wirecount++;

    topelement->SetAttribute("ChipCount",chipcount);
    topelement->SetAttribute("WireCount",wirecount);
    topelement->SetAttribute("key",masterkey);
    topelement->SetAttribute("scale", 16);
    doc.LinkEndChild(decl);
    doc.LinkEndChild(topelement);

    for (i = 0; i < (signed)gChip.size(); i++)
    {
		if (gChip[i]->mBox != 0)
			continue;        
		TiXmlElement *element = new TiXmlElement("Chip");
        topelement->LinkEndChild(element);
        element->SetAttribute("Name", gChipName[i]);
        element->SetAttribute("xpos", (int)floor((1 << 16) * gChip[i]->mX));
        element->SetAttribute("ypos", (int)floor((1 << 16) * gChip[i]->mY));        
        element->SetAttribute("rot", gChip[i]->mAngleIn90DegreeSteps);        
        element->SetAttribute("key", gChip[i]->mKey ^ masterkey);        
        MemoryFile f;
        gChip[i]->serialize(&f);
        if (!f.mData.empty())
        {
            string s;
            int j;
            for (j = 0; j < (signed)f.mData.size(); j++)
            {
                int d = f.mData[j] & 0xff;
                char temp[16];
                sprintf(temp,"%02X",d);
                s.push_back(temp[0]);
                s.push_back(temp[1]);
            }
            TiXmlText *text = new TiXmlText(s.c_str());
            element->LinkEndChild(text);
        }

    }
    for (i = 0; i < (signed)gWire.size(); i++)
    {
		if (gWire[i]->mBox != 0)
			continue;
        TiXmlElement *element = new TiXmlElement("Wire");
        topelement->LinkEndChild(element);
        Pin *pn[2];
        pn[0] = gWire[i]->mFirst;
        pn[1] = gWire[i]->mSecond;
        int j;
        for (j = 0; j < 2; j++)
        {
            int pinid = 0;
            int k, l;
			int chipno = 0;
            for (k = 0; pinid == 0 && k < (signed)gChip.size(); k++)
            {
				if (gChip[k]->mBox == 0)
				{
					for (l = 0; pinid == 0 && l < (signed)gChip[k]->mPin.size(); l++)
					{
						if (gChip[k]->mPin[l] == pn[j])
						{
							pinid = (k << 16) | l;
							if (j == 0)
							{
								element->SetAttribute("chip1", chipno);
								element->SetAttribute("pad1", l);
							}
							else
							{
								element->SetAttribute("chip2", chipno);
								element->SetAttribute("pad2", l);
							}
						}
					}
					chipno++;
                }
            }
        }        
        element->SetAttribute("key", gWire[i]->mKey ^ masterkey);
    }
    
    doc.SaveFile(filehandle);
    fclose(filehandle);
}
Esempio n. 19
0
// save world information into file
void MapInfoXmlWriter::SaveWorld(const std::string Filename, const WorldInfo & wi)
{
	TiXmlDocument doc;
	TiXmlComment * comment;
	std::string s;

 	TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
	doc.LinkEndChild( decl );

	TiXmlElement * root = new TiXmlElement("World");
	doc.LinkEndChild( root );
	root->SetAttribute("name", wi.Name);
	root->SetAttribute("firstmap", wi.FirstMap);
	root->SetAttribute("firstsparea", wi.FirstSpawning);

	TiXmlElement * desc = new TiXmlElement( "description" );
	root->LinkEndChild(desc);
	desc->LinkEndChild(new TiXmlText(wi.Description));

	// block: teleport
	{
		comment = new TiXmlComment();
		s="Define the place it is possible to teleport to, the first place is the place where we arrive in the world";
		comment->SetValue(s.c_str());
		root->LinkEndChild( comment );

		TiXmlElement * tps = new TiXmlElement( "teleports" );
		root->LinkEndChild(tps);


		std::map<std::string, TPInfo>::const_iterator it = wi.Teleports.begin();
		std::map<std::string, TPInfo>::const_iterator end = wi.Teleports.end();
		for(; it != end; ++it)
		{
			TiXmlElement * tp = new TiXmlElement( "teleport" );
			tps->LinkEndChild(tp);

			tp->SetAttribute("name", it->second.Name);
			tp->SetAttribute("map", it->second.NewMap);
			tp->SetAttribute("sparea", it->second.Spawning);
		}
	}

		// file info block
		{
			TiXmlElement * files = new TiXmlElement( "files" );
			root->LinkEndChild(files);

			std::map<std::string, std::string>::const_iterator it2 = wi.Files.begin();
			std::map<std::string, std::string>::const_iterator end2 = wi.Files.end();
			for(; it2 != end2; ++it2)
			{
				TiXmlElement * file = new TiXmlElement( "file" );
				files->LinkEndChild(file);

				file->SetAttribute("name", it2->first);
				file->SetAttribute("path", it2->second);
			}
		}



	TiXmlElement * maps = new TiXmlElement( "maps" );
	root->LinkEndChild(maps);

	std::map<std::string, MapInfo>::const_iterator it = wi.Maps.begin();
	std::map<std::string, MapInfo>::const_iterator end = wi.Maps.end();
	for(; it != end; ++it)
	{
		comment = new TiXmlComment();
		s="Map of "+it->second.Description;
		comment->SetValue(s.c_str());
		maps->LinkEndChild( comment );


		TiXmlElement * map = new TiXmlElement( "Map" );
		maps->LinkEndChild(map);

		map->SetAttribute("name", it->first);
		map->SetAttribute("type", it->second.Type);
		map->SetAttribute("music", it->second.Music);
		map->SetAttribute("repeatmusic", it->second.MusicLoop);


		TiXmlElement * descm = new TiXmlElement( "description" );
		map->LinkEndChild(descm);
		descm->LinkEndChild(new TiXmlText(it->second.Description));


		// file info block
		{
			comment = new TiXmlComment();
			s="Give the path of the files containing the island information to be loaded";
			comment->SetValue(s.c_str());
			map->LinkEndChild( comment );

			TiXmlElement * files = new TiXmlElement( "files" );
			map->LinkEndChild(files);

			std::map<std::string, std::string>::const_iterator it2 = it->second.Files.begin();
			std::map<std::string, std::string>::const_iterator end2 = it->second.Files.end();
			for(; it2 != end2; ++it2)
			{
				TiXmlElement * file = new TiXmlElement( "file" );
				files->LinkEndChild(file);

				file->SetAttribute("name", it2->first);
				file->SetAttribute("path", it2->second);
			}
		}


		// light info block
		{
			comment = new TiXmlComment();
			s="Describe the lights present in the scene";
			comment->SetValue(s.c_str());
			map->LinkEndChild( comment );

			TiXmlElement * lights = new TiXmlElement( "lights" );
			map->LinkEndChild(lights);

			std::map<std::string, LighInfo>::const_iterator it2 = it->second.Lights.begin();
			std::map<std::string, LighInfo>::const_iterator end2 = it->second.Lights.end();
			for(; it2 != end2; ++it2)
			{
				TiXmlElement * light = new TiXmlElement( "light" );
				lights->LinkEndChild(light);

				light->SetAttribute("name", it2->first);
				light->SetAttribute("type", it2->second.Type);

				light->SetAttribute("posX", it2->second.PosX);
				light->SetAttribute("posY", it2->second.PosY);
				light->SetAttribute("posZ", it2->second.PosZ);
				light->SetAttribute("dirX", it2->second.DirX);
				light->SetAttribute("dirY", it2->second.DirY);
				light->SetAttribute("dirZ", it2->second.DirZ);
			}
		}


		// spawning areas info block
		{
			comment = new TiXmlComment();
			s="Describe the possible spawning areas of the main character";
			comment->SetValue(s.c_str());
			map->LinkEndChild( comment );

			TiXmlElement * spareas = new TiXmlElement( "spareas" );
			map->LinkEndChild(spareas);

			std::map<std::string, SpawningInfo>::const_iterator it2 = it->second.Spawnings.begin();
			std::map<std::string, SpawningInfo>::const_iterator end2 = it->second.Spawnings.end();
			for(; it2 != end2; ++it2)
			{
				TiXmlElement * sparea = new TiXmlElement( "sparea" );
				spareas->LinkEndChild(sparea);

				sparea->SetAttribute("name", it2->first);

				sparea->SetDoubleAttribute("posX", it2->second.PosX);
				sparea->SetDoubleAttribute("posY", it2->second.PosY);
				sparea->SetDoubleAttribute("posZ", it2->second.PosZ);
				sparea->SetAttribute("RotationAtArrival", it2->second.Rotation);
			}
		}


		// map exit info block
		{
			comment = new TiXmlComment();
			s="Describe the possible map exit places using square areas from TopLeft point to BottomRight point";
			comment->SetValue(s.c_str());
			map->LinkEndChild( comment );

			TiXmlElement * exits = new TiXmlElement( "exits" );
			map->LinkEndChild(exits);

			std::map<std::string, ExitInfo>::const_iterator it2 = it->second.Exits.begin();
			std::map<std::string, ExitInfo>::const_iterator end2 = it->second.Exits.end();
			for(; it2 != end2; ++it2)
			{
				TiXmlElement * exit = new TiXmlElement( "exit" );
				exits->LinkEndChild(exit);

				exit->SetAttribute("name", it2->first);

				exit->SetDoubleAttribute("TopRightX", it2->second.TopRightX);
				exit->SetDoubleAttribute("TopRightY", it2->second.TopRightY);
				exit->SetDoubleAttribute("TopRightZ", it2->second.TopRightZ);

				exit->SetDoubleAttribute("BottomLeftX", it2->second.BottomLeftX);
				exit->SetDoubleAttribute("BottomLeftY", it2->second.BottomLeftY);
				exit->SetDoubleAttribute("BottomLeftZ", it2->second.BottomLeftZ);

				exit->SetAttribute("newMap", it2->second.NewMap);
				exit->SetAttribute("spawning", it2->second.Spawning);
			}
		}

	}

	doc.SaveFile(Filename);
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
	string inPath, outPath;	// in - source code, out - xml report
	if(!processCmdLineArgs(argc, argv, inPath, outPath))
		return 0;
	//
	cout << "Parsing...";
	CppParser cpp;
	Project *project = cpp.parseFile(inPath);
	if(cpp.errorOccured())
	{
		cout << "Error!" << endl;
		return 1;
	}
	cout << "Ok." << endl;
	//
#if YYDEBUG == 1
	//
	// TinyXML test
	TiXmlDocument doc;
	TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "utf-8", "yes");
	doc.LinkEndChild(decl);
	//
	//TiXmlStylesheetReference *style = new TiXmlStylesheetReference("text/xsl", "test.xsl");
	//doc.LinkEndChild(style);
	//
	TiXmlElement *root = new TiXmlElement("ASTM");
	project->dumpXml(root);
	doc.LinkEndChild(root);
	//
	doc.SaveFile("astm_dump.xml");
	//
#endif	// YYDEBUG == 1
	//
	cout << "Analysing...";
	//
	LinesOfCode loc(project->files[0]);
	CommentsDensity commdens(loc);
	CyclomaticComplexityNumber ccn(project->files[0]);
	DecisionDensity decdens(loc, ccn);
	NPathComplexity npath(project->files[0]);
	TotalFunctionCalls tfc(project->files[0]);
	NumberOfClasses noc(project->files[0]);
	LorenzKidd lk(project->files[0]);
	//
	string resultsFile = (outPath.size() > 0) ? outPath : "report.xml";
	ofstream fout;
	fout.open(resultsFile.c_str());
	if(!fout.is_open())
	{
		cout << "Error writing the results!" << endl;
		return 2;
	}
	fout << "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
		 << "<?xml-stylesheet href=\"sw_metrics.xsl\" type=\"text/xml\"?>\n"
		 << "<sw_stats>\n"
		 << "\t<file>" << inPath << "</file>\n"
		 << loc.dumpResultXml()
		 << commdens.dumpResultXml()
		 << ccn.dumpResultXml()
		 << decdens.dumpResultXml()
		 << npath.dumpResultXml()
		 << tfc.dumpResultXml()
		 << noc.dumpResultXml()
		 << lk.dumpResultXml()
		 << "</sw_stats>\n";
	//
	fout.close();
	cout << "Ok." << endl;
	cout << "Results written into '" << resultsFile << "'." << endl;
	//
	//delete project;
	return 0;
}
// This method generates an XML file describing the crash
BOOL CErrorReportExporter::CreateCrashDescriptionXML(CErrorReportInfo& eri)
{
	BOOL bStatus = FALSE;
	ERIFileItem fi;
	CString sFileName = eri.GetErrorReportDirName() + _T("\\crashrpt.xml");
	CString sErrorMsg;
	strconv_t strconv;
	TiXmlDocument doc;
	FILE* f = NULL; 
	CString sNum;
	CString sCrashRptVer;
	CString sOSIs64Bit;
	CString sExceptionType;

	fi.m_bMakeCopy = false;
	fi.m_sDesc = _T("±ÀÀ£³ÌÐòÊôÐÔ¼¯");
	fi.m_sDestFile = _T("crashrpt.xml");
	fi.m_sSrcFile = sFileName;
	fi.m_sErrorStatus = sErrorMsg;  
	// Add this file to the list
	eri.AddFileItem(&fi);

	TiXmlNode* root = root = new TiXmlElement("CrashRpt");
	doc.LinkEndChild(root);  
	sCrashRptVer.Format(_T("%d"), CRASHRPT_VER);
	TiXmlHandle(root).ToElement()->SetAttribute("version", strconv.t2utf8(sCrashRptVer));

	TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "UTF-8", "" );
	doc.InsertBeforeChild(root, *decl);
	
	AddElemToXML(_T("CrashGUID"), eri.GetCrashGUID(), root);
	AddElemToXML(_T("AppName"), eri.GetAppName(), root);
	AddElemToXML(_T("AppVersion"), eri.GetAppVersion(), root);  
	AddElemToXML(_T("ImageName"), eri.GetImageName(), root);
	AddElemToXML(_T("OperatingSystem"), eri.GetOSName(), root);


	sOSIs64Bit.Format(_T("%d"), eri.IsOS64Bit());
	AddElemToXML(_T("OSIs64Bit"), sOSIs64Bit, root);

	AddElemToXML(_T("GeoLocation"), eri.GetGeoLocation(), root);
	AddElemToXML(_T("SystemTimeUTC"), eri.GetSystemTimeUTC(), root);
		
	if(eri.GetExceptionAddress()!=0)
	{
		sNum.Format(_T("0x%I64x"), eri.GetExceptionAddress());
		AddElemToXML(_T("ExceptionAddress"), sNum, root);

		AddElemToXML(_T("ExceptionModule"), eri.GetExceptionModule(), root);

		sNum.Format(_T("0x%I64x"), eri.GetExceptionModuleBase());
		AddElemToXML(_T("ExceptionModuleBase"), sNum, root);

		AddElemToXML(_T("ExceptionModuleVersion"), eri.GetExceptionModuleVersion(), root);
	}

	sExceptionType.Format(_T("%d"), m_CrashInfo.m_nExceptionType);
	AddElemToXML(_T("ExceptionType"), sExceptionType, root);
	if(m_CrashInfo.m_nExceptionType==CR_SEH_EXCEPTION)
	{
		CString sExceptionCode;
		sExceptionCode.Format(_T("%d"), m_CrashInfo.m_dwExceptionCode);
		AddElemToXML(_T("ExceptionCode"), sExceptionCode, root);
	}
	else if(m_CrashInfo.m_nExceptionType==CR_CPP_SIGFPE)
	{
		CString sFPESubcode;
		sFPESubcode.Format(_T("%d"), m_CrashInfo.m_uFPESubcode);
		AddElemToXML(_T("FPESubcode"), sFPESubcode, root);
	}
	else if(m_CrashInfo.m_nExceptionType==CR_CPP_INVALID_PARAMETER)
	{
		AddElemToXML(_T("InvParamExpression"), m_CrashInfo.m_sInvParamExpr, root);
		AddElemToXML(_T("InvParamFunction"), m_CrashInfo.m_sInvParamFunction, root);
		AddElemToXML(_T("InvParamFile"), m_CrashInfo.m_sInvParamFile, root);

		CString sInvParamLine;
		sInvParamLine.Format(_T("%d"), m_CrashInfo.m_uInvParamLine);
		AddElemToXML(_T("InvParamLine"), sInvParamLine, root);
	}

	CString sGuiResources;
	sGuiResources.Format(_T("%d"), eri.GetGuiResourceCount());
	AddElemToXML(_T("GUIResourceCount"), sGuiResources, root);

	CString sProcessHandleCount;
	sProcessHandleCount.Format(_T("%d"), eri.GetProcessHandleCount());
	AddElemToXML(_T("OpenHandleCount"), sProcessHandleCount, root);

	AddElemToXML(_T("MemoryUsageKbytes"), eri.GetMemUsage(), root);

	if(eri.GetScreenshotInfo().m_bValid)
	{
		TiXmlHandle hScreenshotInfo = new TiXmlElement("ScreenshotInfo");
		root->LinkEndChild(hScreenshotInfo.ToNode());

		TiXmlHandle hVirtualScreen = new TiXmlElement("VirtualScreen");    

		sNum.Format(_T("%d"), eri.GetScreenshotInfo().m_rcVirtualScreen.left);
		hVirtualScreen.ToElement()->SetAttribute("left", strconv.t2utf8(sNum));

		sNum.Format(_T("%d"), eri.GetScreenshotInfo().m_rcVirtualScreen.top);
		hVirtualScreen.ToElement()->SetAttribute("top", strconv.t2utf8(sNum));

		sNum.Format(_T("%d"), eri.GetScreenshotInfo().m_rcVirtualScreen.Width());
		hVirtualScreen.ToElement()->SetAttribute("width", strconv.t2utf8(sNum));

		sNum.Format(_T("%d"), eri.GetScreenshotInfo().m_rcVirtualScreen.Height());
		hVirtualScreen.ToElement()->SetAttribute("height", strconv.t2utf8(sNum));

		hScreenshotInfo.ToNode()->LinkEndChild(hVirtualScreen.ToNode());

		TiXmlHandle hMonitors = new TiXmlElement("Monitors");
		hScreenshotInfo.ToElement()->LinkEndChild(hMonitors.ToNode());                  

		size_t i;
		for(i=0; i<eri.GetScreenshotInfo().m_aMonitors.size(); i++)
		{ 
			MonitorInfo& mi = eri.GetScreenshotInfo().m_aMonitors[i];      
			TiXmlHandle hMonitor = new TiXmlElement("Monitor");

			sNum.Format(_T("%d"), mi.m_rcMonitor.left);
			hMonitor.ToElement()->SetAttribute("left", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), mi.m_rcMonitor.top);
			hMonitor.ToElement()->SetAttribute("top", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), mi.m_rcMonitor.Width());
			hMonitor.ToElement()->SetAttribute("width", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), mi.m_rcMonitor.Height());
			hMonitor.ToElement()->SetAttribute("height", strconv.t2utf8(sNum));

			hMonitor.ToElement()->SetAttribute("file", strconv.t2utf8(Utility::GetFileName(mi.m_sFileName)));

			hMonitors.ToElement()->LinkEndChild(hMonitor.ToNode());                  
		}

		TiXmlHandle hWindows = new TiXmlElement("Windows");
		hScreenshotInfo.ToElement()->LinkEndChild(hWindows.ToNode());                  

		for(i=0; i<eri.GetScreenshotInfo().m_aWindows.size(); i++)
		{ 
			WindowInfo& wi = eri.GetScreenshotInfo().m_aWindows[i];      
			TiXmlHandle hWindow = new TiXmlElement("Window");

			sNum.Format(_T("%d"), wi.m_rcWnd.left);
			hWindow.ToElement()->SetAttribute("left", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), wi.m_rcWnd.top);
			hWindow.ToElement()->SetAttribute("top", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), wi.m_rcWnd.Width());
			hWindow.ToElement()->SetAttribute("width", strconv.t2utf8(sNum));

			sNum.Format(_T("%d"), wi.m_rcWnd.Height());
			hWindow.ToElement()->SetAttribute("height", strconv.t2utf8(sNum));

			hWindow.ToElement()->SetAttribute("title", strconv.t2utf8(wi.m_sTitle));

			hWindows.ToElement()->LinkEndChild(hWindow.ToNode());                  
		}
	}

	TiXmlHandle hCustomProps = new TiXmlElement("CustomProps");
	root->LinkEndChild(hCustomProps.ToNode());

	int i;
	for(i=0; i<eri.GetPropCount(); i++)
	{ 
		CString sName;
		CString sVal;
		eri.GetPropByIndex(i, sName, sVal);

		TiXmlHandle hProp = new TiXmlElement("Prop");

		hProp.ToElement()->SetAttribute("name", strconv.t2utf8(sName));
		hProp.ToElement()->SetAttribute("value", strconv.t2utf8(sVal));

		hCustomProps.ToElement()->LinkEndChild(hProp.ToNode());                  
	}

	TiXmlHandle hFileItems = new TiXmlElement("FileList");
	root->LinkEndChild(hFileItems.ToNode());

	for(i=0; i<eri.GetFileItemCount(); i++)
	{    
		ERIFileItem* rfi = eri.GetFileItemByIndex(i);
		TiXmlHandle hFileItem = new TiXmlElement("FileItem");

		hFileItem.ToElement()->SetAttribute("name", strconv.t2utf8(rfi->m_sDestFile));
		hFileItem.ToElement()->SetAttribute("description", strconv.t2utf8(rfi->m_sDesc));
		if(rfi->m_bAllowDelete)
			hFileItem.ToElement()->SetAttribute("optional", "1");
		if(!rfi->m_sErrorStatus.IsEmpty())
			hFileItem.ToElement()->SetAttribute("error", strconv.t2utf8(rfi->m_sErrorStatus));

		hFileItems.ToElement()->LinkEndChild(hFileItem.ToNode());                  
	}

#if _MSC_VER<1400
	f = _tfopen(sFileName, _T("w"));
#else
	_tfopen_s(&f, sFileName, _T("w"));
#endif

	if(f==NULL)
	{
		sErrorMsg = _T("Error opening file for writing");
		goto cleanup;
	}

	doc.useMicrosoftBOM = true;
	bool bSave = doc.SaveFile(f); 
	if(!bSave)
	{
		sErrorMsg = doc.ErrorDesc();
		goto cleanup;
	}

	fclose(f);
	f = NULL;

	bStatus = TRUE;

cleanup:

	if(f)
		fclose(f);

	if(!bStatus)
	{
		eri.GetFileItemByName(fi.m_sDestFile)->m_sErrorStatus = sErrorMsg;
	}

	return bStatus;
}
bool XMLModelDefinitionSerializer::exportScript(ModelDefinitionPtr modelDef, const std::string& directory, const std::string& filename)
{
	if (filename == "") {
		return false;
	}

	TiXmlDocument xmlDoc;

	try
	{

		if (!oslink::directory(directory).isExisting()) {
			S_LOG_INFO("Creating directory " << directory);
			oslink::directory::mkdir(directory.c_str());
		}

		TiXmlElement elem("models");
		TiXmlElement modelElem("model");
		modelElem.SetAttribute("name", modelDef->getName().c_str());

		std::string useScaleOf;
		switch (modelDef->getUseScaleOf()) {
			case ModelDefinition::MODEL_ALL:
				useScaleOf = "all";
				break;
			case ModelDefinition::MODEL_DEPTH:
				useScaleOf = "depth";
				break;
			case ModelDefinition::MODEL_HEIGHT:
				useScaleOf = "height";
				break;
			case ModelDefinition::MODEL_NONE:
				useScaleOf = "none";
				break;
			case ModelDefinition::MODEL_WIDTH:
				useScaleOf = "width";
				break;
		}
		modelElem.SetAttribute("usescaleof", useScaleOf.c_str());

		if (modelDef->getRenderingDistance() != 0.0f) {
			modelElem.SetDoubleAttribute("renderingdistance", modelDef->getRenderingDistance());
		}

		if (modelDef->getScale() != 0) {
			modelElem.SetDoubleAttribute("scale", modelDef->getScale());
		}

		modelElem.SetAttribute("showcontained", modelDef->getShowContained() ? "true" : "false");

		if (modelDef->getContentOffset() != Ogre::Vector3::ZERO) {
			TiXmlElement contentOffset("contentoffset");
			XMLHelper::fillElementFromVector3(contentOffset, modelDef->getContentOffset());
			modelElem.InsertEndChild(contentOffset);
		}

		const RenderingDefinition* renderingDef = modelDef->getRenderingDefinition();
		if (renderingDef) {
			TiXmlElement rendering("rendering");
			rendering.SetAttribute("scheme", renderingDef->getScheme().c_str());
			for (StringParamStore::const_iterator I  = renderingDef->getParameters().begin();
					I != renderingDef->getParameters().end(); ++I)
			{
				TiXmlElement param("param");
				param.SetAttribute("key", I->first.c_str());
				param.SetValue(I->second.c_str());
				rendering.InsertEndChild(param);
			}
			modelElem.InsertEndChild(rendering);
		}


		TiXmlElement translate("translate");
		XMLHelper::fillElementFromVector3(translate, modelDef->getTranslate());
		modelElem.InsertEndChild(translate);

		TiXmlElement rotation("rotation");
		XMLHelper::fillElementFromQuaternion(rotation, modelDef->getRotation());
		modelElem.InsertEndChild(rotation);

		modelElem.SetAttribute("icon", modelDef->getIconPath().c_str());

		if (modelDef->getRenderingDefinition()) {
			TiXmlElement rendering("rendering");
			rendering.SetAttribute("scheme", modelDef->getRenderingDefinition()->getScheme().c_str());
			for (StringParamStore::const_iterator I = modelDef->getRenderingDefinition()->getParameters().begin(); I != modelDef->getRenderingDefinition()->getParameters().end(); ++I) {
				TiXmlElement param("param");
				param.SetAttribute("key", I->first.c_str());
				param.SetValue(I->second.c_str());
			}
		}

		//start with submodels
		exportSubModels(modelDef, modelElem);

		//now do actions
		exportActions(modelDef, modelElem);

		exportAttachPoints(modelDef, modelElem);

		exportViews(modelDef, modelElem);

		exportLights(modelDef, modelElem);

		exportParticleSystems(modelDef, modelElem);

		exportBoneGroups(modelDef, modelElem);

		exportPoses(modelDef, modelElem);

		elem.InsertEndChild(modelElem);

		xmlDoc.InsertEndChild(elem);
		xmlDoc.SaveFile((directory + filename).c_str());
		S_LOG_INFO("Saved file " << (directory + filename));
		return true;
	}
	catch (...)
	{
		S_LOG_FAILURE("An error occurred saving the modeldefinition for "<< modelDef->getName() << "." );
		return false;
	}


}
Esempio n. 23
0
void SaveDevicedataXml(const char *path, const t_DeviceData *deviceData) {
	int lane_count;
	int lane_index;
	int point_index;
	char ach_index[8];
	char ach_x[16];
	char ach_y[16];
	char ach_type[16];

	const t_DeviceLine *deviceLine = &deviceData->m_device_line;
	TiXmlDocument *doc = new TiXmlDocument();
	TiXmlDeclaration *declar = new TiXmlDeclaration( "1.0", "UTF-8", "" );
	TiXmlElement *root = new TiXmlElement("DeviceLine");
	TiXmlElement *first = new TiXmlElement("DetectArea");
	TiXmlElement *second = new TiXmlElement("KakouLine");
	TiXmlElement *third = new TiXmlElement("LaneLine");
	doc->LinkEndChild(declar);
	doc->LinkEndChild(root);
	root->LinkEndChild(first);
	root->LinkEndChild(second);
	root->LinkEndChild(third);
	for (point_index = 0; point_index < deviceLine->m_point_count; point_index++) {
		sprintf(ach_index, "%d", point_index);
		sprintf(ach_x, "%d", deviceLine->m_detect_area[point_index].m_x);
		sprintf(ach_y, "%d", deviceLine->m_detect_area[point_index].m_y);
		TiXmlElement *point = new TiXmlElement("point");
		first->LinkEndChild(point);
		point->SetAttribute("index", ach_index);
		point->SetAttribute("X", ach_x);
		point->SetAttribute("Y", ach_y);
	}
	TiXmlElement *line = new TiXmlElement("Line");
	second->LinkEndChild(line);
	for (point_index = 0; point_index < 2; point_index++) {
		sprintf(ach_index, "%d", point_index);
		if (0 == point_index) {
			sprintf(ach_x, "%d", deviceLine->m_kakou_line.m_head.m_x);
			sprintf(ach_y, "%d", deviceLine->m_kakou_line.m_head.m_y);	
		}
		else {
			sprintf(ach_x, "%d", deviceLine->m_kakou_line.m_tail.m_x);
			sprintf(ach_y, "%d", deviceLine->m_kakou_line.m_tail.m_y);	
		}
		TiXmlElement *point = new TiXmlElement("point");
		line->LinkEndChild(point);
		point->SetAttribute("index", ach_index);
		point->SetAttribute("X", ach_x);
		point->SetAttribute("Y", ach_y);
	}
	lane_count = deviceLine->m_lane_count + 1;
	for (lane_index = 0; lane_index < lane_count; lane_index++) {
		TiXmlElement *lane = new TiXmlElement("Lane");
		third->LinkEndChild(lane);
		for (point_index = 0; point_index < deviceLine->m_lane_line[lane_index].m_count; point_index++) {
			sprintf(ach_index, "%d", point_index);
			if (0 == point_index) {
				sprintf(ach_x, "%d", deviceLine->m_lane_line[lane_index].m_point[point_index].m_x);
				sprintf(ach_y, "%d", deviceLine->m_lane_line[lane_index].m_point[point_index].m_y);	
				sprintf(ach_type, "%d", deviceLine->m_lane_line[lane_index].m_type);	
			}
			else {
				sprintf(ach_x, "%d", deviceLine->m_lane_line[lane_index].m_point[point_index].m_x);
				sprintf(ach_y, "%d", deviceLine->m_lane_line[lane_index].m_point[point_index].m_y);	
				sprintf(ach_type, "%d", deviceLine->m_lane_line[lane_index].m_type);	
			}
			TiXmlElement *point = new TiXmlElement("point");
			lane->SetAttribute("index", lane_index);
			lane->SetAttribute("Type", ach_type);
			lane->LinkEndChild(point);
			point->SetAttribute("index", ach_index);
			point->SetAttribute("X", ach_x);
			point->SetAttribute("Y", ach_y);
		}
	}
	doc->SaveFile(path);
	delete doc;
}
Esempio n. 24
0
void WatchDog::CPingJob::DoWork()
{
  if (!m_jobHandler)
  {
    CLog::Log(LOGWARNING,"CPingJob::DoWork - Can't execute the job. [jobHandler=NULL] (ping)");
    return;
  }

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - Enter function. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());


  if (!m_jobHandler->IsConnectedToInternet())
  {
    CLog::Log(LOGDEBUG,"CPingJob::DoWork - There is no internet connection -> Don't try to send ping. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());
    return;
  }

  std::set<CStdString> allowedPaths;
  std::set<CStdString> allowedExt;

  allowedPaths.insert("special://xbmc");
  allowedPaths.insert("special://home");
  allowedPaths.insert("special://temp");

  allowedExt.insert(".xml");
  allowedExt.insert(".png");
  allowedExt.insert(".gif");
  allowedExt.insert(".jpg");
  allowedExt.insert(".tbn");

  // test boxee
  BOXEE::BXCurl curl;

  CStdString strClientPingVersion = "";
  CStdString pingUrl = "";

  bool succeed = InitPingRequest(pingUrl,strClientPingVersion);

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - Call to InitPingRequest() returned [%d]. [strClientPingVersion=%s][pingUrl=%s] (ping)",succeed,strClientPingVersion.c_str(),pingUrl.c_str());

  if(!succeed)
  {
    CLog::Log(LOGERROR,"CPingJob::DoWork - Call to InitPingParams() FAILED. [retVal=%d] (ping)",succeed);
    return;
  }

  int nClientPingVersion = atoi(strClientPingVersion.c_str());

  CLog::Log(LOGWARNING,"CPingJob::DoWork - Going to check ping. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());

  std::string strResp = curl.HttpGetString(pingUrl, false);
  g_application.SetBoxeeServerIP(curl.GetServerIP());

  long retCode = curl.GetLastRetCode();
  CLog::Log(LOGWARNING,"CPingJob::DoWork - Check ping returned [retCode=%ld][Response-IsEmpty=%d]. [server=%d][internet=%d] (ping)",retCode,strResp.empty(),m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());

  m_jobHandler->SetIsConnectedToServer((retCode == 200));

  BOXEE::BXXMLDocument reader;
  if (strResp.empty())
  {
    CLog::Log(LOGDEBUG,"WatchDog::Process - Not handling server response to [pingUrl=%s] because it is empty (ping)",pingUrl.c_str());
    return;
  }

  if(!reader.LoadFromString(strResp))
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Not handling server response to [pingUrl=%s] because failed to load it to BXXMLDocument (ping)",pingUrl.c_str());
    return;
  }

  TiXmlElement* root = reader.GetRoot();

  if(!root)
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Failed to get root from BXXMLDocument of the ping response (ping)");
    return;
  }

  if((strcmp(root->Value(),"ping") != 0))
  {
    CLog::Log(LOGERROR,"WatchDog::Process - Failed to parse ping response because the root tag ISN'T <ping> (ping)");
    return;
  }

  CLog::Log(LOGDEBUG,"CPingJob::DoWork - The root tag <ping> was found. Going to parse the ping response (ping)");

  TiXmlElement* pingChildElem = NULL;
  pingChildElem = root->FirstChildElement();

  while (pingChildElem)
  {
    if (strcmp(pingChildElem->Value(), "cmds") == 0)
    {
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <cmds> tag was found (ping)");

      CStdString strServerPingVersion = "";
      strServerPingVersion = pingChildElem->Attribute("ping_version");
      int nServerPingVersion = atoi(strServerPingVersion.c_str());

      if (nServerPingVersion > nClientPingVersion)
      {
        CLog::Log(LOGDEBUG,"CPingJob::DoWork - Because [nServerPingVersion=%d] > [%d=nClientPingVersion] going to parse the <cmds> tag (ping)",nServerPingVersion,nClientPingVersion);

        TiXmlElement* cmdsChildElem = NULL;
        cmdsChildElem = pingChildElem->FirstChildElement();

        while (cmdsChildElem)
        {
          if (strcmp(cmdsChildElem->Value(), "download") == 0)
          {
            CStdString url = cmdsChildElem->Attribute("url");
            CStdString local = cmdsChildElem->Attribute("local");
            CStdString hash = cmdsChildElem->Attribute("hash");

            CLog::Log(LOGDEBUG,"CPingJob::DoWork - Found <download> tag with attributes [url=%s][local=%s][hash=%s] (ping)",url.c_str(),local.c_str(),hash.c_str());

            if (!url.IsEmpty() && !local.IsEmpty())
            {
              CStdString strDir;
              CStdString strLocal = local;
              CStdString ext = CUtil::GetExtension(strLocal);
              CStdString strName = CUtil::GetFileName(strLocal);
              CUtil::GetDirectory(strLocal, strDir);
              if (allowedExt.find(ext.c_str()) != allowedExt.end() && allowedPaths.find(CUtil::GetSpecialPathPrefix(local).c_str()) != allowedPaths.end() && CUtil::CreateDirectoryEx(strDir))
              {
                CLog::Log(LOGDEBUG,"CPingJob::DoWork - Going to download [url=%s] (ping)",url.c_str());
                BoxeeUtils::SafeDownload(url.c_str(), strLocal.c_str(), hash);
              }
            }
          }
          else if (strcmp(cmdsChildElem->Value(), "remove") == 0)
          {
            CStdString local = cmdsChildElem->Attribute("path");

            CLog::Log(LOGDEBUG,"CPingJob::DoWork - Found <remove> tag with attributes [local=%s] (ping)",local.c_str());

            CStdString strLocal = local;
            CStdString ext = CUtil::GetExtension(strLocal);
            if (allowedExt.find(ext.c_str()) != allowedExt.end() && allowedPaths.find(CUtil::GetSpecialPathPrefix(local).c_str()) != allowedPaths.end())
            {
              CLog::Log(LOGDEBUG,"CPingJob::DoWork - Going to delete [strLocal=%s] (ping)",strLocal.c_str());
              ::DeleteFile(strLocal);
            }
          }

          cmdsChildElem = cmdsChildElem->NextSiblingElement();
        }

        if (!strServerPingVersion.IsEmpty())
        {
          // currently - version is the only info kept so we take a shortcut...
          TiXmlDocument *infoDoc = NULL;
          CStdString strInfoDoc = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><info><ping_version>"+strServerPingVersion+"</ping_version></info>";
          BOXEE::BXXMLDocument newinfo;
          if (newinfo.LoadFromString(strInfoDoc))
          {
            infoDoc = newinfo.GetRoot()->GetDocument();
          }

          if (infoDoc)
          {
            infoDoc->SaveFile(PTH_IC(BXINFO_FILE_PATH));
          }
        }
      }
      else
      {
        CLog::Log(LOGDEBUG,"CPingJob::DoWork - Because [nServerPingVersion=%d] <= [%d=nClientPingVersion] NOT going to parse the <cmds> tag (ping)",nServerPingVersion,nClientPingVersion);
      }
    }
#ifndef HAS_EMBEDDED
    else if (strcmp(pingChildElem->Value(),"version_update") == 0)
    {
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <version_update> tag was found (ping)");

      succeed = g_boxeeVersionUpdateManager.HandleVersionUpdate(root, pingChildElem);
      CLog::Log(LOGDEBUG,"CPingJob::DoWork - Call to CBoxeeVersionUpdateManager::HandleVersionUpdate returned [%d]",succeed);
    }
#else
    else if (strcmp(pingChildElem->Value(),"timestamp") == 0)
    {
      time_t currentTime = time(NULL);
      time_t timeStamp = 0;
      char *endptr;

      CLog::Log(LOGDEBUG,"CPingJob::DoWork - The <timestamp> tag was found (ping)");

      CStdString strTimestamp = pingChildElem->Attribute("utc");

      timeStamp = strtol(strTimestamp.c_str(), &endptr, 10);

      if(abs(currentTime - timeStamp) > 60 * 60 )
      {
        IHalServices& client = CHalServicesFactory::GetInstance();
        client.SetTime(strTimestamp);
      }
    }
#endif

    pingChildElem = pingChildElem->NextSiblingElement();
  }

  //CLog::Log(LOGDEBUG,"CPingJob::DoWork - Exit function. [server=%d][internet=%d] (ping)",m_jobHandler->IsConnectedToServer(),m_jobHandler->IsConnectedToInternet());
}
Esempio n. 25
0
bool Scene::SaveXml(String file)
{
	TiXmlDocument xml;	TiXmlElement root("scene");

	TiXmlElement car("car");
		car.SetAttribute("tires",	asphalt ? "1":"0");
		if (damageMul != 1.f)
			car.SetAttribute("damage",	toStrC( damageMul ));

		if (denyReversed)
			car.SetAttribute("denyRev",	"1");
		if (gravity != 9.81f)
			car.SetAttribute("gravity",	toStrC( gravity ));
	root.InsertEndChild(car);


	TiXmlElement st("start");
		std::string s = toStr(startPos[0])+" "+toStr(startPos[1])+" "+toStr(startPos[2]);
		st.SetAttribute("pos",	s.c_str());

		s = toStr(startRot[0])+" "+toStr(startRot[1])+" "+toStr(startRot[2])+" "+toStr(startRot[3]);
		st.SetAttribute("rot",	s.c_str());
	root.InsertEndChild(st);


	TiXmlElement sky("sky");
		sky.SetAttribute("material",	skyMtr.c_str());
		if (rainEmit > 0 && rainName != "")
		{	sky.SetAttribute("rainName",	rainName.c_str());
			sky.SetAttribute("rainEmit",	toStrC( rainEmit ));
		}
		if (rain2Emit > 0 && rain2Name != "")
		{	sky.SetAttribute("rain2Name",	rain2Name.c_str());
			sky.SetAttribute("rain2Emit",	toStrC( rain2Emit ));
		}
		if (windAmt != 0.f)
			sky.SetAttribute("windAmt",	toStrC( windAmt ));
	root.InsertEndChild(sky);

	TiXmlElement fog("fog");
		fog.SetAttribute("color",		toStrC( fogClr ));
		fog.SetAttribute("color2",		toStrC( fogClr2 ));
		fog.SetAttribute("linStart",	toStrC( fogStart ));
		fog.SetAttribute("linEnd",		toStrC( fogEnd ));
	root.InsertEndChild(fog);

	TiXmlElement fogH("fogH");
		fogH.SetAttribute("color",		toStrC( fogClrH ));
		fogH.SetAttribute("height",		toStrC( fogHeight ));
		fogH.SetAttribute("dens",		toStrC( fogHDensity ));
		fogH.SetAttribute("linStart",	toStrC( fogHStart ));
		fogH.SetAttribute("linEnd",		toStrC( fogHEnd ));
	root.InsertEndChild(fogH);

	TiXmlElement li("light");
		li.SetAttribute("sceneryId",	sceneryId.c_str() );
		li.SetAttribute("pitch",		toStrC( ldPitch ));
		li.SetAttribute("yaw",			toStrC( ldYaw ));
		li.SetAttribute("ambient",		toStrC( lAmb ));
		li.SetAttribute("diffuse",		toStrC( lDiff ));
		li.SetAttribute("specular",		toStrC( lSpec ));
	root.InsertEndChild(li);
	

	TiXmlElement fls("fluids");
		for (int i=0; i < fluids.size(); ++i)
		{
			const FluidBox* fb = &fluids[i];
			TiXmlElement fe("fluid");
			fe.SetAttribute("name",		fb->name.c_str() );
			fe.SetAttribute("pos",		toStrC( fb->pos ));
			fe.SetAttribute("rot",		toStrC( fb->rot ));
			fe.SetAttribute("size",		toStrC( fb->size ));
			fe.SetAttribute("tile",		toStrC( fb->tile ));
			fls.InsertEndChild(fe);
		}
	root.InsertEndChild(fls);


	TiXmlElement ter("terrain");
		ter.SetAttribute("size",		toStrC( td.iVertsX ));
		ter.SetAttribute("triangle",	toStrC( td.fTriangleSize ));
		ter.SetAttribute("errNorm",		fToStr( td.errorNorm, 2,4 ).c_str());
		if (td.normScale != 1.f)
			ter.SetAttribute("normSc",		toStrC( td.normScale ));
		if (td.emissive)
			ter.SetAttribute("emissive",	td.emissive ? 1 : 0);
		if (td.specularPow != 32.f)
			ter.SetAttribute("specPow",		toStrC( td.specularPow ));
		if (td.specularPowEm != 2.f)
			ter.SetAttribute("specPowEm",	toStrC( td.specularPowEm ));

		const TerLayer* l;
		for (int i=0; i < 6; ++i)
		{
			l = &td.layersAll[i];
			TiXmlElement tex("texture");
			tex.SetAttribute("on",		l->on ? 1 : 0);
			tex.SetAttribute("file",	l->texFile.c_str());
			tex.SetAttribute("fnorm",	l->texNorm.c_str());
			tex.SetAttribute("scale",	toStrC( l->tiling ));
			tex.SetAttribute("surf",	l->surfName.c_str());
			#define setDmst()  \
				tex.SetAttribute("dust",	toStrC( l->dust ));  \
				tex.SetAttribute("dustS",	toStrC( l->dustS )); \
				tex.SetAttribute("mud",		toStrC( l->mud ));   \
				tex.SetAttribute("smoke",	toStrC( l->smoke )); \
				tex.SetAttribute("tclr",	toStrC( l->tclr ));
			setDmst();
			tex.SetAttribute("angMin",	toStrC( l->angMin ));
			tex.SetAttribute("angMax",	toStrC( l->angMax ));
			tex.SetAttribute("angSm",	toStrC( l->angSm ));
			tex.SetAttribute("hMin",	toStrC( l->hMin ));
			tex.SetAttribute("hMax",	toStrC( l->hMax ));
			tex.SetAttribute("hSm",		toStrC( l->hSm ));

			tex.SetAttribute("nOn",		l->nOnly ? 1 : 0);
			if (l->triplanar)  tex.SetAttribute("triplanar", 1);

			tex.SetAttribute("noise",	toStrC( l->noise ));
			tex.SetAttribute("n_1",		toStrC( l->nprev ));
			tex.SetAttribute("n2",		toStrC( l->nnext2 ));

			TiXmlElement noi("noise");
			for (int n=0; n < 2; ++n)
			{	std::string sn = toStr(n), s;
				s = "frq"+sn;  noi.SetAttribute(s.c_str(),  toStrC( l->nFreq[n] ));
				s = "oct"+sn;  noi.SetAttribute(s.c_str(),  toStrC( l->nOct[n] ));
				s = "prs"+sn;  noi.SetAttribute(s.c_str(),  toStrC( l->nPers[n] ));
				s = "pow"+sn;  noi.SetAttribute(s.c_str(),  toStrC( l->nPow[n] ));
			}
			tex.InsertEndChild(noi);
			ter.InsertEndChild(tex);
		}
		l = &td.layerRoad;
		TiXmlElement tex("texture");
		tex.SetAttribute("road",	1);
		tex.SetAttribute("surf",	l->surfName.c_str());
		setDmst();
		ter.InsertEndChild(tex);
	
		TiXmlElement par("par");
			par.SetAttribute("dust",	sParDust.c_str());
			par.SetAttribute("mud",		sParMud.c_str());
			par.SetAttribute("smoke",	sParSmoke.c_str());
		ter.InsertEndChild(par);
	root.InsertEndChild(ter);
	

	TiXmlElement pgd("paged");
		pgd.SetAttribute("densGrass",	toStrC( densGrass ));
		pgd.SetAttribute("densTrees",	toStrC( densTrees ));
		//  grass
		pgd.SetAttribute("grPage",		toStrC( grPage ));
		pgd.SetAttribute("grDist",		toStrC( grDist ));
		pgd.SetAttribute("grDensSmooth",toStrC( grDensSmooth ));

		//  trees
		pgd.SetAttribute("trPage",		toStrC( trPage ));
		pgd.SetAttribute("trDist",		toStrC( trDist ));
		pgd.SetAttribute("trDistImp",	toStrC( trDistImp ));
		pgd.SetAttribute("trRdDist",	toStrC( trRdDist  ));

		int i;
		for (int i=0; i < ciNumGrLay; ++i)
		{
			const SGrassLayer& g = grLayersAll[i];
			TiXmlElement grl("grass");
			grl.SetAttribute("on",		g.on ? 1 : 0);
			grl.SetAttribute("mtr",		g.material.c_str());
			grl.SetAttribute("clr",		g.colorMap.c_str());
			grl.SetAttribute("dens",	toStrC( g.dens ));
			grl.SetAttribute("chan",	toStrC( g.iChan ));

			grl.SetAttribute("minSx",	toStrC( g.minSx ));
			grl.SetAttribute("maxSx",	toStrC( g.maxSx ));
			grl.SetAttribute("minSy",	toStrC( g.minSy ));
			grl.SetAttribute("maxSy",	toStrC( g.maxSy ));

			grl.SetAttribute("swayDistr",	toStrC( g.swayDistr ));
			grl.SetAttribute("swayLen",		toStrC( g.swayLen ));
			grl.SetAttribute("swaySpeed",	toStrC( g.swaySpeed ));
			pgd.InsertEndChild(grl);
		}

		for (i=0; i < 4; ++i)
		{
			const SGrassChannel& g = grChan[i];
			TiXmlElement gch("gchan");
			gch.SetAttribute("amin",	toStrC( g.angMin ));
			gch.SetAttribute("amax",	toStrC( g.angMax ));
			gch.SetAttribute("asm",		toStrC( g.angSm ));

			gch.SetAttribute("hmin",	toStrC( g.hMin ));
			gch.SetAttribute("hmax",	toStrC( g.hMax ));
			gch.SetAttribute("hsm",		toStrC( g.hSm ));

			gch.SetAttribute("ns",		toStrC( g.noise ));
			gch.SetAttribute("frq",		toStrC( g.nFreq ));
			gch.SetAttribute("oct",		toStrC( g.nOct ));
			gch.SetAttribute("prs",		toStrC( g.nPers ));
			gch.SetAttribute("pow",		toStrC( g.nPow ));

			gch.SetAttribute("rd",		toStrC( g.rdPow ));
			pgd.InsertEndChild(gch);
		}

		for (i=0; i < ciNumPgLay; ++i)
		{
			const PagedLayer& l = pgLayersAll[i];
			TiXmlElement pgl("layer");
			pgl.SetAttribute("on",			l.on ? 1 : 0);
			pgl.SetAttribute("name",		l.name.c_str());
			pgl.SetAttribute("dens",		toStrC( l.dens ));
			pgl.SetAttribute("minScale",	toStrC( l.minScale ));
			pgl.SetAttribute("maxScale",	toStrC( l.maxScale ));

			pgl.SetAttribute("ofsY",		toStrC( l.ofsY ));
			pgl.SetAttribute("addTrRdDist",	toStrC( l.addRdist ));
			pgl.SetAttribute("maxRdist",	toStrC( l.maxRdist ));
			pgl.SetAttribute("windFx",		toStrC( l.windFx ));
			pgl.SetAttribute("windFy",		toStrC( l.windFy ));

			pgl.SetAttribute("maxTerAng",	toStrC( l.maxTerAng ));
			pgl.SetAttribute("minTerH",		toStrC( l.minTerH ));
			pgl.SetAttribute("maxTerH",		toStrC( l.maxTerH ));
			pgl.SetAttribute("maxDepth",	toStrC( l.maxDepth ));
			pgd.InsertEndChild(pgl);
		}
	root.InsertEndChild(pgd);


	TiXmlElement cam("cam");
		cam.SetAttribute("pos",		toStrC( camPos ));
		cam.SetAttribute("dir",		toStrC( camDir ));
	root.InsertEndChild(cam);


	TiXmlElement objs("objects");
		for (i=0; i < objects.size(); ++i)
		{
			const Object* o = &objects[i];
			TiXmlElement oe("o");
			oe.SetAttribute("name",		o->name.c_str() );

			std::string s = toStr(o->pos[0])+" "+toStr(o->pos[1])+" "+toStr(o->pos[2]);
			oe.SetAttribute("pos",		s.c_str());

			s = toStr(o->rot[0])+" "+toStr(o->rot[1])+" "+toStr(o->rot[2])+" "+toStr(o->rot[3]);
			oe.SetAttribute("rot",		s.c_str());

			if (o->scale != Vector3::UNIT_SCALE)  // dont save default
				oe.SetAttribute("sc",	toStrC( o->scale ));
			objs.InsertEndChild(oe);
		}
	root.InsertEndChild(objs);


	xml.InsertEndChild(root);
	return xml.SaveFile(file.c_str());
}
Esempio n. 26
0
//---------------------------------------------------------------------------
// ----- Methods :: File Serialize (XML) ----- //
//---------------------------------------------------------------------------
bool	Strip::Save		(const TCHAR* lpszFileName)
{
	// ----- Initialize & Declare ----- //
	FILE* stream = _tfopen(lpszFileName, _T("wb") CHARSET);

	if (stream == NULL || _pPimpl == NULL)
	{
		return false;
	}

	TiXmlDocument		doc;
	TiXmlDeclaration*	pDecl;
	TiXmlElement*		pRoot;
	TiXmlElement*		pBlockNode;
	TiXmlElement*		pUnitNode;
	TiXmlElement*		pBallNode;

	Block*				pBlockObject;
	Unit*				pUnitObject;
	Ball*				pBallObject;

	int					vectorBlockSize;
	int					vectorUnitCountX;
	int					vectorUnitCountY;
	int					vectorBallSize;

	pDecl = new TiXmlDeclaration("1.0", "euc-kr", "");
	doc.LinkEndChild(pDecl);

	// ----- Set a Strip Data ----- //
	pRoot = new TiXmlElement(ROOT_NAME_STRIP);
	pRoot->SetDoubleAttribute(ATTR_NAME_WIDTH,	_pPimpl->dWidth);
	pRoot->SetDoubleAttribute(ATTR_NAME_HEIGHT,	_pPimpl->dHeight);
	doc.LinkEndChild(pRoot);

	// ----- Insert a Block Data ----- //
	pBlockObject = FirstBlock();
	if (pBlockObject != NULL)
	{
		do
		{
			pBlockNode = new TiXmlElement(NODE_NAME_BLOCK);

			pBlockNode->SetDoubleAttribute(ATTR_NAME_COLUMN,	pBlockObject->GetColumn	());
			pBlockNode->SetDoubleAttribute(ATTR_NAME_ROW,		pBlockObject->GetRow	());
			pBlockNode->SetDoubleAttribute(ATTR_NAME_WIDTH,		pBlockObject->GetWidth	());
			pBlockNode->SetDoubleAttribute(ATTR_NAME_HEIGHT,	pBlockObject->GetHeight	());
			pBlockNode->SetDoubleAttribute(ATTR_NAME_START_X,	pBlockObject->GetStartX	());
			pBlockNode->SetDoubleAttribute(ATTR_NAME_START_Y,	pBlockObject->GetStartY	());

			// ----- Insert a Unit (in Block) Data ----- //
			pUnitObject = pBlockObject->FirstUnit();
			if (pUnitObject != NULL)
			{
				do
				{
					pUnitNode = new TiXmlElement(NODE_NAME_UNIT);

					pUnitNode->SetDoubleAttribute(ATTR_NAME_COLUMN,		pUnitObject->GetColumn	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_ROW,		pUnitObject->GetRow		());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_START_X,	pUnitObject->GetStartX	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_START_Y,	pUnitObject->GetStartY	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_CENTER_X,	pUnitObject->GetCenterX	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_CENTER_Y,	pUnitObject->GetCenterY	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_WIDTH,		pUnitObject->GetWidth	());
					pUnitNode->SetDoubleAttribute(ATTR_NAME_HEIGHT,		pUnitObject->GetHeight	());

					// ----- Insert a Ball (in Unit) Data ----- //
					pBallObject = pUnitObject->FirstBall();
					if (pBallObject != NULL)
					{
						do
						{
							pBallNode = new TiXmlElement(NODE_NAME_BALL);

							pBallNode->SetDoubleAttribute(ATTR_NAME_DIAMETER,		pBallObject->GetDiameter	());
							pBallNode->SetDoubleAttribute(ATTR_NAME_CENTER_X,		pBallObject->GetCenterX		());
							pBallNode->SetDoubleAttribute(ATTR_NAME_CENTER_Y,		pBallObject->GetCenterY		());
							pBallNode->SetDoubleAttribute(ATTR_NAME_BALL_STATUS,	pBallObject->GetStatus		());

							pUnitNode->LinkEndChild(pBallNode);
						}
						while ((pBallObject = pUnitObject->NextBall()) != NULL);
					}

					pBlockNode->LinkEndChild(pUnitNode);
				}
				while ((pUnitObject = pBlockObject->NextUnit()) != NULL);
			}

			pRoot->LinkEndChild(pBlockNode);
		}
		while ((pBlockObject = NextBlock()) != NULL);
	}

	// ----- Save and Close ----- //
	doc.SaveFile(stream);

	fclose(stream);

	return true;
}
Esempio n. 27
0
void MarkovDecisionProcess::writeValueFunction(double reward) {
  
    int a,i,j,k,n;
    int max_action;
    double max_value;
    int c,s,swap;
    int user_specified_action = 0;

    TiXmlDocument doc;
    TiXmlElement *msg;
    TiXmlComment *comment;

    cout << "MDP -- writing value function to file: " << _valueFile.c_str() << endl;

    TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "", "");
    doc.LinkEndChild(decl);

    TiXmlElement *root = new TiXmlElement("QVALUES");
    doc.LinkEndChild(root);
    root->SetAttribute("NUM-STATES", _numStates);
    root->SetAttribute("NUM-ACTIONS", _numActions);

    // store reward
    _rewards.push_back(reward);
    _maxVals.push_back(getMaxReward(s,a));

    // print out the goal states
    for(i=0; i<_goalStates.size(); i++) {
        TiXmlElement *gElem = new TiXmlElement("GOAL");
        root->LinkEndChild(gElem);
        gElem->SetAttribute("ID", _goalStates[i]);
    }

    // go through each state and print its information 
    // (including the qvals for each action, and the possible next states observed 
    // after taking those actions)
    for(i=0; i<_numStates; i++) {
    
        max_value = -100000;
        max_action = getMaxAction(i, false);
        //        cout << "state[" << i <<"] got max action: " << max_action << endl;        
        user_specified_action = 0;

        if(_policy.find(i) != _policy.end()) {
            //        if(_policy[i] != -1) {
            if(max_action != _policy[i]) {
                max_action = _policy[i];
            }
            //	cout << "found a user-specified action for state[" << i << "]: " << _policy[i] << endl;
            user_specified_action = 1;
        }

        // print out the action information for each state
        TiXmlElement *sElem = new TiXmlElement("STATE");
        root->LinkEndChild(sElem);
        sElem->SetAttribute("ID", i);
        sElem->SetAttribute("BEST-ACTION", max_action);
        
        if(user_specified_action==1) {
            sElem->SetAttribute("USER-SPECIFIED", user_specified_action);
        } 

        // print out the qvalue for each state action pair
        for(j=0; j<_numActions; j++) {
            TiXmlElement *aElem = new TiXmlElement("ACTION");
            sElem->LinkEndChild(aElem);
            aElem->SetAttribute("ID", j);
            aElem->SetDoubleAttribute("QVAL", getValue(i,j));

            for(n=0; n<_numStates; n++) {
                // only print if there has been a transition
                if(getTransitions(i,j,n) > 0) {	 
                    TiXmlElement *nElem = new TiXmlElement("NEXT-STATE");
                    aElem->LinkEndChild(nElem);
                    nElem->SetAttribute("ID", n);
                    nElem->SetAttribute("N", getTransitions(i,j,n));
                }
            }
        }      
    }

    // print out the reward information for each episode
    for(i=0; i<_rewards.size(); i++) {
        TiXmlElement *rElem = new TiXmlElement("REWARD");
        root->LinkEndChild(rElem);
        rElem->SetAttribute("EPISODE", i);
        rElem->SetDoubleAttribute("VAL", _rewards[i]);
        rElem->SetDoubleAttribute("MAX_Q", _maxVals[i]);
    }

    cout << endl << "MDP::writeValueFunction() -- writing to file: " << _valueFile.c_str() << endl;
    doc.SaveFile(_valueFile.c_str());

}
Esempio n. 28
0
void gen_tierfee_xml(std::vector<FeeScaleXML*> & feeScale)
{
	// Make xml: <?xml ..><Hello>World</Hello>
	TiXmlDocument doc;
	TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "", "");
	TiXmlElement * element = new TiXmlElement("import");

	//TiXmlText * text = new TiXmlText("World");
	element->SetAttribute("mode", "synchronize");
	doc.LinkEndChild(decl);
	doc.LinkEndChild(element);

	{
		
		for (std::vector < FeeScaleXML* >::iterator iter = feeScale.begin();
			iter != feeScale.end(); iter++) {
			TiXmlElement * feescales = new TiXmlElement("feescale");
			element->LinkEndChild(feescales);
			FeeScaleXML *feescale = *iter;

			TiXmlElement * name = new TiXmlElement("name");
			TiXmlElement * currency = new TiXmlElement("currency");
			TiXmlElement * baseValue = new TiXmlElement("baseValue");
			TiXmlElement * calculationBase = new TiXmlElement("calculationBase");

			TiXmlElement * calculationMethod = new TiXmlElement("calculationMethod");
			TiXmlElement * orderEstimationMode = new TiXmlElement("orderEstimationMode");
			TiXmlElement * overlappingIntervals = new TiXmlElement("overlappingIntervals");
			TiXmlElement * FeeAggregationScheme = new TiXmlElement("FeeAggregationScheme");
			
		


			feescales->LinkEndChild(name);
			feescales->LinkEndChild(currency);
			feescales->LinkEndChild(baseValue);
			feescales->LinkEndChild(calculationBase);
			feescales->LinkEndChild(calculationMethod);
			feescales->LinkEndChild(orderEstimationMode);
			feescales->LinkEndChild(overlappingIntervals);
			feescales->LinkEndChild(FeeAggregationScheme);


			//feescales->LinkEndChild(name);
			name->LinkEndChild(new TiXmlText((feescale->name).c_str() ));
			currency->LinkEndChild(new TiXmlText((feescale->currency).c_str()));
			baseValue->LinkEndChild(new TiXmlText((feescale->baseValue).c_str() ));
			calculationBase->LinkEndChild(new TiXmlText((feescale->calculationBase).c_str() ));
			calculationMethod->LinkEndChild(new TiXmlText((feescale->calculationMethod).c_str()));
			orderEstimationMode->LinkEndChild(new TiXmlText((feescale->orderEstimationMode).c_str()));
			overlappingIntervals->LinkEndChild(new TiXmlText((feescale->overlappingIntervals).c_str()));
			FeeAggregationScheme->LinkEndChild(new TiXmlText((feescale->FeeAggregationScheme).c_str()));
			for (std::vector <interval> ::iterator interval_it = feescale->intervals.begin();
				interval_it != feescale->intervals.end();
				interval_it++) {

				TiXmlElement * intervals = new TiXmlElement("intervals");
				feescales->LinkEndChild(intervals);
				interval feeInterval = *interval_it;

				//-----------------------------------------------------
				TiXmlElement * value = new TiXmlElement("value");
				value->LinkEndChild(new TiXmlText(feeInterval.value.c_str()));
				//-----------------------------------------------------
				TiXmlElement * lowerLimit = new TiXmlElement("lowerLimit");

				if (feeInterval.lowerLimit == "true") {
					lowerLimit->SetAttribute("nil", feeInterval.lowerLimit.c_str());
				}
				else {
					lowerLimit->LinkEndChild(new TiXmlText(feeInterval.lowerLimit.c_str()));
				}
				//-----------------------------------------------------
				TiXmlElement * upperLimit = new TiXmlElement("upperLimit");

				if (feeInterval.upperLimit == "true") {
					upperLimit->SetAttribute("nil", feeInterval.upperLimit.c_str());
				}
				else {
					upperLimit->LinkEndChild(new TiXmlText(feeInterval.upperLimit.c_str()));
				}
				//-----------------------------------------------------
				intervals->LinkEndChild(lowerLimit);
				intervals->LinkEndChild(upperLimit);
				intervals->LinkEndChild(value);

			}
			

			

		}

		doc.SaveFile("BSBFeeScale.xml");
	}
}
Esempio n. 29
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" );
			if ( saved && verify )
			{
				while ( fgets( verifyBuf, 256, verify ) )
				{
					fgets( savedBuf, 256, saved );
					if ( strcmp( verifyBuf, savedBuf ) )
					{
						okay = 0;
						break;
					}
				}
				fclose( saved );
				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() );
	}

	{
		// 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;
}
void HTMLGenerator::createSrcFileResults() {
    TiXmlDocument doc;
	TiXmlElement *eHTML = new TiXmlElement( "html" );
    TiXmlElement *eHEAD = new TiXmlElement( "head" );
    TiXmlElement *eTITLE = new TiXmlElement( "title" );
    TiXmlElement *eBODY = new TiXmlElement( "body" );
    
	TiXmlText * tTITLE = new TiXmlText( "YacStat Results" );
	eHTML->LinkEndChild( eHEAD );
    eHEAD->LinkEndChild( eTITLE );
    eTITLE->LinkEndChild( tTITLE );


    // create head to use code style
    TiXmlElement *meta = new TiXmlElement( "meta" );
    meta->SetAttribute("http-equiv", "Content-Type");
    meta->SetAttribute("content", "text/html; charset=UTF-8");
    TiXmlElement *script1 = new TiXmlElement( "script");
    script1->SetAttribute("type", "text/javascript");
    script1->SetAttribute("src", "scripts/shCore.js");
    script1->LinkEndChild( new TiXmlText(""));
    TiXmlElement *script2 = new TiXmlElement( "script");
    script2->SetAttribute("type", "text/javascript");
    script2->SetAttribute("src", "scripts/shBrushJScript.js");
    script2->LinkEndChild( new TiXmlText(""));
    TiXmlElement *script3 = new TiXmlElement( "script");
    script3->SetAttribute("type", "text/javascript");
    // script3->LinkEndChild( new TiXmlText("SyntaxHighlighter.defaults[\'wrap-lines\'] = true;"));
    // script3->LinkEndChild( new TiXmlText("SyntaxHighlighter.config.bloggerMode = true;"));
    script3->LinkEndChild( new TiXmlText("SyntaxHighlighter.all();"));
    script3->LinkEndChild( new TiXmlText(""));
    TiXmlElement *link = new TiXmlElement( "link" );
    link->SetAttribute("type","text/css");
    link->SetAttribute("rel", "stylesheet");
    link->SetAttribute("href","styles/shCoreDefault.css");
    TiXmlElement *style = new TiXmlElement( "style" );
    style->SetAttribute("type","text/css");
    style->LinkEndChild( new TiXmlText( "body { font-family: courier; }"));

    // style->LinkEndChild( new TiXmlText( "body .syntaxhighlighter .line { white-space: pre-wrap !important; }" ));

    eHEAD->LinkEndChild(meta);
    eHEAD->LinkEndChild(script1);
    eHEAD->LinkEndChild(script2);
    eHEAD->LinkEndChild(link);
    eHEAD->LinkEndChild(script3);
    eHEAD->LinkEndChild(style);
    
    TiXmlElement *mainTable = new TiXmlElement( "table" );
    // for each clone...
    for (t_uint16 i = 0; i < clones.size(); i++) {
        if (i > MAX) {
            break;
        }
        t_clonePair *pair = clones[i];
        // t_cursorInfo *clone_1 = pair->first;
        t_node *clone_1 = pair->first;
        // t_cursorInfo *clone_2 = pair->second;
        t_node *clone_2 = pair->second;
        t_htmlCursorInfo *info;
        TiXmlElement *tr = new TiXmlElement( "tr" );
        TiXmlElement *tr_type = new TiXmlElement( "tr" );
        TiXmlElement *h_type = new TiXmlElement( "h3" );

        // create row to contain all clone pairs found
        // to contain type of clone
        TiXmlElement *td1 = new TiXmlElement( "td" );
        // contain each clone information
        TiXmlElement *td_type = new TiXmlElement( "td" );
        TiXmlElement *h2 = new TiXmlElement( "h4" );
        TiXmlElement *pre1 = new TiXmlElement( "pre" );
        
        h_type->LinkEndChild(new TiXmlText( getCursorKindName(clone_1->kind) ));
        td_type->LinkEndChild(h_type);
        tr_type->LinkEndChild(td_type);

        // now add the code!
        /*
        info = getCursorText(clang_getCursor(*clone_1->loc->tu,
                clone_1->loc->srcLoc));
        */
        info = getCursorText(clone_1);
        string header = info->fileName;
        header.append(": [");
        header.append(info->columnBegin);
        header.append(",");
        header.append(info->columnEnd);
        header.append("]");
        // header.append(getCursorKindName(clone_1->kind));
        // add file name
        // h2->LinkEndChild( new TiXmlText( info->fileName.c_str() ));
        h2->LinkEndChild( new TiXmlText( header.c_str() ));
        // add the source code
        pre1->LinkEndChild( new TiXmlText( info->contents.c_str() ));
        addHighlightToCode(pre1, info);
        td1->LinkEndChild( h2 );
        td1->LinkEndChild( pre1 );

        // now create div with table to contain list of source files
        TiXmlElement *td2 = new TiXmlElement( "td" );
        TiXmlElement *h3 = new TiXmlElement( "h4" );
        TiXmlElement *pre2 = new TiXmlElement( "pre" );
        // now add the code!
        /*
        info = getCursorText(clang_getCursor(*clone_2->loc->tu,
                clone_2->loc->srcLoc));
        */
        info = getCursorText(clone_2);
        header = info->fileName;
        header.append(": [");
        header.append(info->columnBegin);
        header.append(",");
        header.append(info->columnEnd);
        header.append("]");
        h3->LinkEndChild( new TiXmlText( header.c_str() ));
        // add the source code
        pre2->LinkEndChild( new TiXmlText( info->contents.c_str() ));
        addHighlightToCode(pre2, info);
        td2->LinkEndChild( h3 );
        td2->LinkEndChild( pre2 );


        tr->LinkEndChild(td1);
        tr->LinkEndChild(td2);
        mainTable->LinkEndChild(tr_type);
        mainTable->LinkEndChild(tr);
    }

    eBODY->LinkEndChild(mainTable);
    eHTML->LinkEndChild( eBODY );
    // eBODY->LinkEndChild(d1);
	doc.LinkEndChild( eHTML );
	doc.SaveFile( "html/results.html" );

}