Пример #1
0
Progress::Progress(void)
{
	Logger::DiagnosticOut() << "Loading progress record\n";
	//Load XML
	TiXmlDocument doc = TiXmlDocument("Progress.xml");
	doc.LoadFile();
	TiXmlElement* root = doc.FirstChildElement("Progress");
	if(root)
	{
		TiXmlElement* record = root->FirstChildElement("Record");
		int record_number = 0;
		while(record)
		{
			std::string filename = "";
			bool completed = false;
			bool error = false;
			error |= (record->QueryValueAttribute("Filename", &filename) != TIXML_SUCCESS);
			error |= (record->QueryValueAttribute("Completed", &completed) != TIXML_SUCCESS);
			if(error)
				Logger::DiagnosticOut() << "Error parsing record number: " << record_number << ". Possible data: Filename:" << filename << ", completed: " << completed << "\n";
			else
			{
				ProgressRecord pr;
				pr.completed = completed;
				progress_[filename] = pr;
			}
			record = record->NextSiblingElement("Record");
			record_number++;
		}
	}
}
Пример #2
0
// Component transform
void 
CEntityBuilder::buildTransform (TiXmlElement *pNode, Entity* e, Resources *pResource){
  TiXmlElement *pChar = pNode->FirstChildElement("position");
  if ( pChar) {
    int x(0), y(0);
    if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "x", &x) && 
        TIXML_SUCCESS == pChar->QueryValueAttribute( "y", &y) ) {
      e->addComponent(new Transform((float) x, (float) y));
      return;
    }
  }
  LOG2ERR<<"Bad xml description for [Tranform] component\n";
  throw "Bad xml description for [Tranform] component";
}
Пример #3
0
void 
CEntityBuilder::buildComponentResourcesImage( TiXmlElement *pNode,  Entity *e, Resources *pResource ){
  TiXmlElement *pChar = pNode->FirstChildElement("image");
  if ( pChar) {
    std::string alias;
    if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "alias", &alias)){
      BVisual *image = pResource->makeImage( alias);
      addCommonAttributes(pNode, pResource, image);
      // std::string gui;
      // if ( TIXML_SUCCESS == pNode->QueryValueAttribute( "gui", &gui)) {
      //   if (gui == "true") {
      //     image->setGUI(true);
      //   } else {
      //     image->setGUI(false);
      //   }
      // }
      // std::string center;
      // if ( TIXML_SUCCESS == pNode->QueryValueAttribute( "center", &center)) {
      //   if (center == "false") {
      //     image->setCenter(0, 0);
      //   }
      // }
      // int zOrder;
      // if ( TIXML_SUCCESS == pNode->QueryValueAttribute( "z-order", &zOrder)) {
      //   image->setZOrder(zOrder);
      // }
      e->addComponent( image);
      return;
    }
  }
  LOG2ERR<<"Bad kind for  [Resources/Image] component\n";
  throw "Bad kind for  [Resources/Image] component";
}
	void ObjectLibrary::loadDatabase(string filename) {
		TiXmlDocument doc(filename);
		if (!doc.LoadFile()) {
			Error::addMessage(Error::FILE_NOT_FOUND, LIBGENS_LIBRARY_ERROR_FILE + filename);
			return;
		}

		TiXmlHandle hDoc(&doc);
		TiXmlElement* pElem;
		TiXmlHandle hRoot(0);

		pElem=hDoc.FirstChildElement().Element();
		if (!pElem) {
			Error::addMessage(Error::EXCEPTION, LIBGENS_LIBRARY_ERROR_FILE_ROOT);
			return;
		}

		pElem=pElem->FirstChildElement();
		for(pElem; pElem; pElem=pElem->NextSiblingElement()) {
			string entry_name="";
			string category_name="";
			string folder_name="";

			entry_name = pElem->ValueStr();
			pElem->QueryValueAttribute(LIBGENS_LIBRARY_NAME_ATTRIBUTE, &category_name);
			pElem->QueryValueAttribute(LIBGENS_LIBRARY_FOLDER_ATTRIBUTE, &folder_name);

			if ((entry_name==LIBGENS_LIBRARY_ENTRY) && category_name.size() && folder_name.size()) {
				loadCategory(category_name, folder_name);
			}
		}
	}
Пример #5
0
/*
--------------------------------------------------------------------------------------------------
- get a text from file
--------------------------------------------------------------------------------------------------
*/
std::map<long, std::string> MapInfoXmlReader::LoadTextFile(const std::string &Filename)
{
	std::map<long, std::string> res;

	TiXmlDocument doc(Filename);
	if (!doc.LoadFile())
		return res;

	TiXmlHandle hDoc(&doc);
	TiXmlElement* pElem;

	// block: text attributes
	{
		pElem=hDoc.FirstChildElement().Element();

		// should always have a valid root but handle gracefully if it does
		if (!pElem)
			return res;


		// for each text
		pElem=pElem->FirstChildElement("quotes");
		pElem=pElem->FirstChildElement();
		for(;pElem; pElem=pElem->NextSiblingElement())
		{
			long ctid = -1;
			pElem->QueryValueAttribute("id", &ctid);

			if(pElem->FirstChild())
				res[ctid] = pElem->FirstChild()->Value();
		}
	}

	return res;
}
Пример #6
0
// configure the design matrix from an xml element
bool RtDesignMatrix::configure(TiXmlElement *designEle,
                               const RtConfig &config) {
  string name;
  TiXmlElement *optionElmt;

  bool ret = true;

  // iterate over options
  for (TiXmlNode *option = 0;
       (option = designEle->IterateChildren("option", option));) {
    if (option->Type() != TiXmlNode::ELEMENT)
      continue;

    optionElmt = (TiXmlElement*) option;
    if (TIXML_SUCCESS != optionElmt->QueryValueAttribute("name", &name)) {
      continue;
    }

    // build the map between atrribute names and values
    map<string, string> attr = RtConfig::getAttributeMap(*optionElmt);

    // figure out which option we have and process it
    if (!processOption(name, optionElmt->GetText(), attr)) {
      ret = false;
    }
  }

  return ret;
}
EditorLevelDatabase::EditorLevelDatabase(string filename) {
	TiXmlDocument doc(filename);
	if (!doc.LoadFile()) {
		LibGens::Error::addMessage(LibGens::Error::FILE_NOT_FOUND, (string)SONICGLVL_DATABASE_ERROR_FILE + filename);
		return;
	}

	TiXmlHandle hDoc(&doc);
	TiXmlElement* pElem;
	TiXmlHandle hRoot(0);

	pElem=hDoc.FirstChildElement().Element();
	if (!pElem) {
		LibGens::Error::addMessage(LibGens::Error::EXCEPTION, SONICGLVL_DATABASE_ERROR_FILE_ROOT);
		return;
	}

	pElem=pElem->FirstChildElement();
	for(pElem; pElem; pElem=pElem->NextSiblingElement()) {
		string entry_name="";
		string level_name="";
		string geometry_name="";
		string layout_merge_name="";
		string slot_name="";
		string game_name="";

		entry_name = pElem->ValueStr();
		pElem->QueryValueAttribute(SONICGLVL_DATABASE_NAME_ATTRIBUTE, &level_name);
		pElem->QueryValueAttribute(SONICGLVL_DATABASE_GEOMETRY_ATTRIBUTE, &geometry_name);
		pElem->QueryValueAttribute(SONICGLVL_DATABASE_MERGE_ATTRIBUTE, &layout_merge_name);
		pElem->QueryValueAttribute(SONICGLVL_DATABASE_SLOT_ATTRIBUTE, &slot_name);
		pElem->QueryValueAttribute(SONICGLVL_DATABASE_GAME_ATTRIBUTE, &game_name);

		if (!game_name.size()) {
			game_name = LIBGENS_LEVEL_GAME_STRING_GENERATIONS;
		}

		if ((entry_name==SONICGLVL_DATABASE_ENTRY) && level_name.size() && geometry_name.size()) {
			EditorLevelEntry *entry=new EditorLevelEntry(level_name, geometry_name, layout_merge_name, slot_name, game_name);
			entries.push_back(entry);
		}
	}
}
Пример #8
0
void 
CEntityBuilder::buildComponentResourcesText( TiXmlElement *pNode,  Entity *e, Resources *pResource){
  std::string   text, police;
  int           r(0), g(0), b(0), a(0);
  TiXmlElement  *pFontAttr = pNode->FirstChildElement( "text");
  if ( pFontAttr){
    // Warning : only text is accepted here! no formatted text like <b>hello</b>
    text = pFontAttr->GetText();
  }
  
  pFontAttr = pNode->FirstChildElement( "police");
  if( pFontAttr){
    pFontAttr->QueryValueAttribute( "name", &police);
  }
  
  pFontAttr = pNode->FirstChildElement( "color");
  if ( pFontAttr){
    pFontAttr->QueryValueAttribute( "r", &r);
    pFontAttr->QueryValueAttribute( "g", &g);
    pFontAttr->QueryValueAttribute( "b", &b);
    pFontAttr->QueryValueAttribute( "a", &a);
  }
  
  
  if ( !text.empty() && !police.empty()){
    BVisual *textVis = NULL;
    // Color is defined
    if ( pFontAttr) {
      textVis = pResource->makeText( text, police, CPColor(r, g, b, a));
    }
    else {
      textVis = pResource->makeText( text, police);
    }
    
    addCommonAttributes(pNode, pResource, textVis);
    // int zOrder;
    // if ( TIXML_SUCCESS == pNode->QueryValueAttribute( "z-order", &zOrder)) {
    //   textVis->setZOrder(zOrder);
    // }

    e->addComponent(textVis);
  }
}
Пример #9
0
// Component Scriptable
void 
CEntityBuilder::buildScriptable( TiXmlElement *pNode, Entity *e, Resources*){
  TiXmlElement *pChar = pNode->FirstChildElement("script");
  std::string script;
  if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "name", &script)){
    e->addComponent( new Scriptable( script));
    return;
  }
  LOG2ERR<<"Bad xml description for [Scriptable] component\n";
  throw "Bad xml description for [Scriptable] component";
}
Пример #10
0
void 
CEntityBuilder::buildComponentResourcesAudio( TiXmlElement *pNode,  Entity *e, Resources *pResource ){
  TiXmlElement *pChar = pNode->FirstChildElement("audio");
  if ( pChar) {
    std::string alias;
    if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "alias", &alias)){
      bool looping = false;
      std::string loop;
      if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "loop", &loop)) {
        if (loop == "true") {
          looping = true;
        }
      }
      Audio *audio = pResource->makeAudio( alias, looping);
      e->addComponent( audio);
      return;
    }
  }
  LOG2ERR<<"Bad kind for  [Resources/Audio] component\n";
  throw "Bad kind for  [Resources/Audio] component";
}
Пример #11
0
void 
CEntityBuilder::BuildEntity( TiXmlElement *pParent, EntityManager &em, Resources *pResources){
  // Create entity (new id)
  Entity *ent = em.createEntity();
  if ( !ent){
    LOG2ERR<<"Could not create entity\n";
    throw "Could not create entity";
  }
  TiXmlElement* pChilds = pParent->FirstChildElement( "tags");
  if ( pChilds ){
    // Add tags
    for(pChilds=pChilds->FirstChildElement( "tag" ); pChilds; pChilds = pChilds->NextSiblingElement() ){
      std::string name;
      if ( TIXML_SUCCESS == pChilds->QueryValueAttribute( "name", &name))
      {
        std::string unique;
        bool        isUnique(false);
        if ( TIXML_SUCCESS == pChilds->QueryValueAttribute( "unique", &unique) ){
          isUnique = ( unique=="true");
        }
        em.tagEntity( ent, name, isUnique);
      }
    }
  }
  
  // Add components
  pChilds = pParent->FirstChildElement( "components");
  if ( pChilds ){
    for( pChilds=pChilds->FirstChildElement( "component" ); pChilds; pChilds = pChilds->NextSiblingElement() ){
      std::string type; 
      if ( TIXML_SUCCESS == pChilds->QueryValueAttribute( "type", &type)){
        //LOG2 <<name<<"\n";
        buildComponents(pChilds, type, ent, pResources);
      }
      else {
        LOG2ERR<<"Attribute [type] not found\n";
      }
    }
  }
}
Пример #12
0
// Component Animated
void 
CEntityBuilder::buildAnimated(TiXmlElement *pNode, Entity *e, Resources*){
  TiXmlElement *pChar = pNode->FirstChildElement("image");
  if ( pChar ){
    std::string name; 
    if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "name", &name)){
      e->addComponent( new Animated( name));
      return;
    }
  }
  LOG2ERR<<"Bad xml description for [Animated] component\n";
  throw "Bad xml description for [Animated] component";
}
Пример #13
0
// Component Character
void 
CEntityBuilder::buildCharacter ( TiXmlElement *pNode, Entity *e, Resources*){
  if ( pNode ){
    // Check nickname to identify entity
    std::string nickname ("XXX");
    pNode->QueryValueAttribute( "nickname", &nickname);
    // Parse stats
    TiXmlElement *pChar = pNode->FirstChildElement("stats");
    if ( pChar ){
      Character *character = new Character( nickname);
      for(; pChar; pChar= pChar->NextSiblingElement()){
        std::string name;
        long        value(0);
        if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "name", &name) &&
            TIXML_SUCCESS == pChar->QueryValueAttribute( "value", &value)){
          buildStats( character, name, CVariant( value));
        }
      }
      e->addComponent( character);
    }
  }
}
Пример #14
0
// Component Mobile
void 
CEntityBuilder::buildMobile(TiXmlElement *pNode, Entity *e, Resources*){
  // Build Mobile with arguments
  TiXmlElement *pChar = pNode->FirstChildElement("position");
  if ( pChar ){
    float x(0.f), y(0.f);
    if ( TIXML_SUCCESS == pChar->QueryValueAttribute( "x", &x) && 
         TIXML_SUCCESS == pChar->QueryValueAttribute( "y", &y) ) {
      e->addComponent( new Mobile(x, y));
      return;
    }
  }
  // Else, build Mobile without argument
  e->addComponent( new Mobile);
}
Пример #15
0
string GetElementAttributeByTagName(TiXmlElement* root,const string& name,
		const string& attribute)
{
	if (root == NULL) return string("");

	string strValue("");

	TiXmlElement* toFind = GetElementByTagName(root,name);

	if (toFind != NULL)
	{
		toFind->QueryValueAttribute(attribute,&strValue);
	}

	return strValue;
}
Пример #16
0
void PlayerAI::LoadBindings()
{
	TiXmlDocument doc("Controls.xml");
	bool xml_error = false;
	if(doc.LoadFile())
	{
		TiXmlElement* root = doc.FirstChildElement("Controls");
		if(root)
		{
			TiXmlElement* player = root->FirstChildElement("PlayerBindings");
			while(player)
			{
				int player_id = 0;
				if(player->QueryIntAttribute("id", &player_id) == TIXML_SUCCESS)
				{
					TiXmlElement* ic = player->FirstChildElement("InputConfig");
					while(ic)
					{
						std::string action_string;
						if(ic->QueryValueAttribute("Action", &action_string) != TIXML_SUCCESS)
						{
							Logger::ErrorOut() << "Error reading action attribute, continuing\n";
							continue;
						}
						std::string binding_type_string;
						if(ic->QueryValueAttribute("BindingType", &binding_type_string) != TIXML_SUCCESS)
						{
							Logger::ErrorOut() << "Error reading binding attribute, continuing\n";
							continue;
						}
						
						Action::Enum action = Action::FromStr(action_string);
						BindingType::Enum binding_type = BindingType::FromStr(binding_type_string);
						TiXmlElement* binding = ic->FirstChildElement("Binding");
						if(binding)
						{
							switch(binding_type)
							{
								case BindingType::KeyboardBinding:
									{
										int key = 0;
										if(binding->QueryValueAttribute("Key", &key) == TIXML_SUCCESS)
										{
											bindings[player_id].push_back(InputConfig(binding_type, Binding((SDLKey)key), action));
										} else
										{
											Logger::ErrorOut() << "Missing Key attribute, continuing\n";
											continue;
										}
									}
									break;
								case BindingType::JoystickButtonBinding:
									{
										int joystick_index = 0;
										int joystick_button_index = 0;
										if(binding->QueryValueAttribute("JoystickIndex", &joystick_index) == TIXML_SUCCESS && 
										   binding->QueryValueAttribute("JoystickButton", &joystick_button_index) == TIXML_SUCCESS)
										{
											bindings[player_id].push_back(InputConfig(binding_type, Binding(JoystickButton::Create(joystick_index, joystick_button_index)), action));
										} else
										{
											Logger::ErrorOut() << "Missing JoystickIndex or JoystickButton atttribute, continuing\n";
										}
									}
									break;
								case BindingType::JoystickAxisBinding:
									{
										int joystick_index = 0;
										int joystick_axis_index = 0;
										if(binding->QueryValueAttribute("JoystickIndex", &joystick_index) == TIXML_SUCCESS && 
										   binding->QueryValueAttribute("JoystickAxis", &joystick_axis_index) == TIXML_SUCCESS)
										{
											bindings[player_id].push_back(InputConfig(binding_type, Binding(JoystickAxis::Create(joystick_index, joystick_axis_index)), action));
										} else
										{
											Logger::ErrorOut() << "Missing JoystickIndex or JoystickAxis atttribute, continuing\n";
										}
									}
									break;
								case BindingType::MouseAxisBinding:
									{
										std::string axis;
										if(binding->QueryValueAttribute("MouseAxis", &axis) == TIXML_SUCCESS)
										{
											MouseAxis::Enum mouse_axis = MouseAxis::FromStr(axis);
											if(mouse_axis != MouseAxis::InvalidFirst && mouse_axis != MouseAxis::InvalidLast)
											{
												bindings[player_id].push_back(InputConfig(binding_type, Binding(mouse_axis), action));
											} else
											{
												Logger::ErrorOut() << "MouseAxis attribute incorrect: " << axis << "\n";
											}
										} else
										{
											Logger::ErrorOut() << "Missing MouseAxis attribute\n";
										}
									}
									break;
								case BindingType::MouseButtonBinding:
									{
										std::string button;
										if(binding->QueryValueAttribute("MouseButton", &button) == TIXML_SUCCESS)
										{
											MouseButton::Enum mouse_button = MouseButton::FromStr(button);
											if(mouse_button != MouseButton::InvalidFirst && mouse_button != MouseButton::InvalidLast)
											{
												bindings[player_id].push_back(InputConfig(binding_type, Binding(mouse_button), action));
											} else
											{
												Logger::ErrorOut() << "Missing MouseAxis attribute\n";
											}

										} else
										{
											Logger::ErrorOut() << "Missing MouseButton attribute\n";
										}
									}
									break;

							}
						} else 
						{
							xml_error = true;
							Logger::ErrorOut() << "Missing Binding element\n";
						}

						
						ic = ic->NextSiblingElement("InputConfig");
					}
					
				} else xml_error = true;
				player = player->NextSiblingElement("PlayerBindings");
			}
		} else xml_error = true;
	} else xml_error = true;
	if(xml_error)
	{
		ResetToDefault();
	}
}
Пример #17
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( "data/utf8testout.xml", "r" );
			FILE* verify = fopen( "data/utf8testverify.xml", "r" );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		#endif
	}	

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

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

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

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

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

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

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

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


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

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

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

		doc.Clear();

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

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

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

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

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

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

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

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

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

		#ifdef TIXML_USE_STL

		doc.Clear();

		istringstream parse0( str );
		parse0 >> doc;

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

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

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



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

	const int FUZZ_ITERATION = 300;

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

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

		TiXmlDocument xml;
		xml.Parse( demoCopy );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	{
		// [ 870502 ] White space issues
		TiXmlDocument doc;
		TiXmlText* text;
		TiXmlHandle docH( &doc );
	
		const char* doctype0 = "<element> This has leading and trailing space </element>";
		const char* doctype1 = "<element>This has  internal space</element>";
		const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

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

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

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

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

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

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

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

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

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

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

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

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

            TiXmlDocument doc;
            doc.Parse( str );

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

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

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

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

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

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

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

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

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

		std::string bar = "bar";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

	printf ("\nPass %d, Fail %d\n", gPass, gFail);
	return gFail;
}
Пример #18
0
bool XmlODESettings::GetSettings(ODESimulator& sim)
{
  string globals="globals";
  TiXmlElement* c = e->FirstChildElement(globals);
  if(c) {
    printf("Parsing globals...\n");
    //parse globals: gravity, etc
    Vector3 gravity;
    if(c->QueryValueAttribute("gravity",&gravity)==TIXML_SUCCESS)
      sim.SetGravity(gravity);
    double worldERP,worldCFM;
    if(c->QueryValueAttribute("ERP",&worldERP)==TIXML_SUCCESS)
      sim.SetERP(worldERP);
    if(c->QueryValueAttribute("CFM",&worldCFM)==TIXML_SUCCESS)
      sim.SetCFM(worldCFM);
    int maxContacts;
    if(c->QueryValueAttribute("maxContacts",&maxContacts)==TIXML_SUCCESS)
      sim.GetSettings().maxContacts = maxContacts;
    int rigidObjectCollisions,robotSelfCollisions,robotRobotCollisions;
    if(c->QueryValueAttribute("rigidObjectCollisions",&rigidObjectCollisions)==TIXML_SUCCESS)
      sim.GetSettings().rigidObjectCollisions = rigidObjectCollisions;
    if(c->QueryValueAttribute("robotSelfCollisions",&robotSelfCollisions)==TIXML_SUCCESS)
      sim.GetSettings().robotSelfCollisions = robotSelfCollisions;
    if(c->QueryValueAttribute("robotRobotCollisions",&robotRobotCollisions)==TIXML_SUCCESS)
      sim.GetSettings().robotRobotCollisions = robotRobotCollisions;
  }
  else c=e->FirstChildElement();

  while(c!=NULL) {
    const char* name=c->Value();
    printf("Parsing element %s\n",name);
    if(0 == strcmp(name,"env")) {
      int index;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numEnvs());
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(!g.Get(*sim.envMesh(index))) {
	    fprintf(stderr,"Error reading environment geometry from XML\n");
	    return false;
	  }
	}
      }
      else {
	fprintf(stderr,"Error reading environment index from XML file\n");
	return false;
      }
    }
    else if(0 == strcmp(name,"object")) {
      int index;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numObjects());
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(!g.Get(*sim.object(index)->triMesh())) {
	    fprintf(stderr,"Error reading object geometry from XML\n");
	    return false;
	  }
	}
      }
      else {
	fprintf(stderr,"Error reading object index from XML file\n");
	return false;
      }
    }
    else if(0 == strcmp(name,"robot")) {
      int index,bodyIndex=-1;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numRobots());
	if(c->QueryValueAttribute("body",&bodyIndex)==TIXML_SUCCESS) {
	}
	else bodyIndex=-1;
	
	ODERobot* robot=sim.robot(index);
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(bodyIndex < 0) {
	    for(size_t i=0;i<robot->robot.links.size();i++) {
	      if(robot->triMesh(i))
		g.Get(*robot->triMesh(i));
	    }
	  }
	  else {
	    Assert(bodyIndex < (int)robot->robot.links.size());
	    if(robot->triMesh(bodyIndex))
	      g.Get(*robot->triMesh(bodyIndex));
	  }
	}
      }
      else {
	fprintf(stderr,"Error reading robot index from XML file\n");
	return false;
      }
    }
    c=c->NextSiblingElement();
  }
  return true;
}
Пример #19
0
bool XmlSimulationSettings::GetSettings(WorldSimulation& sim)
{
  string globals="globals";
  TiXmlElement* c = e->FirstChildElement(globals);
  if(c) {
    printf("Parsing timestep...\n");
    //parse timestep
    double timestep;
    if(c->QueryValueAttribute("timestep",&timestep)==TIXML_SUCCESS)
      sim.simStep = timestep;
  }
  printf("Parsing ODE...\n");
  XmlODESettings ode(e);
  if(!ode.GetSettings(sim.odesim)) {
    return false;
  }


  printf("Parsing robot controllers / sensors\n");
  c = e->FirstChildElement("robot");
  while(c != NULL) {
    int index;
    if(c->QueryValueAttribute("index",&index)!=TIXML_SUCCESS) {
      fprintf(stderr,"Unable to read index of robot element\n");
      continue;
    }
    Assert(index < (int)sim.robotControllers.size());
	
    ControlledRobotSimulator& robotSim=sim.controlSimulators[index];
    TiXmlElement* ec=c->FirstChildElement("controller");
    if(ec) {
      RobotControllerFactory::RegisterDefault(*robotSim.robot);
      SmartPointer<RobotController> controller=RobotControllerFactory::Load(ec,*robotSim.robot);
      if(controller)
	sim.SetController(index,controller); 
      else {
	fprintf(stderr,"Unable to load controller from xml file\n");
	return false;
      }
      Real temp;
      if(ec->QueryValueAttribute("rate",&temp)==TIXML_SUCCESS){
	if(!(temp > 0)) {
	  fprintf(stderr,"Invalid rate %g\n",temp);
	  continue;
	}
	sim.controlSimulators[index].controlTimeStep = 1.0/temp;
      }
      if(ec->QueryValueAttribute("timeStep",&temp)==TIXML_SUCCESS){
	if(!(temp > 0)) {
	  fprintf(stderr,"Invalid timestep %g\n",temp);
	  continue;
	}
	sim.controlSimulators[index].controlTimeStep = temp;
      }
    }
    TiXmlElement*es=c->FirstChildElement("sensors");
    if(es) {
      if(!sim.controlSimulators[index].sensors.LoadSettings(es)) {
	fprintf(stderr,"Unable to load sensors from xml file\n");
	return false;
      }
    }

    /*
    TiXmlElement* es=c->FirstChildElement("sensors");
    if(es) {
      printf("Parsing sensors...\n");
      TiXmlElement* pos=es->FirstChildElement("position");
      int ival;
      Real fval;
      if(pos) {
	if(pos->QueryValueAttribute("enabled",&ival)==TIXML_SUCCESS) {
	  if(bodyIndex >= 0) 
	    fprintf(stderr,"Warning: cannot enable individual joint encoders yet\n");
	  robotSim.sensors.hasJointPosition=(ival!=0);
	}
	if(pos->QueryValueAttribute("variance",&fval)==TIXML_SUCCESS) {
	  if(robotSim.sensors.qvariance.n==0)
	    robotSim.sensors.qvariance.resize(robotSim.robot->q.n,Zero);
	  if(bodyIndex >= 0)
	    robotSim.sensors.qvariance(bodyIndex)=fval;
	  else
	    robotSim.sensors.qvariance.set(fval);
	}
	if(pos->QueryValueAttribute("resolution",&fval)==TIXML_SUCCESS) {
	  if(robotSim.sensors.qresolution.n==0)
	    robotSim.sensors.qresolution.resize(robotSim.robot->q.n,Zero);
	  if(bodyIndex >= 0)
	    robotSim.sensors.qresolution(bodyIndex)=fval;
	  else
	    robotSim.sensors.qresolution.set(fval);
	}
      }
      TiXmlElement* vel=c->FirstChildElement("velocity");
      if(vel) {
	if(vel->QueryValueAttribute("enabled",&ival)==TIXML_SUCCESS) {
	  if(bodyIndex >= 0) 
	    fprintf(stderr,"Warning: cannot enable individual joint encoders yet\n");
	  robotSim.sensors.hasJointVelocity=(ival!=0);
	}
	if(vel->QueryValueAttribute("variance",&fval)==TIXML_SUCCESS) {
	  if(robotSim.sensors.dqvariance.n==0)
	    robotSim.sensors.dqvariance.resize(robotSim.robot->q.n,Zero);
	  if(bodyIndex >= 0)
	    robotSim.sensors.dqvariance(bodyIndex)=fval;
	  else
	    robotSim.sensors.dqvariance.set(fval);
	}
	if(vel->QueryValueAttribute("resolution",&fval)==TIXML_SUCCESS) {
	  if(robotSim.sensors.dqresolution.n==0)
	    robotSim.sensors.dqresolution.resize(robotSim.robot->q.n,Zero);
	  if(bodyIndex >= 0)
	    robotSim.sensors.dqresolution(bodyIndex)=fval;
	  else
	    robotSim.sensors.dqresolution.set(fval);
	}
      }
      //TODO: other sensors?
    }
    */
    /*
    TiXmlElement* ec=c->FirstChildElement("controller");
    if(ec) {
      printf("Parsing controller...\n");
      TiXmlAttribute* setting = ec->FirstAttribute();
      while(setting) {
	bool res=robotSim.controller->SetSetting(setting->Name(),setting->Value());
	if(!res) {
	  printf("Setting %s not valid for current controller, or failed parsing\n",setting->Name());
	}
	setting = setting->Next();
      }
    }
    */
    c = c->NextSiblingElement("robot");
  }

  printf("Parsing state\n");
  c = e->FirstChildElement("state");
  if(c) {
    const char* data=c->Attribute("data");
    if(!data) {
      fprintf(stderr,"No 'data' attribute in state\n");
      return false;
    }
    string decoded=FromBase64(data);
    if(!sim.ReadState(decoded)) {
      fprintf(stderr,"Unable to read state from data\n");
      return false;
    }
  }

  return true;
}
Пример #20
0
SkillManager::SkillManager(void)
{
	error_ = false;
	/* Populate upgrade paths, costs etc*/
	TiXmlDocument doc("Skills.xml");
	doc.LoadFile();
	if(doc.Error())
	{
		Logger::ErrorOut() << "Unable to load skills.xml\n";
		Logger::ErrorOut() << "Error: " << doc.ErrorDesc() << "\n";
	}

	TiXmlElement* root = doc.FirstChildElement("Skills");
	if(root)
	{
		TiXmlElement* skill = root->FirstChildElement("Skill");
		while(skill)
		{
			std::vector<SkillLevel> upgrades;
			std::string name;
			std::string alignment;
			unsigned int init_cost = 0;
			error_ |= (skill->QueryValueAttribute("name", &name) != TIXML_SUCCESS);
			error_ |= (skill->QueryValueAttribute("alignment", &alignment)  != TIXML_SUCCESS);


			TiXmlElement* initialcost = skill->FirstChildElement("InitialCost");
			if(initialcost)
			{
				std::string init_cost_str = initialcost->GetText();
				init_cost = boost::lexical_cast<unsigned int, std::string>(init_cost_str);
			} else
			{
				Logger::ErrorOut() << "No initial cost for skill " << name << "\n";
				error_ = true;
			}

			//TODO upgrades
			TiXmlElement* upgrade = skill->FirstChildElement("Upgrade");
			while(upgrade)
			{
				std::string upgrade_name;
				upgrade->QueryValueAttribute("name", &upgrade_name);
				SkillLevel sl(upgrade_name);

				int ltv_rank = 1;
				TiXmlElement* level = upgrade->FirstChildElement("Level");
				while(level)
				{
					int rank = 0;
					int cost = 0;
					error_ |= (level->QueryIntAttribute("rank", &rank) != TIXML_SUCCESS);
					error_ |= (level->QueryIntAttribute("cost", &cost) != TIXML_SUCCESS);
					error_ |= (rank != ltv_rank + 1);
					ltv_rank = rank;
					sl.AddRank(cost);
					level = level->NextSiblingElement("Level");
				}
				upgrades.push_back(sl);
				upgrade = upgrade->NextSiblingElement("Upgrade");
			}

			if(error_)
				break;
			else
			{
				Skill* sk = new Skill();
				sk->SetCost(init_cost);
				sk->SetName(name);
				for(std::vector<SkillLevel>::iterator it = upgrades.begin(); it != upgrades.end(); ++it)
				{
					sk->AddUpgrade(*it);
				}
				if(alignment == "good")
					sk->SetAlignment(SkillAlignment::Good);
				else if(alignment == "evil")
					sk->SetAlignment(SkillAlignment::Evil);
				else if(alignment == "neutral")
					sk->SetAlignment(SkillAlignment::Neutral);
				else
				{
					Logger::ErrorOut() << "Skill alignment can only be 'good', 'evil' or 'neutral'\n";
					error_ = true;
					break;
				}
				if(cheat_)
					sk->SetUnlocked(true);
				skills_.push_back(sk);
			}

			skill = skill->NextSiblingElement("Skill");
		}
	} else
	{
		Logger::ErrorOut() << "Malformed skills.xml, no root element 'Skills'\n";
		error_ = true;
	}
}
Пример #21
0
bool Progression::LoadSavefile()
{
	description_.save_exists = false;
	bool error = false;
	TiXmlDocument doc(savefile_);
	doc.LoadFile();
	if(!doc.Error())
	{
		description_.save_exists = true;
		TiXmlElement* root = doc.FirstChildElement("Progress");
		if(root)
		{
			TiXmlElement* points = root->FirstChildElement("Points");
			if(points)
			{
				int good = 0;
				int evil = 0;
				if(points->QueryValueAttribute("Good", &good) == TIXML_SUCCESS &&
				   points->QueryValueAttribute("Evil", &evil) == TIXML_SUCCESS)
				{
					good_points_ = good;
					evil_points_ = evil;
				} else error = true;
			} else error = true;

			TiXmlElement* levels = root->FirstChildElement("Levels");
			if(levels)
			{
				TiXmlElement* level = levels->FirstChildElement("Level");
				while(level)
				{
					std::string id;
					int beaten = 0;
					if(level->QueryValueAttribute("id", &id) == TIXML_SUCCESS &&
					   level->QueryIntAttribute("Beaten", &beaten) == TIXML_SUCCESS)
					{
						for(std::vector<ProgressLevel*>::iterator it = levels_.begin(); it != levels_.end(); ++it)
						{
							if((*it)->GetFilename() == id)
							{
								(*it)->SetLocked(false);
								(*it)->SetBeaten(beaten ? 1 : 0);
							}
						}
					} else
					{
						error = true;
						break;
					}

					level = level->NextSiblingElement("Level");
				}
			} else error = true;
			
			TiXmlElement* skills = root->FirstChildElement("Skills");
			if(skills)
			{
				TiXmlElement* skill = skills->FirstChildElement("Skill");
				while(skill)
				{
					std::string id;
					int purchased = 0;
					if(skill->QueryValueAttribute("id", &id) == TIXML_SUCCESS &&
					   skill->QueryIntAttribute("Purchased", &purchased) == TIXML_SUCCESS)
					{
						std::vector<Skill*> sm_skills = skill_manager_.GetAllSkills();
						for(std::vector<Skill*>::iterator it = sm_skills.begin(); it != sm_skills.end(); ++it)
						{
							if((*it)->GetName() == id)
							{
								(*it)->SetUnlocked(true);
								(*it)->SetPurchased(purchased ? 1 : 0);
								TiXmlElement* rank = skill->FirstChildElement("Rank");
								while(rank)
								{
									std::string rid;
									int level = 0;
									if(rank->QueryValueAttribute("id", &rid) == TIXML_SUCCESS &&
									   rank->QueryIntAttribute("Level", &level) == TIXML_SUCCESS)
									{
										SkillLevel* sl = (*it)->GetSkillLevel(rid);
										if(sl)
										{
											sl->SetLevel(level);
										} else
											Logger::DiagnosticOut() << "Malformed skill in campaign savefile\n";
									} else Logger::DiagnosticOut() << "Malformed skill in campaign savefile\n";
									rank = rank->NextSiblingElement("Rank");
								}

							}
						}
					} else
					{
						error = true;
						break;
					}

					skill = skill->NextSiblingElement("Skill");
				}
			} else error = true;
		}
	}
	if(error)
		Logger::ErrorOut() << "Malformed savefile\n";
	return error;
}
Пример #22
0
bool Progression::LoadCampaign(TiXmlDocument* _doc)
{
	bool error_found = false;
	TiXmlElement* root = _doc->FirstChildElement("Campaign");
	if(root)
	{
		root->QueryValueAttribute("name", &description_.name);
		root->QueryValueAttribute("desc", &description_.description);
		root->QueryValueAttribute("icon", &description_.icon_filename);

		TiXmlElement* level = root->FirstChildElement("Level");
		while(level)
		{
			std::string levelname;
			std::string filename;
			bool locked = false;
			error_found |= level->QueryValueAttribute("name", &levelname) != TIXML_SUCCESS;
			error_found |= level->QueryValueAttribute("file", &filename) != TIXML_SUCCESS;
			error_found |= level->QueryValueAttribute("locked", &locked) != TIXML_SUCCESS;

			
			if(error_found)
				break;
			else
			{
				ProgressLevel* pl = new ProgressLevel(levelname, filename);
				if(cheat_)
					pl->SetLocked(false);
				else
					pl->SetLocked(locked);
				LoadUnlockables(level->FirstChildElement("Unlockable"), pl);
				levels_.push_back(pl);
			}
			level = level->NextSiblingElement("Level");
		}

		TiXmlElement* skill = root->FirstChildElement("StartingSkill");
		while(skill)
		{
			bool purchased = false;
			std::string skillname;
			skill->QueryValueAttribute("name", &skillname);
			skill->QueryValueAttribute("purchased", &purchased);
			if(skill_manager_.SkillExists(skillname))
			{
				skill_manager_.Unlock(skillname);
				if(purchased)
					skill_manager_.Purchase(skillname);
			} else
			{
				Logger::DiagnosticOut() << "Skill " << skillname << " does not exist in skills.xml\n";
			}

			skill = skill->NextSiblingElement("StartingSkill");
		}
	} else
	{
		Logger::ErrorOut() << "Unable to find root Campaign node\n";
		error_found = true;
	}
	return !error_found;
}
Пример #23
0
bool Progression::LoadUnlockables(TiXmlElement* _first, ProgressLevel* _progress_level)
{
	description_.unlockable_count = 0;
	bool error_found = false;
	TiXmlElement* unlockable = _first;
	while(unlockable)
	{
		bool require_good = false;
		bool require_evil = false;
		bool require_flawless = false;
		std::vector<std::string> skill_unlocks;
		std::vector<std::string> level_unlocks;

		TiXmlElement* condition = unlockable->FirstChildElement("Condition");
		while(condition)
		{
			std::string alignment;
			if(condition->QueryValueAttribute("alignment", &alignment) == TIXML_SUCCESS)
			{
				if(alignment == "Evil")
				{
					require_evil = true;
				} else if(alignment == "Good")
				{
					require_good = true;
				}
			}
			condition->QueryValueAttribute("flawless", &require_flawless);
			condition = condition->NextSiblingElement("Condition");
		}
		
		TiXmlElement* level_unlock = unlockable->FirstChildElement("LevelUnlock");
		while(level_unlock)
		{
			std::string name;
			if(level_unlock->QueryValueAttribute("name", &name) != TIXML_SUCCESS)
			{
				error_found = true;
				Logger::ErrorOut() << "LevelUnlock requires a name attribute\n";
			} else
				level_unlocks.push_back(name);

			level_unlock = level_unlock->NextSiblingElement("LevelUnlock");
		}

		TiXmlElement* skill_unlock = unlockable->FirstChildElement("SkillUnlock");
		while(skill_unlock)
		{
			std::string name;
			if(skill_unlock->QueryValueAttribute("name", &name) != TIXML_SUCCESS)
			{
				error_found = true;
				Logger::ErrorOut() << "SkillUnlock requires a name attribute\n";
			} else
				skill_unlocks.push_back(name);
			skill_unlock = skill_unlock ->NextSiblingElement("SkillUnlock");
		}
		_progress_level->AddUnlock(require_good, require_evil, require_flawless, level_unlocks, skill_unlocks);
		description_.unlockable_count++;
		unlockable = unlockable->NextSiblingElement("Unlockable");
	}
	return false;
}
Пример #24
0
bool VirtualTrajClient::SetupVirtual(const char* xmlFile)
{
  virtualTimer.Reset();

  Vector q(6,0.0);
  qmin.resize(6);
  qmax.resize(6);
  vmax.resize(6);
  amax.resize(6);
  dmax.resize(6);
  if(!xmlFile) {
    fill(qmin.begin(),qmin.end(),-45.0);
    fill(qmax.begin(),qmax.end(),45.0);
    fill(vmax.begin(),vmax.end(),20.0);
    fill(amax.begin(),amax.end(),50.0);
    fill(dmax.begin(),dmax.end(),50.0);
    maxSegments = 3000;  
    maxRate = 250.0;  //same as Staubli CS8
  }
  else {
    TiXmlDocument doc;
    if(!doc.LoadFile(xmlFile)) {
      fprintf(stderr,"Error reading XML file %s\n",xmlFile);
      return false;
    }
    if(0!=strcmp(doc.RootElement()->Value(),"val3specs")) {
      fprintf(stderr,"Wrong type of root element %s\n",doc.RootElement()->Value());
      return false;
    }
    TiXmlElement* e;
    e=doc.RootElement()->FirstChildElement("rate");
    if(e && e->QueryValueAttribute("value",&maxRate) != TIXML_SUCCESS) {
      fprintf(stderr,"Could not read value attribute of rate\n");
      maxRate = 250.0;
    }
    e=doc.RootElement()->FirstChildElement("queue");
    if(e && e->QueryValueAttribute("size",&maxSegments) != TIXML_SUCCESS) {
      fprintf(stderr,"Could not read size attribute of queue\n");
      maxSegments = 3000;
    }
    e=doc.RootElement()->FirstChildElement("joints");
    if(e) {
      int n;
      if(e->QueryValueAttribute("num",&n) == TIXML_SUCCESS) {
	q.resize(n);
	qmin.resize(n);
	qmax.resize(n);
	vmax.resize(n);
	amax.resize(n);
	dmax.resize(n);
      }
      if(e->Attribute("value")) {
	stringstream ss(e->Attribute("value"));
	for(size_t i=0;i<q.size();i++)
	  ss >> q[i];
      }
      if(e->Attribute("min")) {
	stringstream ss(e->Attribute("min"));
	for(size_t i=0;i<q.size();i++)
	  ss >> qmin[i];
      }
      if(e->Attribute("max")) {
	stringstream ss(e->Attribute("max"));
	for(size_t i=0;i<q.size();i++)
	  ss >> qmax[i];
      }
Пример #25
0
bool XmlODESettings::GetSettings(ODESimulator& sim)
{
  string globals="globals";
  TiXmlElement* c = e->FirstChildElement(globals);
  if(c) {
    printf("Parsing globals...\n");
    //parse globals: gravity, etc
    Vector3 gravity;
    if(c->QueryValueAttribute("gravity",&gravity)==TIXML_SUCCESS)
      sim.SetGravity(gravity);
    double worldERP,worldCFM;
    if(c->QueryValueAttribute("ERP",&worldERP)==TIXML_SUCCESS)
      sim.SetERP(worldERP);
    if(c->QueryValueAttribute("CFM",&worldCFM)==TIXML_SUCCESS)
      sim.SetCFM(worldCFM);
    int maxContacts;
    if(c->QueryValueAttribute("maxContacts",&maxContacts)==TIXML_SUCCESS)
      sim.GetSettings().maxContacts = maxContacts;
    int boundaryLayer,rigidObjectCollisions,robotSelfCollisions,robotRobotCollisions;
    if(c->QueryValueAttribute("boundaryLayer",&boundaryLayer)==TIXML_SUCCESS) {
      printf("XML simulator: warning, boundary layer settings don't have an effect\n");
      sim.GetSettings().boundaryLayerCollisions = boundaryLayer;
    }
    if(c->QueryValueAttribute("rigidObjectCollisions",&rigidObjectCollisions)==TIXML_SUCCESS)
      sim.GetSettings().rigidObjectCollisions = rigidObjectCollisions;
    if(c->QueryValueAttribute("robotSelfCollisions",&robotSelfCollisions)==TIXML_SUCCESS)
      sim.GetSettings().robotSelfCollisions = robotSelfCollisions;
    if(c->QueryValueAttribute("robotRobotCollisions",&robotRobotCollisions)==TIXML_SUCCESS)
      sim.GetSettings().robotRobotCollisions = robotRobotCollisions;
  }
  else c=e->FirstChildElement();

  while(c!=NULL) {
    const char* name=c->Value();
    printf("Parsing element %s\n",name);
    if(0 == strcmp(name,"terrain")) {
      int index;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numEnvs());
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(!g.Get(*sim.envGeom(index))) {
	    fprintf(stderr,"Error reading terrain geometry from XML\n");
	    return false;
	  }
	}
      }
      else {
	fprintf(stderr,"Error reading terrain index from XML file\n");
	return false;
      }
    }
    else if(0 == strcmp(name,"object")) {
      int index;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numObjects());
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(!g.Get(*sim.object(index)->triMesh())) {
	    fprintf(stderr,"Error reading object geometry from XML\n");
	    return false;
	  }
	}
	TiXmlElement *ev=c->FirstChildElement("velocity");
	if(ev) {
	  Vector3 v,w;
	  if(ev->QueryValueAttribute("linear",&v) != TIXML_SUCCESS)
	    v.setZero();
	  if(ev->QueryValueAttribute("angular",&w) != TIXML_SUCCESS)
	    w.setZero();
	  cout<<"Setting velocity "<<w<<", "<<v<<endl;
	  sim.object(index)->SetVelocity(w,v);
	}
      }
      else {
	fprintf(stderr,"Error reading object index from XML file\n");
	return false;
      }
    }
    else if(0 == strcmp(name,"robot")) {
      int index,bodyIndex=-1;
      if(c->QueryValueAttribute("index",&index)==TIXML_SUCCESS) {
	Assert(index < (int)sim.numRobots());
	if(c->QueryValueAttribute("body",&bodyIndex)==TIXML_SUCCESS) {
	}
	else bodyIndex=-1;
	
	ODERobot* robot=sim.robot(index);
	TiXmlElement* eg=c->FirstChildElement("geometry");
	if(eg) {
	  XmlODEGeometry g(eg);
	  if(bodyIndex < 0) {
	    for(size_t i=0;i<robot->robot.links.size();i++) {
	      if(robot->triMesh(i))
		g.Get(*robot->triMesh(i));
	    }
	  }
	  else {
	    Assert(bodyIndex < (int)robot->robot.links.size());
	    if(robot->triMesh(bodyIndex))
	      g.Get(*robot->triMesh(bodyIndex));
	  }
	}
      }
      else {
	fprintf(stderr,"Error reading robot index from XML file\n");
	return false;
      }
    }
    c=c->NextSiblingElement();
  }
  return true;
}
Пример #26
0
int CDBServiceConfig::LoadServiceTypes(TiXmlElement* pType, SServiceType& sServiceType)
{
	SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s Start!\n",__FUNCTION__);
	
	char szName[256] = {0};
	int nRet = pType->QueryValueAttribute("name", &szName);
	if(nRet != TIXML_SUCCESS)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Type Name\n",__FUNCTION__);
		return -1;
	}
	sServiceType.sTypeName = szName;
	boost::to_lower(sServiceType.sTypeName);
	//
	char szClass[16] = {0};
	nRet = pType->QueryValueAttribute("class", &szClass);
	if(nRet != TIXML_SUCCESS)
	{
		SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,No Type Class\n",__FUNCTION__);
		return -1;
	}

	if(strncmp(szClass,"int",3)==0)
	{
		sServiceType.eType = DBP_DT_INT;
	}
	else if(strncmp(szClass,"string",6) == 0)
	{
		sServiceType.eType = DBP_DT_STRING;

		int nStrLen = 0;
		nRet = pType->QueryValueAttribute("length", (int *)&nStrLen);
		if(nRet == TIXML_SUCCESS)
		{
			sServiceType.nStrLen = nStrLen;
		}
	}
	else if(strncmp(szClass,"array",5) == 0)
	{
		sServiceType.eType = DBP_DT_ARRAY;
		char szItemType[256] = {0};
		nRet = pType->QueryValueAttribute("itemtype", &szItemType);

		if(nRet != TIXML_SUCCESS)
		{
			SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get Array Element Error,Name=[%s]\n",__FUNCTION__,szName);
			return -1;
		}
		sServiceType.sElementName = szItemType;
	}
	else if(strncmp(szClass,"tlv",3) == 0)
	{
		char szArrayField[32] = {0};
		nRet = pType->QueryValueAttribute("arrayfield", &szArrayField);
		if((nRet == TIXML_SUCCESS)&&(strncmp(szArrayField,"true",4) == 0))
		{
			sServiceType.eType = DBP_DT_TLV_ARRAY;
			TiXmlElement * pTlvType = NULL;
			
			int nTypeCode = 0;
			nRet = pType->QueryValueAttribute("code", (int *)&nTypeCode);
			if(nRet != TIXML_SUCCESS)
			{
				SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s, Name=[%s] TLV-Array no code\n",__FUNCTION__,szName);
				return -1;
			}
			sServiceType.nTypeCode = nTypeCode;
			
			if((pTlvType=pType->FirstChildElement("field"))==NULL)
			{
				SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s, Name=[%s] TLV-Array Child No Type_Type\n",__FUNCTION__,szName);
				return -1; 
			}
			else
			{
				char szItemType[256] = {0};
				nRet = pTlvType->QueryValueAttribute("type", &szItemType);

				if(nRet != TIXML_SUCCESS)
				{
					SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Get TLV-Array Element Error,Name=[%s]\n",__FUNCTION__,szName);
					return -1;
				}
				sServiceType.sElementName = szItemType;
			}
		}
		else
		{
			sServiceType.eType = DBP_DT_TLV;
			TiXmlElement * pTlvType = NULL;
			
			if((pTlvType=pType->FirstChildElement("field"))==NULL)
			{
				SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,TLV Child No Type_Type\n",__FUNCTION__);
				return -1; 
			}
			else
			{	
				SServiceType tlvElementType;
				if(LoadTlvServiceTypes(pTlvType,tlvElementType)<0)
				{
					return -1;
				}
				sServiceType.vecSubType.push_back(tlvElementType);
			}
			
			while((pTlvType=pTlvType->NextSiblingElement("field"))!=NULL)
			{
				SServiceType tlvElementType;
				if(LoadTlvServiceTypes(pTlvType,tlvElementType)<0)
				{
					return -1;
				}
				sServiceType.vecSubType.push_back(tlvElementType);
			}
		}
			
	}
	else if(strncmp(szClass,"struct",6) == 0)
	{
		sServiceType.eType = DBP_DT_STRUCT;
		
		TiXmlElement * pStructType = NULL;
		if((pStructType=pType->FirstChildElement("field"))==NULL)
		{
			SC_XLOG(XLOG_ERROR, "CDBServiceConfig::%s,Struct Child No Type_Type\n",__FUNCTION__);
			return -1; 
		}
		else
		{	
			SServiceType structElementType;
			if(LoadStructServiceTypes(pStructType,structElementType)<0)
			{
				return -1;
			}
			sServiceType.vecSubType.push_back(structElementType);
		}
		
		while((pStructType=pStructType->NextSiblingElement("field"))!=NULL)
		{
			SServiceType structElementType;
			if(LoadStructServiceTypes(pStructType,structElementType)<0)
			{
				return -1;
			}
			sServiceType.vecSubType.push_back(structElementType);
		}

		
	}

	int nTypeCode = 0;
	nRet = pType->QueryValueAttribute("code", (int *)&nTypeCode);
	if(nRet == TIXML_SUCCESS)
	{
		sServiceType.nTypeCode = nTypeCode;
	}
	else
	{
		sServiceType.nTypeCode = 0;
	}

	SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,code=[%d],name=[%s]\n",
		__FUNCTION__,sServiceType.nTypeCode,sServiceType.sTypeName.c_str());
	
	
	return 0;
}
Пример #27
0
int CDBServiceConfig::LoadSQLs(TiXmlElement* pSQL,SMsgAttri& sMsgAtrri)
{

	SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s\n",__FUNCTION__);
	char szIsFullScan[16] = {0};
	int nRet = pSQL->QueryValueAttribute("isfullscan", &szIsFullScan);
	if(nRet == TIXML_SUCCESS)
	{
		if(strncmp(szIsFullScan,"true",4) == 0)
		{
			sMsgAtrri.bIsFullScan = true;
		}
		else
		{
			sMsgAtrri.bIsFullScan = false;
		}
	}

	TiXmlElement *pMulPart = NULL;
	vector<SPartSql> parts;
	pMulPart = pSQL->FirstChildElement("mulpart");
	while(pMulPart != NULL)
	{
		SPartSql ss;
		string strSql;
		if(pMulPart->GetText()==NULL)
		{
			/* cdata */
			const char* pCDataSQL = pMulPart->FirstChild()->Value();
			if(pCDataSQL)
			{
				strSql = pCDataSQL;
			}
		}
		else
		{
			strSql = pMulPart->GetText();
		}
		ss.strSql = strSql;
		ss.dwConditon = OP_NOTHING;
		char szConditon[128] = {0};
		char szVariable[128] = {0};
		if (pMulPart->QueryValueAttribute("test", &szConditon)==TIXML_SUCCESS)
		{
			if (strcmp(szConditon,"null")==0)
			{
				ss.dwConditon=OP_NULL;
			}
			else if (strcmp(szConditon,"notnull")==0)
			{
				ss.dwConditon=OP_NOTNULL;
			}
		}
		if (pMulPart->QueryValueAttribute("variable", &szVariable)==TIXML_SUCCESS)
		{
			ss.strVariable=szVariable;
			boost::to_lower(ss.strVariable);
		}
		parts.push_back(ss);
		pMulPart=pMulPart->NextSiblingElement("mulpart");
	}
	
	sMsgAtrri.exePartSQLs.push_back(parts);
	
	TiXmlElement *pPrefix = NULL;
	if(( pPrefix = pSQL->FirstChildElement("prefix")) == NULL)
	{
		/* simple sql */
		string strTmp;
		if(pSQL->GetText()==NULL)
		{
			/* cdata */
			const char* pCDataSQL = pSQL->FirstChild()->Value();
			if(pCDataSQL)
			{
				strTmp = pCDataSQL;
			}
		}
		else
		{
			strTmp = pSQL->GetText();
		}
		
		SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,ORISQL=[%s]\n",__FUNCTION__,strTmp.c_str());
		
		ProcessXMLCDATA(strTmp);

		MakeSQLToLower(strTmp);
		sMsgAtrri.exeSQLs.push_back(strTmp);
		
		char szParaCounts[16] = {0};
		int paraCounts = -1;
		
		if (pSQL->QueryValueAttribute("paracounts", &szParaCounts)==TIXML_SUCCESS)
		{
			paraCounts = atoi(szParaCounts);
		}
		
		sMsgAtrri.paraCounts.push_back(paraCounts);
		
		SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,SQL=[%s] ParaCounts=[%d]\n",__FUNCTION__,strTmp.c_str(),
		paraCounts);
		

		if(boost::istarts_with(strTmp,"update") 
			|| boost::istarts_with(strTmp,"delete") 
			|| boost::istarts_with(strTmp,"insert"))
		{
			sMsgAtrri.eOperType = DBO_WRITE;
		}
	}
	else
	{
		/* compose sql */
		SComposeSQL composeSQL;
		composeSQL.sPrefix = pPrefix->GetText();

		TiXmlElement *pSuffix = NULL;
		if( (pSuffix = pSQL->FirstChildElement("suffix")) != NULL)
		{
			composeSQL.sSuffix = pSuffix->GetText();
		}

		TiXmlElement *pDetail = NULL;
		if( (pDetail = pSQL->FirstChildElement("detail")) != NULL)
		{
			string strDetail = pDetail->GetText();
			MakeSQLToLower(strDetail);
			composeSQL.vecDetail.push_back(strDetail);
			
			while((pDetail=pDetail->NextSiblingElement("detail"))!=NULL)
			{
				strDetail = pDetail->GetText();
				MakeSQLToLower(strDetail);
				composeSQL.vecDetail.push_back(strDetail);
			}
		}

		sMsgAtrri.exeComposeSQLs.push_back(composeSQL);

		if(boost::istarts_with(composeSQL.sPrefix,"update") || boost::istarts_with(composeSQL.sPrefix,"delete"))
		{
			sMsgAtrri.eOperType = DBO_WRITE;
		}
	}

	return 0;
}
Пример #28
0
int CDBServiceConfig::LoadXmlByFileName(const string& sFileName)
{
	SC_XLOG(XLOG_DEBUG, "CDBServiceConfig::%s,FileName=[%s]\n",__FUNCTION__,sFileName.c_str());

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

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

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

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

	PostProcessServiceTypes(serviceDesc.mapServiceType);

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

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

	PostProcessMsgAttri(serviceDesc.mapMsgAttri,serviceDesc.mapServiceType);

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

	return 0;
	
}
Пример #29
0
void CButtonTranslator::MapJoystickActions(int windowID, TiXmlNode *pJoystick)
{
  string joyname = "_xbmc_"; // default global map name
  vector<string> joynames;
  map<int, string> buttonMap;
  map<int, string> axisMap;
  map<int, string> hatMap;

  TiXmlElement *pJoy = pJoystick->ToElement();
  if (pJoy && pJoy->Attribute("name"))
    joyname = pJoy->Attribute("name");
  else
    CLog::Log(LOGNOTICE, "No Joystick name specified, loading default map");

  joynames.push_back(joyname);

  // parse map
  TiXmlElement *pButton = pJoystick->FirstChildElement();
  int id = 0;
  //char* szId;
  const char* szType;
  const char *szAction;
  while (pButton)
  {
    szType = pButton->Value();
    szAction = pButton->GetText();
    if (szAction == NULL)
      szAction = "";
    if (szType)
    {
      if ((pButton->QueryIntAttribute("id", &id) == TIXML_SUCCESS) && id>=0 && id<=256)
      {
        if (strcmpi(szType, "button")==0)
        {
          buttonMap[id] = string(szAction);
        }
        else if (strcmpi(szType, "axis")==0)
        {
          int limit = 0;
          if (pButton->QueryIntAttribute("limit", &limit) == TIXML_SUCCESS)
          {
            if (limit==-1)
              axisMap[-id] = string(szAction);
            else if (limit==1)
              axisMap[id] = string(szAction);
            else if (limit==0)
              axisMap[id|0xFFFF0000] = string(szAction);
            else
            {
              axisMap[id] = string(szAction);
              axisMap[-id] = string(szAction);
              CLog::Log(LOGERROR, "Error in joystick map, invalid limit specified %d for axis %d", limit, id);
            }
          }
          else
          {
            axisMap[id] = string(szAction);
            axisMap[-id] = string(szAction);
          }
        }
        else if (strcmpi(szType, "hat")==0)
        {
          string position;
          if (pButton->QueryValueAttribute("position", &position) == TIXML_SUCCESS)
          {
            uint32_t hatID = id|0xFFF00000;
            if (position.compare("up") == 0)
              hatMap[(JACTIVE_HAT_UP<<16)|hatID] = string(szAction);
            else if (position.compare("down") == 0)
              hatMap[(JACTIVE_HAT_DOWN<<16)|hatID] = string(szAction);
            else if (position.compare("right") == 0)
              hatMap[(JACTIVE_HAT_RIGHT<<16)|hatID] = string(szAction);
            else if (position.compare("left") == 0)
              hatMap[(JACTIVE_HAT_LEFT<<16)|hatID] = string(szAction);
            else
              CLog::Log(LOGERROR, "Error in joystick map, invalid position specified %s for axis %d", position.c_str(), id);
          }
        }
        else
          CLog::Log(LOGERROR, "Error reading joystick map element, unknown button type: %s", szType);
      }
      else if (strcmpi(szType, "altname")==0)
        joynames.push_back(string(szAction));
      else
        CLog::Log(LOGERROR, "Error reading joystick map element, Invalid id: %d", id);
    }
    else
      CLog::Log(LOGERROR, "Error reading joystick map element, skipping");

    pButton = pButton->NextSiblingElement();
  }
  vector<string>::iterator it = joynames.begin();
  while (it!=joynames.end())
  {
    m_joystickButtonMap[*it][windowID] = buttonMap;
    m_joystickAxisMap[*it][windowID] = axisMap;
    m_joystickHatMap[*it][windowID] = hatMap;
//    CLog::Log(LOGDEBUG, "Found Joystick map for window %d using %s", windowID, it->c_str());
    it++;
  }
}
Пример #30
0
    AnimationPtr AnimationLoader::load(const std::string& filename) {
        bfs::path animPath(filename);

        std::string animationFilename = animPath.string();

        TiXmlDocument doc;

        AnimationPtr animation;

        try {
            RawData* data = m_vfs->open(animationFilename);

            if (data) {
                if (data->getDataLength() != 0) {
                    doc.Parse(data->readString(data->getDataLength()).c_str());

                    if (doc.Error()) {
                        return animation;
                    }

                    // done with data delete resource
                    delete data;
                    data = 0;
                }
            }
        }
        catch (NotFound& e) {
            FL_ERR(_log, e.what());

            // TODO - should we abort here
            //        or rethrow the exception
            //        or just keep going

            return animation;
        }

        // if we get here then everything loaded properly
        // so we can just parse out the contents
        TiXmlElement* root = doc.RootElement();

        if (root) {
            animation.reset(new Animation());

            int animDelay = 0;
            root->QueryValueAttribute("delay", &animDelay);

            int animXoffset = 0;
            int animYoffset = 0;
            int action = -1;
            root->QueryValueAttribute("x_offset", &animXoffset);
            root->QueryValueAttribute("y_offset", &animYoffset);
            root->QueryValueAttribute("action", &action);

            for (TiXmlElement* frameElement = root->FirstChildElement("frame"); frameElement; frameElement = frameElement->NextSiblingElement("frame")) {
                if (animation) {
                    animation->setActionFrame(action);

                    const std::string* sourceId = frameElement->Attribute(std::string("source"));

                    if (sourceId) {
                        bfs::path framePath(filename);

                        if (HasParentPath(framePath)) {
							framePath = GetParentPath(framePath) / *sourceId;
						} else {
							framePath = bfs::path(*sourceId);
						}

						ImagePtr imagePtr;
						if(!m_imageManager->exists(framePath.string())) {
                        	imagePtr = m_imageManager->create(framePath.string());
						}
						else {
							imagePtr = m_imageManager->getPtr(framePath.string());
						}

                        if (imagePtr) {
                            int frameXoffset = 0;
                            int frameYoffset = 0;

                            int success = root->QueryValueAttribute("x_offset", &frameXoffset);

                            if (success == TIXML_SUCCESS) {
                                imagePtr->setXShift(frameXoffset);
                            }
                            else {
                                imagePtr->setXShift(animXoffset);
                            }

                            success = root->QueryValueAttribute("y_offset", &frameYoffset);

                            if (success == TIXML_SUCCESS) {
                                imagePtr->setYShift(frameYoffset);
                            }
                            else {
                                imagePtr->setYShift(animYoffset);
                            }

                            int frameDelay = 0;
                            success = root->QueryValueAttribute("delay", &frameDelay);

                            if (success == TIXML_SUCCESS) {
                                animation->addFrame(imagePtr, frameDelay);
                            }
                            else {
                                animation->addFrame(imagePtr, animDelay);
                            }
                        }
                    }
                }
            }
        }

        return animation;
    }