Esempio n. 1
0
void Preprocess::RunPipe(std::string filename)
{
	TiXmlDocument doc;
	if ( !doc.LoadFile( filename.c_str() ) )
		return;

	TiXmlElement* rootElement = doc.FirstChildElement();
	const char* docname = rootElement->Value();
	if ( strcmp( docname, "Preprocess" ) != 0 )
		return;

	TiXmlElement* parentElement = rootElement->FirstChildElement();
	while (parentElement)
	{
		const char * parent = parentElement->Value();
		if ( strcmp( parent, "LaplacianOfGaussian" ) == 0 )
		{
			int sigma = 10;
			int min = 0;
			parentElement->QueryIntAttribute("sigma", &sigma);
			parentElement->QueryIntAttribute("min", &min);
			std::cout << "Starting LOG...";
			this->LaplacianOfGaussian(sigma, min);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "InvertIntensity" ) == 0 )
		{
			std::cout << "Starting InvertIntensity...";
			this->InvertIntensity();
			std::cout << "done\n";
		}
		else if( strcmp( parent, "DownSample" ) == 0 )
		{
			std::cout << "Starting DownSample...";
			this->DownSample();
			std::cout << "done\n";
		}
		else if( strcmp( parent, "OtsuBinarize" ) == 0 )
		{
			int numThresh = 2, numFore = 1;
			int fgrndDark = 0;
			parentElement->QueryIntAttribute("num_thresholds",&numThresh);
			parentElement->QueryIntAttribute("num_in_foreground",&numFore);
			parentElement->QueryIntAttribute("fgrnd_dark", &fgrndDark);
			std::cout << "Starting OtsuBinarize...";
			this->OtsuBinarize(numThresh,numFore, (bool)fgrndDark);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "ManualThreshold" ) == 0 )
		{
			int threshold = 128;
			int binary = 0;
			parentElement->QueryIntAttribute("threshold", &threshold);
			parentElement->QueryIntAttribute("binary", &binary);
			std::cout << "Starting Manual Threshold of " << threshold << "...";
			this->ManualThreshold(threshold, (bool)binary);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "RemoveConnectedComponents" ) == 0 )
		{
			int minObjSize = 1000;
			parentElement->QueryIntAttribute("minObjSize", &minObjSize);
			std::cout << "Starting RemoveCC...";
			this->RemoveConnectedComponents(minObjSize);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "BinaryThinning" ) == 0 )
		{
			std::cout << "Starting BinaryThinning...";
			this->BinaryThinning();
			std::cout << "done\n";
		}
		else if( strcmp( parent, "DanielssonDistanceMap" ) == 0 )
		{
			std::cout << "Starting DanielssonDistanceMap...";
			this->DanielssonDistanceMap();
			std::cout << "done\n";
		}
		else if( strcmp( parent, "MedianFilter" ) == 0 )
		{
			int radiusX=2, radiusY=3, radiusZ=0;
			parentElement->QueryIntAttribute("radiusX",&radiusX);
			parentElement->QueryIntAttribute("radiusY",&radiusY);
			parentElement->QueryIntAttribute("radiusZ",&radiusZ);
			std::cout << "Starting MedianFilter...";
			this->MedianFilter(radiusX,radiusY,radiusZ);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "MinErrorThresholding" ) == 0 )
		{
			float alpha_B, alpha_F, P_I;
			std::cout << "Starting MinErrorThresholding...";
			this->MinErrorThresholding(&alpha_B, &alpha_F, &P_I);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "GraphCutBinarize" ) == 0 )
		{
			int xyDivs=1;//, zDivs=1;
			parentElement->QueryIntAttribute("xyDivs",&xyDivs);
			std::cout << "Starting GraphCutBinarize...";
			this->GraphCutBinarize(false,xyDivs);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "OpeningFilter" ) == 0 )
		{
			int radius=3;
			parentElement->QueryIntAttribute("radius",&radius);
			std::cout << "Starting OpeningFilter...";
			this->OpeningFilter(radius);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "ClosingFilter" ) == 0 )
		{
			int radius=3;
			parentElement->QueryIntAttribute("radius",&radius);
			std::cout << "Starting ClosingFilter...";
			this->ClosingFilter(radius);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "CannyEdgeDetection" ) == 0 )
		{
			float variance=1.0;
			float upperThreshold = 6;
			float lowerThreshold = 3;
			parentElement->QueryFloatAttribute("variance",&variance);
			parentElement->QueryFloatAttribute("upperThreshold",&upperThreshold);
			parentElement->QueryFloatAttribute("lowerThreshold",&lowerThreshold);
			std::cout << "Starting CannyEdgeDetection...";
			this->CannyEdgeDetection(variance, upperThreshold, lowerThreshold);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "DiscreteGaussian") == 0 )
		{
			float varX=1.0, varY=1.0, varZ=1.0, maxError=0.1;
			parentElement->QueryFloatAttribute("varX",&varX);
			parentElement->QueryFloatAttribute("varY",&varY);
			parentElement->QueryFloatAttribute("varZ",&varZ);
			parentElement->QueryFloatAttribute("maxError",&maxError);
			std::cout << "Starting DiscreteGaussianFilter...";
			this->DiscreteGaussianFilter(varX, varY, varZ, maxError);
			std::cout << "done\n";
		}
		else if( strcmp( parent, "SaveVTKPoints") == 0 )
		{
			const char * filename = parentElement->Attribute("filename");
			float xyFactor = 1.0;
			int min=255, max=255;
			parentElement->QueryFloatAttribute("xyFactor", &xyFactor);
			parentElement->QueryIntAttribute("min",&min);
			parentElement->QueryIntAttribute("max",&max);
			std::cout << "Saving VTK Points...";
			if(!filename)
				this->SaveVTKPoints("points.vtk", xyFactor, min, max);
			else
				this->SaveVTKPoints(filename, xyFactor, min, max);
			std::cout << "done\n";
		}

		parentElement = parentElement->NextSiblingElement();
	} // end while(parentElement)
	//doc.close();
}
Esempio n. 2
0
int CCrashInfoReader::ParseCrashDescription(CString sFileName, BOOL bParseFileItems, ErrorReportInfo& eri)
{
  strconv_t strconv;

  TiXmlDocument doc;
  bool bOpen = doc.LoadFile(strconv.t2a(sFileName));
  if(!bOpen)
    return 1;

  TiXmlHandle hRoot = doc.FirstChild("CrashRpt");
  if(hRoot.ToElement()==NULL)
    return 1;

  {
    TiXmlHandle hCrashGUID = hRoot.FirstChild("CrashGUID");
    if(hCrashGUID.FirstChild().ToText()!=NULL)
    {
      const char* szCrashGUID = hCrashGUID.FirstChild().ToText()->Value();
      if(szCrashGUID!=NULL)
        eri.m_sCrashGUID = strconv.utf82t(szCrashGUID);
    }
  }

  {
    TiXmlHandle hAppName = hRoot.FirstChild("AppName");
    const char* szAppName = hAppName.FirstChild().ToText()->Value();
    if(szAppName!=NULL)
      eri.m_sAppName = strconv.utf82t(szAppName);
  }

  {
    TiXmlHandle hAppVersion = hRoot.FirstChild("AppVersion");
    const char* szAppVersion = hAppVersion.FirstChild().ToText()->Value();
    if(szAppVersion!=NULL)
      eri.m_sAppVersion = strconv.utf82t(szAppVersion);
  }

  {
    TiXmlHandle hImageName = hRoot.FirstChild("ImageName");
    const char* szImageName = hImageName.FirstChild().ToText()->Value();
    if(szImageName!=NULL)
      eri.m_sImageName = strconv.utf82t(szImageName);
  }

  {
    TiXmlHandle hSystemTimeUTC = hRoot.FirstChild("SystemTimeUTC");
    const char* szSystemTimeUTC = hSystemTimeUTC.FirstChild().ToText()->Value();
    if(szSystemTimeUTC!=NULL)
      eri.m_sSystemTimeUTC = strconv.utf82t(szSystemTimeUTC);
  }

  if(bParseFileItems)
  {
    // Get directory name
    CString sReportDir = sFileName;
    int pos = sFileName.ReverseFind('\\');
    if(pos>=0)
      sReportDir = sFileName.Left(pos);
    if(sReportDir.Right(1)!=_T("\\"))
      sReportDir += _T("\\");
   
    TiXmlHandle fl = hRoot.FirstChild("FileList");
    if(fl.ToElement()==0)
    {    
      return 1;
    }

    TiXmlHandle fi = fl.FirstChild("FileItem");
    while(fi.ToElement()!=0)
    {
      const char* pszDestFile = fi.ToElement()->Attribute("name");      
      const char* pszDesc = fi.ToElement()->Attribute("description");      

      if(pszDestFile!=NULL)
      {
	      CString sDestFile = strconv.utf82t(pszDestFile);      
        FileItem item;
        item.m_sDestFile = sDestFile;
        item.m_sSrcFile = sReportDir + sDestFile;
        if(pszDesc)
          item.m_sDesc = strconv.utf82t(pszDesc);
        item.m_bMakeCopy = FALSE;
        
        // Check that file really exists
        DWORD dwAttrs = GetFileAttributes(item.m_sSrcFile);
        if(dwAttrs!=INVALID_FILE_ATTRIBUTES &&
           (dwAttrs&FILE_ATTRIBUTE_DIRECTORY)==0)
        {
          eri.m_FileItems[sDestFile] = item;
        }
      }

      fi = fi.ToElement()->NextSibling("FileItem");
    }    
  }

  return 0;
}
Esempio n. 3
0
bool CPlanarGraph::LoadGraphFromXML(const char* fileName, bool flagDetectFaces /* = true */, bool flagIgnoreIndiv /* = true */)
{
	// Clear the current graph...
	ClearGraph();

	TiXmlDocument doc;
	bool loadFlag = doc.LoadFile(fileName);
	if ( loadFlag == false )
	{
		std::cout << "Failed to load graph from " << fileName << "!\n";
		return loadFlag;
	}
	//doc.Print();

	TiXmlNode* xmlRoot = 0;
	xmlRoot = doc.RootElement();
	assert( xmlRoot );

	TiXmlNode* xmlNode = xmlRoot->FirstChild();
	while ( xmlNode != 0 )
	{
		if ( strcmp(xmlNode->Value(), "Node") == 0 )
		{
			// Parse a node...
			CGraphNode graphNode;
			float px, py;
			int rx = xmlNode->ToElement()->QueryFloatAttribute("px", &px);
			int ry = xmlNode->ToElement()->QueryFloatAttribute("py", &py);
			if ( rx != TIXML_SUCCESS || ry != TIXML_SUCCESS )
			{
				graphNode.RandomlyInitPos();
			}
			else
			{
				graphNode.SetPos(px, py);
			}
			int type;
			int r = xmlNode->ToElement()->QueryIntAttribute("type", &type);
			if ( r == TIXML_SUCCESS )
			{
				graphNode.SetType(type);
			}
			int boundary;
			int rb = xmlNode->ToElement()->QueryIntAttribute("boundary", &boundary);
			if ( rb == TIXML_SUCCESS )
			{
				graphNode.SetBoundaryType(boundary);
			}
			int fixed;
			int rf = xmlNode->ToElement()->QueryIntAttribute("fix", &fixed);
			if ( rf == TIXML_SUCCESS && fixed != 0 )
			{
				graphNode.SetFlagFixed(true);
			}
			const char* str = xmlNode->ToElement()->Attribute("name");
			if ( *str != '\0' )
			{
				graphNode.SetName(str);
			}
			AddGraphNode(graphNode);
		}
		else if ( strcmp(xmlNode->Value(), "Edge") == 0 )
		{
			// Parse an edge...
			int idx0 = -1;
			int idx1 = -1;
			int r0 = xmlNode->ToElement()->QueryIntAttribute("node0", &idx0);
			int r1 = xmlNode->ToElement()->QueryIntAttribute("node1", &idx1);
			if ( r0 != TIXML_SUCCESS )
			{
				const char* str = xmlNode->ToElement()->Attribute("name0");
				idx0 = FindNodeAccordingToName(str);
			}
			if ( r1 != TIXML_SUCCESS )
			{
				const char* str = xmlNode->ToElement()->Attribute("name1");
				idx1 = FindNodeAccordingToName(str);
			}
			if ( idx0 >= 0 && idx1 >= 0 )
			{
				CGraphEdge graphEdge(idx0, idx1);
				AddGraphEdge(graphEdge);
			}
		}

		// Move to the next sibling...
		xmlNode = xmlNode->NextSibling();
	}

	SetNodeNeighbors();
	if ( flagIgnoreIndiv == true )
	{
		RemoveIndividualNodes();
	}
	if ( flagDetectFaces == false )
	{
		return loadFlag;
	}
	//PrintGraph();

	// Step 1: Detect faces of the planar graph...
	DetectFaces();
	return loadFlag;
}
void loadActorsData(char *filaname)
{
	TiXmlDocument doc;
	doc.SetTabSize(8);
	doc.LoadFile(filaname);
	TiXmlNode *unit = doc.FirstChild("units");
	unit = unit->FirstChild("unit");
	while (unit)
	{
		ActorData* actorData = new ActorData();
		actorData->ActorType = ActorsData.size();
		ActorsData.push_back(actorData);
		actorData->Caption = unit->FirstChildElement("name")->GetText();
		actorData->Name = unit->FirstChildElement("id")->GetText();
		actorData->Price = atoi(unit->FirstChildElement("price")->GetText());
		actorData->RequireUpgrade = atoi(unit->FirstChildElement("RequireUpgrade")->GetText());
		actorData->BattleUpgradeClass = unit->FirstChildElement("BattleUpgradeClass")->GetText();
		actorData->Damage[ActorData::DamageLight] = (float)atof(unit->FirstChildElement("DamageLight")->GetText());
		actorData->Damage[ActorData::DamageArmored] = (float)atof(unit->FirstChildElement("DamageArmored")->GetText());
		actorData->Damage[ActorData::DamageMassive] = (float)atof(unit->FirstChildElement("DamageMassive")->GetText());
		actorData->Damage[ActorData::DamageShield] = (float)atof(unit->FirstChildElement("DamageShield")->GetText());
		actorData->Damage[ActorData::DamageOrganic] = (float)atof(unit->FirstChildElement("DamageOrganic")->GetText());
		actorData->Damage[ActorData::DamageBuilding] = (float)atof(unit->FirstChildElement("DamageBuilding")->GetText());
		actorData->Damage[ActorData::DamageLightAir] = (float)atof(unit->FirstChildElement("DamageLightAir")->GetText());
		actorData->Damage[ActorData::DamageArmoredAir] = (float)atof(unit->FirstChildElement("DamageArmoredAir")->GetText());
		actorData->Damage[ActorData::DamageMassiveAir] = (float)atof(unit->FirstChildElement("DamageMassiveAir")->GetText());
		actorData->Damage[ActorData::DamageShieldAir] = (float)atof(unit->FirstChildElement("DamageShieldAir")->GetText());
		actorData->Damage[ActorData::DamageOrganicAir] = (float)atof(unit->FirstChildElement("DamageOrganicAir")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageLight] = (float)atof(unit->FirstChildElement("DamageLightUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageArmored] = (float)atof(unit->FirstChildElement("DamageArmoredUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageMassive] = (float)atof(unit->FirstChildElement("DamageMassiveUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageShield] = (float)atof(unit->FirstChildElement("DamageShieldUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageOrganic] = (float)atof(unit->FirstChildElement("DamageOrganicUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageBuilding] = (float)atof(unit->FirstChildElement("DamageBuildingUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageLightAir] = (float)atof(unit->FirstChildElement("DamageLightAirUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageArmoredAir] = (float)atof(unit->FirstChildElement("DamageArmoredAirUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageMassiveAir] = (float)atof(unit->FirstChildElement("DamageMassiveAirUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageShieldAir] = (float)atof(unit->FirstChildElement("DamageShieldAirUpgradeFactor")->GetText());
		actorData->DamageUpgradeFactor[ActorData::DamageOrganicAir] = (float)atof(unit->FirstChildElement("DamageOrganicAirUpgradeFactor")->GetText());
		actorData->SplashDamage = (float)atof(unit->FirstChildElement("SplashDamage")->GetText());
		actorData->SplashDamageShield = (float)atof(unit->FirstChildElement("SplashDamageShield")->GetText());
		actorData->SplashType = unit->FirstChildElement("SplashType")->GetText();
		actorData->DistanceSplash = (float)atof(unit->FirstChildElement("DistanceSplash")->GetText());
		actorData->AttackDelayAir = 1000.0f * TIME_SCALE * (float)atof(unit->FirstChildElement("AttackDelayAir")->GetText());
		actorData->AttackDelayGround = 1000.0f * TIME_SCALE * (float)atof(unit->FirstChildElement("AttackDelayGround")->GetText());
		actorData->armour = (float)atof(unit->FirstChildElement("armour")->GetText());
		actorData->shield = (float)atof(unit->FirstChildElement("shield")->GetText());
		actorData->HP = (float)atof(unit->FirstChildElement("HP")->GetText());
		actorData->mana = (float)atof(unit->FirstChildElement("mana")->GetText());
		actorData->MoveSpeed = (float)atof(unit->FirstChildElement("MoveSpeed")->GetText());
		actorData->UndergroundSpeed = (float)atof(unit->FirstChildElement("UndergroundSpeed")->GetText());
		actorData->ImmediateAttack = (bool)atoi(unit->FirstChildElement("ImmediateAttack")->GetText());
		actorData->DistanceGround = (float)atof(unit->FirstChildElement("DistanceGround")->GetText());
		actorData->DistanceAir = (float)atof(unit->FirstChildElement("DistanceAir")->GetText());
		actorData->DetectionDistance = DETECTION_DISTANCE;
		actorData->AttackCountGround = atoi(unit->FirstChildElement("AttackCountGround")->GetText());
		actorData->AttackCountAir = atoi(unit->FirstChildElement("AttackCountAir")->GetText());
		actorData->Detection = (float)atof(unit->FirstChildElement("Detection")->GetText());
		actorData->TargetGround = (bool)atoi(unit->FirstChildElement("TargetGround")->GetText());
		actorData->TargetAir = (bool)atoi(unit->FirstChildElement("TargetAir")->GetText());
		actorData->MovementGround = (bool)atoi(unit->FirstChildElement("MovementGround")->GetText());
		actorData->MovementAir = (bool)atoi(unit->FirstChildElement("MovementAir")->GetText());
		actorData->LightArmor = (bool)atoi(unit->FirstChildElement("LightArmor")->GetText());
		actorData->HavyArmor = (bool)atoi(unit->FirstChildElement("HavyArmor")->GetText());
		actorData->Organic = (bool)atoi(unit->FirstChildElement("Organic")->GetText());
		actorData->Psionic = (bool)atoi(unit->FirstChildElement("Psionic")->GetText());
		actorData->Mechanic = (bool)atoi(unit->FirstChildElement("Mechanic")->GetText());
		actorData->Massive = (bool)atoi(unit->FirstChildElement("Massive")->GetText());
		actorData->Building = (bool)atoi(unit->FirstChildElement("Building")->GetText());
		actorData->effectivity = unit->FirstChildElement("effectivity")->GetText();
		actorData->noneffectivity = unit->FirstChildElement("noneffectivity")->GetText();
		actorData->GeometryRadius = (float)atof(unit->FirstChildElement("GeometryRadius")->GetText());

		unit = unit->NextSibling("unit");
	}

	//empty data
	ActorData* actorData = new ActorData();
	ActorsData.push_back(actorData);
}
Esempio n. 5
0
int SC2Map::readObjects( const HANDLE archive )
{
  if( debugObjects > 0 )
  {
    printMessage( "Debugging Objects.\n" );
  }

  char strFilename[] = "Objects";

  int bufferSize;
  u8* bufferFreeAfterUse;

  if( readArchiveFile( archive, strFilename, &bufferSize, &bufferFreeAfterUse ) < 0 )
  {
    return -1;
  }

  bool continueProcessing = true;

  // we need a FILE* instead of data buffer for tinyxml lib
  char strTemp[] = "Objects.tmp";
  FILE* fileTemp = fopen( strTemp, "w+" );

  if( fileTemp == NULL )
  {
    printError( "Could not open temp file for %s.\n", strFilename );
    continueProcessing = false;
  }

  if( continueProcessing )
  {
    int bytesWritten = fwrite( (char*)bufferFreeAfterUse, 1, bufferSize, fileTemp );
    if( bytesWritten != bufferSize )
    {
      printError( "Could not dump %s to temp file.\n", strFilename );
      continueProcessing = false;
    }

    // from here on out a temporary file holds the XML
    // so after processing delete the file
    fclose( fileTemp );
  }

  // whether or not we continue processing we have to
  // release the buffer with the file's data
  delete bufferFreeAfterUse;


  bool continueXML = false;
  if( continueProcessing )
  {
    continueXML = true;
  }

  TiXmlDocument doc;

  if( continueXML )
  {
    // open temp file as XML stream
    if( !doc.LoadFile( strTemp ) )
    {
      printError( "Could not open temp file for %s.\n", strFilename );
      continueXML = false;
    }
  }

  TiXmlHandle docHandle( &doc );
  TiXmlElement* placedObjects = NULL;

  if( continueXML )
  {
    placedObjects = docHandle
      .FirstChildElement( "PlacedObjects" )
      .ToElement();
    if( !placedObjects )
    {
      printWarning( "%s is not valid.\n", strFilename );
      continueXML = false;
    }
  }

  ObjectMode objMode;

  if( continueXML )
  {
    const char* strVersion;

    // try the OBJMODE_BETAPH1_v26 format first
    const char* strVersion1 = placedObjects->Attribute( "version" );
    if( strVersion1 != NULL )
    {
      strVersion = strVersion1;
      objMode    = OBJMODE_BETAPH1_v26;

    } else {
      const char* strVersion2 = placedObjects->Attribute( "Version" );
      if( strVersion2 != NULL )
      {
        strVersion = strVersion2;
        objMode    = OBJMODE_BETAPH2_v26;
      }
    }

    if( strVersion == NULL )
    {
      printWarning( "%s has an unknown version.\n", strFilename );
      continueXML = false;
    }
    else if( strcmp( strVersion, "26" ) != 0 )
    {
      printWarning( "%s is version %s, file version 26 expected.\n", strFilename, strVersion );
    }
  }

  if( continueXML )
  {
    for( TiXmlElement* object = placedObjects->FirstChildElement();
         object;
         object = object->NextSiblingElement() )
    {
      // in placedobjects.cpp
      processPlacedObject( objMode, object );
    }
  }

  // delete the temporary file
  char cmd[512];
  sprintf( cmd, "if exist %s del %s", strTemp, strTemp );
  system( cmd );

  if( continueProcessing && continueXML )
  {
    return 0;
  }

  return -1;
}
Esempio n. 6
0
// 获得比特彗星的下载目录
BOOL bigfilehelper::GetBitCometDownloadDirs(std::vector<CString>& vDirs)
{
    BOOL retval = FALSE;
    TiXmlDocument xmlDoc;
    const TiXmlElement *pBT = NULL;
    const TiXmlElement *pSet = NULL;
    const TiXmlElement *pDownLoad = NULL;
    const char* szDefaultDownPath = NULL;
    CString strDirs;
    int pos = -1;
    TCHAR szAppPath[MAX_PATH] = { 0 };
    ULONG dwLength = MAX_PATH;
    CRegKey regKey;
    LONG lRetCode;

    WCHAR szAppDataPath[MAX_PATH] = {0};
    szAppDataPath[0] = GetSystemDrive();
    wcscat(szAppDataPath,L":\\downloads");
    vDirs.push_back(szAppDataPath);

    lRetCode = regKey.Open(HKEY_CURRENT_USER, _T("Software\\BitComet"), KEY_READ);
    if (lRetCode)
        goto clean0;

    lRetCode = regKey.QueryStringValue(NULL, szAppPath, &dwLength);
    if (lRetCode)
        goto clean0;

    PathRemoveFileSpec(szAppPath);
    PathAppend(szAppPath, _T("BitComet.xml"));

    if (GetFileAttributes(szAppPath) == INVALID_FILE_ATTRIBUTES)
        goto clean0;

    if (!xmlDoc.LoadFile(UnicodeToAnsi(szAppPath).c_str(), TIXML_ENCODING_UTF8))
        goto clean0;

    pBT = xmlDoc.FirstChildElement("BitComet");
    if (!pBT)
        goto clean0;

    pSet = xmlDoc.FirstChildElement("Settings");
    if (!pSet)
        goto clean0;

    pDownLoad = xmlDoc.FirstChildElement("DefaultDownloadPath");
    if (!pDownLoad)
        goto clean0;


    szDefaultDownPath = pDownLoad->GetText();
    if (!szDefaultDownPath)
        goto clean0;

    strDirs = Utf8ToUnicode(szDefaultDownPath).c_str();
    if (GetFileAttributes(strDirs) != INVALID_FILE_ATTRIBUTES)
    { 
        if(strDirs.GetAt(0)==GetSystemDrive()||strDirs.GetAt(0)==GetSystemDrive()-32||strDirs.GetAt(0)==GetSystemDrive()+32)
            vDirs.push_back(strDirs);
        else goto clean0;
    }
    retval = TRUE;

clean0:
    return retval;
}
Esempio n. 7
0
Level* LevelParser::parseLevel(const char *levelFile)
{
    // create a tinyXML document and load the map xml
    TiXmlDocument levelDocument;
    levelDocument.LoadFile(levelFile);
    
    // create the level object
    Level* pLevel = new Level();
    
    // get the root node and display some values
    TiXmlElement* pRoot = levelDocument.RootElement();
    
    std::cout << "Loading level:\n" << "Version: " << pRoot->Attribute("version") << "\n";
    std::cout << "Width:" << pRoot->Attribute("width") << " - Height:" << pRoot->Attribute("height") << "\n";
    std::cout << "Tile Width:" << pRoot->Attribute("tilewidth") << " - Tile Height:" << pRoot->Attribute("tileheight") << "\n";
    
    pRoot->Attribute("tilewidth", &m_tileSize);
    pRoot->Attribute("width", &m_width);
    pRoot->Attribute("height", &m_height);
    
    //we know that properties is the first child of the root
    TiXmlElement* pProperties = pRoot->FirstChildElement();
    
    // we must parse the textures needed for this level, which have been added to properties
    for(TiXmlElement* e = pProperties->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("property"))
        {
            parseTextures(e);
        }
    }
    
    // we must now parse the tilesets
    for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("tileset"))
        {
            parseTilesets(e, pLevel->getTilesets());
        }
    }
    
    // parse any object layers
    for(TiXmlElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("objectgroup") || e->Value() == std::string("layer"))
        {
            if(e->FirstChildElement()->Value() == std::string("object"))
            {
                parseObjectLayer(e, pLevel->getLayers(), pLevel);
            }
            else if(e->FirstChildElement()->Value() == std::string("data") ||
                    (e->FirstChildElement()->NextSiblingElement() != 0 && e->FirstChildElement()->NextSiblingElement()->Value() == std::string("data")))
            {
                parseTileLayer(e, pLevel->getLayers(), pLevel->getTilesets(), pLevel->getCollisionLayers());
            }
        }
    }
    
    // set the players collision layer
   // pLevel->getPlayer()->setCollisionLayers(pLevel->getCollisionLayers());
    
    return pLevel;
}
Esempio n. 8
0
bool CMinotaurSpawn::LoadFromXML(const char* prefabName, CObjectManager* objManager)
{
	TiXmlDocument doc;

	string path = "../Game/Assets/Scripts/Prefabs/";
	path += prefabName;
	path += ".xml";


	if (doc.LoadFile(path.c_str(), TiXmlEncoding::TIXML_ENCODING_UTF8))
	{
		CAssetManager* pAssetManager = CAssetManager::GetInstance();
		TiXmlElement * root = doc.RootElement();


		TiXmlElement * ContentList = root->FirstChildElement("Meshes");
		if (ContentList)
		{
			TiXmlElement * Mesh = ContentList->FirstChildElement("Mesh");

			while (Mesh != nullptr)
			{
				double pos[4] = { 0.0 };
				XMFLOAT3 position;
				const char* name = Mesh->Attribute("name");
				const char* diffuse = Mesh->Attribute("diffuse");
				const char* normal = Mesh->Attribute("normalMap");

				Mesh->Attribute("transX", &pos[0]);
				Mesh->Attribute("transY", &pos[1]);
				Mesh->Attribute("transZ", &pos[2]);

				if (diffuse)
					diffuseTextures.push_back(diffuse);
				if (normal)
					normalMaps.push_back(normal);
				CMesh* mesh = pAssetManager->GetPrefabMesh(name);
				if (pos[3] == 90.0f)
				{
					for (size_t i = 0; i < mesh->GetPlanes().size(); i++)
						std::swap(mesh->GetPlanes()[i].extents.x, mesh->GetPlanes()[i].extents.z);

					for (size_t i = 0; i < mesh->GetAABBs().size(); i++)
						std::swap(mesh->GetAABBs()[i].extents.x, mesh->GetAABBs()[i].extents.z);
				}
				XMFLOAT4X4 local = {};
				XMStoreFloat4x4(&local, XMMatrixTranslation(pos[0], pos[1], pos[2]));
				meshLocalMatricies.push_back(local);
				meshes.push_back(mesh);
				Mesh = Mesh->NextSiblingElement();
			}
		}

		ContentList = root->FirstChildElement("Objects");
		if (ContentList && objManager)
		{

			TiXmlElement * Object = ContentList->FirstChildElement("Object");
			while (Object != nullptr)
			{
				int _type = 0;
				double data[4];
				XMFLOAT3 position;

				Object->Attribute("type", &_type);

				Object->Attribute("transX", &data[0]);
				Object->Attribute("transY", &data[1]);
				Object->Attribute("transZ", &data[2]);
				position = XMFLOAT3(float(data[0]), float(data[1]), float(data[2]));


				int orientation = 0;
				Object->Attribute("dir", &orientation);
				m_vObjects.push_back(new CItemCrate((IChest::EDirection)orientation, position, m_pDayNight));


				Object = Object->NextSiblingElement();
			}
		}
	}
	return true;
}
Esempio n. 9
0
	result nekoParticleInstance::LoadParticle(const char8 *fileName, bool forUseOnly)
	{
		char8 *fileData;

		TiXmlDocument doc;

		if(forUseOnly)
		{
			if(FAILED(GetNekoNovel()->GetFileSystem()->LoadData( (string("ÆÄƼŬ\\") + fileName).c_str(), &fileData)))
				return E_NOT_EXIST;
			doc.Parse(fileData);

			// ¸Þ¸ð¸® ¾ø¾Ö±â..
			delete []fileData;

			mForUseOnly = true;
		}
		else
		{
			doc.LoadFile(fileName);
		}
		mFileName = fileName;

		if(doc.Error())
		{
			LogPrint(LOG_LEVEL_WARN, "'%s' ÆÄÀÏÀº XML ±¸¹®ÀÌ À߸øµÇ¾ú½À´Ï´Ù.", fileName);
			return E_FAIL;
		}

		TiXmlElement *root = doc.FirstChildElement("NekoNovel_Particle");
		if(!root)
		{
			LogPrint(LOG_LEVEL_WARN, "'%s' ÆÄÀÏ¿¡ ÆÄƼŬ Á¤º¸°¡ Á¸ÀçÇÏÁö ¾Ê½À´Ï´Ù.", fileName);
			return E_FAIL;
		}

		Clear();

		TiXmlElement *emitter = root->FirstChildElement("Emitter");
		TiXmlElement *events;
		TiXmlElement *event;
		while(emitter)
		{
			nekoParticleEmitter *emt = AddEmitter(emitter->Attribute("Name"));

			emt->mEmitDelay = atof(emitter->Attribute("EmitDelay"));
			emt->mMinDir.x = atof(emitter->Attribute("MinDirX"));
			emt->mMinDir.y = atof(emitter->Attribute("MinDirY"));
			emt->mMaxDir.x = atof(emitter->Attribute("MaxDirX"));
			emt->mMaxDir.y = atof(emitter->Attribute("MaxDirY"));

			emt->mMinScale = atof(emitter->Attribute("MinScale"));
			emt->mMaxScale = atof(emitter->Attribute("MaxScale"));
			emt->mMaxCount = atoi(emitter->Attribute("MaxCount"));

			emt->mLoop = stricmp(emitter->Attribute("Loop"), "true") == 0;

			emt->mSpawnPos.x = atof(emitter->Attribute("SpawnPosX"));
			emt->mSpawnPos.y = atof(emitter->Attribute("SpawnPosY"));
			emt->mSpawnRadius.x = atof(emitter->Attribute("SpawnRadiusX"));
			emt->mSpawnRadius.y = atof(emitter->Attribute("SpawnRadiusY"));

			emt->mMinLifeTime = atof(emitter->Attribute("MinLifeTime"));
			emt->mMaxLifeTime = atof(emitter->Attribute("MaxLifeTime"));

			if(emitter->Attribute("MinFirstAppearTime"))
				emt->mMinFirstAppearTime = atof(emitter->Attribute("MinFirstAppearTime"));

			if(emitter->Attribute("MaxFirstAppearTime"))
				emt->mMaxFirstAppearTime = atof(emitter->Attribute("MaxFirstAppearTime"));

			emt->mMinStartColor = _atoi64(emitter->Attribute("MinStartColor"));
			emt->mMaxStartColor = _atoi64(emitter->Attribute("MaxStartColor"));

			emt->mMinEndColor = _atoi64(emitter->Attribute("MinEndColor"));
			emt->mMaxEndColor = _atoi64(emitter->Attribute("MaxEndColor"));

			emt->mRotation = atof(emitter->Attribute("Rotation"));
			emt->mRotationSpeed = atof(emitter->Attribute("RotationSpeed"));
			emt->mScaleSpeed = atof(emitter->Attribute("ScaleSpeed"));

			emt->mGravity.x = atof(emitter->Attribute("GravityX"));
			emt->mGravity.y = atof(emitter->Attribute("GravityY"));

			emt->mSrcBlend = atoi(emitter->Attribute("SrcBlend"));
			emt->mDestBlend = atoi(emitter->Attribute("DestBlend"));

			emt->SetTexture(emitter->Attribute("Image"));

			events = emitter->FirstChildElement("Events");
			if(events)
			{
				event = events->FirstChildElement("Event");
				while(event)
				{
					nekoParticleEvent pevt;

					pevt.mTime = atof(event->Attribute("Time"));
					pevt.mFlags = atoi(event->Attribute("Flags"));
					pevt.mMinDir.x = atof(event->Attribute("MinDirX"));
					pevt.mMinDir.y = atof(event->Attribute("MinDirY"));
					pevt.mMaxDir.x = atof(event->Attribute("MaxDirX"));
					pevt.mMaxDir.y = atof(event->Attribute("MaxDirY"));
					pevt.mGravity.x = atof(event->Attribute("GravityX"));
					pevt.mGravity.y = atof(event->Attribute("GravityY"));
					pevt.mRotationSpeed = atof(event->Attribute("RotationSpeed"));
					pevt.mScaleSpeed = atof(event->Attribute("ScaleSpeed"));
					pevt.mColor = _atoi64(event->Attribute("Color"));

					emt->ImportEvent(pevt);
					event = event->NextSiblingElement("Event");
				}
			}

			emt->FillNodes();
			emitter = emitter->NextSiblingElement("Emitter");
		}

		//LogPrint(LOG_LEVEL_INFO, "ÆÄƼŬ ºÒ·¯¿À±â°¡ ¿Ï·áµÇ¾ú½À´Ï´Ù. '%s'.", fileName);
		return S_OK;
	}
Esempio n. 10
0
bool CAdvancedSettings::Load()
{
  // NOTE: This routine should NOT set the default of any of these parameters
  //       it should instead use the versions of GetString/Integer/Float that
  //       don't take defaults in.  Defaults are set in the constructor above
  CStdString advancedSettingsXML;
  advancedSettingsXML  = g_settings.GetUserDataItem("advancedsettings.xml");
  TiXmlDocument advancedXML;
  if (!CFile::Exists(advancedSettingsXML))
  { // tell the user it doesn't exist
    CLog::Log(LOGNOTICE, "No advancedsettings.xml to load (%s)", advancedSettingsXML.c_str());
    return false;
  }

  if (!advancedXML.LoadFile(advancedSettingsXML))
  {
    CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", advancedSettingsXML.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc());
    return false;
  }

  TiXmlElement *pRootElement = advancedXML.RootElement();
  if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0)
  {
    CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", advancedSettingsXML.c_str());
    return false;
  }

  // succeeded - tell the user it worked
  CLog::Log(LOGNOTICE, "Loaded advancedsettings.xml from %s", advancedSettingsXML.c_str());

  // Dump contents of AS.xml to debug log
  TiXmlPrinter printer;
  printer.SetLineBreak("\n");
  printer.SetIndent("  ");
  advancedXML.Accept(&printer);
  CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", advancedSettingsXML.c_str(), printer.CStr());

  TiXmlElement *pElement = pRootElement->FirstChildElement("audio");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f);
    XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12);
    XMLUtils::GetFloat(pElement, "karaokesyncdelay", m_karaokeSyncDelay, -3.0f, 3.0f);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f);

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0);

    XMLUtils::GetInt(pElement, "resample", m_musicResample, 0, 48000);

    TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps);

    pAudioExcludes = pElement->FirstChildElement("excludefromscan");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps);

    XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc);
    XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV);
  }

  pElement = pRootElement->FirstChildElement("video");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600);
    XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600);
    XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255);
    XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f);
    XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900);
    XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f);

    XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX);
    XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10);
    XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0);

    TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludefromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("cleanstrings");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps);

    XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp);
    XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint);
    XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc);
  }

  pElement = pRootElement->FirstChildElement("musiclibrary");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "hideallitems", m_bMusicLibraryHideAllItems);
    XMLUtils::GetInt(pElement, "recentlyaddeditems", m_iMusicLibraryRecentlyAddedItems, 1, INT_MAX);
    XMLUtils::GetBoolean(pElement, "prioritiseapetags", m_prioritiseAPEv2tags);
    XMLUtils::GetBoolean(pElement, "allitemsonbottom", m_bMusicLibraryAllItemsOnBottom);
    XMLUtils::GetBoolean(pElement, "albumssortbyartistthenyear", m_bMusicLibraryAlbumsSortByArtistThenYear);
    XMLUtils::GetString(pElement, "albumformat", m_strMusicLibraryAlbumFormat);
    XMLUtils::GetString(pElement, "albumformatright", m_strMusicLibraryAlbumFormatRight);
    XMLUtils::GetString(pElement, "itemseparator", m_musicItemSeparator);
  }

  pElement = pRootElement->FirstChildElement("videolibrary");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "hideallitems", m_bVideoLibraryHideAllItems);
    XMLUtils::GetBoolean(pElement, "allitemsonbottom", m_bVideoLibraryAllItemsOnBottom);
    XMLUtils::GetInt(pElement, "recentlyaddeditems", m_iVideoLibraryRecentlyAddedItems, 1, INT_MAX);
    XMLUtils::GetBoolean(pElement, "hiderecentlyaddeditems", m_bVideoLibraryHideRecentlyAddedItems);
    XMLUtils::GetBoolean(pElement, "hideemptyseries", m_bVideoLibraryHideEmptySeries);
    XMLUtils::GetBoolean(pElement, "cleanonupdate", m_bVideoLibraryCleanOnUpdate);
    XMLUtils::GetString(pElement, "itemseparator", m_videoItemSeparator);
    XMLUtils::GetBoolean(pElement, "exportautothumbs", m_bVideoLibraryExportAutoThumbs);
    XMLUtils::GetBoolean(pElement, "importwatchedstate", m_bVideoLibraryImportWatchedState);

    TiXmlElement* pMyMovies = pElement->FirstChildElement("mymovies");
    if (pMyMovies)
      XMLUtils::GetBoolean(pMyMovies, "categoriestogenres", m_bVideoLibraryMyMoviesCategoriesToGenres);
  }

  pElement = pRootElement->FirstChildElement("videoscanner");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "ignoreerrors", m_bVideoScannerIgnoreErrors);
  }

  pElement = pRootElement->FirstChildElement("slideshow");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "panamount", m_slideshowPanAmount, 0.0f, 20.0f);
    XMLUtils::GetFloat(pElement, "zoomamount", m_slideshowZoomAmount, 0.0f, 20.0f);
    XMLUtils::GetFloat(pElement, "blackbarcompensation", m_slideshowBlackBarCompensation, 0.0f, 50.0f);
  }

  pElement = pRootElement->FirstChildElement("lcd");
  if (pElement)
  {
    XMLUtils::GetInt(pElement, "rows", m_lcdRows, 1, 4);
    XMLUtils::GetInt(pElement, "columns", m_lcdColumns, 1, 40);
    XMLUtils::GetInt(pElement, "address1", m_lcdAddress1, 0, 0x100);
    XMLUtils::GetInt(pElement, "address2", m_lcdAddress2, 0, 0x100);
    XMLUtils::GetInt(pElement, "address3", m_lcdAddress3, 0, 0x100);
    XMLUtils::GetInt(pElement, "address4", m_lcdAddress4, 0, 0x100);
  }

  pElement = pRootElement->FirstChildElement("network");
  if (pElement)
  {
    XMLUtils::GetInt(pElement, "autodetectpingtime", m_autoDetectPingTime, 1, 240);
    XMLUtils::GetInt(pElement, "curlclienttimeout", m_curlconnecttimeout, 1, 1000);
    XMLUtils::GetInt(pElement, "curllowspeedtime", m_curllowspeedtime, 1, 1000);
    XMLUtils::GetInt(pElement, "curlretries", m_curlretries, 0, 10);
    XMLUtils::GetUInt(pElement, "cachemembuffersize", m_cacheMemBufferSize);
  }

  pElement = pRootElement->FirstChildElement("samba");
  if (pElement)
  {
    XMLUtils::GetString(pElement,  "doscodepage",   m_sambadoscodepage);
    XMLUtils::GetInt(pElement, "clienttimeout", m_sambaclienttimeout, 5, 100);
    XMLUtils::GetBoolean(pElement, "statfiles", m_sambastatfiles);
  }

  pElement = pRootElement->FirstChildElement("httpdirectory");
  if (pElement)
    XMLUtils::GetBoolean(pElement, "statfilesize", m_bHTTPDirectoryStatFilesize);

  pElement = pRootElement->FirstChildElement("ftp");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "remotethumbs", m_bFTPThumbs);
  }

  pElement = pRootElement->FirstChildElement("loglevel");
  if (pElement)
  { // read the loglevel setting, so set the setting advanced to hide it in GUI
    // as altering it will do nothing - we don't write to advancedsettings.xml
    XMLUtils::GetInt(pRootElement, "loglevel", m_logLevelHint, LOG_LEVEL_NONE, LOG_LEVEL_MAX);
    CSettingBool *setting = (CSettingBool *)g_guiSettings.GetSetting("debug.showloginfo");
    if (setting)
    {
      const char* hide;
      if (!((hide = pElement->Attribute("hide")) && strnicmp("false", hide, 4) == 0))
        setting->SetAdvanced();
    }
    g_advancedSettings.m_logLevel = std::max(g_advancedSettings.m_logLevel, g_advancedSettings.m_logLevelHint);
    CLog::SetLogLevel(g_advancedSettings.m_logLevel);
  }

  pElement = pRootElement->FirstChildElement("python");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "verbose", m_bPythonVerbose);
  }

  XMLUtils::GetString(pRootElement, "cddbaddress", m_cddbAddress);

  XMLUtils::GetBoolean(pRootElement, "usepcdvdrom", m_usePCDVDROM);
  XMLUtils::GetBoolean(pRootElement, "nodvdrom", m_noDVDROM);
  XMLUtils::GetBoolean(pRootElement, "enableintro", m_enableintro);
  XMLUtils::GetBoolean(pRootElement, "fasterscanning", m_fastscanning);
  XMLUtils::GetBoolean(pRootElement, "slowscrolling", m_slowscrolling);
  XMLUtils::GetBoolean(pRootElement, "splash", m_splashImage);
  XMLUtils::GetBoolean(pRootElement, "disablemodchipdetection", m_DisableModChipDetection);
  XMLUtils::GetBoolean(pRootElement, "powersave", m_bPowerSave);

  XMLUtils::GetInt(pRootElement, "songinfoduration", m_songInfoDuration, 0, INT_MAX);
  XMLUtils::GetInt(pRootElement, "busydialogdelay", m_busyDialogDelay, 0, 5000);
  XMLUtils::GetInt(pRootElement, "playlistretries", m_playlistRetries, -1, 5000);
  XMLUtils::GetInt(pRootElement, "playlisttimeout", m_playlistTimeout, 0, 5000);

  XMLUtils::GetBoolean(pRootElement,"virtualshares", m_bVirtualShares);
  XMLUtils::GetBoolean(pRootElement,"navigatevirtualkeyboard", m_bNavVKeyboard);

  //Tuxbox
  pElement = pRootElement->FirstChildElement("tuxbox");
  if (pElement)
  {
    XMLUtils::GetInt(pElement, "streamtsport", m_iTuxBoxStreamtsPort, 0, 65535);
    XMLUtils::GetBoolean(pElement, "audiochannelselection", m_bTuxBoxAudioChannelSelection);
    XMLUtils::GetBoolean(pElement, "submenuselection", m_bTuxBoxSubMenuSelection);
    XMLUtils::GetBoolean(pElement, "pictureicon", m_bTuxBoxPictureIcon);
    XMLUtils::GetBoolean(pElement, "sendallaudiopids", m_bTuxBoxSendAllAPids);
    XMLUtils::GetInt(pElement, "epgrequesttime", m_iTuxBoxEpgRequestTime, 0, 3600);
    XMLUtils::GetInt(pElement, "defaultsubmenu", m_iTuxBoxDefaultSubMenu, 1, 4);
    XMLUtils::GetInt(pElement, "defaultrootmenu", m_iTuxBoxDefaultRootMenu, 0, 4);
    XMLUtils::GetInt(pElement, "zapwaittime", m_iTuxBoxZapWaitTime, 0, 120);
    XMLUtils::GetBoolean(pElement, "zapstream", m_bTuxBoxZapstream);
    XMLUtils::GetInt(pElement, "zapstreamport", m_iTuxBoxZapstreamPort, 0, 65535);
  }

  // Myth TV
  pElement = pRootElement->FirstChildElement("myth");
  if (pElement)
  {
    XMLUtils::GetInt(pElement, "movielength", m_iMythMovieLength);
  }

  // EDL commercial break handling
  pElement = pRootElement->FirstChildElement("edl");
  if (pElement)
  {
    XMLUtils::GetBoolean(pElement, "mergeshortcommbreaks", m_bEdlMergeShortCommBreaks);
    XMLUtils::GetInt(pElement, "maxcommbreaklength", m_iEdlMaxCommBreakLength, 0, 10 * 60); // Between 0 and 10 minutes
    XMLUtils::GetInt(pElement, "mincommbreaklength", m_iEdlMinCommBreakLength, 0, 5 * 60);  // Between 0 and 5 minutes
    XMLUtils::GetInt(pElement, "maxcommbreakgap", m_iEdlMaxCommBreakGap, 0, 5 * 60);        // Between 0 and 5 minutes.
    XMLUtils::GetInt(pElement, "maxstartgap", m_iEdlMaxStartGap, 0, 10 * 60);               // Between 0 and 10 minutes
    XMLUtils::GetInt(pElement, "commbreakautowait", m_iEdlCommBreakAutowait, 0, 10);        // Between 0 and 10 seconds
    XMLUtils::GetInt(pElement, "commbreakautowind", m_iEdlCommBreakAutowind, 0, 10);        // Between 0 and 10 seconds
  }

  // picture exclude regexps
  TiXmlElement* pPictureExcludes = pRootElement->FirstChildElement("pictureexcludes");
  if (pPictureExcludes)
    GetCustomRegexps(pPictureExcludes, m_pictureExcludeFromListingRegExps);

  // picture extensions
  CStdString extraExtensions;
  TiXmlElement* pExts = pRootElement->FirstChildElement("pictureextensions");
  if (pExts)
    GetCustomExtensions(pExts,g_settings.m_pictureExtensions);

  // music extensions
  pExts = pRootElement->FirstChildElement("musicextensions");
  if (pExts)
    GetCustomExtensions(pExts,g_settings.m_musicExtensions);

  // video extensions
  pExts = pRootElement->FirstChildElement("videoextensions");
  if (pExts)
    GetCustomExtensions(pExts,g_settings.m_videoExtensions);

  m_vecTokens.clear();
  CLangInfo::LoadTokens(pRootElement->FirstChild("sorttokens"),m_vecTokens);

  XMLUtils::GetBoolean(pRootElement, "displayremotecodes", m_displayRemoteCodes);

  // TODO: Should cache path be given in terms of our predefined paths??
  //       Are we even going to have predefined paths??
  CSettings::GetPath(pRootElement, "cachepath", m_cachePath);
  URIUtils::AddSlashAtEnd(m_cachePath);

  XMLUtils::GetBoolean(pRootElement, "ftpshowcache", m_FTPShowCache);

  g_LangCodeExpander.LoadUserCodes(pRootElement->FirstChildElement("languagecodes"));

  // trailer matching regexps
  TiXmlElement* pTrailerMatching = pRootElement->FirstChildElement("trailermatching");
  if (pTrailerMatching)
    GetCustomRegexps(pTrailerMatching, m_trailerMatchRegExps);

  //everything thats a trailer is not a movie
  m_moviesExcludeFromScanRegExps.insert(m_moviesExcludeFromScanRegExps.end(),
                                        m_trailerMatchRegExps.begin(),
                                        m_trailerMatchRegExps.end());

  // stacking regexps
  TiXmlElement* pVideoStacking = pRootElement->FirstChildElement("moviestacking");
  if (pVideoStacking)
    GetCustomRegexps(pVideoStacking, m_videoStackRegExps);

  //tv stacking regexps
  TiXmlElement* pTVStacking = pRootElement->FirstChildElement("tvshowmatching");
  if (pTVStacking)
    GetCustomTVRegexps(pTVStacking, m_tvshowStackRegExps);

  // path substitutions
  TiXmlElement* pPathSubstitution = pRootElement->FirstChildElement("pathsubstitution");
  if (pPathSubstitution)
  {
    m_pathSubstitutions.clear();
    CLog::Log(LOGDEBUG,"Configuring path substitutions");
    TiXmlNode* pSubstitute = pPathSubstitution->FirstChildElement("substitute");
    while (pSubstitute)
    {
      CStdString strFrom, strTo;
      TiXmlNode* pFrom = pSubstitute->FirstChild("from");
      if (pFrom)
        strFrom = pFrom->FirstChild()->Value();
      TiXmlNode* pTo = pSubstitute->FirstChild("to");
      if (pTo)
        strTo = pTo->FirstChild()->Value();

      if (!strFrom.IsEmpty() && !strTo.IsEmpty())
      {
        CLog::Log(LOGDEBUG,"  Registering substition pair:");
        CLog::Log(LOGDEBUG,"    From: [%s]", strFrom.c_str());
        CLog::Log(LOGDEBUG,"    To:   [%s]", strTo.c_str());
        // keep literal commas since we use comma as a seperator
        strFrom.Replace(",",",,");
        strTo.Replace(",",",,");
        m_pathSubstitutions.push_back(strFrom + " , " + strTo);
      }
      else
      {
        // error message about missing tag
        if (strFrom.IsEmpty())
          CLog::Log(LOGERROR,"  Missing <from> tag");
        else
          CLog::Log(LOGERROR,"  Missing <to> tag");
      }

      // get next one
      pSubstitute = pSubstitute->NextSiblingElement("substitute");
    }
  }

  XMLUtils::GetInt(pRootElement, "remoterepeat", m_remoteRepeat, 1, INT_MAX);
  XMLUtils::GetFloat(pRootElement, "controllerdeadzone", m_controllerDeadzone, 0.0f, 1.0f);
  XMLUtils::GetInt(pRootElement, "thumbsize", m_thumbSize, 0, 1024);
  XMLUtils::GetInt(pRootElement, "fanartheight", m_fanartHeight, 0, 1080);
  //dds support
  XMLUtils::GetBoolean(pRootElement, "useddsfanart", m_useddsfanart);


  XMLUtils::GetBoolean(pRootElement, "playlistasfolders", m_playlistAsFolders);
  XMLUtils::GetBoolean(pRootElement, "detectasudf", m_detectAsUdf);

  // music thumbs
  CStdString extraThumbs;
  TiXmlElement* pThumbs = pRootElement->FirstChildElement("musicthumbs");
  if (pThumbs)
  {
    // remove before add so that the defaults can be restored after user defined ones
    // (ie, the list can be:cover.jpg|cover.png|folder.jpg)
    CSettings::GetString(pThumbs, "remove", extraThumbs, "");
    if (extraThumbs != "")
    {
      CStdStringArray thumbs;
      StringUtils::SplitString(extraThumbs, "|", thumbs);
      for (unsigned int i = 0; i < thumbs.size(); ++i)
      {
        int iPos = m_musicThumbs.Find(thumbs[i]);
        if (iPos == -1)
          continue;
        m_musicThumbs.erase(iPos, thumbs[i].size() + 1);
      }
    }
    CSettings::GetString(pThumbs, "add", extraThumbs,"");
    if (extraThumbs != "")
    {
      if (!m_musicThumbs.IsEmpty())
        m_musicThumbs += "|";
      m_musicThumbs += extraThumbs;
    }
  }

  // dvd thumbs
  pThumbs = pRootElement->FirstChildElement("dvdthumbs");
  if (pThumbs)
  {
    // remove before add so that the defaults can be restored after user defined ones
    // (ie, the list can be:cover.jpg|cover.png|folder.jpg)
    CSettings::GetString(pThumbs, "remove", extraThumbs, "");
    if (extraThumbs != "")
    {
      CStdStringArray thumbs;
      StringUtils::SplitString(extraThumbs, "|", thumbs);
      for (unsigned int i = 0; i < thumbs.size(); ++i)
      {
        int iPos = m_dvdThumbs.Find(thumbs[i]);
        if (iPos == -1)
          continue;
        m_dvdThumbs.erase(iPos, thumbs[i].size() + 1);
      }
    }
    CSettings::GetString(pThumbs, "add", extraThumbs,"");
    if (extraThumbs != "")
    {
      if (!m_dvdThumbs.IsEmpty())
        m_dvdThumbs += "|";
      m_dvdThumbs += extraThumbs;
    }
  }

  // movie fanarts
  TiXmlElement* pFanart = pRootElement->FirstChildElement("fanart");
  if (pFanart)
    GetCustomExtensions(pFanart,m_fanartImages);

  // music filename->tag filters
  TiXmlElement* filters = pRootElement->FirstChildElement("musicfilenamefilters");
  if (filters)
  {
    TiXmlNode* filter = filters->FirstChild("filter");
    while (filter)
    {
      if (filter->FirstChild())
        m_musicTagsFromFileFilters.push_back(filter->FirstChild()->ValueStr());
      filter = filter->NextSibling("filter");
    }
  }

  TiXmlElement* pHostEntries = pRootElement->FirstChildElement("hosts");
  if (pHostEntries)
  {
    TiXmlElement* element = pHostEntries->FirstChildElement("entry");
    while(element)
    {
      CStdString name  = element->Attribute("name");
      CStdString value;
      if(element->GetText())
        value = element->GetText();

      if(name.length() > 0 && value.length() > 0)
        CDNSNameCache::Add(name, value);
      element = element->NextSiblingElement("entry");
    }
  }

  XMLUtils::GetInt(pRootElement, "bginfoloadermaxthreads", m_bgInfoLoaderMaxThreads);
  m_bgInfoLoaderMaxThreads = std::max(3, m_bgInfoLoaderMaxThreads);

  // load in the GUISettings overrides:
  g_guiSettings.LoadXML(pRootElement, true);  // true to hide the settings we read in

  return true;
}
Esempio n. 11
0
bool cxProjectInfo::Load(const wxFileName& rootPath, const wxString& path, bool onlyFilters) {
	wxFileName projectPath(path, wxEmptyString);
	this->path = path;
	this->isRoot = (projectPath == rootPath);

	projectPath.SetFullName(wxT(".eprj"));
	if (!projectPath.FileExists()) return false;

	// Load plist file
	TiXmlDocument doc;
	wxFFile docffile(projectPath.GetFullPath(), _T("rb"));
	wxCHECK(docffile.IsOpened() && doc.LoadFile(docffile.fp()), false);

	// Get top dict
	const TiXmlHandle docHandle(&doc);
	const TiXmlElement* topDict = docHandle.FirstChildElement("plist").FirstChildElement().Element();
	if (!topDict || strcmp(topDict->Value(), "dict") != 0) return false; // empty plist

	// Parse entries
	const TiXmlElement* entry = topDict->FirstChildElement();
	for(; entry; entry = entry->NextSiblingElement() ) {
		if (strcmp(entry->Value(), "key") != 0) return false; // invalid dict
		const TiXmlElement* const value = entry->NextSiblingElement();

		if (strcmp(entry->GetText(), "filters") == 0) {
			// Load all filters
			const TiXmlElement* filter = value->FirstChildElement();
			for(; filter; filter = filter->NextSiblingElement() ) {
				if (strcmp(filter->Value(), "key") != 0) return false; // invalid dict

				// Set target array
				wxArrayString* filterArray = NULL;
				const char* filterName = filter->GetText();
				if (strcmp(filterName, "includeDirs") == 0) filterArray = &this->includeDirs;
				else if (strcmp(filterName, "excludeDirs") == 0) filterArray = &this->excludeDirs;
				else if (strcmp(filterName, "includeFiles") == 0) filterArray = &this->includeFiles;
				else if (strcmp(filterName, "excludeFiles") == 0) filterArray = &this->excludeFiles;
				else {
					wxASSERT(false);
					break;
				}

				const TiXmlElement* const array = filter->NextSiblingElement();
				if (strcmp(array->Value(), "array") != 0) return false; // invalid dict

				const TiXmlElement* child = array->FirstChildElement();
				for(; child; child = child->NextSiblingElement() ) {
					const char* valType = child->Value();

					if (strcmp(valType, "string") == 0) {
						const char* pattern = child->GetText();
						if (pattern) filterArray->Add(wxString(pattern, wxConvUTF8));
					}
					else {
						wxASSERT(false);
					}
				}

				filter = array; // jump over value
			}

			this->hasFilters = true;
			if (onlyFilters) return true;
		}
		else if (strcmp(entry->GetText(), "environment") == 0) {
			// Load all env variables
			const TiXmlElement* env = value->FirstChildElement();
			for(; env; env = env->NextSiblingElement() ) {
				// Get Key
				if (strcmp(env->Value(), "key") != 0) return false; // invalid dict
				const char* key = env->GetText();

				const TiXmlElement* const val = env->NextSiblingElement();
				if (strcmp(val->Value(), "string") != 0) return false; // invalid dict
				const char* value = val->GetText();

				if (key) {
					this->env[wxString(key, wxConvUTF8)] = value ? wxString(value, wxConvUTF8) : *wxEmptyString;
				}

				env = val; // jump over value
			}
		}
		else if (strcmp(entry->GetText(), "fileTriggers") == 0) {
			// Load all env variables
			const TiXmlElement* trigger = value->FirstChildElement();
			for(; trigger; trigger = trigger->NextSiblingElement() ) {
				// Get Key
				if (strcmp(trigger->Value(), "key") != 0) return false; // invalid dict
				const char* key = trigger->GetText();

				const TiXmlElement* const val = trigger->NextSiblingElement();
				if (strcmp(val->Value(), "string") != 0) return false; // invalid dict
				const char* value = val->GetText();

				if (key && value) {
					wxFileName path(wxString(value, wxConvUTF8));
					path.MakeAbsolute(rootPath.GetPath());

					this->triggers[wxString(key, wxConvUTF8)] = path.GetFullPath();
				}

				trigger = val; // jump over value
			}
		}

		entry = value; // jump over value
	}

	if (onlyFilters && !this->hasFilters) return false;
	return true;
}
Esempio n. 12
0
void ResultMap::LoadPredefinedResultFromFile(const wxString& FileName)
{
    TiXmlDocument Doc;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            GetShortCode(Result->ShortCode).Add(Result);
        }
    }
}
Esempio n. 13
0
///////////////////////////////////////////////////////////////////////////////
/// This is the main API for users.
mvl_camera_t *mvl_read_camera(
        const char *filename, //< Input:
        double *hpose         //< Output:
        )
{
    mvl_camera_t* cam;
    cam = (mvl_camera_t*)calloc( 1, sizeof( mvl_camera_t ));


    // if not found, try adding .gz
    string sFileName( filename ), sPath;
    if( _mvl_camera_is_file( sFileName ) == false ){
        if( _mvl_camera_is_file( sFileName+".gz" ) ){
            sFileName = sFileName+".gz";
        }
    }

    string sTmp1, sTmp2;
    _FilePartsMVL( sFileName, sPath, sTmp1, sTmp2 );




    int nPos = sFileName.find_last_of(".");
    string sExt = sFileName.substr( nPos );
    std::transform( sExt.begin(), sExt.end(), sExt.begin(), ::tolower );

    // load from zipped file or not
    TiXmlDocument doc;
    bool success = false;
    if( sExt == ".gz" ){
        char* pBuf = AllocReadIntoBuffer( sFileName.c_str() );
        success = doc.Parse( pBuf );
        free( pBuf );
    }
    else{
        success = doc.LoadFile( sFileName.c_str() );
    }
    if( !success ){
        fprintf( stderr, "ERROR: opening or parsing camera model XML file '%s'\n", sFileName.c_str() );
        return NULL;
    }

    TiXmlElement* pCamNode = doc.FirstChildElement( "camera_model" );
    if( !pCamNode ){
        return NULL;
    }

    /// Get version
    const char* sVer = pCamNode->Attribute("version");
    if( !sVer ){
        fprintf( stderr, "ERROR: Unknown camera model version (no version attribute)" );
        return NULL;
    }
    cam->version = atoi(sVer);

    /// Get name
    const char* sName = pCamNode->Attribute("name");
    sprintf( cam->name, "%s", sName ? sName : "" );

    /// Get index
    const char* sIndex = pCamNode->Attribute("index");
    cam->index = sIndex ? atoi(sIndex) : 0;

    /// Get serial number
    const char* sSerial = pCamNode->Attribute("serialno");
    cam->serialno = sSerial ? atoi(sSerial) : -1;

    /// Get Type
    const char* sType = pCamNode->Attribute("type");
    if( !sType ){
        fprintf( stderr, "ERROR: Unknown camera model type (no type attribute)" );
        return NULL;
    }
    if( !strcmp( sType, "MVL_CAMERA_WARPED" ) ) {
        cam->type = MVL_CAMERA_WARPED;
    }
    else if( !strcmp( sType, "MVL_CAMERA_LINEAR") ) {
        cam->type = MVL_CAMERA_LINEAR;
    }
    else if( !strcmp( sType, "MVL_CAMERA_LUT") ) {
        cam->type = MVL_CAMERA_LUT;
    }
    else {
        cam->type = -1;
    }

    if( g_nMvlCameraModelVerbosityLevel > 0 &&
            cam->version != CURRENT_CMOD_XML_FILE_VERSION ){
        printf( "WARNING: Camera model v%d is outdated -- things should be fine, but you\n"
                "         should consider updating your camera models.\n", cam->version );
        printf( "         To do so, just run the 'cmodupdate' utility.\n\n" );
        //        printf( "       *** WILL TRY TO CONTINUE BUT BEHAVIOUR IS UNDEFINED AFTER THIS POINT ***\n\n\n" );
    }

    success = false;
    switch( cam->type ) {
        case MVL_CAMERA_LINEAR:
           success = _mvl_read_linear_camera(
                    pCamNode,
                    &cam->linear.width,
                    &cam->linear.height,
                    hpose,
                    cam->linear.RDF,
                    &cam->linear.fx,
                    &cam->linear.fy,
                    &cam->linear.cx,
                    &cam->linear.cy,
                    &cam->linear.sx );
            break;
        case MVL_CAMERA_WARPED:
           success = _mvl_read_warped_camera(
                    pCamNode,
                    &cam->warped.width,
                    &cam->warped.height,
                    hpose,
                    cam->warped.RDF,
                    &cam->warped.fx,
                    &cam->warped.fy,
                    &cam->warped.cx,
                    &cam->warped.cy,
                    &cam->warped.sx,
                    &cam->warped.kappa1,
                    &cam->warped.kappa2,
                    &cam->warped.kappa3,
                    &cam->warped.tau1,
                    &cam->warped.tau2 );
            break;
        case MVL_CAMERA_LUT:
            if( cam->version >= 7 ){ //  version when we switched to merged LUT+xml files.
                success = _mvl_read_lut_camera(
                        pCamNode,
                        &cam->lut.width,
                        &cam->lut.height,
                        hpose,
                        cam->lut.RDF,
                        &cam->lut.fx,
                        &cam->lut.fy,
                        &cam->lut.cx,
                        &cam->lut.cy,
                        &cam->lut.sx,
                        &(cam->lut.pLUT) );
            }
            else{
                success = _mvl_read_old_lut_camera(
                        pCamNode,
                        &cam->old_lut.width,
                        &cam->old_lut.height,
                        hpose,
                        cam->old_lut.RDF,
                        &cam->old_lut.fx,
                        &cam->old_lut.fy,
                        &cam->old_lut.cx,
                        &cam->old_lut.cy,
                        &cam->old_lut.sx,
                        sPath,
                        cam->old_lut.lutfilename,
                        &(cam->old_lut.pLUT)
                        );
            }
            break;
        default:
            printf("unknown camera model type?\n");
            break;

    }

    if( !success ) {
        free( cam );
        fprintf( stderr, "ERROR: reading camera model '%s', returning NULL.\n", filename );
        return NULL;
    }

    return cam;
}
		/*!
		 * \brief
		 * Processes an xml document to parse the map part definition it contains and add it to the list.
		 * 
		 * \param definition_path
		 * The path to the xml document on disk.
		 * 
		 * \returns
		 * Returns true if the xml was valid and processed successfully otherwise returns false.
		 * 
		 * Processes an xml document to parse the map part definition it contains and add it to the list.
		 */
		static bool AddMapDefinition(const char* definition_path)
		{
			TiXmlDocument definition;
			// load the map part definition
			definition.LoadFile(definition_path);

			// check the xml loaded correctly
			if(definition.Error())
			{
				blam::console_printf("Failed to load and parse the map part definition\nError: %s", definition.ErrorDesc());
				return false;
			}

			// get the xml root
			TiXmlElement* root_node = definition.FirstChildElement("osHTTPServer");
			if(!root_node)
			{
				blam::console_printf(false, "The map part definition has no osHTTPServer root node");
				return false;
			}

			// get the map element
			const TiXmlElement* map_node = root_node->FirstChildElement("map_download");
			if(!map_node)
			{
				blam::console_printf(false, "The map part definition has no map_download node");
				return false;
			}

			const char* name = map_node->Attribute("name");
			const char* md5 = map_node->Attribute("md5");
			const char* algorithm = map_node->Attribute("algorithm");
			const char* host_directory = map_node->Attribute("host_directory");

			// check the md5 string is the correct length
			bool md5_valid = false;
			if(md5)
				md5_valid = (strlen(md5) == 32);

			// if the map is valid, create a new map element
			if(name && md5 && md5_valid && algorithm)
			{
				// remove the extension from the map name
				std::string map_name(name);
				std::string::size_type extension_offset = std::string::npos;

				if((extension_offset = map_name.find(Cache::K_MAP_FILE_EXTENSION)) != std::string::npos)
					map_name.resize(extension_offset);
				else if((extension_offset = map_name.find(Cache::K_MAP_FILE_EXTENSION_YELO)) != std::string::npos)
					map_name.resize(extension_offset);

				if(FindMap(map_name.c_str()))
				{
					blam::console_printf(false, "Map definition for %s already exists", map_name.c_str());
					return false;
				}

				c_map_element* map_element = new c_map_element();
				map_element->Ctor();

				// assign the name of the map and remove its extension for later comparisons
				map_element->m_name = map_name;

				// create a copy of the maps part definition to send to the client
				// remove the host_directory attribute from the client copy as it is unnecessary
				map_element->m_part_definition = map_node->Clone()->ToElement();
				map_element->m_part_definition->RemoveAttribute("host_directory");

				// add the parts to the map element, host_directory can be null
				if(!AddMapParts(map_element, map_node, host_directory))
				{
					// a problem occurred when adding the maps part elements so delete the map element and return
					delete map_element;
					return false;
				}

				// add the completed map element to the definition lists
				if(!AddMapToList(map_element))
				{
					RemoveMapParts(map_element);

					delete map_element;
					return false;
				}
			}
			else
			{
				if(!name)
					blam::console_printf(false, "A map node is missing its name");
				if(!md5)
					blam::console_printf(false, "A map node is missing its md5 checksum");
				else if(!md5_valid)
					blam::console_printf(false, "A map nodes md5 checksum is too long/short");
				if(!algorithm)
					blam::console_printf(false, "A map node does not state its compression algorithm");
				if(!host_directory)
					blam::console_printf(false, "A map node is missing its host_directory");

				return false;
			}

			return true;
		}
Esempio n. 15
0
SystemParser::SystemParser(const char* filename, unsigned int verbosity, LeafType leaf_type)
{
    // Open the document
    TiXmlDocument document = TiXmlDocument(filename);
    if (!document.LoadFile()) {
        throw ParseError("[ERROR] Could not load the input file.");
    }

    // Get the root node of the XML-document
    TiXmlNode* rootNode = document.RootElement();
    if (rootNode == NULL) {
        throw ParseError("[ERROR] Could not access the root node of the XML-tree");
    }

    // Find out the type of the transition system (lts, ctmc, imc)
    const std::string type_str = readStringAttribute(rootNode, "type");
    if (type_str == "lts") system_type = lts_type;
    else if (type_str == "ctmc") system_type = ctmc_type;
    else if (type_str == "imc") system_type = imc_type;
    else system_type = lts_type;

    this->leaf_type = leaf_type;

    // Traverse the children of the root node and collect the pointers to the parts we need.
    TiXmlNode* varinfoNode = NULL;
    TiXmlNode* initialstateNode = NULL;
    TiXmlNode* transNode = NULL;
    TiXmlNode* markovtransNode = NULL;
    TiXmlNode* initialpartitionNode = NULL;
    TiXmlNode* tauNode = NULL;

    for (TiXmlNode* currentNode = rootNode->FirstChild();
         currentNode != NULL;
         currentNode = currentNode->NextSibling()) {

        if (currentNode->ToElement() == NULL) continue;

        const char* const name = currentNode->ToElement()->Value();

        if (strcmp(name, "variables") == 0) {
            varinfoNode = currentNode;
        } else if (strcmp(name, "dd") == 0) {
            std::string bdd_type = readStringAttribute(currentNode, "type");
            if (bdd_type == "initial_state") {
                initialstateNode = currentNode;
            } else if (bdd_type == "trans") {
                transNode = currentNode;
            } else if (bdd_type == "markov_trans") {
                markovtransNode = currentNode;
            } else if (bdd_type == "tau") {
                tauNode = currentNode;
            }
        } else if (strcmp(name, "initial_partition") == 0) {
            initialpartitionNode = currentNode;
        }
    }

    // Check if we have found the variable information
    if (varinfoNode == NULL) {
        throw ParseError("[ERROR] No variable information found!");
    }

    // Check if the correct information exists for the system type
    switch (system_type) {
    case lts_type:
        if (markovtransNode != NULL) {
            throw ParseError("[ERROR] LTS must not have any Markov transitions!");
        }
        if (transNode == NULL) {
            throw ParseError("[ERROR] LTS must have an interactive transition relation!");
        }
        break;
    case ctmc_type:
        if (transNode != NULL) {
            throw ParseError("[ERROR] CTMCs must not have any interactive transitions!");
        }
        if (markovtransNode == NULL) {
            throw ParseError("[ERROR] CTMCs must have a Markov transition relation!");
        }
        break;
    case imc_type:
        if (transNode == NULL) {
            throw ParseError("[ERROR] IMCs must have an interactive transition relation!");
        }
        if (markovtransNode == NULL) {
            throw ParseError("[ERROR] IMCs must have a Markov transition relation!");
        }
        break;
    }

        // Parse the variable information and create the BDD variables
        // together with an appropriate order for refinement
        if (verbosity > 0) std::cout << "[INFO] Creating BDD variables ... " << std::flush;
        createVariables(varinfoNode);
        if (verbosity > 0) std::cout << "finished." << std::endl;

        // Build the BDDs/ADDs for all parts
        if (verbosity > 0) std::cout << "[INFO] Building BDDs ... " << std::flush;

        std::vector<std::pair<Bdd, Bdd>> transitions;
        Bdd _transitions = Bdd::bddZero();
        if (transNode != NULL) {
            _transitions = nodeToBdd(transNode);
            transitions.push_back(std::make_pair(_transitions, varS * varT));
        }

        Mtbdd markov_transitions;
        if (markovtransNode != NULL) markov_transitions = nodeToMtbdd(markovtransNode);

        Bdd tau;
        if (tauNode != NULL) tau = nodeToBdd(tauNode);
        else {
            // Default value of tau: 0
            int action_bits = sylvan_set_count(varA.GetBDD());
            std::vector<uint8_t> tau_value;
            for (int i=0; i<action_bits; i++) tau_value.push_back(0);
            tau = Bdd::bddCube(varA, tau_value);
        }

        Bdd initial_state;
        if (initialstateNode != NULL) initial_state = nodeToBdd(initialstateNode);

        Bdd states = computeStateSpace(_transitions, markov_transitions);

        std::vector<Bdd> initial_partition;
        if (initialpartitionNode != NULL) {
            for (TiXmlNode* currentNode = initialpartitionNode->FirstChild();
                 currentNode != NULL; currentNode = currentNode->NextSibling()) {
                initial_partition.push_back(nodeToBdd(currentNode));
            }
        }
        if (initial_partition.size() == 0) initial_partition.push_back(states);
        if (verbosity > 0) std::cout << "finished." << std::endl;

        // Fill the right system with information
        switch (system_type) {
        case lts_type:
            lts.transitions = transitions;
            lts.states = states;
            lts.tau = tau;
            lts.initialStates = initial_state;
            lts.initialPartition = initial_partition;
            lts.varS = varS;
            lts.varT = varT;
            lts.varA = varA;
            break;

        case imc_type:
            imc.transitions = transitions;
            imc.markov_transitions = markov_transitions;
            imc.states = states;
            imc.tau = tau;
            imc.initialStates = initial_state;
            imc.initialPartition = initial_partition;
            imc.varS = varS;
            imc.varT = varT;
            imc.varA = varA;
            break;

        case ctmc_type:
            ctmc.markov_transitions = markov_transitions;
            ctmc.states = states;
            ctmc.initialStates = initial_state;
            ctmc.initialPartition = initial_partition;
            ctmc.varS = varS;
            ctmc.varT = varT;
            break;

        default:
            break;
        }
}
Esempio n. 16
0
int CCrashDescReader::Load(CString sFileName)
{
    TiXmlDocument doc;
    FILE* f = NULL;
    strconv_t strconv;

    if(m_bLoaded)
        return 1; // already loaded

    // Check that the file exists
#if _MSC_VER<1400
    f = _tfopen(sFileName, _T("rb"));
#else
    _tfopen_s(&f, sFileName, _T("rb"));
#endif

    if(f==NULL)
        return -1; // File can't be opened

    // Open XML document  
    bool bLoaded = doc.LoadFile(f);
    if(!bLoaded)
    {
        fclose(f);
        return -2; // XML is corrupted
    }

    TiXmlHandle hDoc(&doc);

    TiXmlHandle hRoot = hDoc.FirstChild("CrashRpt").ToElement();
    if(hRoot.ToElement()==NULL)
    {
        if(LoadXmlv10(hDoc)==0)
        {
            fclose(f);
            return 0;
        }  

        return -3; // Invalid XML structure
    }

    // Get generator version

    const char* szCrashRptVersion = hRoot.ToElement()->Attribute("version");
    if(szCrashRptVersion!=NULL)
    {
        m_dwGeneratorVersion = atoi(szCrashRptVersion);
    }

    // Get CrashGUID
    TiXmlHandle hCrashGUID = hRoot.ToElement()->FirstChild("CrashGUID");
    if(hCrashGUID.ToElement())
    {    
        TiXmlText* pTextElem = hCrashGUID.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sCrashGUID = strconv.utf82t(text);    
        }    
    }

    // Get AppName
    TiXmlHandle hAppName = hRoot.ToElement()->FirstChild("AppName");
    if(hAppName.ToElement())
    {    
        TiXmlText* pTextElem = hAppName.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sAppName = strconv.utf82t(text);        
        }
    }

    // Get AppVersion
    TiXmlHandle hAppVersion = hRoot.ToElement()->FirstChild("AppVersion");
    if(hAppVersion.ToElement())
    {    
        TiXmlText* pTextElem = hAppVersion.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sAppVersion = strconv.utf82t(text);    
        }
    }

    // Get ImageName
    TiXmlHandle hImageName = hRoot.ToElement()->FirstChild("ImageName");
    if(hImageName.ToElement())
    {    
        TiXmlText* pTextElem = hImageName.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sImageName = strconv.utf82t(text);        
        }
    }

    // Get OperatingSystem
    TiXmlHandle hOperatingSystem = hRoot.ToElement()->FirstChild("OperatingSystem");
    if(hOperatingSystem.ToElement())
    {    
        TiXmlText* pTextElem = hOperatingSystem.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sOperatingSystem = strconv.utf82t(text);        
        }
    }

    // Get GeoLocation
    TiXmlHandle hGeoLocation = hRoot.ToElement()->FirstChild("GeoLocation");
    if(hGeoLocation.ToElement())
    {    
        TiXmlText* pTextElem = hGeoLocation.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sGeoLocation = strconv.utf82t(text);        
        }
    }

    // Get OSIs64Bit
    m_bOSIs64Bit = FALSE;
    TiXmlHandle hOSIs64Bit = hRoot.ToElement()->FirstChild("OSIs64Bit");
    if(hOSIs64Bit.ToElement())
    {    
        TiXmlText* pTextElem = hOSIs64Bit.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_bOSIs64Bit = atoi(text);        
        }
    }

    // Get SystemTimeUTC
    TiXmlHandle hSystemTimeUTC = hRoot.ToElement()->FirstChild("SystemTimeUTC");
    if(hSystemTimeUTC.ToElement())
    {    
        TiXmlText* pTextElem = hSystemTimeUTC.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sSystemTimeUTC = strconv.utf82t(text);        
        }
    }

    // Get ExceptionType
    TiXmlHandle hExceptionType = hRoot.ToElement()->FirstChild("ExceptionType");
    if(hExceptionType.ToElement())
    {    
        TiXmlText* pTextElem = hExceptionType.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_dwExceptionType = atoi(text);        
        }
    }

    // Get UserEmail
    TiXmlHandle hUserEmail = hRoot.ToElement()->FirstChild("UserEmail");
    if(hUserEmail.ToElement())
    {    
        TiXmlText* pTextElem = hUserEmail.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sUserEmail = strconv.utf82t(text);    
        }
    }

    // Get ProblemDecription
    TiXmlHandle hProblemDescription = hRoot.ToElement()->FirstChild("ProblemDescription");
    if(hProblemDescription.ToElement())
    {
        TiXmlText* pTextElem = hProblemDescription.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sProblemDescription = strconv.utf82t(text);    
        }
    }

    // Get ExceptionCode (for SEH exceptions only)
    if(m_dwExceptionType==CR_SEH_EXCEPTION)
    {    
        TiXmlHandle hExceptionCode = hRoot.ToElement()->FirstChild("ExceptionCode");
        if(hExceptionCode.ToElement())
        {      
            TiXmlText* pTextElem = hExceptionCode.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_dwExceptionCode = atoi(text);    
            }
        }
    }

    // Get FPESubcode (for FPE exceptions only)
    if(m_dwExceptionType==CR_CPP_SIGFPE)
    {    
        TiXmlHandle hFPESubcode = hRoot.ToElement()->FirstChild("FPESubcode");
        if(hFPESubcode.ToElement())
        {      
            TiXmlText* pTextElem = hFPESubcode.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_dwFPESubcode = atoi(text);          
            }
        }
    }

    // Get InvParamExpression, InvParamFunction, InvParamFile, InvParamLine 
    // (for invalid parameter exceptions only)
    if(m_dwExceptionType==CR_CPP_INVALID_PARAMETER)
    {    
        TiXmlHandle hInvParamExpression = hRoot.ToElement()->FirstChild("InvParamExpression");
        if(hInvParamExpression.ToElement())
        {      
            TiXmlText* pTextElem = hInvParamExpression.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_sInvParamExpression = strconv.utf82t(text);          
            }
        }

        TiXmlHandle hInvParamFunction = hRoot.ToElement()->FirstChild("InvParamFunction");
        if(hInvParamFunction.ToElement())
        {      
            TiXmlText* pTextElem = hInvParamFunction.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_sInvParamFunction = strconv.utf82t(text);          
            }
        }

        TiXmlHandle hInvParamFile = hRoot.ToElement()->FirstChild("InvParamFile");
        if(hInvParamFile.ToElement())
        {      
            TiXmlText* pTextElem = hInvParamFile.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_sInvParamFile = strconv.utf82t(text);          
            }
        }

        TiXmlHandle hInvParamLine = hRoot.ToElement()->FirstChild("InvParamLine");
        if(hInvParamLine.ToElement())
        {      
            TiXmlText* pTextElem = hInvParamLine.FirstChild().Text();     
            if(pTextElem)
            {
                const char* text = pTextElem->Value();
                if(text)
                    m_dwInvParamLine = atoi(text);          
            }
        }
    }

    // Get GUI resource count
    TiXmlHandle hGUIResourceCount = hRoot.ToElement()->FirstChild("GUIResourceCount");
    if(hGUIResourceCount.ToElement())
    {      
        TiXmlText* pTextElem = hGUIResourceCount.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sGUIResourceCount = strconv.utf82t(text);          
        }
    }

    // Get open handle count
    TiXmlHandle hOpenHandleCount = hRoot.ToElement()->FirstChild("OpenHandleCount");
    if(hOpenHandleCount.ToElement())
    {      
        TiXmlText* pTextElem = hOpenHandleCount.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sOpenHandleCount = strconv.utf82t(text);          
        }
    }

    // Get memory usage in KB
    TiXmlHandle hMemoryUsageKbytes = hRoot.ToElement()->FirstChild("MemoryUsageKbytes");
    if(hMemoryUsageKbytes.ToElement())
    {      
        TiXmlText* pTextElem = hMemoryUsageKbytes.FirstChild().Text();     
        if(pTextElem)
        {
            const char* text = pTextElem->Value();
            if(text)
                m_sMemoryUsageKbytes = strconv.utf82t(text);          
        }
    }

    // Get file items list
    TiXmlHandle hFileList = hRoot.ToElement()->FirstChild("FileList");
    if(!hFileList.ToElement())
    {
        // This may work for reports generated by v1.2.1
        hFileList = hRoot.ToElement()->FirstChild("FileItems");
    }
    if(hFileList.ToElement())
    {
        TiXmlHandle hFileItem = hFileList.ToElement()->FirstChild("FileItem");
        while(hFileItem.ToElement())
        {
            const char* szFileName = hFileItem.ToElement()->Attribute("name");
            const char* szFileDescription = hFileItem.ToElement()->Attribute("description");

            CString sFileName, sFileDescription;
            if(szFileName!=NULL)
                sFileName = strconv.utf82t(szFileName);    
            if(szFileName!=NULL)
                sFileDescription = strconv.utf82t(szFileDescription);    

            m_aFileItems[sFileName]=sFileDescription;

            hFileItem = hFileItem.ToElement()->NextSibling();
        }
    }

    // Get custom property list
    TiXmlHandle hCustomProps = hRoot.ToElement()->FirstChild("CustomProps");
    if(hCustomProps.ToElement())
    {
        TiXmlHandle hProp = hCustomProps.ToElement()->FirstChild("Prop");
        while(hProp.ToElement())
        {
            const char* szName = hProp.ToElement()->Attribute("name");
            const char* szValue = hProp.ToElement()->Attribute("value");

            CString sName, sValue;
            if(szName!=NULL)
                sName = strconv.utf82t(szName);    
            if(szValue!=NULL)
                sValue = strconv.utf82t(szValue);    

            m_aCustomProps[sName]=sValue;

            hProp = hProp.ToElement()->NextSibling();
        }
    }

    fclose(f);

    // OK  
    m_bLoaded = true;
    return 0;
}
Esempio n. 17
0
void CAdvancedSettings::ParseSettingsFile(const CStdString &file)
{
  TiXmlDocument advancedXML;
  if (!CFile::Exists(file))
  {
    CLog::Log(LOGNOTICE, "No settings file to load to load (%s)", file.c_str());
    return;
  }

  if (!advancedXML.LoadFile(file))
  {
    CLog::Log(LOGERROR, "Error loading %s, Line %d\n%s", file.c_str(), advancedXML.ErrorRow(), advancedXML.ErrorDesc());
    return;
  }

  TiXmlElement *pRootElement = advancedXML.RootElement();
  if (!pRootElement || strcmpi(pRootElement->Value(),"advancedsettings") != 0)
  {
    CLog::Log(LOGERROR, "Error loading %s, no <advancedsettings> node", file.c_str());
    return;
  }

  // succeeded - tell the user it worked
  CLog::Log(LOGNOTICE, "Loaded settings file from %s", file.c_str());

  // Dump contents of AS.xml to debug log
  TiXmlPrinter printer;
  printer.SetLineBreak("\n");
  printer.SetIndent("  ");
  advancedXML.Accept(&printer);
  CLog::Log(LOGNOTICE, "Contents of %s are...\n%s", file.c_str(), printer.CStr());

  TiXmlElement *pElement = pRootElement->FirstChildElement("audio");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "ac3downmixgain", m_ac3Gain, -96.0f, 96.0f);
    XMLUtils::GetInt(pElement, "headroom", m_audioHeadRoom, 0, 12);
    XMLUtils::GetString(pElement, "defaultplayer", m_audioDefaultPlayer);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_audioPlayCountMinimumPercent, 0.0f, 101.0f);

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_musicUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_musicTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_musicTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_musicTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_musicTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_musicPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_musicPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_musicPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_musicPercentSeekBackwardBig, -100, 0);

    XMLUtils::GetInt(pElement, "resample", m_musicResample, 0, 192000);

    TiXmlElement* pAudioExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromListingRegExps);

    pAudioExcludes = pElement->FirstChildElement("excludefromscan");
    if (pAudioExcludes)
      GetCustomRegexps(pAudioExcludes, m_audioExcludeFromScanRegExps);

    XMLUtils::GetString(pElement, "audiohost", m_audioHost);
    XMLUtils::GetBoolean(pElement, "applydrc", m_audioApplyDrc);
    XMLUtils::GetBoolean(pElement, "dvdplayerignoredtsinwav", m_dvdplayerIgnoreDTSinWAV);

    XMLUtils::GetFloat(pElement, "limiterhold", m_limiterHold, 0.0f, 100.0f);
    XMLUtils::GetFloat(pElement, "limiterrelease", m_limiterRelease, 0.001f, 100.0f);
  }

  pElement = pRootElement->FirstChildElement("karaoke");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "syncdelaycdg", m_karaokeSyncDelayCDG, -3.0f, 3.0f); // keep the old name for comp
    XMLUtils::GetFloat(pElement, "syncdelaylrc", m_karaokeSyncDelayLRC, -3.0f, 3.0f);
    XMLUtils::GetBoolean(pElement, "alwaysreplacegenre", m_karaokeChangeGenreForKaraokeSongs );
    XMLUtils::GetBoolean(pElement, "storedelay", m_karaokeKeepDelay );
    XMLUtils::GetInt(pElement, "autoassignstartfrom", m_karaokeStartIndex, 1, 2000000000);
    XMLUtils::GetBoolean(pElement, "nocdgbackground", m_karaokeAlwaysEmptyOnCdgs );
    XMLUtils::GetBoolean(pElement, "lookupsongbackground", m_karaokeUseSongSpecificBackground );

    TiXmlElement* pKaraokeBackground = pElement->FirstChildElement("defaultbackground");
    if (pKaraokeBackground)
    {
      const char* attr = pKaraokeBackground->Attribute("type");
      if ( attr )
        m_karaokeDefaultBackgroundType = attr;

      attr = pKaraokeBackground->Attribute("path");
      if ( attr )
        m_karaokeDefaultBackgroundFilePath = attr;
    }
  }

  pElement = pRootElement->FirstChildElement("video");
  if (pElement)
  {
    XMLUtils::GetFloat(pElement, "subsdelayrange", m_videoSubsDelayRange, 10, 600);
    XMLUtils::GetFloat(pElement, "audiodelayrange", m_videoAudioDelayRange, 10, 600);
    XMLUtils::GetInt(pElement, "blackbarcolour", m_videoBlackBarColour, 0, 255);
    XMLUtils::GetString(pElement, "defaultplayer", m_videoDefaultPlayer);
    XMLUtils::GetString(pElement, "defaultdvdplayer", m_videoDefaultDVDPlayer);
    XMLUtils::GetBoolean(pElement, "fullscreenonmoviestart", m_fullScreenOnMovieStart);
    // 101 on purpose - can be used to never automark as watched
    XMLUtils::GetFloat(pElement, "playcountminimumpercent", m_videoPlayCountMinimumPercent, 0.0f, 101.0f);
    XMLUtils::GetInt(pElement, "ignoresecondsatstart", m_videoIgnoreSecondsAtStart, 0, 900);
    XMLUtils::GetFloat(pElement, "ignorepercentatend", m_videoIgnorePercentAtEnd, 0, 100.0f);

    XMLUtils::GetInt(pElement, "smallstepbackseconds", m_videoSmallStepBackSeconds, 1, INT_MAX);
    XMLUtils::GetInt(pElement, "smallstepbacktries", m_videoSmallStepBackTries, 1, 10);
    XMLUtils::GetInt(pElement, "smallstepbackdelay", m_videoSmallStepBackDelay, 100, 5000); //MS

    XMLUtils::GetBoolean(pElement, "usetimeseeking", m_videoUseTimeSeeking);
    XMLUtils::GetInt(pElement, "timeseekforward", m_videoTimeSeekForward, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackward", m_videoTimeSeekBackward, -6000, 0);
    XMLUtils::GetInt(pElement, "timeseekforwardbig", m_videoTimeSeekForwardBig, 0, 6000);
    XMLUtils::GetInt(pElement, "timeseekbackwardbig", m_videoTimeSeekBackwardBig, -6000, 0);

    XMLUtils::GetInt(pElement, "percentseekforward", m_videoPercentSeekForward, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackward", m_videoPercentSeekBackward, -100, 0);
    XMLUtils::GetInt(pElement, "percentseekforwardbig", m_videoPercentSeekForwardBig, 0, 100);
    XMLUtils::GetInt(pElement, "percentseekbackwardbig", m_videoPercentSeekBackwardBig, -100, 0);

    TiXmlElement* pVideoExcludes = pElement->FirstChildElement("excludefromlisting");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoExcludeFromListingRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludefromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_moviesExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("excludetvshowsfromscan");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_tvshowExcludeFromScanRegExps);

    pVideoExcludes = pElement->FirstChildElement("cleanstrings");
    if (pVideoExcludes)
      GetCustomRegexps(pVideoExcludes, m_videoCleanStringRegExps);

    XMLUtils::GetString(pElement,"cleandatetime", m_videoCleanDateTimeRegExp);
    XMLUtils::GetString(pElement,"ppffmpegdeinterlacing",m_videoPPFFmpegDeint);
    XMLUtils::GetString(pElement,"ppffmpegpostprocessing",m_videoPPFFmpegPostProc);
    XMLUtils::GetBoolean(pElement,"vdpauscaling",m_videoVDPAUScaling);
    XMLUtils::GetFloat(pElement, "nonlinearstretchratio", m_videoNonLinStretchRatio, 0.01f, 1.0f);
    XMLUtils::GetBoolean(pElement,"enablehighqualityhwscalers", m_videoEnableHighQualityHwScalers);
    XMLUtils::GetFloat(pElement,"autoscalemaxfps",m_videoAutoScaleMaxFps, 0.0f, 1000.0f);
    XMLUtils::GetBoolean(pElement,"allowmpeg4vdpau",m_videoAllowMpeg4VDPAU);
    XMLUtils::GetBoolean(pElement, "disablebackgrounddeinterlace", m_videoDisableBackgroundDeinterlace);
    XMLUtils::GetInt(pElement, "useocclusionquery", m_videoCaptureUseOcclusionQuery, -1, 1);

    TiXmlElement* pAdjustRefreshrate = pElement->FirstChildElement("adjustrefreshrate");
    if (pAdjustRefreshrate)
    {
      TiXmlElement* pRefreshOverride = pAdjustRefreshrate->FirstChildElement("override");
      while (pRefreshOverride)
      {
        RefreshOverride override = {0};

        float fps;
        if (XMLUtils::GetFloat(pRefreshOverride, "fps", fps))
        {
          override.fpsmin = fps - 0.01f;
          override.fpsmax = fps + 0.01f;
        }

        float fpsmin, fpsmax;
        if (XMLUtils::GetFloat(pRefreshOverride, "fpsmin", fpsmin) &&
            XMLUtils::GetFloat(pRefreshOverride, "fpsmax", fpsmax))
        {
          override.fpsmin = fpsmin;
          override.fpsmax = fpsmax;
        }

        float refresh;
        if (XMLUtils::GetFloat(pRefreshOverride, "refresh", refresh))
        {
          override.refreshmin = refresh - 0.01f;
          override.refreshmax = refresh + 0.01f;
    void ExperimentRun::setupExperimentInProgress(
        string populationFileName,
        string _outputFileName
    )
    {
        outputFileName = _outputFileName;

        {
            TiXmlDocument *doc = new TiXmlDocument(populationFileName);
            
            cout << "Loading population\n";

            bool loadStatus;

            if (iends_with(populationFileName,".gz"))
            {
                loadStatus = doc->LoadFileGZ();
            }
            else
            {
                loadStatus = doc->LoadFile();
            }

            if (!loadStatus)
            {
                throw CREATE_LOCATEDEXCEPTION_INFO("Error trying to load the XML file!");
            }

            TiXmlElement *element = doc->FirstChildElement();

            NEAT::Globals* globals = NEAT::Globals::init(element);
            
            //Destroy the document
            delete doc;
            
            cout << "Population loaded\n";


        }


        int experimentType = int(NEAT::Globals::getSingleton()->getParameterValue("ExperimentType")+0.001);

        NEAT::Globals::getSingleton()->seedRandom((unsigned int)(NEAT::Globals::getSingleton()->getParameterValue("ActualRandomSeed")+0.001));

        cout << "Loading Experiment: " << experimentType << endl;

        setupExperiment(experimentType,_outputFileName);

        cout << "Experiment set up.  Creating population...\n";

        createPopulation(populationFileName);

        cout << "Population Created\n";
        
        /*cout << "Cleaning up old generations\n";
        
		population->cleanupOld(population->getGenerationCount()-1);
		
		cout << "Done cleaning\n";*/
		
    }
Esempio n. 19
0
void dModel::LoadXML (const char* name, dLoaderContext& context)
{
	_ASSERTE (0);

	const TiXmlElement* root;
	TiXmlDocument doc (name);
	doc.LoadFile();

	char path[256];
	char* tmpName;
	strcpy (path, name);
	tmpName = strrchr (path, '/');
	if (!tmpName) {
		tmpName = strrchr (path, '\\');
	} 
	if (tmpName) {
		tmpName[0] = 0;
	}

	root = doc.RootElement();
	
	for (TiXmlElement* skeleton = (TiXmlElement*)root->FirstChildElement ("skeleton"); skeleton; skeleton = (TiXmlElement*)root->NextSibling ("skeleton")) {
		char pathName[256];
		ModelComponent<dList<dBone*> >& data = m_skeleton.Append()->GetInfo();
		strncpy (data.m_name, skeleton->GetText(), sizeof (data.m_name) - 1);

		strcpy (pathName, path);
		strcat (pathName, "/");
		strcat (pathName, data.m_name);
		dBone::Load (pathName, data.m_data, context);
	}

	for (TiXmlElement* meshes = (TiXmlElement*)root->FirstChildElement ("mesh"); meshes; meshes = (TiXmlElement*)root->NextSibling ("mesh")) {
		char pathName[256];
		ModelComponent<dList<dMeshInstance> >& data = m_meshList.Append()->GetInfo();

		strncpy (data.m_name, meshes->GetText(), sizeof (data.m_name) - 1);
		strcpy (pathName, path);
		strcat (pathName, "/");
		strcat (pathName, data.m_name);
		dMesh::LoadXML (pathName, data.m_data, context);
	}

	for (ModelComponentList<dList<dMeshInstance> >::dListNode* list = m_meshList.GetFirst(); list; list = list->GetNext()) {
		for (dList<dMeshInstance>::dListNode* node = list->GetInfo().m_data.GetFirst(); node; node = node->GetNext()) { 
			_ASSERTE (0);
//			if (node->GetInfo()->GetType() == dMesh::D_SKIN_MESH) {
//				node->GetInfo()->m_weighList->SetBindingPose(node->GetInfo(), *this); 
//			}
		}
	}

	for (TiXmlElement* anim = (TiXmlElement*)root->FirstChildElement("animation"); anim; anim = (TiXmlElement*)anim->NextSibling("animation")) {
		char pathName[256];
		ModelComponent<dAnimationClip*>& data = m_animations.Append()->GetInfo();

		strncpy (data.m_name, anim->GetText(), sizeof (data.m_name) - 1);
		strcpy (pathName, path);
		strcat (pathName, "/");
		strcat (pathName, data.m_name);
		
		data.m_data = new dAnimationClip ();
		data.m_data->LoadXML (pathName);
	}

	context.LoaderFixup (this);
}
Esempio n. 20
0
void RequestTests::Test_DumpCrashReport_assync()
{
	bool bExec = false;
    CMtClient client("127.0.0.1", 50);
    std::string sErrorMsg;
	int nServerRetCode = -1;
	std::string sServerResponse;
	std::string sCommand;
	std::wstring sFileName;
	std::wstring sTmpDir;
	std::wstring sOutFile;
	int nCreateDir = -1;
	std::vector<std::wstring> asCrashReports;
	CFileFinder FileFinder;
	CFindFileInfo ffi;
	bool bFind = false;
	std::wstring sTmpName;
	TiXmlDocument doc;
	std::string sCmdId;
	int pos1, pos2, pos3, pos4;

	sFileName = Utils::GetTestDataFolder();
	sFileName += L"crashReports\\WTLDemo\\1.4.0.0\\*.zip";

	// Get the list of crash reports in the directory
	bFind = FileFinder.FindFirstFile(sFileName, &ffi);
	while(bFind)
	{
		asCrashReports.push_back(ffi.m_sFileName);
		bFind = FileFinder.FindNextFile(&ffi);
	}
	// Ensure there are enough crash reports found
	TEST_ASSERT(asCrashReports.size()>=10);

	// Create temp out dir
	sTmpDir = Utils::GetTestDataFolder();
	sTmpDir += L"temp_dir1";
	RmDir(sTmpDir, false);
	nCreateDir = CreateDir(sTmpDir);
	TEST_ASSERT_MSG(nCreateDir==0, "Error creating directory '%s'", strconv::w2a(sTmpDir).c_str());

	size_t i;
	for(i=0; i<asCrashReports.size(); i++)
	{
		std::ostringstream stCommand;
		sFileName = asCrashReports[i];

		sOutFile = sTmpDir+L"\\result.xml";

		// Format command
		stCommand << "assync dumper --dump-crash-report \"" <<
			strconv::w2utf8(sFileName) << "\" \"" <<
			strconv::w2utf8(sOutFile) << "\"\n";
		sCommand = stCommand.str();

		// Execute daemon command - assume success
		bExec = client.ExecuteRequest(sCommand.c_str(), nServerRetCode, sServerResponse, sErrorMsg);
		TEST_ASSERT_MSG(bExec, sErrorMsg.c_str());
		TEST_ASSERT_MSG(nServerRetCode==0, "Invalid ret code %d, msg = %s", nServerRetCode, sServerResponse.c_str());

		// Get command id
		pos1 = sServerResponse.find('{');
		pos2 = sServerResponse.find('}', pos1+1);
		sCmdId = sServerResponse.substr(pos1+1, pos2-pos1-1);

		// Wait until command is finished
		for(;;)
		{
			std::string sRetMsg;

			std::ostringstream stCommand;
			stCommand << "daemon get-assync-info -erase-completed  " << sCmdId << "\n";
			sCommand = stCommand.str();

			bExec = client.ExecuteRequest(sCommand.c_str(), nServerRetCode, sServerResponse, sErrorMsg);
			TEST_ASSERT_MSG(bExec, sErrorMsg.c_str());
			TEST_ASSERT_MSG(nServerRetCode==0, "Invalid ret code %d, msg = %s", nServerRetCode, sServerResponse.c_str());

			if(sServerResponse.find("still executing")!=sServerResponse.npos)
			{
				Sleep(1000);
				continue;
			}

			// Get command id and return message
			pos1 = sServerResponse.find('{');
			pos2 = sServerResponse.find('}', pos1+1);
			sCmdId = sServerResponse.substr(pos1+1, pos2-pos1-1);

			pos3 = sServerResponse.find('{', pos2+1);
			pos4 = sServerResponse.find('}', pos3+1);
			sRetMsg = sServerResponse.substr(pos3+1, pos4-pos3-1);

			TEST_ASSERT(sRetMsg=="0 Success");
			break;
		}

		// Check that result is a valid XML file
		bool bLoad = doc.LoadFile(strconv::w2a(sOutFile).c_str());
		TEST_ASSERT(bLoad);

		// Get element
		TiXmlHandle hElem = doc.RootElement();
		TEST_ASSERT(hElem.ToElement()!=NULL);
		hElem = hElem.FirstChild("Summary");
		TEST_ASSERT(hElem.ToElement()!=NULL);

		// Remove file
		remove(strconv::w2a(sOutFile).c_str());
	}

	__TEST_CLEANUP__;

	// Delete temp directory
    RmDir(sTmpDir, false);

}
ProjectStructs::MESHLESS_OBJECT_STRUCT PointCloudHandler::ProcessPointCloud( std::string file, CSGTree *&volumeTree , Volume *&volume)
{
    TiXmlDocument pointCloudXml;

    if(!pointCloudXml.LoadFile(file.c_str())) {
        std::string errorText = "Could not parse " + file;
        std::string errorHeader = "Point Cloud Error";

        MessageBox(0, errorText.c_str(), errorHeader.c_str(), 0);
    }

    ProjectStructs::MESHLESS_OBJECT_STRUCT meshlessStruct;

    TiXmlNode *meshNode = pointCloudXml.FirstChild(XML_MESHLESS_ROOT);

    meshlessStruct.name = meshNode->FirstChild(XML_MESHLESS_NAME)->FirstChild()->Value();
    meshlessStruct.materialProperties.deformable = meshNode->FirstChild(XML_MESHLESS_DEFORMABLE)->FirstChild()->Value() == XML_MESHLESS_TRUE;
    meshlessStruct.materialProperties.texture= meshNode->FirstChild(XML_MESHLESS_TEXTURE)->FirstChild()->Value();

    D3DXVECTOR3 translation = GetVector3(meshNode->FirstChild(XML_MESHLESS_WORLDTRANSLATION)->ToElement());
    D3DXVECTOR3 scale = GetVector3(meshNode->FirstChild(XML_MESHLESS_WORLDSCALE)->ToElement());
    D3DXVECTOR3 yawpitchroll= GetVector3(meshNode->FirstChild(XML_MESHLESS_WORLDYAWPITCHROLL)->ToElement());

    double d;
    meshNode->FirstChild(XML_MESHLESS_LIGHTING)->ToElement()->Attribute(XML_MESHLESS_MATERIAL_RHO.c_str(), &d);
    meshlessStruct.materialProperties.rho = (float)d;
    meshNode->FirstChild(XML_MESHLESS_LIGHTING)->ToElement()->Attribute(XML_MESHLESS_MATERIAL_SIGMA.c_str(), &d);
    meshlessStruct.materialProperties.sigma = (float)d;
    meshlessStruct.materialProperties.vertexGridSize= -1.0f;

    if(meshlessStruct.materialProperties.deformable) {
        meshlessStruct.materialProperties.density = (float)atof(meshNode->FirstChild(XML_MESHLESS_DENSITY)->FirstChild()->Value());
//			meshlessStruct.materialProperties.mass = (float)atof(meshNode->FirstChild(XML_MESHLESS_MASS)->FirstChild()->Value());
        meshlessStruct.materialProperties.toughness = (float)atof(meshNode->FirstChild(XML_MESHLESS_TOUGHNESS)->FirstChild()->Value());
        meshlessStruct.materialProperties.youngsModulus = (float)atof(meshNode->FirstChild(XML_MESHLESS_YOUNGS_MODULUS)->FirstChild()->Value());// * pow(10.0f, 5.0f);
        meshlessStruct.materialProperties.poissonRatio = (float)atof(meshNode->FirstChild(XML_MESHLESS_POISSON_RATIO)->FirstChild()->Value());
        meshlessStruct.materialProperties.phyxelGridSize= (float)atof(meshNode->FirstChild(XML_MESHLESS_PHYXEL_GRID_SIZE)->FirstChild()->Value());
        meshlessStruct.materialProperties.minimunSurfelSize = (float)atof(meshNode->FirstChild(XML_MESHLESS_MINIMUM_SURFEL_SIZE)->FirstChild()->Value());
        meshlessStruct.materialProperties.vertexGridSize= (float)atof(meshNode->FirstChild(XML_MESHLESS_VERTEX_GRID_SIZE)->FirstChild()->Value());
    }


    meshlessStruct.transform = translation;

    D3DXMATRIX translationMatrix, scaleMatrix, yawpitchrollMatrix;
    D3DXMatrixTranslation(&translationMatrix, translation.x, translation.y, translation.z);
    D3DXMatrixScaling(&scaleMatrix, scale.x, scale.y, scale.z);
    D3DXMatrixRotationYawPitchRoll(&yawpitchrollMatrix, yawpitchroll.x, yawpitchroll.y, yawpitchroll.z);
    meshlessStruct.scale = scale;
    meshlessStruct.rotation= yawpitchroll;

    meshlessStruct.world = scaleMatrix * yawpitchrollMatrix * translationMatrix;

    TiXmlNode* volumeNode = meshNode->FirstChild(XML_MESHLESS_VOLUME);

    TiXmlNode* surfel;

    std::vector<Volume*> volumes;

    do {
        surfel = volumeNode->FirstChild(XML_MESHLESS_SURFACE);
        Volume *v = new Volume(meshlessStruct.materialProperties);
        v->SetWorld(meshlessStruct.world);

        do {
            D3DXVECTOR3 pos = GetVector3(surfel ->FirstChild(XML_MESHLESS_SURFACE_POSITION)->ToElement());
            D3DXVECTOR3 majorAxis = GetVector3(surfel ->FirstChild(XML_MESHLESS_SURFACE_SURFEL_MAJOR_AXIS)->ToElement());
            D3DXVECTOR3 minorAxis = GetVector3(surfel ->FirstChild(XML_MESHLESS_SURFACE_SURFEL_MINOR_AXIS)->ToElement());
            D3DXVECTOR3 normal = GetVector3(surfel ->FirstChild(XML_MESHLESS_SURFACE_SURFEL_NORMAL)->ToElement());
            D3DXVECTOR2 count = GetVector2(surfel ->FirstChild(XML_MESHLESS_SURFACE_SURFEL_COUNT)->ToElement());

            CreateSurface(v, pos, majorAxis, minorAxis, normal, count.x, count.y, meshlessStruct.texture);

            surfel = surfel->NextSibling(XML_MESHLESS_SURFACE);

        } while(surfel);

        v->Init();

        volumes.push_back(v);

        volumeNode = volumeNode->NextSibling(XML_MESHLESS_VOLUME);

    } while(volumeNode);

    if(volumes.size() == 1)
    {
        volume = volumes[0];

        volumes.clear();
        return meshlessStruct;
    }
    else if(volumes.size() == 2)
    {
        volumeTree = new CSGTree();
        volumeTree->CreateTree(volumeTree->And(volumes[0], volumes[1]));
        volumes.clear();
        return meshlessStruct;
    }

    volumeTree = new CSGTree();

    std::vector<OPERATOR_NODE*> one, two;

    bool done = false;
    int size = volumes.size();

    for(unsigned int i = 0; i<volumes.size()-1; i+=2) {
        one.push_back(volumeTree->And(volumes[i], volumes[i+1]));
    }
    if(volumes.size() % 2 == 1) {
        one[one.size()-1] = volumeTree->And(one[one.size()-1], volumes[volumes.size()-1]);
    }

    while(!done) {
        two.clear();

        for(unsigned int i = 0; i<one.size()-1; i+=2) {
            two.push_back(volumeTree->And(one[i], one[i+1]));
        }
        if(one.size() % 2 == 1) {
            two[two.size()-1] = volumeTree->And(two[two.size()-1], one[one.size()-1]);
        }

        if(one.size() == 2) {
            volumeTree->CreateTree(volumeTree->And(one[0], one[1]));
            break;
        }
        if(two.size() == 2) {
            volumeTree->CreateTree(volumeTree->And(two[0], two[1]));
            break;
        }
        if(one.size() == 1) {
            volumeTree->CreateTree(one[0]);
            break;
        }
        if(two.size() == 1) {
            volumeTree->CreateTree(two[0]);
            break;
        }

        one.clear();

        for(unsigned int i = 0; i<two.size()-1; i+=2)
            one.push_back(volumeTree->And(two[i], two[i+1]));

        if(two.size() % 2 == 1) {
            one[one.size()-1] = volumeTree->And(one[one.size()-1], two[two.size()-1]);
        }
    }

    volumes.clear();
    return meshlessStruct;
}
Esempio n. 22
0
// LoadSprites
//	- reading all the sprites from the XML file
std::string AnimationManager::LoadSprites(std::string fileName)
{
	TiXmlDocument animationDoc;

	// Check to see if there is anything to load from the file
	if (animationDoc.LoadFile(fileName.c_str()) == false)
		return false;

	Sprite* newSprite = new Sprite();
	TiXmlElement* root = animationDoc.RootElement();
	int numSprites;
	root->Attribute("Sprites", &numSprites);
	// Check to see if there is actually anything to read in the XML
	if (root == nullptr)
		return false;
	// Getting rid of any past data
	if (made == false)
	{
		m_mSprites.clear();
		made = true;
	}

	std::string ID;
	for (int i = 0; i < numSprites; i++)
	{
		TiXmlElement* spriteImg = root->FirstChildElement("sprite");
		while (spriteImg != nullptr)
		{
			if (spriteImg != nullptr)
			{
				std::string file = "resource/animation/";
				file += spriteImg->GetText();

				if (file.c_str() != nullptr)
					newSprite->SetImage(file.c_str());
			}
			spriteImg = spriteImg->NextSiblingElement("spriteID");
			if (spriteImg != nullptr)
			{
				std::string id = spriteImg->GetText();
				if (id.c_str() != nullptr)
				{
					newSprite->SetSpriteID(id);
					ID = id;
				}
			}
			spriteImg = spriteImg->NextSiblingElement("isLooping");
			if (spriteImg != nullptr)
			{
				int boolNum;
				spriteImg->Attribute("isIt", &boolNum);
				if (boolNum == 0)
					newSprite->SetLooping(false);
				else
					newSprite->SetLooping(true);

			}
			spriteImg = spriteImg->NextSiblingElement("Frames");
			int numFrames;
			if (spriteImg != nullptr)
			{
				spriteImg->Attribute("numbers", &numFrames);
			}
			TiXmlElement* frames = spriteImg->NextSiblingElement("frame");
			for (int i = 0; i < numFrames; i++)
			{
				if (frames != nullptr)
				{
					TiXmlElement* info = frames->FirstChildElement("anchorPoint");
					Frame* newFrame = new Frame();
					if (info != nullptr)
					{
						SGD::Point pointTemp;
						double x, y;
						info->Attribute("X", &x);
						pointTemp.x = (float)x;
						info->Attribute("Y", &y);
						pointTemp.y = (float)y;
						newFrame->SetAnchorPoint(pointTemp);
					}
					info = info->NextSiblingElement("collisionRect");

					if (info != nullptr)
					{
						SGD::Rectangle collTemp;
						double l, t, r, b;
						info->Attribute("left", &l);
						collTemp.left = (float)l;
						info->Attribute("right", &r);
						collTemp.right = (float)r;
						info->Attribute("top", &t);
						collTemp.top = (float)t;
						info->Attribute("bottom", &b);
						collTemp.bottom = (float)b;

						newFrame->SetCollisionRect(collTemp);
					}

					info = info->NextSiblingElement("drawRect");
					if (info != nullptr)
					{
						SGD::Rectangle drawTemp;
						double l, t, r, b;
						info->Attribute("left", &l);
						drawTemp.left = (float)l;
						info->Attribute("right", &r);
						drawTemp.right = (float)r;
						info->Attribute("top", &t);
						drawTemp.top = (float)t;
						info->Attribute("bottom", &b);
						drawTemp.bottom = (float)b;

						newFrame->SetFrameRect(drawTemp);
					}

					info = info->NextSiblingElement("duration");
					if (info != nullptr)
					{
						double durtemp;
						info->Attribute("time", &durtemp);
						newFrame->SetDuration((float)durtemp);

					}

					info = info->NextSiblingElement("triggerID");
					if (info != nullptr)
					{
						std::string trigid = info->GetText();
						if (trigid.c_str() != nullptr)
							newFrame->SetTriggerID(trigid);
					}
					newSprite->AddFrame(newFrame);
					//frames->
					frames = frames->NextSiblingElement("frame");
				}
			}
			m_mSprites[newSprite->GetSpriteID()] = newSprite;
			m_vSpriteNames.push_back(newSprite->GetSpriteID());
			spriteImg = spriteImg->NextSiblingElement("sprite");
		}
	}
	if (m_mSprites.size() > 0)
		return ID;
	else
		return nullptr;
}
Esempio n. 23
0
// this file has a bunch of cosmetic stuff we don't need, but it
// does have ramps so skip right to them
int SC2Map::readt3Terrain_xml( const HANDLE archive )
{
  char strFilename[] = "t3Terrain.xml";

  int bufferSize;
  u8* bufferFreeAfterUse;

  if( readArchiveFile( archive, strFilename, &bufferSize, &bufferFreeAfterUse ) < 0 )
  {
    return -1;
  }

  bool continueProcessing = true;

  // we need a FILE* instead of data buffer for tinyxml lib
  char strTemp[] = "t3Terrain.tmp";
  FILE* fileTemp = fopen( strTemp, "w+" );

  if( fileTemp == NULL )
  {
    printError( "Could not open temp file for %s.\n", strFilename );
    continueProcessing = false;
  }

  if( continueProcessing )
  {
    int bytesWritten = fwrite( (char*)bufferFreeAfterUse, 1, bufferSize, fileTemp );
    if( bytesWritten != bufferSize )
    {
      printError( "Could not dump %s to temp file.\n", strFilename );
      continueProcessing = false;
    }

    // from here on out a temporary file holds the XML
    // so after processing delete the file
    fclose( fileTemp );
  }

  // whether or not we continue processing we have to
  // release the buffer with the file's data
  delete bufferFreeAfterUse;


  bool continueXML = false;
  if( continueProcessing )
  {
    continueXML = true;
  }


  TiXmlDocument doc;

  if( continueXML )
  {
    // open temp file as XML stream
    if( !doc.LoadFile( strTemp ) )
    {
      printError( "Could not open temp file for %s.\n", strFilename );
      continueXML = false;
    }
  }

  TiXmlHandle docHandle( &doc );
  TiXmlElement* terrain = NULL;

  if( continueXML )
  {
    terrain = docHandle
      .FirstChildElement( "terrain" )
      .ToElement();
    if( !terrain )
    {
      printWarning( "%s has no terrain element.\n", strFilename );
      continueXML = false;
    }
  }

  if( continueXML )
  {
    const char* strVersion = terrain->Attribute( "version" );
    if( strcmp( strVersion, "112" ) != 0 &&
        strcmp( strVersion, "113" ) != 0 )
    {
      printWarning( "%s is version %s, file version 112 or 113 expected.\n", strFilename, strVersion );
      continueXML = false;
    }
  }

  TiXmlElement* heightMap = NULL;
  const char* strDim;

  if( continueXML )
  {
    heightMap = terrain->FirstChildElement( "heightMap" );

    if( heightMap == NULL )
    {
      printWarning( "%s has no heightMap element.\n", strFilename );
      continueXML = false;
    }
  }

  if( continueXML )
  {
    strDim = heightMap->Attribute( "dim" );
    if( strDim == NULL )
    {
      printWarning( "%s does not specify dimensions for the heightMap.\n", strFilename );
      continueXML = false;
    }
  }

  if( continueXML )
  {
    u32 mtWidth;
    u32 mtHeight;

    sscanf( strDim, "%u %u", &mtWidth, &mtHeight );

    if( mtWidth != txDimMap || mtHeight != tyDimMap )
    {
      // we are trying to read in the map of height data, and it should
      // match the dimensions we read in from MapInfo
      printWarning( "Terrain dimensions %dx%d in %s do not match %dx%d from MapInfo.\n",
                    mtWidth, mtHeight,
                    strFilename,
                    txDimMap, tyDimMap );
      continueXML = false;
    }
  }



  TiXmlElement* rampList = NULL;

  if( continueXML )
  {
    rampList = heightMap->FirstChildElement( "rampList" );

    if( rampList == NULL )
    {
      // don't warn about this, if there's no list, no problem!
      continueXML = false;
    }
  }

  if( continueXML )
  {
    for( TiXmlElement* ramp = rampList->FirstChildElement();
         ramp;
         ramp = ramp->NextSiblingElement() )
    {
      processRamp( ramp );
    }
  }

  // delete the temporary file
  char cmd[512];
  sprintf( cmd, "if exist %s del %s", strTemp, strTemp );
  system( cmd );

  if( continueProcessing && continueXML )
  {
    return 0;
  }

  return -1;
}
Esempio n. 24
0
bool cPVRClientMediaPortal::LoadGenreXML(const std::string &filename)
{
  TiXmlDocument xmlDoc;
  if (!xmlDoc.LoadFile(filename))
  {
    XBMC->Log(LOG_DEBUG, "unable to load %s: %s at line %d", filename.c_str(), xmlDoc.ErrorDesc(), xmlDoc.ErrorRow());
    return false;
  }

  XBMC->Log(LOG_DEBUG, "Opened %s to read genre string to type/subtype translation table", filename.c_str());

  TiXmlHandle hDoc(&xmlDoc);
  TiXmlElement* pElem;
  TiXmlHandle hRoot(0);
  string sGenre;
  const char* sGenreType = NULL;
  const char* sGenreSubType = NULL;
  genre_t genre;

  // block: genrestrings
  pElem = hDoc.FirstChildElement("genrestrings").Element();
  // should always have a valid root but handle gracefully if it does
  if (!pElem)
  {
    XBMC->Log(LOG_DEBUG, "Could not find <genrestrings> element");    
    return false;
  }

  //This should hold: pElem->Value() == "genrestrings"

  // save this for later
  hRoot=TiXmlHandle(pElem);

  // iterate through all genre elements
  TiXmlElement* pGenreNode = hRoot.FirstChildElement("genre").Element();
  //This should hold: pGenreNode->Value() == "genre"

  if (!pGenreNode)
  {
    XBMC->Log(LOG_DEBUG, "Could not find <genre> element");
    return false;
  }

  for (; pGenreNode != NULL; pGenreNode = pGenreNode->NextSiblingElement("genre"))
  {
    const char* sGenreString = pGenreNode->GetText();

    if (sGenreString)
    {
      sGenreType = pGenreNode->Attribute("type");
      sGenreSubType = pGenreNode->Attribute("subtype");

      if ((sGenreType) && (strlen(sGenreType) > 2))
      {
        if(sscanf(sGenreType + 2, "%x", &genre.type) != 1)
          genre.type = 0;
      }
      else
      {
        genre.type = 0;
      }

      if ((sGenreSubType) && (strlen(sGenreSubType) > 2 ))
      {
        if(sscanf(sGenreSubType + 2, "%x", &genre.subtype) != 1)
          genre.subtype = 0;
      }
      else
      {
        genre.subtype = 0;
      }

      if (genre.type > 0)
      {
        XBMC->Log(LOG_DEBUG, "Genre '%s' => 0x%x, 0x%x", sGenreString, genre.type, genre.subtype);
        m_genremap.insert(std::pair<std::string, genre_t>(sGenreString, genre));
      }
    }
  }

  return true;
}
Esempio n. 25
0
int CCrashInfoReader::Init(CString sCrashInfoFileName)
{ 
  strconv_t strconv;
  ErrorReportInfo eri;
  
  TiXmlDocument doc;
  bool bOpen = doc.LoadFile(strconv.t2a(sCrashInfoFileName));
  if(!bOpen)
    return 1;

  TiXmlHandle hRoot = doc.FirstChild("CrashRptInternal");
  if(hRoot.ToElement()==NULL)
    return 1;

  {    
    TiXmlHandle hUnsentCrashReportsFolder = hRoot.FirstChild("UnsentCrashReportsFolder");
    if(hUnsentCrashReportsFolder.FirstChild().ToText()!=NULL)
    {      
      const char* szUnsentCrashReportsFolder = hUnsentCrashReportsFolder.FirstChild().ToText()->Value();
      if(szUnsentCrashReportsFolder!=NULL)
      {
        m_sUnsentCrashReportsFolder = strconv.utf82t(szUnsentCrashReportsFolder);
        Utility::CreateFolder(m_sUnsentCrashReportsFolder);
        
        m_sINIFile = m_sUnsentCrashReportsFolder + _T("\\~CrashRpt.ini");        
      }
    }
  }  
  
  {
    TiXmlHandle hReportFolder = hRoot.FirstChild("ReportFolder");
    if(hReportFolder.FirstChild().ToText()!=NULL)
    {
      const char* szReportFolder = hReportFolder.FirstChild().ToText()->Value();
      if(szReportFolder!=NULL)
        eri.m_sErrorReportDirName = strconv.utf82t(szReportFolder);
    }
  }

  {
    m_bQueueEnabled = FALSE;
    TiXmlHandle hQueueEnabled = hRoot.FirstChild("QueueEnabled");
    if(hQueueEnabled.FirstChild().ToText()!=NULL)
    {      
      const char* szQueueEnabled = hQueueEnabled.FirstChild().ToText()->Value();
      if(szQueueEnabled!=NULL)
      {
        m_bQueueEnabled = atoi(szQueueEnabled);        
      }
    }
  }  

  {
    m_bSendRecentReports = FALSE;
    TiXmlHandle hSendRecentReports = hRoot.FirstChild("SendRecentReports");
    if(hSendRecentReports.FirstChild().ToText()!=NULL)
    {      
      const char* szSendRecentReports = hSendRecentReports.FirstChild().ToText()->Value();
      if(szSendRecentReports!=NULL)
      {
        m_bSendRecentReports = atoi(szSendRecentReports);        
      }
    }
  }  


  {
    TiXmlHandle hCrashGUID = hRoot.FirstChild("CrashGUID");
    if(hCrashGUID.FirstChild().ToText()!=NULL)
    {
      const char* szCrashGUID = hCrashGUID.FirstChild().ToText()->Value();
      if(szCrashGUID!=NULL)
        eri.m_sCrashGUID = strconv.utf82t(szCrashGUID);
    }
  }

  {
    TiXmlHandle hAppName = hRoot.FirstChild("AppName");
    if(hAppName.FirstChild().ToText()!=NULL)
    {
      const char* szAppName = hAppName.FirstChild().ToText()->Value();
      if(szAppName!=NULL)
        m_sAppName = strconv.utf82t(szAppName);
    }
  }

  {
    TiXmlHandle hLangFileName = hRoot.FirstChild("LangFileName");
    if(hLangFileName.FirstChild().ToText()!=NULL)
    {
      const char* szLangFileName = hLangFileName.FirstChild().ToText()->Value();
      if(szLangFileName!=NULL)
        m_sLangFileName = strconv.utf82t(szLangFileName);
    }
  }

  {
    TiXmlHandle hDbgHelpPath = hRoot.FirstChild("DbgHelpPath");
    if(hDbgHelpPath.FirstChild().ToText()!=NULL)
    {
      const char* szDbgHelpPath = hDbgHelpPath.FirstChild().ToText()->Value();
      if(szDbgHelpPath!=NULL)
        m_sDbgHelpPath = strconv.utf82t(szDbgHelpPath);
    }
  }

  {
    m_bGenerateMinidump = TRUE;
    TiXmlHandle hGenerateMinidump = hRoot.FirstChild("GenerateMinidump");
    if(hGenerateMinidump.FirstChild().ToText()!=NULL)
    {
      const char* szGenerateMinidump = hGenerateMinidump.FirstChild().ToText()->Value();
      if(szGenerateMinidump!=NULL)
        m_bGenerateMinidump = (MINIDUMP_TYPE)atol(szGenerateMinidump);      
    }    
  }

  {
    TiXmlHandle hMinidumpType = hRoot.FirstChild("MinidumpType");
    if(hMinidumpType.FirstChild().ToText()!=NULL)
    {
      const char* szMinidumpType = hMinidumpType.FirstChild().ToText()->Value();
      if(szMinidumpType!=NULL)
        m_MinidumpType = (MINIDUMP_TYPE)atol(szMinidumpType);
      else
        m_MinidumpType = MiniDumpNormal;
    }
    else
      m_MinidumpType = MiniDumpNormal;
  }

  {
    TiXmlHandle hUrl = hRoot.FirstChild("Url");
    if(hUrl.FirstChild().ToText()!=NULL)
    {
      const char* szUrl = hUrl.FirstChild().ToText()->Value();
      if(szUrl!=NULL)
        m_sUrl = strconv.utf82t(szUrl);
    }
  }

  {
    TiXmlHandle hEmailTo = hRoot.FirstChild("EmailTo");
    if(hEmailTo.FirstChild().ToText()!=NULL)
    {
      const char* szEmailTo = hEmailTo.FirstChild().ToText()->Value();
      if(szEmailTo!=NULL)
        m_sEmailTo = strconv.utf82t(szEmailTo);
    }
  }

  {
    m_nSmtpPort = 25;
    TiXmlHandle hSmtpPort = hRoot.FirstChild("SmtpPort");
    if(hSmtpPort.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpPort = hSmtpPort.FirstChild().ToText()->Value();
      if(szSmtpPort!=NULL)
        m_nSmtpPort = atoi(szSmtpPort);
    }
  }

  {
    TiXmlHandle hEmailSubject = hRoot.FirstChild("EmailSubject");
    if(hEmailSubject.FirstChild().ToText()!=NULL)
    {
      const char* szEmailSubject = hEmailSubject.FirstChild().ToText()->Value();
      if(szEmailSubject!=NULL)
        m_sEmailSubject = strconv.utf82t(szEmailSubject);
    }
  }

  {
    TiXmlHandle hEmailText = hRoot.FirstChild("EmailText");
    if(hEmailText.FirstChild().ToText()!=NULL)
    {
      const char* szEmailText = hEmailText.FirstChild().ToText()->Value();
      if(szEmailText!=NULL)
        m_sEmailText = strconv.utf82t(szEmailText);
    }
  }

  {
    TiXmlHandle hPrivacyPolicyUrl = hRoot.FirstChild("PrivacyPolicyUrl");    
    if(hPrivacyPolicyUrl.FirstChild().ToText()!=NULL)
    {
      const char* szPrivacyPolicyUrl = hPrivacyPolicyUrl.FirstChild().ToText()->Value();
      if(szPrivacyPolicyUrl!=NULL)
        m_sPrivacyPolicyURL = strconv.utf82t(szPrivacyPolicyUrl);
    }
  }

  {
    TiXmlHandle hHttpPriority = hRoot.FirstChild("HttpPriority");
    if(hHttpPriority.FirstChild().ToText()!=NULL)
    {
      const char* szHttpPriority = hHttpPriority.FirstChild().ToText()->Value();
      if(szHttpPriority!=NULL)
        m_uPriorities[CR_HTTP] = atoi(szHttpPriority);
      else
        m_uPriorities[CR_HTTP] = 0;
    }
  }

  {
    TiXmlHandle hSmtpPriority = hRoot.FirstChild("SmtpPriority");
    if(hSmtpPriority.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpPriority = hSmtpPriority.FirstChild().ToText()->Value();
      if(szSmtpPriority!=NULL)
        m_uPriorities[CR_SMTP] = atoi(szSmtpPriority);
      else
        m_uPriorities[CR_SMTP] = 0;
    }
  }

  {
    TiXmlHandle hMapiPriority = hRoot.FirstChild("MapiPriority");
    if(hMapiPriority.FirstChild().ToText()!=NULL)
    {
      const char* szMapiPriority = hMapiPriority.FirstChild().ToText()->Value();
      if(szMapiPriority!=NULL)
        m_uPriorities[CR_SMAPI] = atoi(szMapiPriority);
      else
        m_uPriorities[CR_SMAPI] = 0;
    }
  }

  {
    TiXmlHandle hProcessId = hRoot.FirstChild("ProcessId");
    if(hProcessId.FirstChild().ToText()!=NULL)
    {
      const char* szProcessId = hProcessId.FirstChild().ToText()->Value();
      if(szProcessId!=NULL)
        m_dwProcessId = strtoul(szProcessId, NULL, 10);
      else
        m_dwProcessId = 0;
    }
  }

  {
    TiXmlHandle hThreadId = hRoot.FirstChild("ThreadId");
    if(hThreadId.FirstChild().ToText()!=NULL)
    {
      const char* szThreadId = hThreadId.FirstChild().ToText()->Value();
      if(szThreadId!=NULL)
        m_dwThreadId = strtoul(szThreadId, NULL, 10);
      else 
        m_dwThreadId = 0;
    }
  }

  {
    m_pExInfo = NULL;
    TiXmlHandle hExceptionPointersAddress = hRoot.FirstChild("ExceptionPointersAddress");
    if(hExceptionPointersAddress.FirstChild().ToText()!=NULL)
    {
      const char* szExceptionPointersAddress = hExceptionPointersAddress.FirstChild().ToText()->Value();
      if(szExceptionPointersAddress!=NULL)
        m_pExInfo = (PEXCEPTION_POINTERS)_strtoui64(szExceptionPointersAddress, NULL, 16);     
    }    
  }

  {
    TiXmlHandle hAddScreenshot = hRoot.FirstChild("AddScreenshot");
    if(hAddScreenshot.FirstChild().ToText()!=NULL)
    {
      const char* szAddScreenshot = hAddScreenshot.FirstChild().ToText()->Value();
      if(szAddScreenshot!=NULL)
        m_bAddScreenshot = strtol(szAddScreenshot, NULL, 10);
      else
        m_bAddScreenshot = FALSE;
    }
  }

  {
    m_dwScreenshotFlags = 0;
    TiXmlHandle hScreenshotFlags = hRoot.FirstChild("ScreenshotFlags");
    if(hScreenshotFlags.FirstChild().ToText()!=NULL)
    {
      const char* szScreenshotFlags = hScreenshotFlags.FirstChild().ToText()->Value();
      if(szScreenshotFlags!=NULL)
        m_dwScreenshotFlags = strtoul(szScreenshotFlags, NULL, 10);        
    }
  }

  {
    m_ptCursorPos.SetPoint(0, 0);
    TiXmlHandle hCursorPos = hRoot.FirstChild("CursorPos");
    if(hCursorPos.ToElement()!=NULL)
    {
      const char* szX = hCursorPos.ToElement()->Attribute("x");
      const char* szY = hCursorPos.ToElement()->Attribute("y");
      if(szX && szY)
      {
        m_ptCursorPos.x = atoi(szX);
        m_ptCursorPos.y = atoi(szY);
      }
    }
  }

  {
    m_rcAppWnd.SetRectEmpty();
    TiXmlHandle hAppWndRect = hRoot.FirstChild("AppWindowRect");
    if(hAppWndRect.ToElement()!=NULL)
    {
      const char* szLeft = hAppWndRect.ToElement()->Attribute("left");
      const char* szTop = hAppWndRect.ToElement()->Attribute("top");
      const char* szRight = hAppWndRect.ToElement()->Attribute("right");
      const char* szBottom = hAppWndRect.ToElement()->Attribute("bottom");

      if(szLeft && szTop && szRight && szBottom)
      {
        m_rcAppWnd.left = atoi(szLeft);
        m_rcAppWnd.top = atoi(szTop);
        m_rcAppWnd.right = atoi(szRight);
        m_rcAppWnd.bottom = atoi(szBottom);
      }
    }
  }

  {
    m_bHttpBinaryEncoding = FALSE;    
    TiXmlHandle hHttpBinaryEncoding = hRoot.FirstChild("HttpBinaryEncoding");
    if(hHttpBinaryEncoding.FirstChild().ToText()!=NULL)
    {
      const char* szHttpBinaryEncoding = hHttpBinaryEncoding.FirstChild().ToText()->Value();
      if(szHttpBinaryEncoding!=NULL)
        m_bHttpBinaryEncoding = atoi(szHttpBinaryEncoding);
    }      
  }

  {
    m_bSilentMode = FALSE;    
    TiXmlHandle hSilentMode = hRoot.FirstChild("SilentMode");
    if(hSilentMode.FirstChild().ToText()!=NULL)
    {
      const char* szSilentMode = hSilentMode.FirstChild().ToText()->Value();
      if(szSilentMode!=NULL)
        m_bSilentMode = atoi(szSilentMode);
    }      
  }

  {
    m_bSendErrorReport = FALSE;    
    TiXmlHandle hSendErrorReport = hRoot.FirstChild("SendErrorReport");
    if(hSendErrorReport.FirstChild().ToText()!=NULL)
    {
      const char* szSendErrorReport = hSendErrorReport.FirstChild().ToText()->Value();
      if(szSendErrorReport!=NULL)
        m_bSendErrorReport = atoi(szSendErrorReport);     
    }      
  }

  {
    m_bAppRestart = FALSE;    
    TiXmlHandle hAppRestart = hRoot.FirstChild("AppRestart");
    if(hAppRestart.FirstChild().ToText()!=NULL)
    {
      const char* szAppRestart = hAppRestart.FirstChild().ToText()->Value();
      if(szAppRestart!=NULL)
        m_bAppRestart = atoi(szAppRestart);     
    }      
  }

  {    
    TiXmlHandle hRestartCmdLine = hRoot.FirstChild("RestartCmdLine");
    if(hRestartCmdLine.FirstChild().ToText()!=NULL)
    {
      const char* szRestartCmdLine = hRestartCmdLine.FirstChild().ToText()->Value();
      if(szRestartCmdLine!=NULL)
        m_sRestartCmdLine = strconv.utf82t(szRestartCmdLine);     
    }      
  }

  {    
    TiXmlHandle hSmtpProxyServer = hRoot.FirstChild("SmtpProxyServer");
    if(hSmtpProxyServer.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpProxyServer = hSmtpProxyServer.FirstChild().ToText()->Value();
      if(szSmtpProxyServer!=NULL)
        m_sSmtpProxyServer = strconv.utf82t(szSmtpProxyServer);     
    }      
  }

  {    
    m_nSmtpProxyPort = 25;
    TiXmlHandle hSmtpProxyPort = hRoot.FirstChild("SmtpProxyPort");
    if(hSmtpProxyPort.FirstChild().ToText()!=NULL)
    {
      const char* szSmtpProxyPort = hSmtpProxyPort.FirstChild().ToText()->Value();
      if(szSmtpProxyPort!=NULL)
        m_nSmtpProxyPort = atoi(szSmtpProxyPort);     
    }      
  }

  if(!m_bSendRecentReports)
  {    
    // Get the list of files that should be included to report
    ParseFileList(hRoot, eri);

    // Get some info from crashrpt.xml
    CString sXmlName = eri.m_sErrorReportDirName + _T("\\crashrpt.xml");
    ParseCrashDescription(sXmlName, FALSE, eri);    
    
    m_Reports.push_back(eri);
  }  
  else
  {
    // Look for unsent error reports
    CString sSearchPattern = m_sUnsentCrashReportsFolder + _T("\\*");
    CFindFile find;
    BOOL bFound = find.FindFile(sSearchPattern);
    while(bFound)
    {
      if(find.IsDirectory() && !find.IsDots())
      {
        CString sErrorReportDirName = m_sUnsentCrashReportsFolder + _T("\\") + 
          find.GetFileName();
        CString sFileName = sErrorReportDirName + _T("\\crashrpt.xml");
        ErrorReportInfo eri;
        eri.m_sErrorReportDirName = sErrorReportDirName;
        if(0==ParseCrashDescription(sFileName, TRUE, eri))
        {          
          eri.m_uTotalSize = GetUncompressedReportSize(eri);
          m_Reports.push_back(eri);
        }
      }

      bFound = find.FindNextFile();
    }
  }
  
  return 0;
}
int PluginsManager::loadPlugin(const TCHAR *pluginFilePath, vector<generic_string> & dll2Remove)
{
	const TCHAR *pluginFileName = ::PathFindFileName(pluginFilePath);
	if (isInLoadedDlls(pluginFileName))
		return 0;

	NppParameters * nppParams = NppParameters::getInstance();

	PluginInfo *pi = new PluginInfo;
	try
	{
		pi->_moduleName = pluginFileName;

		if (GetBinaryArchitectureType(pluginFilePath) != ARCH_TYPE)
			throw generic_string(ARCH_ERR_MSG);

	    pi->_hLib = ::LoadLibrary(pluginFilePath);
        if (!pi->_hLib)
        {
			generic_string lastErrorMsg = GetLastErrorAsString();
            if (lastErrorMsg.empty())
                throw generic_string(TEXT("Load Library has failed.\nChanging the project's \"Runtime Library\" setting to \"Multi-threaded(/MT)\" might solve this problem."));
            else
                throw generic_string(lastErrorMsg.c_str());
        }
        
		pi->_pFuncIsUnicode = (PFUNCISUNICODE)GetProcAddress(pi->_hLib, "isUnicode");
		if (!pi->_pFuncIsUnicode || !pi->_pFuncIsUnicode())
			throw generic_string(TEXT("This ANSI plugin is not compatible with your Unicode Notepad++."));

		pi->_pFuncSetInfo = (PFUNCSETINFO)GetProcAddress(pi->_hLib, "setInfo");

		if (!pi->_pFuncSetInfo)
			throw generic_string(TEXT("Missing \"setInfo\" function"));

		pi->_pFuncGetName = (PFUNCGETNAME)GetProcAddress(pi->_hLib, "getName");
		if (!pi->_pFuncGetName)
			throw generic_string(TEXT("Missing \"getName\" function"));
		pi->_funcName = pi->_pFuncGetName();

		pi->_pBeNotified = (PBENOTIFIED)GetProcAddress(pi->_hLib, "beNotified");
		if (!pi->_pBeNotified)
			throw generic_string(TEXT("Missing \"beNotified\" function"));

		pi->_pMessageProc = (PMESSAGEPROC)GetProcAddress(pi->_hLib, "messageProc");
		if (!pi->_pMessageProc)
			throw generic_string(TEXT("Missing \"messageProc\" function"));

		pi->_pFuncSetInfo(_nppData);

		pi->_pFuncGetFuncsArray = (PFUNCGETFUNCSARRAY)GetProcAddress(pi->_hLib, "getFuncsArray");
		if (!pi->_pFuncGetFuncsArray)
			throw generic_string(TEXT("Missing \"getFuncsArray\" function"));

		pi->_funcItems = pi->_pFuncGetFuncsArray(&pi->_nbFuncItem);

		if ((!pi->_funcItems) || (pi->_nbFuncItem <= 0))
			throw generic_string(TEXT("Missing \"FuncItems\" array, or the nb of Function Item is not set correctly"));

		pi->_pluginMenu = ::CreateMenu();

		GetLexerCountFn GetLexerCount = (GetLexerCountFn)::GetProcAddress(pi->_hLib, "GetLexerCount");
		// it's a lexer plugin
		if (GetLexerCount)
		{
			GetLexerNameFn GetLexerName = (GetLexerNameFn)::GetProcAddress(pi->_hLib, "GetLexerName");
			if (!GetLexerName)
				throw generic_string(TEXT("Loading GetLexerName function failed."));

			GetLexerStatusTextFn GetLexerStatusText = (GetLexerStatusTextFn)::GetProcAddress(pi->_hLib, "GetLexerStatusText");

			if (!GetLexerStatusText)
				throw generic_string(TEXT("Loading GetLexerStatusText function failed."));

			// Assign a buffer for the lexer name.
			char lexName[MAX_EXTERNAL_LEXER_NAME_LEN];
			lexName[0] = '\0';
			TCHAR lexDesc[MAX_EXTERNAL_LEXER_DESC_LEN];
			lexDesc[0] = '\0';

			int numLexers = GetLexerCount();

			ExternalLangContainer *containers[30];

			WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
			for (int x = 0; x < numLexers; ++x)
			{
				GetLexerName(x, lexName, MAX_EXTERNAL_LEXER_NAME_LEN);
				GetLexerStatusText(x, lexDesc, MAX_EXTERNAL_LEXER_DESC_LEN);
				const TCHAR *pLexerName = wmc->char2wchar(lexName, CP_ACP);
				if (!nppParams->isExistingExternalLangName(pLexerName) && nppParams->ExternalLangHasRoom())
					containers[x] = new ExternalLangContainer(pLexerName, lexDesc);
				else
					containers[x] = NULL;
			}

			TCHAR xmlPath[MAX_PATH];
            lstrcpy(xmlPath, nppParams->getNppPath().c_str());
			PathAppend(xmlPath, TEXT("plugins\\Config"));
            PathAppend(xmlPath, pi->_moduleName.c_str());
			PathRemoveExtension(xmlPath);
			PathAddExtension(xmlPath, TEXT(".xml"));

			if (!PathFileExists(xmlPath))
			{
				lstrcpyn(xmlPath, TEXT("\0"), MAX_PATH );
				lstrcpy(xmlPath, nppParams->getAppDataNppDir() );
				PathAppend(xmlPath, TEXT("plugins\\Config"));
                PathAppend(xmlPath, pi->_moduleName.c_str());
				PathRemoveExtension( xmlPath );
				PathAddExtension( xmlPath, TEXT(".xml") );

				if (! PathFileExists( xmlPath ) )
				{
					throw generic_string(generic_string(xmlPath) + TEXT(" is missing."));
				}
			}

			TiXmlDocument *pXmlDoc = new TiXmlDocument(xmlPath);

			if (!pXmlDoc->LoadFile())
			{
				delete pXmlDoc;
				pXmlDoc = NULL;
				throw generic_string(generic_string(xmlPath) + TEXT(" failed to load."));
			}

			for (int x = 0; x < numLexers; ++x) // postpone adding in case the xml is missing/corrupt
			{
				if (containers[x] != NULL)
					nppParams->addExternalLangToEnd(containers[x]);
			}

			nppParams->getExternalLexerFromXmlTree(pXmlDoc);
			nppParams->getExternalLexerDoc()->push_back(pXmlDoc);
			const char *pDllName = wmc->wchar2char(pluginFilePath, CP_ACP);
			::SendMessage(_nppData._scintillaMainHandle, SCI_LOADLEXERLIBRARY, 0, reinterpret_cast<LPARAM>(pDllName));

		}
		addInLoadedDlls(pluginFilePath, pluginFileName);
		_pluginInfos.push_back(pi);
		return static_cast<int32_t>(_pluginInfos.size() - 1);
	}
	catch (std::exception& e)
	{
		::MessageBoxA(NULL, e.what(), "Exception", MB_OK);
		return -1;
	}
	catch (generic_string s)
	{
		s += TEXT("\n\n");
		s += pluginFileName;
		s += USERMSG;
		if (::MessageBox(NULL, s.c_str(), pluginFilePath, MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
	catch (...)
	{
		generic_string msg = TEXT("Failed to load");
		msg += TEXT("\n\n");
		msg += pluginFileName;
		msg += USERMSG;
		if (::MessageBox(NULL, msg.c_str(), pluginFilePath, MB_YESNO) == IDYES)
		{
			dll2Remove.push_back(pluginFilePath);
		}
		delete pi;
        return -1;
	}
}
Esempio n. 27
0
File: Edl.cpp Progetto: Kr0nZ/boxee
bool CEdl::ReadBeyondTV(const CStdString& strMovie)
{
  Clear();

  CStdString beyondTVFilename;
  CUtil::ReplaceExtension(strMovie, CUtil::GetExtension(strMovie) + ".chapters.xml", beyondTVFilename);
  if (!CFile::Exists(beyondTVFilename))
    return false;

  TiXmlDocument xmlDoc;
  if (!xmlDoc.LoadFile(beyondTVFilename))
  {
    CLog::Log(LOGERROR, "%s - Could not load Beyond TV file: %s. %s", __FUNCTION__, beyondTVFilename.c_str(),
              xmlDoc.ErrorDesc());
    return false;
  }

  if (xmlDoc.Error())
  {
    CLog::Log(LOGERROR, "%s - Could not parse Beyond TV file: %s. %s", __FUNCTION__, beyondTVFilename.c_str(),
              xmlDoc.ErrorDesc());
    return false;
  }

  TiXmlElement *pRoot = xmlDoc.RootElement();
  if (!pRoot || strcmp(pRoot->Value(), "cutlist"))
  {
    CLog::Log(LOGERROR, "%s - Invalid Beyond TV file: %s. Expected root node to be <cutlist>", __FUNCTION__,
              beyondTVFilename.c_str());
    return false;
  }

  bool bValid = true;
  TiXmlElement *pRegion = pRoot->FirstChildElement("Region");
  while (bValid && pRegion)
  {
    TiXmlElement *pStart = pRegion->FirstChildElement("start");
    TiXmlElement *pEnd = pRegion->FirstChildElement("end");
    if (pStart && pEnd && pStart->FirstChild() && pEnd->FirstChild())
    {
      /*
       * Need to divide the start and end times by a factor of 10,000 to get msec.
       * E.g. <start comment="00:02:44.9980867">1649980867</start>
       *
       * Use atof so doesn't overflow 32 bit float or integer / long.
       * E.g. <end comment="0:26:49.0000009">16090090000</end>
       *
       * Don't use atoll even though it is more correct as it isn't natively supported by
       * Visual Studio.
       *
       * GetText() returns 0 if there were any problems and will subsequently be rejected in AddCut().
       */
      Cut cut;
      cut.start = (int64_t)(atof(pStart->GetText()) / 10000);
      cut.end = (int64_t)(atof(pEnd->GetText()) / 10000);
      cut.action = COMM_BREAK;
      bValid = AddCut(cut);
    }
    else
      bValid = false;

    pRegion = pRegion->NextSiblingElement("Region");
  }
  if (!bValid)
  {
    CLog::Log(LOGERROR, "%s - Invalid Beyond TV file: %s. Clearing any valid commercial breaks found.", __FUNCTION__,
              beyondTVFilename.c_str());
    Clear();
    return false;
  }
  else if (HasCut())
  {
    CLog::Log(LOGDEBUG, "%s - Read %zu commercial breaks from Beyond TV file: %s", __FUNCTION__, m_vecCuts.size(),
              beyondTVFilename.c_str());
    return true;
  }
  else
  {
    CLog::Log(LOGDEBUG, "%s - No commercial breaks found in Beyond TV file: %s", __FUNCTION__,
              beyondTVFilename.c_str());
    return false;
  }
}
bool CButtonMapXml::Load(void)
{
  TiXmlDocument xmlFile;
  if (!xmlFile.LoadFile(m_strResourcePath))
  {
    esyslog("Error opening %s: %s", m_strResourcePath.c_str(), xmlFile.ErrorDesc());
    return false;
  }

  TiXmlElement* pRootElement = xmlFile.RootElement();
  if (!pRootElement || pRootElement->NoChildren() || pRootElement->ValueStr() != BUTTONMAP_XML_ROOT)
  {
    esyslog("Can't find root <%s> tag", BUTTONMAP_XML_ROOT);
    return false;
  }

  const TiXmlElement* pDevice = pRootElement->FirstChildElement(DEVICES_XML_ELEM_DEVICE);

  if (!pDevice)
  {
    esyslog("Can't find <%s> tag", DEVICES_XML_ELEM_DEVICE);
    return false;
  }

  if (!CDeviceXml::Deserialize(pDevice, m_device))
    return false;

  const TiXmlElement* pController = pDevice->FirstChildElement(BUTTONMAP_XML_ELEM_CONTROLLER);

  if (!pController)
  {
    esyslog("Device \"%s\": can't find <%s> tag", m_device.Name().c_str(), BUTTONMAP_XML_ELEM_CONTROLLER);
    return false;
  }

  // For logging purposes
  unsigned int totalFeatureCount = 0;

  while (pController)
  {
    const char* id = pController->Attribute(BUTTONMAP_XML_ATTR_CONTROLLER_ID);
    if (!id)
    {
      esyslog("Device \"%s\": <%s> tag has no attribute \"%s\"", m_device.Name().c_str(),
              BUTTONMAP_XML_ELEM_CONTROLLER, BUTTONMAP_XML_ATTR_CONTROLLER_ID);
      return false;
    }

    FeatureVector features;
    if (!Deserialize(pController, features))
      return false;

    if (features.empty())
    {
      esyslog("Device \"%s\" has no features for controller %s", m_device.Name().c_str(), id);
    }
    else
    {
      totalFeatureCount += features.size();
      m_buttonMap[id] = std::move(features);
    }

    pController = pController->NextSiblingElement(BUTTONMAP_XML_ELEM_CONTROLLER);
  }

  dsyslog("Loaded device \"%s\" with %u controller profiles and %u total features", m_device.Name().c_str(), m_buttonMap.size(), totalFeatureCount);

  return true;
}
void AnimationSystem::Load(const char * _filename)
{
	//Game::GetInstance()->GetFont().Draw("Loading", { Game::GetInstance()->GetScreenSize().width / 2, Game::GetInstance()->GetScreenSize().height / 2 }, 1, { 255, 255, 255, 255 });
	double left, top, width, height, cleft, ctop, cheight, cwidth;
	double x, y;
	double ptx, pty;
	double time;
	std::string trigtype;
	std::string trigname;
	TiXmlDocument doc;
	if (doc.LoadFile(_filename) == false)
		return;
	TiXmlElement* root = doc.RootElement();
	m_ImgString = root->Attribute("Image");

#pragma region XML
	TiXmlElement* Animation = root->FirstChildElement("Animation");
	while (Animation != nullptr)
	{
		TiXmlElement* Frames = Animation->FirstChildElement();
		m_AnimationName = Animation->Attribute("Name");
		while (Frames != nullptr)
		{
			TiXmlElement* Draw = Frames->FirstChildElement("Draw");
			Draw->Attribute("RectX", &left);
			Draw->Attribute("RectY", &top);
			Draw->Attribute("RectWidth", &width);
			Draw->Attribute("RectHeight", &height);
			Draw = Draw->NextSiblingElement("Collision");
			Draw->Attribute("RectX", &cleft);
			Draw->Attribute("RectY", &ctop);
			Draw->Attribute("RectWidth", &cwidth);
			Draw->Attribute("RectHeight", &cheight);
			Draw = Draw->NextSiblingElement("AnchorPT");
			Draw->Attribute("X", &x);
			Draw->Attribute("Y", &y);
			Draw = Draw->NextSiblingElement("Particles");
			TiXmlElement* Particles = Draw->FirstChildElement("ParticlePT");
			Frame frame;
			while (Particles != nullptr)
			{
				Particles->Attribute("X", &ptx);
				Particles->Attribute("Y", &pty);
				Particles = Particles->NextSiblingElement();
				frame.AddParticlePoint(SGD::Point{ (float)ptx, (float)pty });
			}
			Draw = Draw->NextSiblingElement("Time");
			Draw->Attribute("Time", &time);
			Draw = Draw->NextSiblingElement("Trigger");
			trigtype = Draw->Attribute("Type");
			trigname = Draw->Attribute("Name");
			Frames = Frames->NextSiblingElement();
			frame.SetDrawFrame(SGD::Rectangle{ (float)left, (float)top, (float)(left + width), (float)(top + height) });
			frame.SetAnchorPt(SGD::Point{ (float)x, (float)y });
			frame.SetCollisionRect(SGD::Rectangle{ SGD::Point((float)cleft, (float)ctop), SGD::Size((float)cwidth, (float)cheight) });
			frame.SetTimer((float)time);
			frame.SetTriggerType(trigtype);
			frame.SetTriggerName(trigname);
			m_Loaded[m_AnimationName].AddFrames(frame);
		}
		Animation = Animation->NextSiblingElement();
	}

	std::string str;
	str = "../resource/graphics/";
	for (unsigned int i = 0; i < str.size(); i++)
	{
		if (i != 20)
			i++;
		else
			str.append(m_ImgString);
	}
	m_Img = GM->LoadTexture(str.c_str());
	m_Imgs.push_back(m_Img);
#pragma endregion 
}
Esempio n. 30
0
void TowerFlyweight::Load(string fileName)
{
	// Create a TinyXML document
	TiXmlDocument doc;

	// Attempt to load from the file
	doc.LoadFile(fileName.c_str());

	// Access the 'root' TinyXML Element
	TiXmlElement* pRoot = doc.RootElement();

	// Double for temp storage
	double temp;

#pragma region Machine Gun Tower

	// Machine Gun Tower
	TiXmlElement* machineGun = pRoot->FirstChildElement("machine_gun");

	// Starting Values
	machineGun->FirstChildElement("damage")->Attribute("value", &m_nMachineGunDamage[0]);
	machineGun->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMachineGunFireRate[0] = (float)temp;
	machineGun->FirstChildElement("range")->Attribute("value", &m_nMachineGunRange[0]);

	// Power Upgrade Values
	TiXmlElement* machineGunPower = machineGun->FirstChildElement("power_upgrade");

	// Tier 1
	TiXmlElement* machineGunPowerOne = machineGunPower->FirstChildElement("tier_one");
	machineGunPowerOne->FirstChildElement("cost")->Attribute("value", &m_nMachineGunPowerUpgradeCost[0]);
	machineGunPowerOne->FirstChildElement("damage")->Attribute("value", &m_nMachineGunDamage[1]);
	machineGunPowerOne->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMachineGunFireRate[1] = (float)temp;

	// Tier 2
	TiXmlElement* machineGunPowerTwo = machineGunPower->FirstChildElement("tier_two");
	machineGunPowerTwo->FirstChildElement("cost")->Attribute("value", &m_nMachineGunPowerUpgradeCost[1]);
	machineGunPowerTwo->FirstChildElement("damage")->Attribute("value", &m_nMachineGunDamage[2]);
	machineGunPowerTwo->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMachineGunFireRate[2] = (float)temp;

	// Tier 3
	TiXmlElement* machineGunPowerThree = machineGunPower->FirstChildElement("tier_three");
	machineGunPowerThree->FirstChildElement("cost")->Attribute("value", &m_nMachineGunPowerUpgradeCost[2]);
	machineGunPowerThree->FirstChildElement("damage")->Attribute("value", &m_nMachineGunDamage[3]);
	machineGunPowerThree->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMachineGunFireRate[3] = (float)temp;

	// Range Upgrade Values
	TiXmlElement* machineGunRange = machineGun->FirstChildElement("range_upgrade");

	// Tier 1
	TiXmlElement* machineGunRangeOne = machineGunRange->FirstChildElement("tier_one");
	machineGunRangeOne->FirstChildElement("cost")->Attribute("value", &m_nMachineGunRangeUpgradeCost[0]);
	machineGunRangeOne->FirstChildElement("range")->Attribute("value", &m_nMachineGunRange[1]);

	// Tier 2
	TiXmlElement* machineGunRangeTwo = machineGunRange->FirstChildElement("tier_two");
	machineGunRangeTwo->FirstChildElement("cost")->Attribute("value", &m_nMachineGunRangeUpgradeCost[1]);
	machineGunRangeTwo->FirstChildElement("range")->Attribute("value", &m_nMachineGunRange[2]);

	// Tier 3
	TiXmlElement* machineGunRangeThree = machineGunRange->FirstChildElement("tier_three");
	machineGunRangeThree->FirstChildElement("cost")->Attribute("value", &m_nMachineGunRangeUpgradeCost[2]);
	machineGunRangeThree->FirstChildElement("range")->Attribute("value", &m_nMachineGunRange[3]);

#pragma endregion

#pragma region Maple Syrup Tower

	// Maple Syrup Tower
	TiXmlElement* mapleSyrup = pRoot->FirstChildElement("maple_syrup");

	// Starting Values
	mapleSyrup->FirstChildElement("effect_duration")->Attribute("value", &temp);
	m_fMapleSyrupEffectDuration[0] = (float)temp;
	mapleSyrup->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMapleSyrupFireRate[0] = (float)temp;
	mapleSyrup->FirstChildElement("range")->Attribute("value", &m_nMapleSyrupRange[0]);

	// Power Upgrade Values
	TiXmlElement* mapleSyrupPower = mapleSyrup->FirstChildElement("power_upgrade");

	// Tier 1
	TiXmlElement* mapleSyrupPowerOne = mapleSyrupPower->FirstChildElement("tier_one");
	mapleSyrupPowerOne->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupPowerUpgradeCost[0]);
	mapleSyrupPowerOne->FirstChildElement("effect_duration")->Attribute("value", &temp);
	m_fMapleSyrupEffectDuration[1] = (float)temp;
	mapleSyrupPowerOne->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMapleSyrupFireRate[1] = (float)temp;

	// Tier 2
	TiXmlElement* mapleSyrupPowerTwo = mapleSyrupPower->FirstChildElement("tier_two");
	mapleSyrupPowerTwo->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupPowerUpgradeCost[1]);
	mapleSyrupPowerTwo->FirstChildElement("effect_duration")->Attribute("value", &temp);
	m_fMapleSyrupEffectDuration[2] = (float)temp;
	mapleSyrupPowerTwo->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMapleSyrupFireRate[2] = (float)temp;

	// Tier 3
	TiXmlElement* mapleSyrupPowerThree = mapleSyrupPower->FirstChildElement("tier_three");
	mapleSyrupPowerThree->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupPowerUpgradeCost[2]);
	mapleSyrupPowerThree->FirstChildElement("effect_duration")->Attribute("value", &temp);
	m_fMapleSyrupEffectDuration[3] = (float)temp;
	mapleSyrupPowerThree->FirstChildElement("fire_rate")->Attribute("value", &temp);
	m_fMapleSyrupFireRate[3] = (float)temp;

	// Range Upgrade Values
	TiXmlElement* mapleSyrupRange = mapleSyrup->FirstChildElement("range_upgrade");

	// Tier 1
	TiXmlElement* mapleSyrupRangeOne = mapleSyrupRange->FirstChildElement("tier_one");
	mapleSyrupRangeOne->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupRangeUpgradeCost[0]);
	mapleSyrupRangeOne->FirstChildElement("range")->Attribute("value", &m_nMapleSyrupRange[1]);

	// Tier 2
	TiXmlElement* mapleSyrupRangeTwo = mapleSyrupRange->FirstChildElement("tier_two");
	mapleSyrupRangeTwo->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupRangeUpgradeCost[1]);
	mapleSyrupRangeTwo->FirstChildElement("range")->Attribute("value", &m_nMapleSyrupRange[2]);

	// Tier 3
	TiXmlElement* mapleSyrupRangeThree = mapleSyrupRange->FirstChildElement("tier_three");
	mapleSyrupRangeThree->FirstChildElement("cost")->Attribute("value", &m_nMapleSyrupRangeUpgradeCost[2]);
	mapleSyrupRangeThree->FirstChildElement("range")->Attribute("value", &m_nMapleSyrupRange[3]);

#pragma endregion

#pragma region Hockey Stick Tower

	// Hockey Stick Tower
	TiXmlElement* hockeyStick = pRoot->FirstChildElement("hockey_stick");

	// Starting Values
	hockeyStick->FirstChildElement("damage")->Attribute("value", &temp);
	m_fHockeyStickDamage[0] = (float)temp;
	hockeyStick->FirstChildElement("spin_rate")->Attribute("value", &temp);
	m_fHockeyStickSpinRate[0] = (float)temp;

	// Damage Upgrade Values
	TiXmlElement* hockeyStickDamage = hockeyStick->FirstChildElement("damage_upgrade");

	// Tier 1
	TiXmlElement* hockeyStickDamageOne = hockeyStickDamage->FirstChildElement("tier_one");
	hockeyStickDamageOne->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickDamageUpgradeCost[0]);
	hockeyStickDamageOne->FirstChildElement("damage")->Attribute("value", &temp);
	m_fHockeyStickDamage[1] = (float)temp;

	// Tier 2
	TiXmlElement* hockeyStickDamageTwo = hockeyStickDamage->FirstChildElement("tier_two");
	hockeyStickDamageTwo->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickDamageUpgradeCost[1]);
	hockeyStickDamageTwo->FirstChildElement("damage")->Attribute("value", &temp);
	m_fHockeyStickDamage[2] = (float)temp;

	// Tier 3
	TiXmlElement* hockeyStickDamageThree = hockeyStickDamage->FirstChildElement("tier_three");
	hockeyStickDamageThree->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickDamageUpgradeCost[2]);
	hockeyStickDamageThree->FirstChildElement("damage")->Attribute("value", &temp);
	m_fHockeyStickDamage[3] = (float)temp;

	// Spin Rate Upgrade Values
	TiXmlElement* hockeyStickSpinRate = hockeyStick->FirstChildElement("spin_rate_upgrade");

	// Tier 1
	TiXmlElement* hockeyStickSpinRateOne = hockeyStickSpinRate->FirstChildElement("tier_one");
	hockeyStickSpinRateOne->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickSpinRateUpgradeCost[0]);
	hockeyStickSpinRateOne->FirstChildElement("spin_rate")->Attribute("value", &temp);
	m_fHockeyStickSpinRate[1] = (float)temp;

	// Tier 2
	TiXmlElement* hockeyStickSpinRateTwo = hockeyStickSpinRate->FirstChildElement("tier_two");
	hockeyStickSpinRateTwo->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickSpinRateUpgradeCost[1]);
	hockeyStickSpinRateTwo->FirstChildElement("spin_rate")->Attribute("value", &temp);
	m_fHockeyStickSpinRate[2] = (float)temp;

	// Tier 3
	TiXmlElement* hockeyStickSpinRateThree = hockeyStickSpinRate->FirstChildElement("tier_three");
	hockeyStickSpinRateThree->FirstChildElement("cost")->Attribute("value", &m_nHockeyStickSpinRateUpgradeCost[2]);
	hockeyStickSpinRateThree->FirstChildElement("spin_rate")->Attribute("value", &temp);
	m_fHockeyStickSpinRate[3] = (float)temp;

#pragma endregion

#pragma region Laser Tower

	// Laser Tower
	TiXmlElement* laser = pRoot->FirstChildElement("laser");

	// Starting Values
	laser->FirstChildElement("damage")->Attribute("value", &m_nLaserDamage[0]);
	laser->FirstChildElement("range")->Attribute("value", &m_nLaserRange[0]);

	// Damage Upgrade Values
	TiXmlElement* laserDamage = laser->FirstChildElement("damage_upgrade");

	// Tier 1
	TiXmlElement* laserDamageOne = laserDamage->FirstChildElement("tier_one");
	laserDamageOne->FirstChildElement("cost")->Attribute("value", &m_nLaserDamageUpgradeCost[0]);
	laserDamageOne->FirstChildElement("damage")->Attribute("value", &m_nLaserDamage[1]);

	// Tier 2
	TiXmlElement* laserDamageTwo = laserDamage->FirstChildElement("tier_two");
	laserDamageTwo->FirstChildElement("cost")->Attribute("value", &m_nLaserDamageUpgradeCost[1]);
	laserDamageTwo->FirstChildElement("damage")->Attribute("value", &m_nLaserDamage[2]);

	// Tier 3
	TiXmlElement* laserDamageThree = laserDamage->FirstChildElement("tier_three");
	laserDamageThree->FirstChildElement("cost")->Attribute("value", &m_nLaserDamageUpgradeCost[2]);
	laserDamageThree->FirstChildElement("damage")->Attribute("value", &m_nLaserDamage[3]);

	// Range Upgrade Values
	TiXmlElement* laserRange = laser->FirstChildElement("range_upgrade");

	// Tier 1
	TiXmlElement* laserRangeOne = laserRange->FirstChildElement("tier_one");
	laserRangeOne->FirstChildElement("cost")->Attribute("value", &m_nLaserRangeUpgradeCost[0]);
	laserRangeOne->FirstChildElement("range")->Attribute("value", &m_nLaserRange[1]);

	// Tier 2
	TiXmlElement* laserRangeTwo = laserRange->FirstChildElement("tier_two");
	laserRangeTwo->FirstChildElement("cost")->Attribute("value", &m_nLaserRangeUpgradeCost[1]);
	laserRangeTwo->FirstChildElement("range")->Attribute("value", &m_nLaserRange[2]);

	// Tier 3
	TiXmlElement* laserRangeThree = laserRange->FirstChildElement("tier_three");
	laserRangeThree->FirstChildElement("cost")->Attribute("value", &m_nLaserRangeUpgradeCost[2]);
	laserRangeThree->FirstChildElement("range")->Attribute("value", &m_nLaserRange[3]);

#pragma endregion

	// Load Sounds
	SGD::AudioManager* pAudio = SGD::AudioManager::GetInstance();
	m_hSellSound = pAudio->LoadAudio("resource/audio/doorClose.wav");
	m_hInvalidSound = pAudio->LoadAudio("resource/audio/invalidPurchase.wav");
	m_hMachineGunShotSound = pAudio->LoadAudio("resource/audio/machineGunShot.wav");
	m_hMapleSyrupShotSound = pAudio->LoadAudio("resource/audio/mapleSyrupShot.wav");
	m_hHockeyStickSlashSound = pAudio->LoadAudio("resource/audio/hockeyStickSlash.wav");
}