Beispiel #1
0
	// -----------------------------------------------------------------------
	bool load (const string &sFilename)
	{
		FILE * f = fopen (sFilename.c_str(), "rt");
		if (f == NULL)
			return false;
		else 
			fclose (f);

		try
		{			
			CConfigFile cf;

			cf.load (sFilename);

			// Out
			CConfigFile::CVar &cvOutputIGDir = cf.getVar("OutputIGDir");
			OutputIGDir = cvOutputIGDir.asString();

			// In
			CConfigFile::CVar &cvInputIGDir = cf.getVar("InputIGDir");
			InputIGDir = cvInputIGDir.asString();

			CConfigFile::CVar &cvCellSize = cf.getVar("CellSize");
			CellSize = cvCellSize.asFloat();

			CConfigFile::CVar &cvHeightMapFile1 = cf.getVar("HeightMapFile1");
			HeightMapFile1 = cvHeightMapFile1.asString();

			CConfigFile::CVar &cvZFactor1 = cf.getVar("ZFactor1");
			ZFactor1 = cvZFactor1.asFloat();

			CConfigFile::CVar &cvHeightMapFile2 = cf.getVar("HeightMapFile2");
			HeightMapFile2 = cvHeightMapFile2.asString();

			CConfigFile::CVar &cvZFactor2 = cf.getVar("ZFactor2");
			ZFactor2 = cvZFactor2.asFloat();

			CConfigFile::CVar &cvLandFile = cf.getVar("LandFile");
			LandFile = cvLandFile.asString();
		}
		catch (const EConfigFile &e)
		{
			string sTmp = string("ERROR : Error in config file : ") + e.what() + "\n";
			outString (sTmp);
			return false;
		}
		return true;
	}
Beispiel #2
0
void LoadKeyCfg ()
{
	// Path of the dll
	HMODULE hModule = hInstance;
	if (hModule)
	{
		char sModulePath[256];
		int res=GetModuleFileName(hModule, sModulePath, 256);
		if (res)
		{
			// split path
			char drive[256];
			char dir[256];
			_splitpath (sModulePath, drive, dir, NULL, NULL);

			// Make a new path
			char cgfPath[256];
			_makepath (cgfPath, drive, dir, "keys", ".cfg");

	
			CConfigFile cf;

			// Load and parse "test.txt" file
			cf.load (cgfPath);
			
			// For each keys
			for (uint key=0; key<KeyCounter; key++)
			{
				// go
				try
				{
					// Get the foo variable (suppose it's a string variable)
					CConfigFile::CVar &value= cf.getVar (PainterKeysName[key]);

					// Get value
					PainterKeys[key]=value.asInt ();
				}
				catch (EConfigFile &e)
				{
					// Something goes wrong... catch that
					const char* what=e.what();
				}
			}
		}
	}
}
Beispiel #3
0
	bool loadFromCfg (const string &filename)
	{
		FileName = filename;
		FILE * f = fopen (filename.c_str(), "rt");
		if (f == NULL)
			return false;
		else 
			fclose (f);
		
		
		try
		{			
			cf.load (filename);
			this->OutZoneDir = getStr ("OutZoneDir");
			this->OutIGDir = getStr ("OutIGDir");
			this->RefZoneDir = getStr ("RefZoneDir");
			this->RefIGDir = getStr ("RefIGDir");
			this->LigoBankDir = getStr ("LigoBankDir");
			this->TileBankFile = getStr ("TileBankFile");
			this->ColorMapFile = getStr ("ColorMapFile");
			this->HeightMapFile = getStr ("HeightMapFile1");
			this->ZFactor = getFloat ("ZFactor1");
			this->HeightMapFile2 = getStr ("HeightMapFile2");
			this->ZFactor2 = getFloat ("ZFactor2");
			this->Light = (uint8)getInt ("ZoneLight");
			this->CellSize = getFloat ("CellSize");
			this->Threshold = getFloat ("Threshold");
			this->ZoneRegionFile = getStr ("ZoneRegionFile");						
			this->ContinentFile = getStr("ContinentFile");			
			this->RefCMBDir = getStr("RefCMBDir");
			this->OutCMBDir = getStr("OutCMBDir");			
			this->AdditionnalIGInDir = getStr("AdditionnalIGInDir");
			this->AdditionnalIGOutDir = getStr("AdditionnalIGOutDir");
			this->ExportCollisions = getInt("ExportCollisions") != 0;						
			this->ExportAdditionnalIGs = getInt("ExportAdditionnalIGs") != 0;			
			this->DFNDir = getStr("DFNDir");
			this->ContinentsDir = getStr("ContinentsDir");
		}
		catch (EConfigFile &e)
		{
			string sTmp = string("ERROR : Error in config file : ") + e.what() + "\n";
			outString (sTmp);
			return false;
		}
		return true;
	}
Beispiel #4
0
void loadConfigFile ()
{
	FILE *fp = fopen ("client.cfg", "rt");
	if (fp == NULL)
	{
		createConfigFile();
	}
	else
	{
		fclose (fp);
	}

	ConfigFile.load ("client.cfg");

	// set internet simulation values
	CUdpSimSock::setSimValues (ConfigFile);

	ServerAddr = ConfigFile.getVar("ServerAddress").asString();

	ConnectionName = ConfigFile.getVar("ConnectionName").asString();

	if (ConnectionName.empty())
	{
		InfoLog->displayRawNL ("Please, enter a connection name");
		InfoLog->displayRawNL ("(only alphanumeric character limited to 30 character, no space)");
		InfoLog->displayRawNL ("For example enter your name and/or your location (ie: \"AceHome\"),");
		InfoLog->displayRawNL ("It'll be use to find your stat file easier:");
		char cn[128];
		if (fgets (cn, 127, stdin) == NULL)
		{
			exit ("Error during the keyboard scanning");
		}
		ConnectionName = cn;
		checkConnectionName ();
		ConfigFile.getVar ("ConnectionName").setAsString(ConnectionName);
		ConfigFile.save ();
	}
	else
	{
		checkConnectionName ();
	}
}
Beispiel #5
0
void	init()
{
	registerSerial3d();

	try
	{
#ifdef NL_OS_UNIX
	        std::string homeDir = getenv("HOME");
        	NLMISC::CPath::addSearchPath( homeDir + "/.nel");
#endif // NL_OS_UNIX

	        NLMISC::CPath::addSearchPath(NL_BIB_CFG);

		CConfigFile cf;
		uint			i;
	
		cf.load("build_ig_boxes.cfg");
	
		Output = getString(cf, "Output");
		// nlinfo("Output=%s", Output.c_str());

		CConfigFile::CVar &cvIGs = cf.getVar("IGs");
		for (i=0; i<cvIGs.size(); i++)
		{
			IGs.push_back(cvIGs.asString(i));
		}

		CConfigFile::CVar &cvPathes = cf.getVar("Pathes");
		for (i=0; i<cvPathes.size(); ++i)
		{
			nlinfo("Using search path %s", cvPathes.asString(i).c_str());
			CPath::addSearchPath(cvPathes.asString(i));
		}
	}
	catch (EConfigFile &e)
	{
		printf ("Problem in config file : %s\n", e.what ());
	}
}
///=========================================================
int main (int argc, char* argv[])
{
	// Filter addSearchPath
	NLMISC::createDebug();
	InfoLog->addNegativeFilter ("adding the path");

	TShapeMap shapeMap;

	// Check number of args
	if (argc<5)
	{
		// Help message
		printf ("zone_dependencies [properties.cfg] [firstZone.zone] [lastzone.zone] [output_dependencies.cfg]\n");
	}
	else
	{
		NL3D::registerSerial3d();
		// Light direction
		CVector lightDirection;

		// Config file handler
		try
		{
			// Read the properties file
			CConfigFile properties;
			
			// Load and parse the properties file
			properties.load (argv[1]);

			// Get the light direction
			CConfigFile::CVar &sun_direction = properties.getVar ("sun_direction");
			lightDirection.set (sun_direction.asFloat(0), sun_direction.asFloat(1), sun_direction.asFloat(2));
			lightDirection.normalize();


			// Get the search pathes
			CConfigFile::CVar &search_pathes = properties.getVar ("search_pathes");
			uint path;
			for (path = 0; path < (uint)search_pathes.size(); path++)
			{
				// Add to search path
				CPath::addSearchPath (search_pathes.asString(path));
			}
/*
			CConfigFile::CVar &ig_path = properties.getVar ("ig_path");
			NLMISC::CPath::addSearchPath(ig_path.asString(), true, true);

			CConfigFile::CVar &shapes_path = properties.getVar ("shapes_path");
			NLMISC::CPath::addSearchPath(shapes_path.asString(), true, true);
*/
			CConfigFile::CVar &compute_dependencies_with_igs = properties.getVar ("compute_dependencies_with_igs");
			bool computeDependenciesWithIgs = compute_dependencies_with_igs.asInt() != 0;								


			// Get the file extension
			string ext=getExt (argv[2]);

			// Get the file directory
			string dir=getDir (argv[2]);

			// Get output extension
			string outExt=getExt (argv[4]);

			// Get output directory
			string outDir=getDir (argv[4]);

			// Get the first and last name
			string firstName=getName (argv[2]);
			string lastName=getName (argv[3]);

			// Get the coordinates
			uint16 firstX, firstY;
			uint16 lastX, lastY;
			if (getZoneCoordByName (firstName.c_str(), firstX, firstY))
			{
				// Last zone
				if (getZoneCoordByName (lastName.c_str(), lastX, lastY))
				{
					// Take care
					if (lastX<firstX)
					{
						uint16 tmp=firstX;
						firstX=lastX;
						lastX=firstX;
					}
					if (lastY<firstY)
					{
						uint16 tmp=firstY;
						firstY=lastY;
						lastY=firstY;
					}

					// Min z
					float minZ=FLT_MAX;

					// Make a quad grid
					CQuadGrid<CZoneDescriptorBB>	quadGrid;
					quadGrid.create (256, 100);

					// The dependencies list
					vector< CZoneDependencies > dependencies;
					dependencies.resize ((lastX-firstX+1)*(lastY-firstY+1));

					// Ryzom specific: build bbox for villages
					TString2LightingBBox villagesBBox;					
					computeIGBBoxFromContinent(properties, shapeMap, villagesBBox);		


					// Insert each zone in the quad tree
					sint y, x;
					for (y=firstY; y<=lastY; y++)
					for (x=firstX; x<=lastX; x++)
					{
						

						// Progress
						progress ("Build bounding boxes", (float)(x+y*lastX)/(float)(lastX*lastY));

						// Make a zone file name
						string zoneName;
						getZoneNameByCoord (x, y, zoneName);

						// Open the file
						CIFile file;
						if (file.open (dir+zoneName+ext))
						{							
							// The zone
							CZone zone;

							try
							{
								// Serial the zone
								file.serial (zone);

								/// get bbox from the ig of this zone
								CLightingBBox igBBox;								
								if (computeDependenciesWithIgs)
								{
									computeZoneIGBBox(zoneName.c_str(), igBBox, shapeMap, villagesBBox);
								}								
								// Create a zone descriptor
								

								
								NLMISC::CAABBox zoneBox;
								zoneBox.setCenter(zone.getZoneBB().getCenter());
								zoneBox.setHalfSize(zone.getZoneBB().getHalfSize());

								CLightingBBox zoneLBox;
								zoneLBox.OccludingBox = zoneLBox.ReceivingBox = zoneBox; // can't be void
								zoneLBox.makeUnion(igBBox);								
								nlassert(!zoneLBox.ReceivingBox.IsVoid);
								//
								CZoneDescriptorBB zoneDesc;
								zoneDesc.X=x;
								zoneDesc.Y=y;
								zoneDesc.BBox=zoneLBox.ReceivingBox.Box;
								//
								if (!zoneLBox.OccludingBox.IsVoid)
								{
									quadGrid.insert (zoneLBox.ReceivingBox.Box.getMin(), zoneLBox.ReceivingBox.Box.getMax(), zoneDesc);
								}
																								
								// Insert in the dependencies
								// Index 
								uint index=(x-firstX)+(y-firstY)*(lastX-firstX+1);
								

								// Loaded
								dependencies[index].Loaded=true;
								dependencies[index].X=x;
								dependencies[index].Y=y;
								dependencies[index].BBox=zoneLBox.OccludingBox.Box;

								// ZMin
								float newZ=zoneLBox.ReceivingBox.Box.getMin().z;
								if (newZ<minZ)
									minZ=newZ;
							}
							catch (Exception& e)
							{
								// Error handling
								nlwarning ("ERROR in file %s, %s", (dir+zoneName+ext).c_str(), e.what ());
							}
						}
					}

					// Now select each zone in others and make a depencies list
					for (y=firstY; y<=lastY; y++)
					for (x=firstX; x<=lastX; x++)
					{
						// Progress
						progress ("Compute dependencies", (float)(x+y*lastX)/(float)(lastX*lastY));

						// Index 
						uint index=(x-firstX)+(y-firstY)*(lastX-firstX+1);

						// Loaded ?
						if (dependencies[index].Loaded)
						{
							// Min max vectors
							CVector vMin (dependencies[index].BBox.getMin());
							CVector vMax (dependencies[index].BBox.getMax());

							// Make a corner array 
							CVector corners[4] = 
							{
								CVector (vMin.x, vMin.y, vMax.z), CVector (vMax.x, vMin.y, vMax.z), 
								CVector (vMax.x, vMax.y, vMax.z), CVector (vMin.x, vMax.y, vMax.z)
							};

							// Extended bbox
							CAABBox	bBox=dependencies[index].BBox.getAABBox();

							// For each corner
							uint corner;
							for (corner=0; corner<4; corner++)
							{
								// Target position
								CVector target;
								if (lightDirection.z!=0)
								{
									// Not horizontal target
									target=corners[corner]+(lightDirection*((minZ-corners[corner].z)/lightDirection.z));
								}
								else
								{
									// Horizontal target, select 500 meters around.
									target=(500*lightDirection)+corners[corner];
								}

								// Extend the bbox
								bBox.extend (target);
							}

							// Clear quad tree selection
							quadGrid.clearSelection ();

							// Select
							quadGrid.select (bBox.getMin(), bBox.getMax());

							// Check selection
							CQuadGrid<CZoneDescriptorBB>::CIterator it=quadGrid.begin();
							while (it!=quadGrid.end())
							{
								// Index 
								uint targetIndex=((*it).X-firstX)+((*it).Y-firstY)*(lastX-firstX+1);

								// Not the same
								if (targetIndex!=index)
								{
									// Target min z
									float targetMinZ=dependencies[targetIndex].BBox.getMin().z;
									if (targetMinZ<vMax.z)
									{
										// Min z inf to max z ?
										// Target optimized bbox
										CAABBox	bBoxOptimized=dependencies[index].BBox.getAABBox();

										// For each corner
										for (corner=0; corner<4; corner++)
										{
											// Target position
											CVector target;
											if (lightDirection.z!=0)
											{
												// Not horizontal target
												target=corners[corner]+(lightDirection*((targetMinZ-corners[corner].z)
													/lightDirection.z));
											}
											else
											{
												// Horizontal target, select 500 meters around.
												target=(500*lightDirection)+corners[corner];
											}

											// Extend the bbox
											bBoxOptimized.extend (target);
										}

										// Check it more presisly
										//if ((*it).BBox.intersect (bBoxOptimized))
										if ((*it).BBox.intersect (bBox))
										{
											// Insert in the set
											dependencies[targetIndex].Dependences.insert (CZoneDependenciesValue (x, y));
										}
									}
								}

								// Next selected
								it++;
							}
						}
					}

					// For each zone
					for (y=firstY; y<=lastY; y++)
					for (x=firstX; x<=lastX; x++)
					{
						// Progress
						progress ("Save depend files", (float)(x+y*lastX)/(float)(lastX*lastY));

						// Index 
						uint index=(x-firstX)+(y-firstY)*(lastX-firstX+1);

						// Loaded ?
						if (dependencies[index].Loaded)
						{
							// Make a file name
							string outputFileName;
							getZoneNameByCoord(x, y, outputFileName);
							outputFileName=outDir+outputFileName+outExt;

							// Write the dependencies file
							FILE *outputFile;
							if ((outputFile=fopen (toLower (outputFileName).c_str(), "w")))
							{
								// Add a dependency entry
								fprintf (outputFile, "dependencies =\n{\n");

								// Add dependent zones
								set<CZoneDependenciesValue>::iterator ite=dependencies[index].Dependences.begin();
								while (ite!=dependencies[index].Dependences.end())
								{
									// Name of the dependent zone
									std::string zoneName;
									getZoneNameByCoord(ite->first, ite->second, zoneName);

									// Write it
									string message="\t\""+zoneName+"\"";
									fprintf (outputFile, "%s", toLower (message).c_str());

									// Next ite;
									ite++;
									if (ite!=dependencies[index].Dependences.end())
										fprintf (outputFile, ",\n");
								}

								// Close the variable
								fprintf (outputFile, "\n};\n\n");
							}
							else
							{
								nlwarning ("ERROR can't open %s for writing.\n", outputFileName.c_str());
							}

							// Close the file
							fclose (outputFile);
						}
					}

				}
				else
				{
					// Not valid
					nlwarning ("ERROR %s is not a valid zone name.\n", lastName.c_str());
				}
			}
			else
			{
				// Not valid
				nlwarning ("ERROR %s is not a valid zone name.\n", firstName.c_str());
			}
		}
		catch (Exception &ee)
		{
			nlwarning ("ERROR %s\n", ee.what());
		}
	}

	return 0;
}
Beispiel #7
0
//-----------------------------------------------
//	MAIN
//
//-----------------------------------------------
int main( int argc, char ** argv )
{
	// get the output filename
	if( argc > 1 )
	{
		displayHelp();
		return EXIT_FAILURE;
	}
	
	// load the cfg
	CConfigFile configFile;
	string configFileName = "make_alias_file.cfg";
	if(!CFile::fileExists(configFileName))
	{
		nlwarning("Config file %s not found",configFileName.c_str());
		return 1;
	}
	configFile.load(configFileName);

	
	// read the sheet paths
	vector<string> sheetPaths;
	try
	{
		CConfigFile::CVar& cvSheetPaths = configFile.getVar("SheetPaths");
		sint i;
		for( i = 0; i< (sint)cvSheetPaths.size(); ++i)
		{
			sheetPaths.push_back( cvSheetPaths.asString(i) );
		}
	}
	catch(const EUnknownVar &) 
	{
		nlwarning("var 'SheetPaths' not found");
	}

	// add the sheet paths
	cout<<"adding the sheet paths ..."<<endl;
	vector<string>::iterator itPath;
	for( itPath = sheetPaths.begin(); itPath != sheetPaths.end(); ++itPath )
	{
		CPath::addSearchPath(*itPath,true,false);
	}

	// read the name that will be used for packed file
	string aliasFilename = "alias.packed_sheets";
	try
	{
		CConfigFile::CVar &cvAliasFilename = configFile.getVar("AliasFilename");
		aliasFilename = cvAliasFilename.asString();
	}
	catch(const EUnknownVar &) 
	{
		nlwarning("var 'AliasFilename' not found");
	}
	
	// read the extensions list of sheets to read
	vector<string> extensions;
	try
	{
		CConfigFile::CVar& cvExtensions = configFile.getVar("Extensions");
		sint i;
		for( i = 0; i< (sint)cvExtensions.size(); ++i)
		{
			extensions.push_back( cvExtensions.asString(i) );
		}
	}
	catch(const EUnknownVar &) 
	{
		nlwarning("var 'Extensions' not found");
	}

	// load form and create packed sheets
	cout<<"reading the sheets ..."<<endl;
	map<CSheetId, CSheet> sheetMap;
	bool updatePackedSheet = true;
	createDebug(); // needed to init WarningLog
	loadForm (extensions, aliasFilename, sheetMap, updatePackedSheet);
	cout<<"finished."<<endl;

	// display the content of the map
	/*
	map<CSheetId, CSheet>::iterator itAlias;
	for( itAlias = sheetMap.begin(); itAlias != sheetMap.end(); ++itAlias )
	{
		nlinfo("sheet %s  alias = %s",(*itAlias).first.toString().c_str(),(*itAlias).second.Alias.c_str());
	}
	*/

	return EXIT_SUCCESS;

} // main //
Beispiel #8
0
BOOL CData_mirrorApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

	try
	{
		// Get the module
		CConfigFile	cf;
		string exePath = GetCommandLine ();
		if (exePath.size()>0)
		{
			if (exePath[0] == '\"')
			{
				uint end=exePath.find ('\"', 1);
				if (end != string::npos)
				{
					exePath = exePath.substr (1, end-1);
				}
				else
				{
					nlassert (0);	// no!
				}
			}
			else
			{
				uint end=exePath.find (' ', 1);
				exePath = exePath.substr (0, end);
			}
		}

		// Register it
		string temp = "\"" + exePath;
		temp = temp+"\" \"%1\"";
		nlverify (RegisterDirectoryAppCommand ("NeLDataMirror", "&Sync Mirror", temp.c_str ()));

		// Get the app directory
		string path = NLMISC::CFile::getPath (exePath)+"config.cfg";

		cf.load (path);
		MainDirectory = cf.getVar ("MainDirectory").asString ();
		MainDirectory = strlwr (CPath::standardizePath (MainDirectory));
		
		MirrorDirectory = cf.getVar ("MirrorDirectory").asString ();
		MirrorDirectory = strlwr (CPath::standardizePath (MirrorDirectory));
		
		LogDirectory = cf.getVar ("LogDirectory").asString ();
		LogDirectory = strlwr (CPath::standardizePath (LogDirectory));
		
		IgnoreDirectory = cf.getVar ("IgnoreDirectory").asString ();
		IgnoreDirectory = strlwr (CPath::standardizePath (IgnoreDirectory));
		if (IgnoreDirectory.empty())
			IgnoreDirectory = MainDirectory;

		string sBinaryCompare = cf.getVar ("BinaryCompare").asString ();
		sBinaryCompare = strlwr (sBinaryCompare);
		BinaryCompare = false;
		if ((sBinaryCompare == "true") || (sBinaryCompare=="1"))
			BinaryCompare = true;

		CurrentDir = m_lpCmdLine;
		// Remove 
		if (CurrentDir.size ()>=2)
		{
			if (CurrentDir[0] == '"')
				CurrentDir = CurrentDir.substr (1, CurrentDir.size ()-1);
			if (CurrentDir[CurrentDir.size ()-1] == '"')
				CurrentDir = CurrentDir.substr (0, CurrentDir.size ()-1);
		}
		if (CurrentDir.empty ())
			return FALSE;


		// File or directory ?
		bool directory;
		if (NLMISC::CFile::isDirectory (CurrentDir))
		{
			directory = true;
			CurrentDir = strlwr (CPath::standardizePath (CurrentDir));
		}
		else if (NLMISC::CFile::fileExists (CurrentDir))
		{
			directory = false;
			CurrentDir = strlwr (CPath::standardizePath (NLMISC::CFile::getPath (CurrentDir)));
		}
		else
		{
			MessageBox (NULL, (CurrentDir+" is not a directory nor a file.").c_str (), "NeL Data Mirror", MB_OK|MB_ICONEXCLAMATION);
			return FALSE;
		}

		// Get relative dir
		if (CurrentDir.substr (0, MainDirectory.size ()) == MainDirectory)
		{
			CurrentDir = CurrentDir.substr (MainDirectory.size (), CurrentDir.size () - MainDirectory.size ());
		}
		else
		{
			if (CurrentDir.substr (0, MirrorDirectory.size ()) == MirrorDirectory)
			{
				CurrentDir = CurrentDir.substr (MirrorDirectory.size (), CurrentDir.size () - MirrorDirectory.size ());
			}
			else
			{
				MessageBox (NULL, (CurrentDir+" is not a sub directory of "+MainDirectory+" or "+MirrorDirectory).c_str (), 
							"NeL Data Mirror", MB_OK|MB_ICONEXCLAMATION);
				return FALSE;
			}
		}

		/*
		if (CurrentDir.substr (0, MainDirectory.size ()) != MainDirectory)
		{
			MessageBox (NULL, (CurrentDir+" is not a sub directory of "+MainDirectory).c_str (), "NeL Data Mirror", MB_OK|MB_ICONEXCLAMATION);
			return FALSE;
		}
		CurrentDir = CurrentDir.substr (MainDirectory.size (), CurrentDir.size () - MainDirectory.size ());
		*/

		// Load ignore list
		FILE *file = fopen ((IgnoreDirectory+"ignore_list.txt").c_str (), "r");
		if (file)
		{
			char line[512];
			while (fgets (line, 512, file))
			{
				// Remove last back
				int n = strlen (line);
				if (n && (line[n-1] == '\n'))
					line[n-1] = 0;
				IgnoreFiles.insert (line);
			}
		}
	}
	catch (Exception &e)
	{
		MessageBox (NULL, e.what (), "NeL Data Mirror", MB_OK|MB_ICONEXCLAMATION);
	}

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	CData_mirrorDlg dlg;
	m_pMainWnd = &dlg;
	int nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Beispiel #9
0
void CBug_reportDlg::OnClear()
{
	set(IDC_LANGUAGE, "english");
	set(IDC_SUBJECT, "");
	set(IDC_CLIENTVERSION, "");
	set(IDC_SHARDNAME, "Beta");
	set(IDC_SHARDVERSION, "");
	set(IDC_SKU, "Beta2");
	set(IDC_CLASS, "");
	set(IDC_CATEGORY, "");
	set(IDC_FREQUENCY, "Once");
	set(IDC_DESCRIPTION, "");
	set(IDC_REPRODUCESTEPS, "");
	set(IDC_QUEUE, "ryzom");
	set(IDC_ATTACHEDFILE, "");

/*
/////// TEMP pre fill entries
	set(IDC_LANGUAGE, "english");
	set(IDC_SUBJECT, "subject");
	set(IDC_CLIENTVERSION, "0.8.0.360");
	set(IDC_SHARDNAME, "OFFLINE");
	set(IDC_SHARDVERSION, "0.8.0.360");
	set(IDC_SKU, "Beta2");
	set(IDC_CLASS, "A");
	set(IDC_CATEGORY, "Hardware");
	set(IDC_FREQUENCY, "always");
	set(IDC_DESCRIPTION, "description");
	set(IDC_REPRODUCESTEPS, "reproduction steps");
	set(IDC_QUEUE, "zz-ryzom-dummy");
	set(IDC_ATTACHEDFILE, "C:\\Documents and Settings\\nouveau\\Desktop\\pez.bmp");
/////// END TEMP
*/

	if (!NLMISC::CFile::fileExists("bug_report.cfg"))
	{
		createConfigFile ();
	}

	try
	{
		// try to get the client version from the client config file
		CConfigFile cf;
		cf.load ("client.cfg");

		set(IDC_CLIENTVERSION, cf.getVar ("ClientVersion").asString ());
		set(IDC_SHARDVERSION, cf.getVar ("ClientVersion").asString ());
	}
	catch (Exception &)
	{
		nlwarning ("Can't find ClientVersion variable in client.cfg");
	}

	try
	{
		CConfigFile cf;
		cf.load ("bug_report.cfg");

		set(IDC_REQUESTOR, cf.getVar ("FromEMail").asString ());

		SMTPServer = cf.getVar ("SMTPServer").asString ();
		ToEmail = cf.getVar ("ToEMail").asString ();
	}
	catch (Exception &e)
	{
		MessageBox (e.what(), "Error");
		exit (0);
	}

	setDumpFilename("");

	setFocus (IDC_SUBJECT);
}
void regsiterOVPath ()
{
// must test it first, because NL_DEBUG_FAST and NL_DEBUG are declared at same time.
//#ifdef NL_DEBUG_FAST
//	HMODULE hModule = GetModuleHandle("object_viewer_dll_df.dll");
#if defined (NL_DEBUG)
	HMODULE hModule = GetModuleHandle("object_viewer_dll_d.dll");
//#elif defined (NL_RELEASE_DEBUG)
//	HMODULE hModule = GetModuleHandle("object_viewer_dll_rd.dll");
#else
	HMODULE hModule = GetModuleHandle("object_viewer_dll_r.dll");
#endif
	if (!hModule) { ::MessageBox(NULL, "'hModule' failed at '" __FUNCTION__ "' in file '" __FILE__ " on line " NL_MACRO_TO_STR(__LINE__), "NeL Export", MB_OK | MB_ICONERROR); return; }
	char sModulePath[256];
	int res = GetModuleFileName(hModule, sModulePath, 256);
	if (!res) { ::MessageBox(NULL, "'res' failed at '" __FUNCTION__ "' in file '" __FILE__ " on line " NL_MACRO_TO_STR(__LINE__), "NeL Export", MB_OK | MB_ICONERROR); return; }
	char SDrive[512];
	char SDir[512];
	_splitpath (sModulePath, SDrive, SDir, NULL, NULL);
	_makepath (sModulePath, SDrive, SDir, "object_viewer", ".cfg");

	// Load the config file
	CConfigFile cf;
	cf.load (sModulePath);

	try
	{
		// Add search pathes
		CConfigFile::CVar &search_pathes = cf.getVar ("search_pathes");
		for (uint i=0; i<(uint)search_pathes.size(); i++)
			CPath::addSearchPath (search_pathes.asString(i));
	}
	catch(EUnknownVar &)
	{}

	try
	{
		// Add recusrive search pathes
		CConfigFile::CVar &recursive_search_pathes = cf.getVar ("recursive_search_pathes");
		for (uint i=0; i<(uint)recursive_search_pathes.size(); i++)
			CPath::addSearchPath (recursive_search_pathes.asString(i), true, false);
	}
	catch(EUnknownVar &)
	{}

	// Add extension remapping
	try
	{
		CConfigFile::CVar &extensions_remapping = cf.getVar ("extensions_remapping");
		if (extensions_remapping.size()%2 != 0)
		{
			nlwarning ("extensions_remapping must have a multiple of 2 entries (ex: extensions_remapping={\"dds\",\"tga\"};)");
		}
		else
		{
			for (uint i=0; i<(uint)extensions_remapping.size(); i+=2)
				CPath::remapExtension(extensions_remapping.asString(i), extensions_remapping.asString(i+1), true);
		}
	}
	catch (EUnknownVar &)
	{
	}
}
Beispiel #11
0
//******************************************************************************************************
BOOL CDialogFlags::OnInitDialog()
{
    CDialog::OnInitDialog();

    HRSRC rsc = FindResource(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_ENTITY_ICONS_TGA), "TGA");
    if (rsc != NULL)
    {
        NLMISC::CBitmap bm;
        if (_Plugin->getPluginAccess()->buildNLBitmapFromTGARsc(rsc, AfxGetInstanceHandle(), bm))
        {
            m_EntityColorList.setIconBitmap(bm, ENTITY_ICON_SIZE);
        }
    }


    DownloadCtrl.SetRange(512, 32768);
    DetailsDistanceCtrl.SetRange(0, 100);

    for(uint k = 0; k < EntityDisplayModeCount; ++k)
    {
        loadEntityDisplayInfoToRegistry(_EntityDisplayInfo[k], ENTITY_DISPLAY_MODE_REG_ID[k]);
    }

    setCurrentEntityDisplayMode(EntityType);

    updateCtrlGrayedState();

    ((CComboBox *) GetDlgItem(IDC_DISPLAY_MODE_COMBO))->SetCurSel(0);

    ((CButton *) GetDlgItem(IDC_HP_DOWN))->SetCheck(1);
    ((CButton *) GetDlgItem(IDC_CLOSE_UP_SHOW_TYPE))->SetCheck(1);
    ((CButton *) GetDlgItem(IDC_CLOSE_UP_SHOW_MODE))->SetCheck(1);

    ((CButton *) GetDlgItem(IDC_CLOSE_UP_SHOW_HP))->SetCheck(1);

    ::CRect shardListRect;
    GetDlgItem(IDC_SHARD_LIST_PLACEMENT)->GetWindowRect(shardListRect);
    ScreenToClient(&shardListRect);
    ShardCtrl.create(WS_CHILD|WS_TABSTOP, shardListRect, this, 0, REGKEY_BASE_PATH "\\shard_list", 10);
    ShardCtrl.ShowWindow (SW_SHOW);
    CFont* font = GetFont ();
    ShardCtrl.SetFont(font);
    ShardCtrl.refreshStrings();
    //ShardCtrl.setFocus();
    if (ShardCtrl.getCount() != 0)
    {
        ShardCtrl.setCurSel(0);
    }

    CConfigFile ConfigFile;
    ConfigFile.load ("world_editor_plugin.cfg");
    CConfigFile::CVar *var = ConfigFile.getVarPtr("MOSHost");
    if (var)
    {
        ShardCtrl.pushString(var->asString().c_str());
        ShardCtrl.setCurSel(var->asString());
    }

    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
Beispiel #12
0
int extractBotNames(int argc, char *argv[])
{
	//-------------------------------------------------------------------
	// read the parameters
	for (int i=2; i<argc; ++i)
	{
		string s = argv[i];
		if (s == "-r")
		{
			// active remove mode
			RemoveOlds = true;
		}
		else
		{
			nlwarning("Unknow option '%s'", argv[i]);
			return -1;
		}
	}

	//-------------------------------------------------------------------
	// read the configuration file
	CConfigFile	cf;

	cf.load("bin/translation_tools.cfg");

	//-------------------------------------------------------------------
	// read the vars
	CConfigFile::CVar &paths = cf.getVar("Paths");
	CConfigFile::CVar &filtersVar = cf.getVar("Filters");
	CConfigFile::CVar &ligoClassFile= cf.getVar("LigoClassFile");
	CConfigFile::CVar &georgesPaths= cf.getVar("GeorgesPaths");
	CConfigFile::CVar &pathNoRecurse= cf.getVar("PathsNoRecurse");
	CConfigFile::CVar &workBotNamesFile= cf.getVar("WorkBotNamesFile");
	CConfigFile::CVar &transBotNamesFile= cf.getVar("TransBotNamesFile");
	CConfigFile::CVar &workTitleFile= cf.getVar("WorkTitleFile");

	for (uint i=0; i<paths.size(); ++i)
	{
		CPath::addSearchPath(paths.asString(i), true, false);
	}
	for (uint i=0; i<pathNoRecurse.size(); ++i)
	{
		CPath::addSearchPath(pathNoRecurse.asString(i), false, false);
	}

	for (uint i=0; i<filtersVar.size(); ++i)
	{
		Filters.push_back(filtersVar.asString(i));
	}


	//-------------------------------------------------------------------
	// init the sheets
	CSheetId::init(false);
	const string PACKED_SHEETS_NAME = "bin/translation_tools_creature.packed_sheets";
	loadForm("creature", PACKED_SHEETS_NAME, Creatures, false, false);

	if (Creatures.empty())
	{
		for (uint i=0;i<georgesPaths.size();++i)
			CPath::addSearchPath(georgesPaths.asString(i).c_str(), true, false);

		loadForm("creature", PACKED_SHEETS_NAME, Creatures, true);
	}


	//-------------------------------------------------------------------
	// init ligo config
	string ligoPath = CPath::lookup(ligoClassFile.asString(), true, true);
	LigoConfig.readPrimitiveClass(ligoPath.c_str(), false);
	NLLIGO::Register();

	CPrimitiveContext::instance().CurrentLigoConfig = &LigoConfig;

	//-------------------------------------------------------------------
	// ok, ready the the real work,
	// first, read the primitives files and parse the primitives
	vector<string>	files;
	CPath::getFileList("primitive", files);

	for (uint i=0; i<files.size(); ++i)
	{
		string pathName = files[i];
		pathName = CPath::lookup(pathName);

		// check filters
		uint j=0;
		for (j=0; j<Filters.size(); ++j)
		{
			if (pathName.find(Filters[j]) != string::npos)
				break;
		}
		if (j != Filters.size())
			// skip this file
			continue;

		nlinfo("Loading file '%s'...", CFile::getFilename(pathName).c_str());
		
		CPrimitives primDoc;
		CPrimitiveContext::instance().CurrentPrimitive = &primDoc;
		loadXmlPrimitiveFile(primDoc, pathName, LigoConfig);

		// now parse the file

		// look for group template
		{
			TPrimitiveClassPredicate pred("group_template_npc");
			TPrimitiveSet result;

			CPrimitiveSet<TPrimitiveClassPredicate> ps;
			ps.buildSet(primDoc.RootNode, pred, result);

			for (uint i=0; i<result.size(); ++i)
			{
				string name;
				string countStr;
				string sheetStr;
				result[i]->getPropertyByName("name", name);
				result[i]->getPropertyByName("count", countStr);
				result[i]->getPropertyByName("bot_sheet_look", sheetStr);

				uint32 count;
				NLMISC::fromString(countStr, count);

				if (count != 0)
				{
					if (sheetStr.empty())
					{
						nlwarning("In '%s', empty sheet !", buildPrimPath(result[i]).c_str());
					}
					else
					{
						addGenericName(removeAndStoreFunction(name), sheetStr);
					}
				}
			}
		}
		// look for bot template
		{
			TPrimitiveClassPredicate pred("bot_template_npc");
			TPrimitiveSet result;

			CPrimitiveSet<TPrimitiveClassPredicate> ps;
			ps.buildSet(primDoc.RootNode, pred, result);

			for (uint i=0; i<result.size(); ++i)
			{
				string name;
				string sheetStr;
				result[i]->getPropertyByName("name", name);
				result[i]->getPropertyByName("sheet_look", sheetStr);

				if (sheetStr.empty())
				{
					// take the sheet in the parent
					result[i]->getParent()->getPropertyByName("bot_sheet_look", sheetStr);
				}

				if (sheetStr.empty())
				{
					nlwarning("In '%s', empty sheet !", buildPrimPath(result[i]).c_str());
				}
				else
				{
					addGenericName(removeAndStoreFunction(name), sheetStr);
				}
			}
		}
		// look for npc_group 
		{
			TPrimitiveClassPredicate pred("npc_group");
			TPrimitiveSet result;

			CPrimitiveSet<TPrimitiveClassPredicate> ps;
			ps.buildSet(primDoc.RootNode, pred, result);

			for (uint i=0; i<result.size(); ++i)
			{
				string name;
				string countStr;
				string sheetStr;
				result[i]->getPropertyByName("name", name);
				result[i]->getPropertyByName("count", countStr);
				result[i]->getPropertyByName("bot_sheet_client", sheetStr);

				uint32 count;
				NLMISC::fromString(countStr, count);

				if (count > 0 && sheetStr.empty())
				{
					nlwarning("In '%s', empty sheet !", buildPrimPath(result[i]).c_str());
				}
				else
				{
					if (count == 1)
					{
						addSimpleName(removeAndStoreFunction(name), sheetStr);
					}
					else if (count > 1)
					{
						addGenericName(removeAndStoreFunction(name), sheetStr);
					}
				}
			}
		}
		// look for bot 
		{
			TPrimitiveClassPredicate pred("npc_bot");
			TPrimitiveSet result;

			CPrimitiveSet<TPrimitiveClassPredicate> ps;
			ps.buildSet(primDoc.RootNode, pred, result);

			for (uint i=0; i<result.size(); ++i)
			{
				string name;
				string sheetStr;
				result[i]->getPropertyByName("name", name);
				result[i]->getPropertyByName("sheet_client", sheetStr);

				if (sheetStr.empty())
				{
					// take the sheet in the parent
					result[i]->getParent()->getPropertyByName("bot_sheet_client", sheetStr);
				}

				if (sheetStr.empty())
				{
					nlwarning("In '%s', empty sheet !", buildPrimPath(result[i]).c_str());
				}
				else
				{
					TEntryInfo ei;
					addSimpleName(removeAndStoreFunction(name), sheetStr);
				}
			}
		}
	}

	//-------------------------------------------------------------------
	// step 2 : load the reference file

	nlinfo("Looking for missing translation:");

	TWorksheet			botNames;
	loadExcelSheet(workBotNamesFile.asString(), botNames, true);
	TWorksheet			transBotNames;
	loadExcelSheet(transBotNamesFile.asString(), transBotNames, true);

	TWorksheet			fcts;
	loadExcelSheet(workTitleFile.asString(), fcts, true);


	// add missing element

	uint	nbAddSimpleName = 0;
	uint	nbAddFunction = 0;
	uint	nbAddGenericName = 0;

	uint botIdCol;
	nlverify(botNames.findId(botIdCol));
	uint transIdCol;
	nlverify(transBotNames.findId(transIdCol));
	uint	fctsIdCol;
	nlverify(fcts.findId(fctsIdCol));

	// special treatment to add the sheet_name col
	{
		uint sheetCol;
		if (!botNames.findCol(ucstring("sheet_name"), sheetCol))
		{
			botNames.insertColumn(botNames.ColCount);
			botNames.setData(0, botNames.ColCount-1, ucstring("sheet_name"));
		}
		
		if (!transBotNames.findCol(ucstring("sheet_name"), sheetCol))
		{
			transBotNames.insertColumn(transBotNames.ColCount);
			transBotNames.setData(0, transBotNames.ColCount-1, ucstring("sheet_name"));
		}
	}
	// 1 - simple names
	{
		nlinfo("  Simple names...");


		map<string, TEntryInfo>::iterator first(SimpleNames.begin()), last(SimpleNames.end());
		for (; first != last; ++first)
		{
			uint rowIdx;
			if (!botNames.findRow(botIdCol, first->first, rowIdx))
			{
				// we need to add the entry
				rowIdx = botNames.size();
				botNames.resize(botNames.size()+1);

				botNames.setData(rowIdx, ucstring("bot name"), first->first);
				botNames.setData(rowIdx, ucstring("translated name"), first->first);
				botNames.setData(rowIdx, ucstring("sheet_name"), first->second.SheetName);

				nbAddSimpleName++;
			}
			else
			{
				// set/update the sheet name info
				// try to restore the existing translation
				uint transRowIdx;
				if (transBotNames.findRow(transIdCol, first->first, transRowIdx))
				{
					ucstring wkBotName = botNames.getData(rowIdx, ucstring("bot name"));
					ucstring wkSheetName = botNames.getData(rowIdx, ucstring("sheet_name"));								
					ucstring wkTranslationName = botNames.getData(rowIdx, ucstring("translated name"));
					ucstring ucWkHash;
					uint64 hash = CI18N::makeHash(wkBotName + wkTranslationName +wkSheetName);						
					CI18N::hashToUCString(hash, ucWkHash);
					ucstring trUcHash = transBotNames[transRowIdx][0];
					bool isWkTranslationNameAGroupName = wkTranslationName.find(ucstring("$")) != ucstring::npos;
					bool hashIsValide = std::equal(ucWkHash.begin(), ucWkHash.end(), trUcHash.begin()+1);
					// Hash is equal get the translation
					if (hashIsValide && !isWkTranslationNameAGroupName)
					{
						wkTranslationName = transBotNames.getData(transRowIdx, ucstring("translated name"));
						wkSheetName = transBotNames.getData(transRowIdx, ucstring("sheet_name"));
						botNames.setData(rowIdx, ucstring("translated name"), wkTranslationName);
						botNames.setData(rowIdx, ucstring("sheet_name"), wkSheetName);
						hash = CI18N::makeHash(wkBotName + wkTranslationName + wkSheetName);						
  						// update the hash code
						CI18N::hashToUCString(hash, transBotNames[transRowIdx][0]);							
					}
					// bots_name.txt has been manually changed. We trust what the Level Designer has done. We don't destroy is work.
					// or it is a simple 
					else
					{
						//use the "translated name" of the manually changed  work/bot_name.txt
						botNames.setData(rowIdx, ucstring("translated name"), wkTranslationName);
						botNames.setData(rowIdx, ucstring("sheet_name"), wkSheetName);	
					}					
				}
			}
		}
	}

	// 2 - generic names
	
	{
		nlinfo("  Generic names...");

		set<string>::iterator first(GenericNames.begin()), last(GenericNames.end());
		for (; first != last; ++first)
		{
			string gnName = "gn_" + cleanupName(*first);

			ucstring fctsTitleId;
			ucstring fctsName;
			// add or modify the bot names
			uint rowIdx;
			if (!botNames.findRow(botIdCol, *first, rowIdx)) 
			{
				// we need to add the entry
				rowIdx = botNames.size();
				botNames.resize(botNames.size()+1);

				botNames.setData(rowIdx, ucstring("bot name"), *first);
				botNames.setData(rowIdx, ucstring("translated name"), ucstring("$") + gnName + "$");
				botNames.setData(rowIdx, ucstring("sheet_name"), ucstring());
				fctsTitleId = gnName;
				fctsName = *first;

				nbAddSimpleName++;
			}
			else
			{
				// look in the translated table to remember the translated name to write it in the string file
				ucstring wkBotName = botNames.getData(rowIdx, ucstring("bot name"));				
				ucstring wkTranslationName = botNames.getData(rowIdx, ucstring("translated name"));
				ucstring wkSheetName = botNames.getData(rowIdx, ucstring("sheet_name"));

				
				nlinfo("Bot name:%s\n",wkBotName.toString().c_str());
				bool isWkTranslationNameAGroupName = wkTranslationName.find(ucstring("$")) != ucstring::npos;
				
				if ( isWkTranslationNameAGroupName ) //work name looks like "$gn_***$: do not modify
				{

					//Do not change work/bot_name.txt
					// update work/world_title.txt

					ucstring transName;
					fctsTitleId = makeGroupName(wkTranslationName);
					uint transRowIdx;
					if (transBotNames.findRow(transIdCol, *first, transRowIdx))
					{
						transName = transBotNames.getData(transRowIdx, ucstring("translated name"));

						if (transName.find(ucstring("$")) != ucstring::npos)
						{
							transName = fctsTitleId;
						} 
						
					}
					else
					{
						transName = fctsTitleId;
					}
					//Do not touch anything
					botNames.setData(rowIdx, ucstring("translated name"), wkTranslationName);
					botNames.setData(rowIdx, ucstring("sheet_name"), wkSheetName); 
					// fctsTitleId = makeGroupName(wkTranslationName);
					fctsName = transName;

				}
				else // WkTranslationName != "$gn*$"
				{
						uint transRowIdx;
						ucstring transName;
						ucstring wkSheetName;
						// Get the translation as a simple name.
						if (transBotNames.findRow(transIdCol, *first, transRowIdx))
						{
		
							transName = transBotNames.getData(transRowIdx, ucstring("translated name"));
							ucstring trSheetName = transBotNames.getData(transRowIdx, ucstring("sheet_name"));

							//tr."translation name" is 
							if (transName.find(ucstring("$")) != ucstring::npos)
							{
								//get Translation, update hash
								botNames[rowIdx][1] = transName;
								botNames[rowIdx][2] = trSheetName;		
								fctsTitleId = makeGroupName(transName);
								fctsName = makeGroupName(transName);
								ucstring trNewUcHash;
								uint64 hash = CI18N::makeHash(wkBotName + transName +trSheetName);						
								CI18N::hashToUCString(hash, trNewUcHash);
								transBotNames[transRowIdx][0] = ucstring("_") + trNewUcHash;
							}
							else //botNames."translated name" != $gn_$ && tansName."translated name" != $gn_$
							{

								// get the translation back
								//update work/bot_name.txt
								wkTranslationName = ucstring("$")+gnName+"$";
								botNames[rowIdx][0] = wkBotName;
								botNames[rowIdx][1] = wkTranslationName;
								botNames[rowIdx][2] = wkSheetName;		
									
									//update translated/bot_name.txt

								fctsName = transName;	//transName	
								fctsTitleId = gnName;
								ucstring trNewUcHash;
								uint64 hash = CI18N::makeHash(botNames[rowIdx][0] + botNames[rowIdx][1] +botNames[rowIdx][2]);						
								CI18N::hashToUCString(hash, trNewUcHash);
								transBotNames[transRowIdx][0] = ucstring("_") + trNewUcHash;
							}

						}
						else //There is no translation yet
						{
								fctsName = wkTranslationName;
								wkTranslationName = ucstring("$")+gnName+"$";
								botNames[rowIdx][0] = wkBotName;
								botNames[rowIdx][1] = wkTranslationName;
								botNames[rowIdx][2] = wkSheetName;		
								fctsTitleId = gnName;

				
						}				
				}

			}


			// look for a corresponding entry
			uint gnNameRow;


			if (!fcts.findRow(fctsIdCol, fctsTitleId, gnNameRow))
			{
				
				// not found, add it
				gnNameRow = fcts.size();
				fcts.resize(fcts.size()+1);
				fcts.setData(gnNameRow, ucstring("title_id"), fctsTitleId);
				fcts.setData(gnNameRow, ucstring("name"), fctsName);										
				nbAddGenericName++;
				
			}
			else //Update 
			{
			
			}
		}
	}


	// 3 - functions
	{
		nlinfo("  Functions...");

		set<string>::iterator first(Functions.begin()), last(Functions.end());
		for (; first != last; ++first)
		{
			string fctName = *first;
			// look for a corresponding entry
			uint functionRow;
			if (!fcts.findRow(fctsIdCol, fctName, functionRow))
			{
				// not found, add it
				functionRow = fcts.size();
				fcts.resize(fcts.size()+1);

				fcts.setData(functionRow, ucstring("title_id"), fctName);
				fcts.setData(functionRow, ucstring("name"), *first);

				nbAddFunction++;
			}
		}
	}

	// display resumé
	nlinfo("Adding %u new simple name", nbAddSimpleName);
	nlinfo("Adding %u new generic name", nbAddGenericName);
	nlinfo("Adding %u new function name", nbAddFunction);

	// saving the modified files

	ucstring s = prepareExcelSheet(botNames);
	CI18N::writeTextFile(workBotNamesFile.asString(), s, false);
	s = prepareExcelSheet(transBotNames);
	CI18N::writeTextFile(transBotNamesFile.asString(), s, false);
	s = prepareExcelSheet(fcts);
	CI18N::writeTextFile(workTitleFile.asString(), s, false);

	return 0;
}
Beispiel #13
0
/*
 * CSV -> Georges
 */
void	convertCsvFile( const string &file, bool generate, const string& sheetType )
{
	const uint			BUFFER_SIZE = 16*1024;
	char			lineBuffer[BUFFER_SIZE];
	FILE			*s;

	vector<string>	fields;
	vector<string>	args;

	if ((s = fopen(file.c_str(), "r")) == NULL)
	{
		fprintf(stderr, "Can't find file %s to convert\n", file.c_str());
		return;
	}

	loadSheetPath();

	UFormLoader *formLoader = UFormLoader::createLoader ();
	NLMISC::CSmartPtr<CForm> form;
	NLMISC::CSmartPtr<UFormDfn> formDfn;


	fgets(lineBuffer, BUFFER_SIZE, s);
	explode(std::string(lineBuffer), std::string(SEPARATOR), fields);

	vector<bool> activeFields( fields.size(), true );

	// Load DFN (generation only)
	set<CDfnField>	dfnFields;
	if ( generate )
	{
		formDfn = formLoader->loadFormDfn( (sheetType + ".dfn").c_str() );
		if ( ! formDfn )
			nlerror( "Can't find DFN for %s", sheetType.c_str() );
		fillFromDFN( formLoader, dfnFields, formDfn, "", sheetType );

		// Display missing fields and check fields against DFN
		uint i;
		for ( i=1; i!=fields.size(); ++i )
		{
			eraseCarriageReturnsAndMakeBlankNonAsciiChars( fields[i] );
			if ( fields[i].empty() )
			{
				nlinfo( "Skipping field #%u (empty)", i );
				activeFields[i] = false;
			}
			else if ( nlstricmp( fields[i], "parent" ) == 0 )
			{
				strlwr( fields[i] ); // non-const version
			}
			else
			{
				set<CDfnField>::iterator ist = dfnFields.find( CDfnField(fields[i]) );
				if ( ist == dfnFields.end() )
				{
					nlinfo( "Skipping field #%u (%s, not found in %s DFN)", i, fields[i].c_str(), sheetType.c_str() );
					activeFields[i] = false;
				}
			}
		}
		for ( i=1; i!=fields.size(); ++i )
		{
			if ( activeFields[i] )
				nlinfo( "Selected field: %s", fields[i].c_str() );
		}
	}

	string addExtension = "." + sheetType;
	uint dirmapLetterIndex = ~0;
	bool dirmapLetterBackward = false;
	vector<string> dirmapDirs;
	string dirmapSheetCode;
	bool WriteEmptyProperties = false, WriteSheetsToDisk = true;
	bool ForceInsertParents = false;

	if ( generate )
	{
		// Get the directory mapping
		try
		{
			CConfigFile dirmapcfg;
			dirmapcfg.load( sheetType + "_dirmap.cfg" );

			if ( OutputPath.empty() )
			{
				CConfigFile::CVar *path = dirmapcfg.getVarPtr( "OutputPath" );
				if ( path )
					OutputPath = path->asString();
				if ( ! OutputPath.empty() )
				{
					if ( OutputPath[OutputPath.size()-1] != '/' )
						OutputPath += '/';
					else if ( ! CFile::isDirectory( OutputPath ) )
						nlwarning( "Output path does not exist" );
				}
			}

			CConfigFile::CVar *letterIndex1 = dirmapcfg.getVarPtr( "LetterIndex" );
			if ( letterIndex1 && letterIndex1->asInt() > 0 )
			{
				dirmapLetterIndex = letterIndex1->asInt() - 1;

				CConfigFile::CVar *letterWay = dirmapcfg.getVarPtr( "LetterWay" );
				dirmapLetterBackward = (letterWay && (letterWay->asInt() == 1));
				
				CConfigFile::CVar dirs = dirmapcfg.getVar( "Directories" );
				for ( uint idm=0; idm!=dirs.size(); ++idm )
				{
					dirmapDirs.push_back( dirs.asString( idm ) );
					nlinfo( "Directory: %s", dirmapDirs.back().c_str() );
					if ( ! CFile::isExists( OutputPath + dirmapDirs.back() ) )
					{
						CFile::createDirectory( OutputPath + dirmapDirs.back() );
					}
					else
					{
						if ( ! CFile::isDirectory( OutputPath + dirmapDirs.back() ) )
						{
							nlwarning( "Already existing but not a directory!" );
						}
					}
				}

				nlinfo( "Mapping letter #%u (%s) of sheet name to directory", dirmapLetterIndex + 1, dirmapLetterBackward?"backward":"forward" );
			}
			
			CConfigFile::CVar *sheetCode = dirmapcfg.getVarPtr( "AddSheetCode" );
			if ( sheetCode )
				dirmapSheetCode = sheetCode->asString();
			nlinfo( "Sheet code: %s", dirmapSheetCode.c_str() );

			if ( ! dirmapLetterBackward )
				dirmapLetterIndex += dirmapSheetCode.size();

			CConfigFile::CVar *wep = dirmapcfg.getVarPtr( "WriteEmptyProperties" );
			if ( wep )
				WriteEmptyProperties = (wep->asInt() == 1);
			nlinfo( "Write empty properties mode: %s", WriteEmptyProperties ? "ON" : "OFF" );

			CConfigFile::CVar *wstd = dirmapcfg.getVarPtr( "WriteSheetsToDisk" );
			if ( wstd )
				WriteSheetsToDisk = (wstd->asInt() == 1);
			nlinfo( "Write sheets to disk mode: %s", WriteSheetsToDisk ? "ON" : "OFF" );

			CConfigFile::CVar *fiparents = dirmapcfg.getVarPtr( "ForceInsertParents" );
			if ( fiparents )
				ForceInsertParents = (fiparents->asInt() == 1);
			nlinfo( "Force insert parents mode: %s", ForceInsertParents ? "ON" : "OFF" );
		}
		catch ( EConfigFile& e )
		{
			nlwarning( "Problem in directory mapping: %s", e.what() );
		}
		

		nlinfo( "Using output path: %s", OutputPath.c_str() );
		nlinfo( "Press a key to generate *.%s", sheetType.c_str() );
		getchar();
		nlinfo( "Generating...." );

	}
	else
		nlinfo("Updating modifications (only modified fields are updated)");

	set<string> newSheets;
	uint nbNewSheets = 0, nbModifiedSheets = 0, nbUnchangedSheets = 0, nbWritten = 0;
	while (!feof(s))
	{
		lineBuffer[0] = '\0';
		fgets(lineBuffer, BUFFER_SIZE, s);
		explode(std::string(lineBuffer), std::string(SEPARATOR), args);

		if (args.size() < 1)
			continue;

		eraseCarriageReturnsAndMakeBlankNonAsciiChars( args[0] );
		replaceTrueAndFalseTagFromCsv(args);

		// Skip empty lines
		if ( args[0].empty() || (args[0] == string(".")+sheetType) )
			continue;

		//nldebug( "%s: %u", args[0].c_str(), args.size() );
		string	filebase = dirmapSheetCode+args[0]; /*+"."+sheetType;*/
		if (filebase.find("."+sheetType) == string::npos)
		{
			filebase += "." + sheetType;
		}
		strlwr	(filebase);
		string	filename, dirbase;
		bool	isNewSheet=true;

		// Locate existing sheet
//		map<string, string>::iterator it = inputSheetPathContent.find( CFile::getFilenameWithoutExtension( filebase ) );
		map<string, string>::iterator it = inputSheetPathContent.find( CFile::getFilename( filebase ) );
		
		if	(it == inputSheetPathContent.end())
		{
			// Not found
			if ( ! generate )
			{
				if ( ! filebase.empty() )
				{
					nlwarning( "Sheet %s not found", filebase.c_str( )); 
					continue;
				}
			}			
			else
			{
				// Load template sheet
				filename = strlwr( static_cast<const string&>(filebase) );
				form = (CForm*)formLoader->loadForm( (string("_empty.") + sheetType).c_str() );
				if (form == NULL)
				{
					nlerror( "Can't load sheet _empty.%s", sheetType.c_str() );
				}

				// Deduce directory from sheet name
				if ( dirmapLetterIndex != ~0 )
				{
					if ( dirmapLetterIndex < filebase.size() )
					{
						uint letterIndex;
						char c;
						if ( dirmapLetterBackward )
							letterIndex = filebase.size() - 1 - (CFile::getExtension( filebase ).size()+1) - dirmapLetterIndex;
						else
							letterIndex = dirmapLetterIndex;
						c = tolower( filebase[letterIndex] );
						vector<string>::const_iterator idm;
						for ( idm=dirmapDirs.begin(); idm!=dirmapDirs.end(); ++idm )
						{
							if ( (! (*idm).empty()) && (tolower((*idm)[0]) == c) )
							{
								dirbase = (*idm) + "/";
								break;
							}
						}
						if ( idm==dirmapDirs.end() )
						{
							nlinfo( "Directory mapping not found for %s (index %u)", filebase.c_str(), letterIndex );
							dirbase = ""; // put into root
						}
					}
					else
					{
						nlerror( "Can't map directory with letter #%u, greater than size of %s + code", dirmapLetterIndex, filebase.c_str() );
					}
				}

				nlinfo( "New sheet: %s", filebase.c_str() );
				++nbNewSheets;
				if ( ! newSheets.insert( filebase ).second )
					nlwarning( "Found duplicate sheet: %s", filebase.c_str() );
				isNewSheet = true;
			}
		}
		else // an existing sheet was found
		{

			// Load sheet (skip if failed)
			dirbase = "";
			filename = (*it).second; // whole path
			form = (CForm*)formLoader->loadForm( filename.c_str() );
			if (form == NULL)
			{
				nlwarning( "Can't load sheet %s", filename.c_str() );
				continue;
			}

			isNewSheet = false;
		}

		const	UFormElm	&rootForm=form->getRootNode();
		bool displayed = false;
		bool isModified = false;
		uint i;
		for (	i=1;	i<args.size		()
					&&	i<fields.size	();	++i )
		{
			const string	&var = fields[i];
			string			&val = args[i];

			eraseCarriageReturnsAndMakeBlankNonAsciiChars( val );

			// Skip column with inactive field (empty or not in DFN)
			if ( (! activeFields[i]) )
				continue;

			// Skip setting of empty cell except if required
			if ( (! WriteEmptyProperties) && val.empty() )
				continue;

			// Special case for parent sheet
			if	(var == "parent") // already case-lowered
			{
				vector<string> parentVals;
				explode( val, std::string(ARRAY_SEPARATOR), parentVals );
				if ( (parentVals.size() == 1) && (parentVals[0].empty()) )
					parentVals.clear();

				if ( (isNewSheet || ForceInsertParents) && (! parentVals.empty()) )
				{
					// This is slow. Opti: insertParent() should have an option to do it without loading the form
					//	parent have same type that this object (postulat).
					uint	nbinsertedparents=0;

					for ( uint p=0; p!=parentVals.size(); ++p )
					{						
						string	localExtension=(parentVals[p].find(addExtension)==string::npos)?addExtension:"";
						string	parentName=parentVals[p]+localExtension;

						CSmartPtr<CForm> parentForm = (CForm*)formLoader->loadForm(CFile::getFilename(parentName.c_str()).c_str());
						if ( ! parentForm )
						{
							nlwarning( "Can't load parent form %s", parentName.c_str() );
						}
						else
						{
							form->insertParent( p, parentName.c_str(), parentForm );
							isModified=true;
							displayed = true;
							nbinsertedparents++;
						}

					}
					nlinfo( "Inserted %u parent(s)", nbinsertedparents );
				}
				// NOTE: Changing the parent is not currently implemented!
				continue;
			}

			const	UFormElm	*fieldForm=NULL;
						
			if	(rootForm.getNodeByName(&fieldForm, var.c_str()))
			{
				UFormDfn	*dfnForm=const_cast<UFormElm&>(rootForm).getStructDfn();
				nlassert(dfnForm);
								
				vector<string> memberVals;
				explode( val, std::string(ARRAY_SEPARATOR), memberVals );
				uint32	memberIndex=0;
				
				while (memberIndex<memberVals.size())
				{
					const	uint	currentMemberIndex=memberIndex;
					std::string		memberVal=memberVals[memberIndex];
					memberIndex++;
					
					if	(!memberVal.empty())
					{
						if (memberVal[0] == '"')
							memberVal.erase(0, 1);
						if (memberVal.size()>0 && memberVal[memberVal.size()-1] == '"')
							memberVal.resize(memberVal.size()-1);
						
						if (memberVal == "ValueForm" ||
							memberVal == "ValueParentForm" ||
							memberVal == "ValueDefaultDfn" ||
							memberVal == "ValueDefaultType" ||
							memberVal == "ERR")
							continue;
					}


					//				nlassert(fieldDfn);
					//				virtual bool getEntryFilenameExt (uint entry, std::string &name) const = 0;
					//				virtual bool getEntryFilename (uint entry, std::string &name) const = 0;
					if (dfnForm)
					{
						string	fileName;
						string	fileNameExt;
						bool	toto=false;
						static	string	filenameTyp("filename.typ");
						string	extension;
			
						uint	fieldIndex;
						if (dfnForm->getEntryIndexByName (fieldIndex, var))	//	field exists.
						{
							dfnForm->getEntryFilename(fieldIndex,fileName);
							if (fileName==filenameTyp)
							{
								dfnForm->getEntryFilenameExt(fieldIndex,fileNameExt);
								if (	!fileNameExt.empty()
									&&	fileNameExt!="*.*")
								{
									string::size_type	index=fileNameExt.find(".");
									if (index==string::npos)	//	not found.
									{
										extension=fileNameExt;
									}
									else
									{
										extension=fileNameExt.substr(index+1);
									}
									
									if	(memberVal.find(extension)==string::npos)	// extension not found.
									{
										memberVal=NLMISC::toString("%s.%s",memberVal.c_str(),extension.c_str());
									}
									
								}
								
							}
							
						}
						
					}
					

					if	(dfnForm->isAnArrayEntryByName(var))
					{
						if	(	!isNewSheet
							&&	fieldForm!=NULL)
						{
							uint arraySize;
							const UFormElm *arrayNode = NULL;
							if (fieldForm->isArray() 
								&& fieldForm->getArraySize(arraySize) && arraySize == memberVals.size())
							{
								string	test;
								if	(	fieldForm->getArrayValue(test, currentMemberIndex)
									&&	test==memberVal	)
								{
									continue;
								}
							}
						}
						//nldebug( "%s: %s '%s'", args[0].c_str(), var.c_str(), memberVal.c_str() );
						// need to put the value at the correct index.
						const	std::string	fieldName=NLMISC::toString("%s[%d]", var.c_str(), currentMemberIndex).c_str();
						const_cast<UFormElm&>(rootForm).setValueByName(memberVal.c_str(), fieldName.c_str());
						isModified=true;
						displayed = true;
					}
					else
					{
						if	(!isNewSheet)
						{
							string	test;
							if	(	rootForm.getValueByName(test,var.c_str())
								&&	test==memberVal	)
							{
								continue;
							}
							
						}					
						//nldebug( "%s: %s '%s'", args[0].c_str(), var.c_str(), memberVal.c_str() );
						const_cast<UFormElm&>(rootForm).setValueByName(memberVal.c_str(), var.c_str());
						isModified=true;
						displayed = true;
					}
					
					if	(!isNewSheet)
					{
						isModified = true;
						if (!displayed)
							nlinfo("in %s:", filename.c_str());
						displayed = true;
						nlinfo("%s = %s", var.c_str(), memberVal.c_str());
					}

				}

			}
			else	//	field Node not found :\ (bad)
			{
			}
			
		}

		if ( ! isNewSheet )
		{
			if ( isModified )
				++nbModifiedSheets;
			else
				++nbUnchangedSheets;
		}

		// Write sheet
		if ( isNewSheet || displayed )
		{
			if ( WriteSheetsToDisk )
			{
				++nbWritten;
				string	path = isNewSheet ? OutputPath : "";
				string	ext = (filename.find( addExtension ) == string::npos) ? addExtension : "";
				string	absoluteFileName=path + dirbase + filename + ext;
				
//				nlinfo("opening: %s",  absoluteFileName.c_str() );
				COFile	output(absoluteFileName);
				if	(!output.isOpen())
				{
					nlinfo("creating path: %s",  (path + dirbase).c_str() );
					NLMISC::CFile::createDirectory(path + dirbase);
				}

//				nlinfo("opening2: %s",  absoluteFileName.c_str() );
				output.open	(absoluteFileName);
				
				if (!output.isOpen())
				{					
					nlinfo("ERROR! cannot create file path: %s",  absoluteFileName.c_str() );
				}
				else
				{
					form->write(output, true);
					output.close();
					
					if	(!CPath::exists(filename + ext))
						CPath::addSearchFile(absoluteFileName);					
				}					

			}
			clearSheet( form, &form->getRootNode() );
		}

	}
	nlinfo( "%u sheets processed (%u new, %u modified, %u unchanged - %u written)", nbNewSheets+nbModifiedSheets+nbUnchangedSheets, nbNewSheets, nbModifiedSheets, nbUnchangedSheets, nbWritten );
	UFormLoader::releaseLoader (formLoader);
}
// ***************************************************************************
int extractNewSheetNames(int argc, char *argv[])
{
	// **** read the parameters
	for (int i=2; i<argc; ++i)
	{
		string s = argv[i];
		if (s == "-r")
		{
			// active remove mode
			RemoveOlds = true;
		}
		else
		{
			nlwarning("Unknow option '%s'", argv[i]);
			return -1;
		}
	}
	
	// **** avoid some flood
	NLMISC::createDebug();
	NLMISC::DebugLog->addNegativeFilter("numCol changed to");
	NLMISC::InfoLog->addNegativeFilter("CPath::addSearchPath");
	

	// **** read the configuration file
	CConfigFile	cf;
	cf.load("bin/translation_tools.cfg");
	CConfigFile::CVar &paths = cf.getVar("Paths");
	CConfigFile::CVar &pathNoRecurse= cf.getVar("PathsNoRecurse");
	CConfigFile::CVar &ligoClassFile= cf.getVar("LigoClassFile");

	// parse path
	for (uint i=0; i<paths.size(); ++i)
	{
		CPath::addSearchPath(paths.asString(i), true, false);
	}
	for (uint i=0; i<pathNoRecurse.size(); ++i)
	{
		CPath::addSearchPath(pathNoRecurse.asString(i), false, false);
	}
	
	// init ligo config once
	string ligoPath = CPath::lookup(ligoClassFile.asString(), true, true);
	LigoConfig.readPrimitiveClass(ligoPath.c_str(), false);
	NLLIGO::Register();
	CPrimitiveContext::instance().CurrentLigoConfig = &LigoConfig;
	
	
	
	// **** Parse all the different type of sheets
	const char	*sheetDefs[]=
	{
		// 1st is the name of the worksheet file. 
		// 2nd is the Key column identifier. 
		// 3rd is the sheet extension
		// 4th is the directory where to find new sheets
		"work/item_words_wk.txt",		"item ID",		"sitem",		"l:/leveldesign/game_element/sitem",
		"work/creature_words_wk.txt",	"creature ID",	"creature",		"l:/leveldesign/game_elem/creature/fauna",	// take fauna only because other are special
		"work/sbrick_words_wk.txt",		"sbrick ID",	"sbrick",		"l:/leveldesign/game_element/sbrick",
		"work/sphrase_words_wk.txt",	"sphrase ID",	"sphrase",		"l:/leveldesign/game_element/sphrase",
	};
	uint	numSheetDefs= sizeof(sheetDefs) / (4*sizeof(sheetDefs[0]));
	
	// For all different type of sheet
	for(uint i=0;i<numSheetDefs;i++)
	{
		CSheetWordListBuilder	builder;
		builder.SheetExt= sheetDefs[i*4+2];
		builder.SheetPath= sheetDefs[i*4+3];
		extractNewWords(sheetDefs[i*4+0], sheetDefs[i*4+1], builder);
	}


	// **** Parse place and region names
	{
		// build place names
		CRegionPrimWordListBuilder	builder;
		builder.PrimPath= "l:/primitives";
		builder.PrimFilter.push_back("region_*.primitive");
		builder.PrimFilter.push_back("indoors_*.primitive");
		extractNewWords("work/place_words_wk.txt", "placeId", builder);
	}


	return 0;
}
// ***************************************************************************
int main(int argc, char* argv[])
{
	// Register 3d
	registerSerial3d ();

	// Avoid some stupids warnings.
	NLMISC::createDebug();
	skipLog("variable \"RootConfigFilename\"");
	skipLog("variable \"anim_low_precision_tracks\"");
	skipLog("variable \"anim_sample_rate\"");
	InfoLog->addNegativeFilter("FEHTIMER>");
	InfoLog->addNegativeFilter("adding the path");


	// Good number of args ?
	if (argc<4)
	{
		// Help message
		printf ("anim_builder [directoryIn] [pathOut] [parameter_file] \n");
	}
	else
	{
		try
		{
			string	directoryIn= argv[1];
			string	pathOut= argv[2];
			string	paramFile= argv[3];

			// Verify directoryIn.
			directoryIn= CPath::standardizePath(directoryIn);
			if( !CFile::isDirectory(directoryIn) )
			{
				printf("DirectoryIn %s is not a directory", directoryIn.c_str());
				return -1;
			}
			// Verify pathOut.
			pathOut= CPath::standardizePath(pathOut);
			if( !CFile::isDirectory(pathOut) )
			{
				printf("PathOut %s is not a directory", pathOut.c_str());
				return -1;
			}

			// Our Animation optimizer.
			//=================
			CAnimationOptimizer		animationOptimizer;
			// Leave thresholds as default.
			animationOptimizer.clearLowPrecisionTracks();


			// Load and setup configFile.
			//=================
			CConfigFile parameter;
			// Load and parse the param file
			parameter.load (paramFile);

			// Get the Low Precision Track Key Names
			try
			{
				CConfigFile::CVar &anim_low_precision_tracks = parameter.getVar ("anim_low_precision_tracks");
				uint lpt;
				for (lpt = 0; lpt < (uint)anim_low_precision_tracks.size(); lpt++)
				{
					animationOptimizer.addLowPrecisionTrack(anim_low_precision_tracks.asString(lpt));
				}
			}
			catch(EUnknownVar &)
			{
				nlwarning("\"anim_low_precision_tracks\" not found in the parameter file. Add \"Finger\" and \"Ponytail\" by default");
				animationOptimizer.addLowPrecisionTrack("Finger");
				animationOptimizer.addLowPrecisionTrack("Ponytail");
			}

			// Sample Rate.
			try
			{
				CConfigFile::CVar &anim_sample_rate = parameter.getVar ("anim_sample_rate");
				float	sr= anim_sample_rate.asFloat(0);
				// Consider values > 1000 as error values.
				if(sr<=0 || sr>1000)
				{
					nlwarning("Bad \"anim_sample_rate\" value. Use Default of 30 fps.");
					animationOptimizer.setSampleFrameRate(30);
				}
				else
				{
					animationOptimizer.setSampleFrameRate(sr);
				}
			}
			catch(EUnknownVar &)
			{
				nlwarning("\"anim_sample_rate\" not found in the parameter file. Use Default of 30 fps.");
				animationOptimizer.setSampleFrameRate(30);
			}


			// Scan and load all files .ig in directories
			//=================
			uint		numSkipped= 0;
			uint		numBuilded= 0;
			vector<string>				listFile;
			CPath::getPathContent(directoryIn, false, false, true, listFile);
			for(uint iFile=0; iFile<listFile.size(); iFile++)
			{
				string	&igFile= listFile[iFile];
				// verify it is a .anim.
				if( CFile::getExtension(igFile) == "anim" )
				{
					string	fileNameIn= CFile::getFilename(igFile);
					string	fileNameOut= pathOut + fileNameIn;

					// skip the file?
					bool	mustSkip= false;

					// If File Out exist 
					if(CFile::fileExists(fileNameOut))
					{
						// If newer than file In, skip
						uint32		fileOutDate= CFile::getFileModificationDate(fileNameOut);
						if(	fileOutDate > CFile::getFileModificationDate(igFile) )
						{
							mustSkip= true;
						}
					}

					// If must process the file.
					if(!mustSkip)
					{
						// Read the animation.
						CAnimation	animIn;
						CIFile	fin;
						fin.open(CPath::lookup(igFile));
						fin.serial(animIn);

						// process.
						CAnimation	animOut;
						animationOptimizer.optimize(animIn, animOut);

						// Save this animation.
						COFile	fout;
						fout.open(fileNameOut);
						fout.serial(animOut);
						fout.close();

						numBuilded++;
					}
					else
					{
						numSkipped++;
					}

					// progress
					printf("Anim builded: %4d. Anim Skipped: %4d\r", numBuilded, numSkipped);
				}
			}

			// Add some info in the log.
			nlinfo("Anim builded: %4d", numBuilded);
			nlinfo("Anim skipped: %4d", numSkipped);

		}
		catch (Exception& except)
		{
			// Error message
			nlwarning ("ERROR %s\n", except.what());
		}
	}

	// exit.
	return 0;
}
Beispiel #16
0
//****************************************************************************************************************************
int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		nlwarning("Usage : %s config_file_name.cfg", argv[0]);
		return -1;
	}
	CConfigFile cf;
	try
	{	
		cf.load(argv[1]);
	}
	catch(const NLMISC::EConfigFile &)
	{
		nlwarning("Error in config file %s", argv[1]);
		return -1;
	}	
	catch(...)
	{
		nlwarning("Can't read config file %s", argv[1]);
		return -1;
	}
	// output for sheets
	std::string outputPath;
	CConfigFile::CVar *outputPathVar = cf.getVarPtr("output_path");
	if (outputPathVar)
	{
		outputPath = outputPathVar->asString() + "/";
	}
	// output for 'levels' parents
	std::string levelParentsPath;
	CConfigFile::CVar *levelParentsPathVar = cf.getVarPtr("level_parents");
	if (levelParentsPathVar)
	{
		levelParentsPath = levelParentsPathVar->asString() + "/";
	}
	// output for projectile parents
	std::string projectileParentsPath;
	CConfigFile::CVar *projectileParentsPathVar = cf.getVarPtr("projectile_base");
	if (projectileParentsPathVar)
	{
		projectileParentsPath= projectileParentsPathVar->asString() + "/";
	}	
	// output for 'projectile by level and mode' parents
	std::string projectileByLevelAndModeParentsPath;
	CConfigFile::CVar *projectileByLevelAndModeParentsPathVar = cf.getVarPtr("projectile_by_level_and_mode_parents");
	if (projectileByLevelAndModeParentsPathVar)
	{
		projectileByLevelAndModeParentsPath = projectileByLevelAndModeParentsPathVar->asString() + "/";
	}
	// output for 'base spells' parents
	std::string baseSpellPath;
	CConfigFile::CVar *baseSpellPathVar = cf.getVarPtr("spell_base");
	if (baseSpellPathVar)
	{
		baseSpellPath = baseSpellPathVar->asString() + "/";
	}
	// output for 'spell by levels' parents
	std::string spellByLevelParentsPath;
	CConfigFile::CVar *spellByLevelParentsPathVar = cf.getVarPtr("spell_by_level_parents");
	if (spellByLevelParentsPathVar)
	{
		spellByLevelParentsPath = spellByLevelParentsPathVar->asString() + "/";
	}
	// output for 'final spell'
	std::string finalSpellPath;
	CConfigFile::CVar *finalSpellPathVar = cf.getVarPtr("final_spells");
	if (finalSpellPathVar)
	{
		finalSpellPath = finalSpellPathVar->asString() + "/";
	}
	


	// read number of levels
	CConfigFile::CVar *numLevelVar = cf.getVarPtr("num_levels");
	if (!numLevelVar)
	{
		nlwarning("Can't read number of spell levels");
		return -1;
	}
	uint numSpellLevels = numLevelVar->asInt();

	std::vector<CUserParams> userParams(numSpellLevels);

	// read user params set for each level
	for(uint level = 0; level < numSpellLevels; ++level)
	{
		std::string varName = toString("user_params_level%d", (int) (level + 1));
		CConfigFile::CVar *up = cf.getVarPtr(varName);
		if (!up)
		{
			nlwarning("Can't read var %s", varName.c_str());
		}
		else
		{
			for(uint k = 0; k < CUserParams::NumUserParams; ++k)
			{
				userParams[level].UserParam[k] = up->asString(k);
			}
		}		
	}

	// read types of spells (offensif, curatif ...)
	CConfigFile::CVar *spellTypesList = cf.getVarPtr("spell_types"); 
	if (!spellTypesList)
	{
		nlwarning("Can't read types of spells");
		return -1;
	}
	// read modes of spells
	CConfigFile::CVar *spellModesList = cf.getVarPtr("spell_modes");

	// read name of ps for projectiles
	std::vector<std::string> projPSNames;
	projPSNames.resize(spellTypesList->size() * spellModesList->size());
	CConfigFile::CVar *projectileNames = cf.getVarPtr("projectile_fx");
	if (projectileNames)
	{
		for(uint k = 0; k < (uint) projectileNames->size(); ++k)
		{
			// entry are expected to have the following form : 
			// "type|mode|fx_name.ps"
			std::vector<std::string> params;
			NLMISC::splitString(projectileNames->asString(k), "|", params);
			if (params.size() != 3)
			{
				nlwarning("Bad param for projectile ps name : %s", projectileNames->asString(k).c_str());
			}
			else
			{
				bool found = false;
				// find the mode				
				for (uint mode = 0; mode < (uint) spellModesList->size(); ++mode)
				{
					if (spellModesList->asString(mode) == params[1])
					{						
						for (uint type = 0; type < (uint) spellTypesList->size(); ++type)
						{
							if (spellTypesList->asString(type) == params[0])
							{
								projPSNames[type + mode * spellTypesList->size()] = params[2];
								//nlwarning("%s : found", projectileNames->asString(k).c_str());
								found = true;
								break;
							}
						}
						if (found) break;
					}
				}
				//if (!found) nlwarning("%s : not found", projectileNames->asString(k).c_str());
			}			
		}
	}

	nlinfo("Generate projectiles parent sheets...");
	// gen projectiles base sheet
	CSpellSheet baseProjectileSheet;
	baseProjectileSheet.writeSheet(outputPath + projectileParentsPath + "_projectile_base.spell");	
	// gen projectiles parent sheets
	for(uint type = 0; type < (uint) spellTypesList->size(); ++type)
	{
		for(uint mode = 0; mode < (uint) spellModesList->size(); ++mode)
		{
			std::string sheetName = "_projectile_" + spellTypesList->asString(type) + "_" + spellModesList->asString(mode) + ".spell";
			CSpellSheet ss;
			ss.Parents.push_back("_projectile_base.spell");
			// affect ps name if known
			ss.Projectile.FX[0].PSName = projPSNames[type + mode * spellTypesList->size()];
			ss.writeSheet(outputPath + projectileParentsPath + sheetName);			
		}
	}
	
	nlinfo("Generate sheets by level...");
	// generate sheets by level
	for(uint level = 0; level < numSpellLevels; ++level)
	{		
		// gen projectiles by level sheets (parent sheets)
		std::string sheetName = toString("_projectile_lvl%d.spell", (int) (level + 1));
		CSpellSheet projectileSheet;
		projectileSheet.Projectile.setUserParams(userParams[level]);
		projectileSheet.writeSheet(outputPath + levelParentsPath + sheetName);
		// gen impact level sheets
		sheetName = toString("_impact_lvl%d.spell", (int) (level + 1));
		CSpellSheet impactSheet;
		impactSheet.Impact.setUserParams(userParams[level]);
		impactSheet.writeSheet(outputPath + levelParentsPath + sheetName);
		
	}

	nlinfo("Generate projectile list (by mode, type and levels)...");
	// generate projectile list (by mode, type and levels)
	for(uint type = 0; type < (uint) spellTypesList->size(); ++type)
	{
		for(uint mode = 0; mode < (uint) spellModesList->size(); ++mode)
		{
			for(uint level = 0; level < (uint) numSpellLevels; ++level)
			{			
				CSpellSheet ss;
				ss.Parents.resize(2);
				ss.Parents[0] = toString("_projectile_lvl%d.spell", (int) (level + 1)); // inherit level
				ss.Parents[1] = "_projectile_" + spellTypesList->asString(type) + "_" + spellModesList->asString(mode) + ".spell"; // inherit mode and type
				std::string sheetName = "_projectile_" + spellTypesList->asString(type) + "_" + spellModesList->asString(mode) + toString("_lvl%d.spell", (int) (level + 1));
				ss.writeSheet(outputPath + projectileByLevelAndModeParentsPath + sheetName);			
			}
		}
	}
	//
	nlinfo("Generate spell list...");
	// read list of spells
	// the string format for spells is : "sheet_name|ps_name"
	// the name of the particle system is optionnal
	CConfigFile::CVar *spellList = cf.getVarPtr("spell_list");
	if (!spellList)
	{
		nlwarning("Can't read spell list");
		return -1;
	}
	for(uint k = 0; k < (uint) spellList->size(); ++k)
	{
		std::string spellName = spellList->asString(k);
		std::vector<std::string> result;
		NLMISC::splitString(spellName, "|", result);
		if (result.size()  < 3)
		{
			nlwarning("Should provide at least spell name, id and mode");
		}
		else
		{		
			// generate parent sheet
			CSpellSheet baseSpellSheet;
			if (result.size() > 3)
			{			
				baseSpellSheet.Impact.FX[0].PSName = result[3];
			}
			baseSpellSheet.writeSheet(outputPath + baseSpellPath + "_" + result[0] + ".spell");
			// generate child sheet
			// - by spell level
			// - by spell type (chain, bomb, spray ...)

			// save spells by level
			for(uint level = 0; level < numSpellLevels; ++level)
			{
				CSpellSheet leveledSpell;
				leveledSpell.Parents.resize(2);
				leveledSpell.Parents[0] = "_" + result[0] + ".spell";
				leveledSpell.Parents[1] = toString("_impact_lvl%d.spell", (int) (level + 1));
				leveledSpell.writeSheet(outputPath + spellByLevelParentsPath + "_" + result[0] + toString("_lvl%d.spell", (int) (level + 1)));
			}

			// save spell with good projectile and level
			for(uint level = 0; level < numSpellLevels; ++level)
			{
				for(uint mode = 0; mode < (uint) spellModesList->size(); ++mode)
				{
					CSpellSheet finalSheet;
					finalSheet.Parents.resize(2);
					finalSheet.Parents[0] = "_" + result[0] + toString("_lvl%d.spell", (int) (level + 1));
					finalSheet.Parents[1] = "_projectile_" + result[2] + "_" + spellModesList->asString(mode) + toString("_lvl%d.spell", (int) (level + 1));
					//finalSheet.writeSheet(outputPath + finalSpellPath + result[0] + toString("_lvl%d_", (int) (level + 1)) + result[2] + "_" + spellModesList->asString(mode) + ".spell");
					finalSheet.writeSheet(outputPath + finalSpellPath + result[0] + "_" + spellModesList->asString(mode) + toString("_lvl%d", (int) (level + 1)) + ".spell");
				}
			}
		}
	}
	// generate spell list with their ids
	CConfigFile::CVar *spellListFile = cf.getVarPtr("spell_list_file");
	if (spellListFile)
	{	
		generateSpellList(cf, outputPath + spellListFile->asString());
	}
	nlinfo("Done");
	return 0;
}
Beispiel #17
0
void LoadVarCfg ()
{
	// Path of the dll
	HMODULE hModule = hInstance;
	if (hModule)
	{
		char sModulePath[256];
		int res=GetModuleFileName(hModule, sModulePath, 256);
		if (res)
		{
			// split path
			char drive[256];
			char dir[256];
			_splitpath (sModulePath, drive, dir, NULL, NULL);

			// Make a new path
			char cgfPath[256];
			_makepath (cgfPath, drive, dir, "keys", ".cfg");
	
			CConfigFile cf;

			// Load and parse "test.txt" file
			cf.load (cgfPath);
			
			// go
			try
			{
				// Get the light direction variable
				CConfigFile::CVar &light_direction= cf.getVar ("LightDirection");
				if (light_direction.size () == 3)
				{
					// Copy the light direction
					LightDirection.x = light_direction.asFloat (0);
					LightDirection.y = light_direction.asFloat (1);
					LightDirection.z = light_direction.asFloat (2);
				}
			}
			catch (EConfigFile &)
			{
			}

			try
			{
				// Get the light diffuse part
				CConfigFile::CVar &light_diffuse= cf.getVar ("LightDiffuse");
				if (light_diffuse.size () == 3)
				{
					LightDiffuse.R = light_diffuse.asInt (0);
					LightDiffuse.G = light_diffuse.asInt (1);
					LightDiffuse.B = light_diffuse.asInt (2);
				}
			}
			catch (EConfigFile &)
			{
			}

			try
			{
				// Get the light ambiant part
				CConfigFile::CVar &light_ambiant= cf.getVar ("LightAmbiant");
				if (light_ambiant.size () == 3)
				{
					LightAmbiant.R = light_ambiant.asInt (0);
					LightAmbiant.G = light_ambiant.asInt (1);
					LightAmbiant.B = light_ambiant.asInt (2);
				}
			}
			catch (EConfigFile &)
			{
			}

			try
			{
				// Get the light mulitply part
				CConfigFile::CVar &light_multiply= cf.getVar ("LightMultiply");
				LightMultiply = light_multiply.asFloat ();
			}
			catch (EConfigFile &)
			{
			}

			try
			{
				// Get the zoom speed
				CConfigFile::CVar &zoom_speed= cf.getVar ("ZoomSpeed");
				ZoomSpeed = zoom_speed.asFloat ();
			}
			catch (EConfigFile &)
			{
			}
		}
	}
}
int main (int /* argc */, char ** /* argv */)
{

	// look at the debug example
	createDebug();

	// Add the data directory to the search path.
	CPath::addSearchPath(NL_SAMPLE_CFG);

	// load and parse the configfile
	cf.load (CPath::lookup("simpletest.txt"));

	// CConfigFile checks if the config file has been modified by an external program.
	// in this case, the configfile automatically reloads and reparses the file.
	// you can connect a callback function that will be called in this case if
	// you want, for example, reset variables
	
	// link a callback with this configfile.
	cf.setCallback (mainCallback);

	// link a callback with the var12. If and only if the var12 changed, this
	// callback will be called
	cf.setCallback ("var12", var12Callback);

	// display all variables
	cf.display(InfoLog);

	// get the value of var1 as int
	int var1 = cf.getVar ("var1").asInt();
	nlinfo("var1 (int) = %d", var1);

	// get the value of var1 as double, in this case, a conversion from int
	// to double will be done
	double var2 = cf.getVar ("var1").asDouble();
	nlinfo("var1 (double) = %lf", var2);

	// get the value of var2 as int, in this case, a conversion from string
	// to int will be done
	int var3 = cf.getVar ("var2").asInt();
	nlinfo("var2 = %d", var3);

	// if the variable is an array of values, you can access them putting the
	// index of the variable you want. Example, get and print all value of var12:
	for (uint i = 0; i < cf.getVar ("var12").size(); i++)
	{
		int val = cf.getVar ("var12").asInt(i);
		nlinfo("%d -> %d", i, val);
	}

	// if you try to access an unknown variable or if something goes wrong, an
	// exception will be called, you can catch them individually or all together in a try/catch block

	try
	{
		// try to access an unknown variable
		int val = cf.getVar ("unknown_variable").asInt();
		nlinfo("unknown_variable = %d", val);
	}
	catch (EConfigFile &e)
	{
		nlinfo("something goes wrong with configfile: %s", e.what());
	}

	cf.getVar ("var13").asInt (0);
	cf.getVar ("var13").asInt (1);
	cf.getVar ("var13").asInt (2);
	
	nlinfo("Try to modify the var12 in the configfile or any other variable.\n\nPress CTRL-C to exit\n");

	while(true)
	{
		CConfigFile::checkConfigFiles();
	}
	return EXIT_SUCCESS;
}
int	main(int argc, char *argv[])
{
	uint	i;

	// Avoid warnings.
	NLMISC::createDebug();
	DebugLog->addNegativeFilter("Exception will be launched");
	WarningLog->addNegativeFilter("Exception will be launched");
	InfoLog->addNegativeFilter("FEHTIMER>");
	InfoLog->addNegativeFilter("adding the path");

	// Init serial
	registerSerial3d();

	if(argc<4)
	{
		puts("Usage:    build_clod_bank  path_file.cfg  config_file.cfg  destfile.clodbank  [bakeFrameRate=20] ");
		return 0;
	}


	try
	{
		// The bank to fill
		CLodCharacterShapeBank	lodShapeBank;


		// Read the frameRate to process bake of anims
		float	bakeFrameRate= 20;
		if(argc>=5)
		{
			bakeFrameRate= (float)atof(argv[4]);
			if(bakeFrameRate<=1)
			{
				nlwarning("bad bakeFrameRate value, use a default of 20");
				bakeFrameRate= 20;
			}
		}


		// parse the path file.
		//==================

		// try to load the config file.
		CConfigFile pathConfig;
		pathConfig.load (argv[1]);

		// Get the search pathes
		CConfigFile::CVar &search_pathes = pathConfig.getVar ("search_pathes");
		for (i = 0; i < (uint)search_pathes.size(); i++)
		{
			// Add to search path
			CPath::addSearchPath (search_pathes.asString(i));
		}

		// parse the config file.
		//==================

		// try to load the config file.
		CConfigFile config;
		config.load (argv[2]);

		// For all .clod to process
		//==================
		CConfigFile::CVar &clod_list = config.getVar ("clod_list");
		uint	lodId;
		for (lodId = 0; lodId < (uint)clod_list.size(); lodId++)
		{
			string	lodName= clod_list.asString(lodId);

			printf("Process LOD: %s\n", lodName.c_str());

			// Search the variable with this name.
			try
			{
				CIFile		iFile;

				// get the anim list.
				CConfigFile::CVar &clod_anim_list = config.getVar (lodName);

				// Correct format?
				if(clod_anim_list.size()<3)
				{
					nlwarning("%s skipped. Must have at least the skeleton file name, the lod file name, and one animation", lodName.c_str());
					// go to next.
					continue;
				}

				// Init lod shape process
				//===========================

				// The first variable is the name of the skeleton.
				string	skeletonName= clod_anim_list.asString(0);
				CSmartPtr<CSkeletonShape>	skeletonShape;

				// Load it.
				iFile.open(CPath::lookup(skeletonName));
				CShapeStream		strShape;
				strShape.serial(iFile);
				iFile.close();

				// Get the pointer, check it's a skeleton
				if(dynamic_cast<CSkeletonShape*>(strShape.getShapePointer()) == NULL)
					throw Exception("%s is not a Skeleton", skeletonName.c_str());
				skeletonShape= (CSkeletonShape*)strShape.getShapePointer();

				// The second var is the filename of the lod.
				string	lodFileName= clod_anim_list.asString(1);

				// Load the shape.
				CLodCharacterShapeBuild		lodShapeBuild;
				iFile.open( CPath::lookup(lodFileName) );
				iFile.serial(lodShapeBuild);
				iFile.close();

				// Prepare to build the lod.
				CLodCharacterBuilder		lodBuilder;
				lodBuilder.setShape(lodName, skeletonShape, &lodShapeBuild);


				// Traverse all anim in the list.
				//===========================
				uint	animId;
				for (animId = 2; animId < (uint)clod_anim_list.size(); animId++)
				{
					string	animFileName= clod_anim_list.asString(animId);

					// display.
					printf("Process Anim: %d/%d\r", animId-1, clod_anim_list.size()-2);

					// Try to load the animation
					CAnimation			*anim= new CAnimation;
					// NB: continue, to list all ANIM if anim not found
					try
					{
						iFile.open( CPath::lookup(animFileName) );
						iFile.serial(*anim);
						iFile.close();
						// Add to the builder. NB: animation will be delete in this method.
						// NB: the key name here is the entire file, with the .anim, for easier georges editing.
						lodBuilder.addAnim(animFileName.c_str(), anim, bakeFrameRate);
					}
					catch(EPathNotFound &)
					{
						printf("ERROR anim not found %s\n", animFileName.c_str());
						delete	anim;
					}
				}
				printf("\n");

				// Add to the bank.
				//===========================
				uint32	shapeId= lodShapeBank.addShape();
				*lodShapeBank.getShapeFullAcces(shapeId)= lodBuilder.getLodShape();
			}
			catch(EUnknownVar &evar)
			{
				nlwarning(evar.what());
				// Any other exception will make the program quit.
			}

		}

		// Save bank.
		//===========================

		// compile
		lodShapeBank.compile();

		// Save
		COFile	oFile(argv[3]);
		oFile.serial(lodShapeBank);
		oFile.close();
	}
	catch (Exception& except)
	{
		// Error message
		printf ("ERROR %s.\n Aborting.\n", except.what());
	}


	return 0;
}
Beispiel #20
0
int main(int argc, char* argv[])
{
	// Filter addSearchPath
	NLMISC::createDebug();
	InfoLog->addNegativeFilter ("adding the path");

	// Register 3d
	registerSerial3d ();

	// Good number of args ?
	if (argc<5)
	{
		// Help message
		printf ("%s [zonein.zonel] [igout.ig] [parameter_file] [dependancy_file]\n", argv[0]);
	}
	else
	{
		// Ok, read the zone
		CIFile inputFile;

		// Get extension
		string ext=getExt (argv[1]);
		string dir=getDir (argv[1]);

		// Open it for reading
		if (inputFile.open (argv[1]))
		{
			// Zone name
			string zoneName=toLower (string ("zone_"+getName (argv[1])));

			// Load the zone
			try
			{
				// Read the config file
				CConfigFile parameter;

				// Load and parse the parameter file
				parameter.load (argv[3]);

				// **********
				// *** Build the lighter descriptor
				// **********

				CInstanceLighter::CLightDesc lighterDesc;

				// Light direction
				CConfigFile::CVar &sun_direction = parameter.getVar ("sun_direction");
				lighterDesc.LightDirection.x=sun_direction.asFloat(0);
				lighterDesc.LightDirection.y=sun_direction.asFloat(1);
				lighterDesc.LightDirection.z=sun_direction.asFloat(2);
				lighterDesc.LightDirection.normalize ();

				// Grid size
				CConfigFile::CVar &quad_grid_size = parameter.getVar ("quad_grid_size");
				lighterDesc.GridSize=quad_grid_size.asInt();

				// Grid size
				CConfigFile::CVar &quad_grid_cell_size = parameter.getVar ("quad_grid_cell_size");
				lighterDesc.GridCellSize=quad_grid_cell_size.asFloat();

				// Shadows enabled ?
				CConfigFile::CVar &shadow = parameter.getVar ("shadow");
				lighterDesc.Shadow=shadow.asInt ()!=0;

				// OverSampling
				CConfigFile::CVar &ig_oversampling = parameter.getVar ("ig_oversampling");
				lighterDesc.OverSampling= ig_oversampling.asInt ();
				// validate value: 0, 2, 4, 8, 16
				lighterDesc.OverSampling= raiseToNextPowerOf2(lighterDesc.OverSampling);
				clamp(lighterDesc.OverSampling, 0U, 16U);
				if(lighterDesc.OverSampling<2)
					lighterDesc.OverSampling= 0;

				// For ig of Zones, never disable Sun contrib !!!
				lighterDesc.DisableSunContribution= false;

				// Get the search pathes
				CConfigFile::CVar &search_pathes = parameter.getVar ("search_pathes");
				uint path;
				for (path = 0; path < (uint)search_pathes.size(); path++)
				{
					// Add to search path
					CPath::addSearchPath (search_pathes.asString(path));
				}

				// A landscape allocated with new: it is not delete because destruction take 3 secondes more!
				CLandscape *landscape=new CLandscape;
				landscape->init();

				// A zone lighter
				CMyIgZoneLighter lighter;
				lighter.init ();

				// A vector of zone id
				vector<uint> listZoneId;

				// The zone
				CZone zone;

				// List of ig
				std::list<CInstanceGroup*> instanceGroup;

				// Load
				zone.serial (inputFile);
				inputFile.close();

				// Load ig of the zone
				string igName = getName (argv[1])+".ig";
				string igNameLookup = CPath::lookup (igName, false, false);
				if (!igNameLookup.empty())
					igName = igNameLookup;

				bool zoneIgLoaded;

				// Try to open the file
				CInstanceGroup *centerInstanceGroup= NULL;
				if (inputFile.open (igName))
				{
					// load the center ig
					centerInstanceGroup=new CInstanceGroup;

					// Serial it
					centerInstanceGroup->serial (inputFile);
					inputFile.close();

					// Add to the list
					instanceGroup.push_back (centerInstanceGroup);
					zoneIgLoaded = true;
				}
				else
				{
					// Warning
					fprintf (stderr, "Warning: can't load instance group %s\n", igName.c_str());
					zoneIgLoaded = false;
				}

				// If can't load the center instanceGroup, skip it.
				if(!zoneIgLoaded)
					return 0;

				// Get bank path
				CConfigFile::CVar &bank_name_var = parameter.getVar ("bank_name");
				string bank_name = bank_name_var.asString ();
				string bank_name_lookup = CPath::lookup (bank_name);
				if (!bank_name_lookup.empty())
					bank_name = bank_name_lookup;

				// Load the bank
				if (inputFile.open (bank_name))
				{
					try
					{
						// Load
						landscape->TileBank.serial (inputFile);
						landscape->initTileBanks();
					}
					catch (const Exception &e)
					{
						// Error
						nlwarning ("ERROR error loading tile bank %s\n%s\n", bank_name.c_str(), e.what());
					}
				}
				else
				{
					// Error
					nlwarning ("ERROR can't load tile bank %s\n", bank_name.c_str());
				}

				// Add the zone
				landscape->addZone (zone);
				listZoneId.push_back (zone.getZoneId());

				// Load instance group ?
				CConfigFile::CVar &load_ig= parameter.getVar ("load_ig");
				bool loadInstanceGroup = load_ig.asInt ()!=0;

				// Continue to build ?
				bool continu=true;

				// Try to load additionnal instance group.
				if (loadInstanceGroup)
				{
					// Additionnal instance group
					try
					{
						CConfigFile::CVar &additionnal_ig = parameter.getVar ("additionnal_ig");									
						for (uint add=0; add<(uint)additionnal_ig.size(); add++)
						{
							// Input file
							CIFile inputFile;

							// Name of the instance group
							string name = additionnal_ig.asString(add);
							string nameLookup = CPath::lookup (name, false, false);
							if (!nameLookup.empty())
								name = nameLookup;

							// Try to open the file
							if (inputFile.open (name))
							{
								// New ig
								CInstanceGroup *group=new CInstanceGroup;

								// Serial it
								group->serial (inputFile);
								inputFile.close();

								// Add to the list
								instanceGroup.push_back (group);
							}
							else
							{
								// Error
								nlwarning ("ERROR can't load instance group %s\n", name.c_str());

								// Stop before build
								continu=false;
							}
						}
					}
					catch (const NLMISC::EUnknownVar &)
					{
						nlinfo("No additionnal ig's to load");
					}
				}
				
				// Shadow ?
				if (lighterDesc.Shadow)
				{
					// Load and parse the dependency file
					CConfigFile dependency;
					dependency.load (argv[4]);

					// *** Scan dependency file
					CConfigFile::CVar &dependant_zones = dependency.getVar ("dependencies");
					for (uint i=0; i<(uint)dependant_zones.size(); i++)
					{
						// Get zone name
						string zoneName=dependant_zones.asString(i);

						// Load the zone
						CZone zoneBis;

						// Open it for reading
						if (inputFile.open (dir+zoneName+ext))
						{
							// Read it
							zoneBis.serial (inputFile);
							inputFile.close();

							// Add the zone
							landscape->addZone (zoneBis);
							listZoneId.push_back (zoneBis.getZoneId());
						}
						else
						{
							// Error message and continue
							nlwarning ("ERROR can't load zone %s\n", (dir+zoneName+ext).c_str());
						}

						// Try to load an instance group.
						if (loadInstanceGroup)
						{
							string name = zoneName+".ig";
							string nameLookup = CPath::lookup (name, false, false);
							if (!nameLookup.empty())
								name = nameLookup;

							// Name of the instance group
							if (inputFile.open (name))
							{
								// New ig
								CInstanceGroup *group=new CInstanceGroup;

								// Serial it
								group->serial (inputFile);
								inputFile.close();

								// Add to the list
								instanceGroup.push_back (group);
							}
							else
							{
								// Error message and continue
								nlwarning ("WARNING can't load instance group %s\n", name.c_str());
							}
						}
					}
				}

				// A vector of CInstanceLighter::CTriangle
				vector<CInstanceLighter::CTriangle> vectorTriangle;

				// **********
				// *** Build triangle array
				// **********

				landscape->checkBinds ();

				// Add triangles from landscape, for pointLight lighting.
				landscape->enableAutomaticLighting (false);
				lighter.addTriangles (*landscape, listZoneId, 0, vectorTriangle);

				// Load and add shapes

				// Map of shape
				std::map<string, IShape*> shapeMap;

				// For each instance group
				std::list<CInstanceGroup*>::iterator ite=instanceGroup.begin();
				while (ite!=instanceGroup.end())
				{
					// Instance group
					CInstanceGroup *group=*ite;

					// For each instance
					for (uint instance=0; instance<group->getNumInstance(); instance++)
					{
						// Get the instance shape name
						string name=group->getShapeName (instance);

						// Skip it?? use the DontCastShadowForExterior flag. See doc of this flag
						if(group->getInstance(instance).DontCastShadow || group->getInstance(instance).DontCastShadowForExterior)
							continue;

						// Add a .shape at the end ?
						if (!name.empty())
						{
							if (name.find('.') == std::string::npos)
								name += ".shape";

							// Find the file
							string nameLookup = CPath::lookup (name, false, false);
							if (!nameLookup.empty())
								name = nameLookup;

							// Find the shape in the bank
							std::map<string, IShape*>::iterator iteMap=shapeMap.find (name);
							if (iteMap==shapeMap.end())
							{
								// Input file
								CIFile inputFile;

								if (inputFile.open (name))
								{
									// Load it
									CShapeStream stream;
									stream.serial (inputFile);

									// Get the pointer
									iteMap=shapeMap.insert (std::map<string, IShape*>::value_type (name, stream.getShapePointer ())).first;
								}
								else
								{
									// Error
									nlwarning ("WARNING can't load shape %s\n", name.c_str());
								}
							}
							
							// Loaded ?
							if (iteMap!=shapeMap.end())
							{
								// Build the matrix
								CMatrix scale;
								scale.identity ();
								scale.scale (group->getInstanceScale (instance));
								CMatrix rot;
								rot.identity ();
								rot.setRot (group->getInstanceRot (instance));
								CMatrix pos;
								pos.identity ();
								pos.setPos (group->getInstancePos (instance));
								CMatrix mt=pos*rot*scale;

								// If centerInstanceGroup, take good instanceId, to avoid selfShadowing
								sint	instanceId;
								if(group == centerInstanceGroup)
									instanceId= instance;
								else
									instanceId= -1;

								// Add triangles
								lighter.addTriangles (*iteMap->second, mt, vectorTriangle, instanceId);
							}
						}
					}

					// For each point light of the ig
					const std::vector<CPointLightNamed>	&pointLightList= group->getPointLightList();
					for (uint plId=0; plId<pointLightList.size(); plId++)
					{
						// Add it to the Ig.
						lighter.addStaticPointLight(pointLightList[plId], igName.c_str ());
					}

					// Next instance group
					ite++;
				}

				// Continue ?
				if (continu)
				{
					// **********
					// *** Light!
					// **********

					// Start time
					TTime time=CTime::getLocalTime ();

					// Output ig
					CInstanceGroup	output;

					// Light the zone
					lighter.light (*centerInstanceGroup, output, lighterDesc, vectorTriangle, landscape);

					// Compute time
					printf ("\rCompute time: %d ms                                                      \r", 
						(uint)(CTime::getLocalTime ()-time));

					// Save the zone
					COFile outputFile;

					// Open it
					if (outputFile.open (argv[2]))
					{
						try
						{
							// Save the new ig
							outputFile.serial(output);
						}
						catch (const Exception& except)
						{
							// Error message
							nlwarning ("ERROR writing %s: %s\n", argv[2], except.what());
						}
					}
					else
					{
						// Error can't open the file
						nlwarning ("ERROR Can't open %s for writing\n", argv[2]);
					}
				}
				else
				{
					// Error
					nlwarning ("ERROR Abort: files are missing.\n");
				}
			}
			catch (const Exception& except)
			{
				// Error message
				nlwarning ("ERROR %s\n", except.what());
			}
		}
		else
		{
			// Error can't open the file
			nlwarning ("ERROR Can't open %s for reading\n", argv[1]);
		}

	}
	

	// Landscape is not deleted, nor the instanceGroups, for faster quit.
	// Must disalbe BlockMemory checks (for pointLights).
	NL3D_BlockMemoryAssertOnPurge= false;

	// exit.
	return 0;
}
Beispiel #21
0
/****************************************************************\
						init()
\****************************************************************/
void initViewerConfig(const char * configFileName)
{
	FILE * f = fopen(configFileName,"rt");
	if(f==NULL)
	{
		nlwarning("'%s' not found, default values used", configFileName);
		writeConfigFile(configFileName);
	}
	else fclose (f);
	
	try
	{
		CConfigFile cf;
	
		cf.load(configFileName);
	
		CConfigFile::CVar &cvFullScreen = cf.getVar("FullScreen");
		ViewerCfg.Windowed = cvFullScreen.asInt() ? false : true;
		
		CConfigFile::CVar &cvWidth = cf.getVar("Width");
		ViewerCfg.Width = cvWidth.asInt();

		CConfigFile::CVar &cvHeight = cf.getVar("Height");
		ViewerCfg.Height = cvHeight.asInt();

		CConfigFile::CVar &cvDepth = cf.getVar("Depth");
		ViewerCfg.Depth = cvDepth.asInt();

		CConfigFile::CVar &cvPosition = cf.getVar("Position");
		nlassert(cvPosition.size()==3);
		ViewerCfg.Position.x = cvPosition.asFloat(0);
		ViewerCfg.Position.y = cvPosition.asFloat(1);
		ViewerCfg.Position.z = cvPosition.asFloat(2);

		CConfigFile::CVar &cvEyesHeight = cf.getVar("EyesHeight");
		ViewerCfg.EyesHeight = CVector(0,0,cvEyesHeight.asFloat());

		CConfigFile::CVar &cvBackColor = cf.getVar("Background");
		nlassert(cvBackColor.size()==3);
		ViewerCfg.Background.R = cvBackColor.asInt(0);
		ViewerCfg.Background.G = cvBackColor.asInt(1);
		ViewerCfg.Background.B = cvBackColor.asInt(2);

		CConfigFile::CVar &cvZFar = cf.getVar("ZFar");
		ViewerCfg.ZFar = cvZFar.asFloat();

		CConfigFile::CVar &cvAutoLight = cf.getVar("AutoLight");
		ViewerCfg.AutoLight = cvAutoLight.asInt() ? true : false;

		CConfigFile::CVar &cvLightDir = cf.getVar("LightDir");
		nlassert(cvLightDir.size()==3);
		ViewerCfg.LightDir.x = cvLightDir.asFloat(0);
		ViewerCfg.LightDir.y = cvLightDir.asFloat(1);
		ViewerCfg.LightDir.z = cvLightDir.asFloat(2);

		CConfigFile::CVar &cvLandscapeTileNear = cf.getVar("LandscapeTileNear");
		ViewerCfg.LandscapeTileNear = cvLandscapeTileNear.asFloat();

		CConfigFile::CVar &cvLandscapeThreshold = cf.getVar("LandscapeThreshold");
		ViewerCfg.LandscapeThreshold = cvLandscapeThreshold.asFloat();

		CConfigFile::CVar &cvLandscapeNoise = cf.getVar("LandscapeNoise");
		ViewerCfg.LandscapeNoise = cvLandscapeNoise.asInt() != 0;

		CConfigFile::CVar &cvBanksPath = cf.getVar("BanksPath");
		ViewerCfg.BanksPath = cvBanksPath.asString();

		CConfigFile::CVar &cvTilesPath = cf.getVar("TilesPath");
		ViewerCfg.TilesPath = cvTilesPath.asString();

		CConfigFile::CVar &cvUseDDS = cf.getVar("UseDDS");
		ViewerCfg.UseDDS = cvUseDDS.asInt() ? true : false;

		CConfigFile::CVar &cvAllPathRelative = cf.getVar("AllPathRelative");
		ViewerCfg.AllPathRelative = cvAllPathRelative.asInt() ? true : false;

		CConfigFile::CVar &cvBank = cf.getVar("Bank");
		ViewerCfg.Bank = cvBank.asString();
		
		CConfigFile::CVar &cvZonesPath = cf.getVar("ZonesPath");
		ViewerCfg.ZonesPath = cvZonesPath.asString();
		CPath::addSearchPath(cvZonesPath.asString());

		CConfigFile::CVar &cvIgPath = cf.getVar("IgPath");
		ViewerCfg.IgPath = cvIgPath.asString();
		CPath::addSearchPath(cvIgPath.asString());

		CConfigFile::CVar &cvShapePath = cf.getVar("ShapePath");
		ViewerCfg.ShapePath = cvShapePath.asString();
		CPath::addSearchPath(cvShapePath.asString());

		CConfigFile::CVar &cvMapsPath = cf.getVar("MapsPath");
		ViewerCfg.MapsPath = cvMapsPath.asString();
		CPath::addSearchPath(cvMapsPath.asString());

		CConfigFile::CVar &cvFontPath = cf.getVar("FontPath");
		ViewerCfg.FontPath = cvFontPath.asString();

		CConfigFile::CVar &cvHeightFieldName = cf.getVar("HeightFieldName");
		ViewerCfg.HeightFieldName = cvHeightFieldName.asString();
		
		CConfigFile::CVar &cvHeightFieldMaxZ = cf.getVar("HeightFieldMaxZ");
		ViewerCfg.HeightFieldMaxZ = cvHeightFieldMaxZ.asFloat();

		CConfigFile::CVar &cvHeightFieldOriginX = cf.getVar("HeightFieldOriginX");
		ViewerCfg.HeightFieldOriginX = cvHeightFieldOriginX.asFloat();

		CConfigFile::CVar &cvHeightFieldOriginY = cf.getVar("HeightFieldOriginY");
		ViewerCfg.HeightFieldOriginY = cvHeightFieldOriginY.asFloat();

		CConfigFile::CVar &cvHeightFieldSizeX = cf.getVar("HeightFieldSizeX");
		ViewerCfg.HeightFieldSizeX = cvHeightFieldSizeX.asFloat();

		CConfigFile::CVar &cvHeightFieldSizeY = cf.getVar("HeightFieldSizeY");
		ViewerCfg.HeightFieldSizeY = cvHeightFieldSizeY.asFloat();


		CConfigFile::CVar &cvLandAmb = cf.getVar("LandAmbient");
		nlassert(cvLandAmb.size()==3);
		ViewerCfg.LandAmbient.R = cvLandAmb.asInt(0);
		ViewerCfg.LandAmbient.G = cvLandAmb.asInt(1);
		ViewerCfg.LandAmbient.B = cvLandAmb.asInt(2);

		CConfigFile::CVar &cvLandDiff = cf.getVar("LandDiffuse");
		nlassert(cvLandDiff.size()==3);
		ViewerCfg.LandDiffuse.R = cvLandDiff.asInt(0);
		ViewerCfg.LandDiffuse.G = cvLandDiff.asInt(1);
		ViewerCfg.LandDiffuse.B = cvLandDiff.asInt(2);


		CConfigFile::CVar &cvZones = cf.getVar("Zones");
		for(uint i=0; i<cvZones.size(); i++)
		{
			ViewerCfg.Zones.push_back(cvZones.asString(i));
		}

		CConfigFile::CVar &cvIgs = cf.getVar("Ig");
		for(uint i=0; i<cvIgs.size(); i++)
		{
			ViewerCfg.Igs.push_back(cvIgs.asString(i));
		}

	}
	catch (EConfigFile &e)
	{
		nlerror("Problem in config file : %s\n", e.what ());
	}

}
// ***************************************************************************
int main(int argc, char* argv[])
{
	// Filter addSearchPath
	NLMISC::createDebug();
	InfoLog->addNegativeFilter ("adding the path");

	// Register 3d
	registerSerial3d ();

	// Good number of args ?
	if (argc<4)
	{
		// Help message
		printf ("ig_lighter [directoryIn] [pathOut] [parameter_file] \n");
	}
	else
	{
		try
		{
			string	directoryIn= argv[1];
			string	pathOut= argv[2];
			string	paramFile= argv[3];
			CInstanceLighter::CLightDesc	lighterDesc;
			string	grFile, rbankFile;

			// Verify directoryIn.
			directoryIn= CPath::standardizePath(directoryIn);
			if( !CFile::isDirectory(directoryIn) )
			{
				printf("DirectoryIn %s is not a directory", directoryIn.c_str());
				return -1;
			}
			// Verify pathOut.
			pathOut= CPath::standardizePath(pathOut);
			if( !CFile::isDirectory(pathOut) )
			{
				printf("PathOut %s is not a directory", pathOut.c_str());
				return -1;
			}

			// Load and setup configFile.
			//=================
			CConfigFile parameter;
			// Load and parse the param file
			parameter.load (paramFile);

			// Get the search pathes
			CConfigFile::CVar &search_pathes = parameter.getVar ("search_pathes");
			uint path;
			for (path = 0; path < (uint)search_pathes.size(); path++)
			{
				// Add to search path
				CPath::addSearchPath (search_pathes.asString(path));
			}

			// Light direction
			CConfigFile::CVar &sun_direction = parameter.getVar ("sun_direction");
			lighterDesc.LightDirection.x=sun_direction.asFloat(0);
			lighterDesc.LightDirection.y=sun_direction.asFloat(1);
			lighterDesc.LightDirection.z=sun_direction.asFloat(2);
			lighterDesc.LightDirection.normalize ();

			// Grid size
			CConfigFile::CVar &quad_grid_size = parameter.getVar ("quad_grid_size");
			lighterDesc.GridSize=quad_grid_size.asInt();

			// Grid size
			CConfigFile::CVar &quad_grid_cell_size = parameter.getVar ("quad_grid_cell_size");
			lighterDesc.GridCellSize=quad_grid_cell_size.asFloat();

			// Shadows enabled ?
			CConfigFile::CVar &shadow = parameter.getVar ("shadow");
			lighterDesc.Shadow=shadow.asInt ()!=0;

			// OverSampling
				CConfigFile::CVar &ig_oversampling = parameter.getVar ("ig_oversampling");
				lighterDesc.OverSampling= ig_oversampling.asInt ();
			// validate value: 0, 2, 4, 8, 16
			lighterDesc.OverSampling= raiseToNextPowerOf2(lighterDesc.OverSampling);
			clamp(lighterDesc.OverSampling, 0U, 16U);
			if(lighterDesc.OverSampling<2)
				lighterDesc.OverSampling= 0;

			// gr
			CConfigFile::CVar &grbank = parameter.getVar ("grbank");
			grFile= grbank.asString ();

			// rbank
			CConfigFile::CVar &rbank = parameter.getVar ("rbank");
			rbankFile= rbank.asString ();

			// CellSurfaceLightSize;
			CConfigFile::CVar &cell_surface_light_size = parameter.getVar ("cell_surface_light_size");
			float cellSurfaceLightSize= cell_surface_light_size.asFloat ();
			if(cellSurfaceLightSize<=0)
				throw Exception("cell_surface_light_size must be > 0");

			// CellRaytraceDeltaZ
			CConfigFile::CVar &cell_raytrace_delta_z = parameter.getVar ("cell_raytrace_delta_z");
			float cellRaytraceDeltaZ= cell_raytrace_delta_z.asFloat ();


			// colIdentifierPrefix
			CConfigFile::CVar &col_identifier_prefix = parameter.getVar ("col_identifier_prefix");
			string colIdentifierPrefix= col_identifier_prefix.asString ();

			// colIdentifierSuffix
			CConfigFile::CVar &col_identifier_suffix = parameter.getVar ("col_identifier_suffix");
			string colIdentifierSuffix= col_identifier_suffix.asString ();

			// colIdentifierSuffix
			CConfigFile::CVar &build_debug_surface_shape = parameter.getVar ("build_debug_surface_shape");
			bool	buildDebugSurfaceShape= build_debug_surface_shape.asInt()!=0;
			

			// try to open gr and rbank
			CRetrieverBank		*retrieverBank= NULL;
			CGlobalRetriever	*globalRetriever= NULL;
			uint32		grFileDate= 0;
			uint32		rbankFileDate= 0;
			if( grFile!="" && rbankFile!="" )
			{
				CIFile	fin;
				// serial the retrieverBank. Exception if not found.
				fin.open(CPath::lookup(rbankFile));
				retrieverBank= new CRetrieverBank;
				retrieverBank->setNamePrefix(CFile::getFilenameWithoutExtension(rbankFile).c_str ());

				// Add the search path for LR files
				CPath::addSearchPath (CFile::getPath(rbankFile));

				fin.serial(*retrieverBank);
				fin.close();

				// serial the globalRetriever. Exception if not found.
				fin.open(CPath::lookup(grFile));
				globalRetriever= new CGlobalRetriever;

				// set the RetrieverBank before loading
				globalRetriever->setRetrieverBank(retrieverBank);
				fin.serial(*globalRetriever);
				fin.close();

				// Get File Dates
				rbankFileDate= CFile::getFileModificationDate(CPath::lookup(rbankFile));
				grFileDate= CFile::getFileModificationDate(CPath::lookup(grFile));

				// And init them.
				globalRetriever->initAll();
			}


			// Scan and load all files .ig in directories
			//=================
			vector<string>				listFile;
			vector<CInstanceGroup*>		listIg;
			vector<string>				listIgFileName;
			vector<string>				listIgPathName;
			CPath::getPathContent(directoryIn, false, false, true, listFile);
			for(uint iFile=0; iFile<listFile.size(); iFile++)
			{
				string	&igFile= listFile[iFile];
				// verify it is a .ig.
				if( CFile::getExtension(igFile) == "ig" )
				{
					// Read the InstanceGroup.
					CInstanceGroup	*ig= new CInstanceGroup;
					CIFile	fin;
					fin.open(CPath::lookup(igFile));
					fin.serial(*ig);

					// add to list.
					listIg.push_back(ig);
					listIgPathName.push_back(igFile);
					listIgFileName.push_back(CFile::getFilename(igFile));
				}
			}


			// For all ig, light them, and save.
			//=================
			for(uint iIg= 0; iIg<listIg.size(); iIg++)
			{
				string	fileNameIn= listIgFileName[iIg];
				string	fileNameOut= pathOut + fileNameIn;

				// If File Out exist 
				if(CFile::fileExists(fileNameOut))
				{
					// If newer than file In (and also newer than retrieverInfos), skip
					uint32		fileOutDate= CFile::getFileModificationDate(fileNameOut);
					if(	fileOutDate > CFile::getFileModificationDate(listIgPathName[iIg]) &&
						fileOutDate > rbankFileDate && 
						fileOutDate > grFileDate 
						)
					{
						printf("Skiping %s\n", fileNameIn.c_str());
						continue;
					}
				}

				// progress
				printf("Processing %s\n", fileNameIn.c_str());

				CInstanceGroup	igOut;

				// Export a debugSun Name.
				string	debugSunName;
				debugSunName= pathOut + "/" + CFile::getFilenameWithoutExtension(fileNameIn) + "_debug_sun_.shape";
				string	debugPLName;
				debugPLName= pathOut + "/" + CFile::getFilenameWithoutExtension(fileNameIn) + "_debug_pl_.shape";

				// light the ig.
				CIgLighterLib::CSurfaceLightingInfo	slInfo;
				slInfo.CellSurfaceLightSize= cellSurfaceLightSize;
				slInfo.CellRaytraceDeltaZ= cellRaytraceDeltaZ;
				slInfo.RetrieverBank= retrieverBank;
				slInfo.GlobalRetriever= globalRetriever;
				slInfo.IgFileName= CFile::getFilenameWithoutExtension(fileNameIn);
				slInfo.ColIdentifierPrefix= colIdentifierPrefix;
				slInfo.ColIdentifierSuffix= colIdentifierSuffix;
				slInfo.BuildDebugSurfaceShape= buildDebugSurfaceShape;
				slInfo.DebugSunName= debugSunName;
				slInfo.DebugPLName= debugPLName;
				lightIg(*listIg[iIg], igOut, lighterDesc, slInfo, fileNameIn.c_str ());

				// Save this ig.
				COFile	fout;
				fout.open(fileNameOut);
				fout.serial(igOut);
				fout.close();

				// skip a line
				printf("\n");
			}

		}
		catch (Exception& except)
		{
			// Error message
			nlwarning ("ERROR %s\n", except.what());
		}
	}


	// Landscape is not deleted, nor the instanceGroups, for faster quit.
	// Must disalbe BlockMemory checks (for pointLights).
	NL3D_BlockMemoryAssertOnPurge= false;


	// exit.
	return 0;
}
Beispiel #23
0
/* Load the config file and the related words files. Return false in case of failure.
 * Config file variables:
 * - WordsPath: where to find <filter>_words_<languageCode>.txt
 * - LanguageCode: language code (ex: en for English)
 * - Utf8: results are in UTF8, otherwise in ANSI string
 * - Filter: "*" for all files (default) or a name (ex: "item").
 * - AdditionalFiles/AdditionalFileColumnTitles
 */
bool CWordsDictionary::init( const string& configFileName )
{
	// Read config file
	bool cfFound = false;
	CConfigFile cf;
	try
	{
		cf.load( configFileName );
		cfFound = true;
	}
	catch ( EConfigFile& e )
	{
		nlwarning( "WD: %s", e.what() );
	}
	string wordsPath, languageCode, filter = "*";
	vector<string> additionalFiles, additionalFileColumnTitles;
	bool filterAll = true, utf8 = false;
	if ( cfFound )
	{
		CConfigFile::CVar *v = cf.getVarPtr( "WordsPath" );
		if ( v )
		{
			wordsPath = v->asString();
			/*if ( (!wordsPath.empty()) && (wordsPath[wordsPath.size()-1]!='/') )
				wordsPath += '/';*/
		}
		v = cf.getVarPtr( "LanguageCode" );
		if ( v )
			languageCode = v->asString();
		v = cf.getVarPtr( "Utf8" );
		if ( v )
			utf8 = (v->asInt() == 1);
		v = cf.getVarPtr( "Filter" );
		if ( v )
		{
			filter = v->asString();
			filterAll = (filter == "*");
		}
		v = cf.getVarPtr( "AdditionalFiles" );
		if ( v )
		{
			for ( uint i=0; i!=v->size(); ++i )
				additionalFiles.push_back( v->asString( i ) );
			v = cf.getVarPtr( "AdditionalFileColumnTitles" );
			if ( v->size() != additionalFiles.size() )
			{
				nlwarning( "AdditionalFiles and AdditionalFileColumnTitles have different size, ignoring second one" );
				additionalFileColumnTitles.resize( v->size(), DefaultColTitle );
			}
			else
			{
				for ( uint i=0; i!=v->size(); ++i )
					additionalFileColumnTitles.push_back( v->asString( i ) );
			}
		}

	}
	if ( languageCode.empty() )
		languageCode = "en";

	// Load all found words files
	const string ext = ".txt";
	vector<string> fileList;
	CPath::getPathContent( wordsPath, false, false, true, fileList );
	for ( vector<string>::const_iterator ifl=fileList.begin(); ifl!=fileList.end(); ++ifl )
	{
		const string& filename = (*ifl);
		string::size_type p = string::npos;
		bool isAdditionalFile = false;

		// Test if filename is in additional file list
		uint iAdditionalFile;
		for ( iAdditionalFile=0; iAdditionalFile!=additionalFiles.size(); ++iAdditionalFile )
		{
			if ( (p = filename.find( additionalFiles[iAdditionalFile] )) != string::npos )
			{
				isAdditionalFile = true;
				break;
			}
		}

		// Or test if filename is a words_*.txt file
		string pattern = string("_words_") + languageCode + ext;
		if ( isAdditionalFile ||
			 ((p = filename.find( pattern )) != string::npos) )
		{
			// Skip if a filter is specified and does not match the current file
			if ( (!filterAll) && (filename.find( filter+pattern ) == string::npos) )
				continue;

			// Load file
			nldebug( "WD: Loading %s", filename.c_str() );
			_FileList.push_back( filename );
			string::size_type origSize = filename.size() - ext.size();
			const string truncFilename = CFile::getFilenameWithoutExtension( filename );
			const string wordType = isAdditionalFile ? "" : truncFilename.substr( 0, p - (origSize - truncFilename.size()) );
			const string colTitle = isAdditionalFile ? additionalFileColumnTitles[iAdditionalFile] : DefaultColTitle;

			// Load Unicode Excel words file
			STRING_MANAGER::TWorksheet worksheet;
			STRING_MANAGER::loadExcelSheet( filename, worksheet );
			uint ck, cw = 0;
			if ( worksheet.findId( ck ) && worksheet.findCol( ucstring(colTitle), cw ) ) // =>
			{
				for ( std::vector<STRING_MANAGER::TWorksheet::TRow>::iterator ip = worksheet.begin(); ip!=worksheet.end(); ++ip )
				{
					if ( ip == worksheet.begin() ) // skip first row
						continue;
					STRING_MANAGER::TWorksheet::TRow& row = *ip;
					_Keys.push_back( row[ck].toString() );
					string word = utf8 ? row[cw].toUtf8() : row[cw].toString();
					_Words.push_back( word );
				}
			}
			else
				nlwarning( "WD: %s ID or %s not found in %s", wordType.c_str(), colTitle.c_str(), filename.c_str() );
		}
	}

	if ( _Keys.empty() )
	{
		if ( wordsPath.empty() )
			nlwarning( "WD: WordsPath missing in config file %s", configFileName.c_str() );
		nlwarning( "WD: %s_words_%s.txt not found", filter.c_str(), languageCode.c_str() );
		return false;
	}
	else
		return true;
}
Beispiel #24
0
/*
 * main
 */
void main (int argc, char **argv)
{
	string result;

	CConfigFile ConfigFile;
	
	ConfigFile.load ("client.cfg");

	string LSHost(ConfigFile.getVar("LSHost").asString());

	char	buf[256];
	printf("Login: "******"Password: "******"Login").asString();
	}

	if (Password.empty ())
	{
		Password = ConfigFile.getVar("Password").asString();
	}

	/* Try to connect to the login service and check the login, password and version of the client.
	 * return an empty string if all go well
	 */
	result = CLoginClient::authenticate(LSHost+":49999", Login, Password, "sample");
	
	if(!result.empty()) nlerror ("*** Authenticate failed '%s' ***", result.c_str());

	// CLoginClient::ShardList contains all available shards
	for (uint i = 0; i < CLoginClient::ShardList.size (); i++)
	{
		nlinfo("*** shard %d is: %s (%d) ***", i, CLoginClient::ShardList[i].Name.c_str (), CLoginClient::ShardList[i].Id);
	}

	/* Try to connect to the last shard number in the list.
	 * return an empty string if all go well
	 */

	string fs_ip, login_cookie;
	result = CLoginClient::wantToConnectToShard(CLoginClient::ShardList[CLoginClient::ShardList.size() - 1].Id, fs_ip, login_cookie);
	if (!result.empty()) nlerror("*** Select shard failed '%s' ***", result.c_str());
	CLoginCookie cookie; cookie.setFromString(login_cookie); // who's idea was it to send the cookie as a string...
	
	CCallbackClient *cnx = new CCallbackClient();
	result = CLoginClient::connectToShard(cookie, fs_ip, *cnx);

	if (!result.empty()) nlerror("*** Connection to the shard failed '%s' ***", result.c_str());

	nlinfo ("*** Connection granted! You are connected on the frond end ***");

	while (cnx->connected ())
	{
		cnx->update ();
		nlSleep(10);
	}

	if( cnx->connected ())
		cnx->disconnect ();

	delete cnx;
}
Beispiel #25
0
/*
	Demo General Knowledge Skill Tree


*0-COMMON SENSE
0-Luck

*10-PHILOSOPHY (All philosophy skills allow the character to change alignments and goals)
10-Western Secular
11-Pragmatism
12-Humanism
13-Transcendentalism
14-Existentialism
15-Ecstatic Nihilism
*	Eastern Secular
16-		Taoism
17-		Confucianism
*	Theology
18-		Paganism
19-		Judaism
20-		Christianity
21-		Islam
22-		Buddhism
23-		Metaversalism

*40-HISTORY (History Skills provide extra information when examining objects and people)
40-	Ancient (to 1000 AD)
41-	Modern (1000 AD to 2093)
42-	Sagas of the Great Dark
43-	History of the Metaverse

50-SURVIVAL (allows character to make fire)
51-	Foraging (allows the character to search for herbs, vegetation)
52-	Hunting (allows character to locate animals to hunt, track creatures)
53-	Directional Sense (allows character to assess cardinal directions)
*60-FAITH
60-	Piety
61-	Hermeneutics
62-	Divining

Mystic Practice Skill Tree

*70-MAGIC
*70-	Sorcery
*70-		Material Realm
70-			Solid (Earth)
71			Liquid (Water)
72			Gaseous (Air)
73			Plasma (Fire)
*74		Immaterial Realm
74-			Electricity and Magnetism (Air)
75-			Time and Gravity (Earth)
76-			Morphic Resonance (Water)
77-			Weak, Strong & Gamma(Fire)
*78	Invocation
*78		Asatru (each god requires specialization)
-78			Odin (2M, 2H, 4O)
-79			Thor (2M, 4H, 2C)
-80			Frey (4M, 2M, 2O)
-81			Loki (4M, 4M, 4C)
-82			Freya (2M, 2H, N)
-83			Balder (N, 1H, 3O)

*90-RITUALS
*90	Mind
-90		Meditation (Increases Calm & Resonance)
-91		Trancing 	(Increased Mood & Resonance)
*92Body
-92		Chanting (Increased Mood & Resonance, decreases calm)
-93		Body Modification (Increased Mood)


*Action Skill Tree

*100-LOCOMOTION
-100	Jumping
-101	Running

*120-COMBAT
*120-	Throwing
-120		Blades
-121		Spherical
*122	Aimed
-122		Blow dart
-123		Bow
-124		Crossbow
-125		Pistol
-126		Projectile
-127		SMG
-128		Energy
-129		Long Arms
-130			Rifle
-131			Auto
-132			Heavy
-133			Launcher


*140-STEALTH
*140	BodyHide (
-140		Sneak
-141		Pickpocket

*150-PHYSICAL ARTS
-150	Dancing

*/
void			CSkills::createFromConfigFile( std::string configFileName)
{

    printf("Entering createFromConfigFile file.");

    CConfigFile cf;

    cf.load(configFileName+".textskills");

    printf("About to resize\n");

    _I16Skills.resize(151);

    _I16Skills[0] = cf.getVar("Luck").asInt();
    _I16Skills[10] = cf.getVar("WesternSecular").asInt();
    _I16Skills[11] = cf.getVar("Pragmatism").asInt();
    _I16Skills[12] = cf.getVar("Humanism").asInt();
    _I16Skills[13] = cf.getVar("Transcendentalism").asInt();
    _I16Skills[14] = cf.getVar("Existentialism").asInt();
    _I16Skills[15] = cf.getVar("EcstaticNihilism").asInt();
    _I16Skills[16] = cf.getVar("Taoism").asInt();
    _I16Skills[17] = cf.getVar("Confucianism").asInt();
    _I16Skills[18] = cf.getVar("Paganism").asInt();
    _I16Skills[19] = cf.getVar("Judaism").asInt();
    _I16Skills[20] = cf.getVar("Christianity").asInt();
    _I16Skills[21] = cf.getVar("Islam").asInt();
    _I16Skills[22] = cf.getVar("Buddhism").asInt();
    _I16Skills[23] = cf.getVar("Metaversalism").asInt();
    _I16Skills[40] = cf.getVar("AncientHistory").asInt();
    _I16Skills[41] = cf.getVar("ModernHistory").asInt();
    _I16Skills[42] = cf.getVar("GreatDarkSagas").asInt();
    _I16Skills[43] = cf.getVar("MetaverseHistory").asInt();
    _I16Skills[50] = cf.getVar("Survival").asInt();
    _I16Skills[51] = cf.getVar("Foraging").asInt();
    _I16Skills[52] = cf.getVar("Hunting").asInt();
    _I16Skills[53] = cf.getVar("Directional").asInt();
    _I16Skills[60] = cf.getVar("Piety").asInt();
    _I16Skills[61] = cf.getVar("Hermeneutics").asInt();
    _I16Skills[62] = cf.getVar("Divining").asInt();
    _I16Skills[70] = cf.getVar("Solid").asInt();
    _I16Skills[71] = cf.getVar("Liquid").asInt();
    _I16Skills[72] = cf.getVar("Gaseous").asInt();
    _I16Skills[73] = cf.getVar("Plasma").asInt();
    _I16Skills[74] = cf.getVar("Electricity").asInt();
    _I16Skills[75] = cf.getVar("Time").asInt();
    _I16Skills[76] = cf.getVar("Morphic").asInt();
    _I16Skills[77] = cf.getVar("WeakStrongGamma").asInt();
    _I16Skills[78] = cf.getVar("Odin").asInt();
    _I16Skills[79] = cf.getVar("Thor").asInt();
    _I16Skills[80] = cf.getVar("Frey").asInt();
    _I16Skills[81] = cf.getVar("Loki").asInt();
    _I16Skills[82] = cf.getVar("Freya").asInt();
    _I16Skills[83] = cf.getVar("Balder").asInt();
    _I16Skills[90] = cf.getVar("Meditation").asInt();
    _I16Skills[91] = cf.getVar("Trancing").asInt();
    _I16Skills[93] = cf.getVar("Chanting").asInt();
    _I16Skills[94] = cf.getVar("BodyModification").asInt();
    _I16Skills[100] = cf.getVar("Jumping").asInt();
    _I16Skills[101] = cf.getVar("Running").asInt();
    _I16Skills[120] = cf.getVar("ThrowingBlades").asInt();
    _I16Skills[121] = cf.getVar("ThrowingSpherical").asInt();
    _I16Skills[122] = cf.getVar("AimedBlowdart").asInt();
    _I16Skills[123] = cf.getVar("AimedBow").asInt();
    _I16Skills[124] = cf.getVar("AimedCrossbow").asInt();
    _I16Skills[125] = cf.getVar("AimedPistol").asInt();
    _I16Skills[126] = cf.getVar("AimedProjectile").asInt();
    _I16Skills[127] = cf.getVar("AimedSMG").asInt();
    _I16Skills[128] = cf.getVar("AimedEnergy").asInt();
    _I16Skills[129] = cf.getVar("AimedLongArms").asInt();
    _I16Skills[130] = cf.getVar("AimedRifle").asInt();
    _I16Skills[131] = cf.getVar("AimedAuto").asInt();
    _I16Skills[132] = cf.getVar("AimedHeavy").asInt();
    _I16Skills[133] = cf.getVar("AimedLauncher").asInt();
    _I16Skills[140] = cf.getVar("Sneak").asInt();
    _I16Skills[141] = cf.getVar("Pickpocket").asInt();
    _I16Skills[150] = cf.getVar("Dancing").asInt();

    printf("I have created the internal structure from config file.\n");

    save(configFileName);
    printf("I have saved the file\n");

}