示例#1
0
void CTile_edit_dlg::on_saveAsPushButton_clicked()
{
	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getSaveFileName(this, tr("Save Bank"), this->mainFile.absoluteFilePath(), tr("NeL tile bank files (*.bank);;All Files (*.*);;"), &selectedFilter, options);
	if (!fileName.isEmpty())
	{
		// Set MainFile
		mainFile = QFileInfo(fileName);
		ui.savePushButton->setEnabled(true);


		string fullPath = this->mainFile.absoluteFilePath().toUtf8();
		if ( !fullPath.empty() )
		{
			COFile stream;
			if ( stream.open( fullPath.c_str() ) )
			{
				tileBank.serial (stream);
				QString s = tr("Bank %1 saved").arg( QString( fullPath.c_str() ) );
				QMessageBox::information(this, tr("Bank Saved"), s);
				return;
			}
		}

		QMessageBox::information(this, tr("Error"), tr("Can't Save Bank, check the path"));

	}

}
示例#2
0
void CTile_edit_dlg::on_exportPushButton_clicked()
{
	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getSaveFileName(this, tr("Export Bank"), this->mainFile.absolutePath() + QDir::separator() + tr("*.smallbank"), tr("NeL tile small bank files (*.smallbank);;All Files (*.*);;"), &selectedFilter, options);
	if (!fileName.isEmpty())
	{
		// Copy the bank
		CTileBank copy=tileBank;

		// Remove unused data
		copy.cleanUnusedData ();

		QFileInfo fileInfo(fileName);
		string fullPath = fileInfo.absoluteFilePath().toUtf8();
		if ( !fullPath.empty() )
		{
			COFile stream;
			if ( stream.open( fullPath.c_str() ) )
			{
				copy.serial (stream);
				QString s = tr("Bank %1 exported").arg( QString( fullPath.c_str() ) );
				QMessageBox::information(this, tr("Bank Saved"), s);
				return;
			}
		}

		QMessageBox::information(this, tr("Error"), tr("Can't Export the Bank, check the path"));
	}
}
示例#3
0
bool CNelExport::exportVegetable (const char *sPath, INode& node, TimeValue time)
{
	bool bRet=false;

	// Build a vegetable
	NL3D::CVegetableShape vegetable;
	if (_ExportNel->buildVegetableShape (vegetable, node, time))
	{
		// Open a file
		COFile file;
		if (file.open (sPath))
		{
			try
			{
				// Serial the shape
				vegetable.serial (file);

				// All is good
				bRet=true;
			}
			catch (Exception &e)
			{
				// Message box
				const char *message = e.what();
				_ExportNel->outputErrorMessage ("Error during vegetable serialisation");
			}
		}
	}
	return bRet;
}
示例#4
0
void CSoundAnimation::save()
{
	// File stream
	COFile file;
	vector<NLMISC::CSheetId>	sounds;

	// Open the file
	if (!file.open(_Filename.c_str()))
	{
		throw NLMISC::Exception("Can't open the file for writing");
	}

	// Create the XML stream
	COXml output;

	// Init
	if (output.init (&file, "1.0"))
	{
		xmlDocPtr xmlDoc = output.getDocument();

		// Create the first node
		xmlNodePtr root = xmlNewDocNode (xmlDoc, NULL, (const xmlChar*)"SOUNDANIMATION", NULL);
		xmlDocSetRootElement (xmlDoc, root);

		vector<CSoundAnimMarker*>::iterator iter;
		for (iter = _Markers.begin(); iter != _Markers.end(); iter++)
		{
			CSoundAnimMarker* marker = (*iter);

			set<string>::iterator iter;

			char s[64];
			smprintf(s, 64, "%f", marker->getTime());

			xmlNodePtr markerNode = xmlNewChild (root, NULL, (const xmlChar*)"MARKER", NULL);
			xmlSetProp (markerNode, (const xmlChar*) "time", (const xmlChar*) s);

			marker->getSounds(sounds);

			vector<NLMISC::CSheetId>::iterator iter2;
			for (iter2 = sounds.begin(); iter2 != sounds.end(); iter2++)
			{
				xmlNodePtr soundNode = xmlNewChild ( markerNode, NULL, (const xmlChar*)"SOUND", NULL );
				xmlSetProp (soundNode, (const xmlChar*)"name", (const xmlChar*)iter2->toString().c_str() /*CStringMapper::unmap(*iter2).c_str()*/);
			}

			sounds.clear();
		}

		// Flush the stream, write all the output file
		output.flush ();
	}

	// Close the file
	file.close ();

	_Dirty = false;
}
示例#5
0
int main(int argc, char* argv[])
{
	// Arg ?
	if (argc<3)
	{
		// Doc
		printf ("build_smallbank [input.bank] [output.smallbank] [new_absolute_path]\n");
	}
	else
	{
		try
		{
			// Load the bank
			CTileBank bank;

			// Input file
			CIFile input;
			if (input.open (argv[1]))
			{
				// Serial the bank
				bank.serial (input);

				// Make a small bank
				bank.cleanUnusedData ();

				// Absolute path ?
				if (argc>3)
					bank.setAbsPath (argv[3]);

				// Output file
				COFile output;
				if (output.open (argv[2]))
				{
					// Serial the bank
					bank.serial (output);
				}
				else
				{
					// Error
					nlwarning ("ERROR can't open the file %s for writing", argv[2]);
				}
			}
			else
			{
				// Error
				nlwarning ("ERROR can't open the file %s for reading", argv[1]);
			}

		}
		catch (const Exception& e)
		{
			// Error
			nlwarning ("ERROR fatal error: %s", e.what());
		}
	}
	return 0;
}
示例#6
0
int main(int argc, char *argv[])
{
	if(argc != 4)
	{
		usage();
		return -1;
	}
	else
	{
		CBitmap		btmp;
		CIFile		inFile;
		COFile		outFile;

		uint	divideRatio;
		NLMISC::fromString(argv[3], divideRatio);
		if(divideRatio==0 || !isPowerOf2(divideRatio))
		{
			printf("divideRatio must be a powerOf2 (1, 2, 4, 8 ...) \n");
			return 0;
		}

		try
		{
			// read.
			if (!inFile.open(argv[1]))
			{
				printf("Can't open input file %s \n", argv[1]);
				return -1;
			}
			uint8	depth= btmp.load(inFile);
			if(depth==0)
				throw Exception("Bad File Format");
			inFile.close();

			// resize.
			btmp.resample(btmp.getWidth() / divideRatio, btmp.getHeight() / divideRatio);

			// output.
			if (!outFile.open(argv[2]))
			{
				printf("Can't open output file %s \n", argv[2]);
				return -1;
			}
			btmp.writeTGA(outFile, depth);
		}
		catch (const Exception &e)
		{
			printf("Error: %s\n", e.what());
				return -1;
		}

		return 0;
	}
}
示例#7
0
/** Generate list of spell
  */
static void generateSpellList(CConfigFile &cf, const std::string &sheetName)
{
	CConfigFile::CVar *spellList = cf.getVarPtr("spell_list");
	if (!spellList)
	{
		nlwarning("Can't read spell list");
		return;
	}	
	COFile f;
	if (!f.open(sheetName, false, true))
	{
		nlwarning("Can't write %s", sheetName.c_str());
		return;
	}
	try
	{	
		COXml xmlStreamOut;
		xmlStreamOut.init(&f);
		xmlStreamOut.xmlPush("FORM");
		IStream &xmlStream = xmlStreamOut;
		xmlStream.xmlPush("STRUCT");
		xmlStream.xmlPushBegin("ARRAY");
			xmlStream.xmlSetAttrib("Name");
			std::string name = "List";
			xmlStream.serial(name);					
		xmlStream.xmlPushEnd();				
		for(uint k = 0; k < (uint) spellList->size(); ++k)
		{
			std::vector<std::string> result;
			NLMISC::splitString(spellList->asString(k), "|", result);
			if (result.size()  < 2)
			{
				nlwarning("Should provide at list spell name and id");
			}
			xmlStream.xmlPush("STRUCT");				
				writeAtom(xmlStream, "ID", result[1]);
				writeAtom(xmlStream, "SheetBaseName", result[0]);
			xmlStream.xmlPop();
		}
		xmlStream.xmlPop(); // STRUCT
		xmlStream.xmlPop(); // FORM
	}
	catch(const EStream &)
	{
		nlwarning("Cant write %s", sheetName.c_str());
	}
}
// ---------------------------------------------------------------------------
void CGeorgesImpl::MakeTyp( const std::string& filename, TType type, TUI ui, const std::string& _min, const std::string& _max, const std::string& _default, const std::vector< std::pair< std::string, std::string > >* const _pvpredef )
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	// Create a type
	CType t;
	t.Type = (CType::TType)type;
	t.UIType = (CType::TUI)ui;
	t.Min= _min;
	t.Max = _max;
	t.Default = _default;

	if (_pvpredef)
	{
		t.Definitions.resize (_pvpredef->size ());
		uint i;
		for (i=0; i<_pvpredef->size (); i++)
		{
			t.Definitions[i].Label = (*_pvpredef)[i].first;
			t.Definitions[i].Value = (*_pvpredef)[i].second;
		}
	}

	// Save the type
	COFile output;
	if (output.open (filename))
	{
		try
		{
			// XML stream
			COXml outputXml;
			outputXml.init (&output);

			// Write
			t.write (outputXml.getDocument ());
		}
		catch (Exception &e)
		{
			nlwarning ("Error during writing file '%s' : ", filename.c_str (), e.what ());
		}
	}
	else
	{
		nlwarning ("Can't open the file %s for writing", filename.c_str ());
	}
}
示例#9
0
void CTile_edit_dlg::on_savePushButton_clicked()
{
	string fullPath = this->mainFile.absoluteFilePath().toUtf8();
	if ( !fullPath.empty() )
	{
		COFile stream;
		if ( stream.open( fullPath.c_str() ) )
		{
			tileBank.serial (stream);
			QString s = tr("Bank %1 saved").arg( QString( fullPath.c_str() ) );
			QMessageBox::information(this, tr("Bank Saved"), s);
			return;
		}
	}

	QMessageBox::information(this, tr("Error"), tr("Can't Save Bank, check the path"));
}
示例#10
0
// ---------------------------------------------------------------------------
void CGeorgesImpl::createInstanceFile (const std::string &_sxFullnameWithoutExt, const std::string &_dfnname)
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	CFormLoader formLoader;
	CFormDfn *dfn = formLoader.loadFormDfn (_dfnname.c_str(), false);
	if (!dfn)
	{
		char msg[512];
		smprintf (msg, 512, "Can't load DFN '%s'", _dfnname);
		theApp.outputError (msg);
		return;
	}

	NLMISC::CSmartPtr<NLGEORGES::UForm> Form = new CForm;

	std::string fullName;
	fullName = _sxFullnameWithoutExt + ".";

	int i = 0;
	if (_dfnname[i] == '.') ++i;
	for (; i < (int)_dfnname.size(); ++i)
	{
		if (_dfnname[i] == '.') break;
		fullName += _dfnname[i];
	}

	((CFormElmStruct*)&Form->getRootNode ())->build (dfn);
	COFile f;
	COXml ox;
	if (f.open (fullName))
	{
		ox.init(&f);
		((NLGEORGES::CForm*)((UForm*)Form))->write (ox.getDocument(), _sxFullnameWithoutExt.c_str ());
		ox.flush();
		f.close();
	}
	else
	{
		char msg[512];
		smprintf (msg, 512, "Can't write '%s'", fullName);
		theApp.outputError (msg);
		return;
	}
}
示例#11
0
//-----------------------------------------------
// setDebugOutput :
// Set an output file to log debugs.
//-----------------------------------------------
void setDebugOutput(const std::string &filename)
{
	// Remove output
	if(filename.empty())
	{
		DebugFile.close();
		IsDebugFile = false;
		return;
	}

	// Open The Item Association File
	if(!DebugFile.open(filename, false, true))
	{
		nlwarning("setDebugOutput: Cannot Open the '%s'.", filename.c_str());
		IsDebugFile = false;
	}
	else
		IsDebugFile = true;
}// setDebugOutput //
示例#12
0
/*
 * Save a Reference index file
 */
bool	CRefIndex::save(const string& filename)
{
	COFile		reffile;
	COXml		oxml;

	if (!reffile.open(filename) || !oxml.init(&reffile))
		return false;

	try
	{
		serial(oxml);
	}
	catch (const Exception&)
	{
		return false;
	}

	return true;
}
示例#13
0
/*
 * Serialise SheetId String Mapper
 */
void	CDatabase::serialSheetIdStringMapper(NLMISC::IStream& f)
{
	// serial mapper
	_SheetIdStringMapper.serial(f);

	if (f.isReading())
	{
		// if mapper is read, save it now in reference path
		std::string		refPath = _Reference.getPath();

		COFile	ofile;
		if (!ofile.open(refPath+"sheetid_map.bin"))
		{
			PDS_WARNING("serialSheetIdStringMapper(): failed to open reference sheetid_map file '%s' for save", (refPath+"sheetid_map.bin").c_str());
			return;
		}

		_SheetIdStringMapper.serial(ofile);
	}
}
示例#14
0
//-----------------------------------------------
// load :
// Load all sheets.
//-----------------------------------------------
void CSheetManager::load(NLMISC::IProgressCallback &callBack, bool updatePackedSheet, bool needComputeVS, bool dumpVSIndex)
{
	// Open The Item Association File
	if(!fItemAssoc.open("item_association.dbg", false, true))
		nlwarning("CSheetManager::load: Cannot Open the 'item_association.txt'.");
	else
		ItemAssocFileOpen = true;

	// Initialize the Sheet DB.
	loadAllSheet(callBack, updatePackedSheet, needComputeVS, dumpVSIndex);

	// Close the Item Association File.
	fItemAssoc.close();
	ItemAssocFileOpen = false;

	// Optimize memory taken by all strings of all sheets
	ClientSheetsStrings.memoryCompress();

	return;
}// load //
示例#15
0
void	CMailForumService::openSession( uint32 shardid, string username, string cookie )
{
	string	sessionfile = getUserDirectory(shardid, username) + "session";
	string	checkmailfile = getUserDirectory(shardid, username) + "new_mails";

	COFile	ofile;
	if (ofile.open(sessionfile))
	{
		cookie += "\n";
		ofile.serialBuffer((uint8*)(&cookie[0]), (uint)cookie.size());
	}

	if (CFile::fileExists(checkmailfile))
	{
		CFile::deleteFile(checkmailfile);
		CMessage	msgout("MAIL_NOTIF");
		msgout.serial(shardid, username);
		CUnifiedNetwork::getInstance()->send("EGS", msgout);
	}
}
示例#16
0
/*
 * Save State
 */
bool	CDatabaseState::save(CRefIndex& ref)
{
	COFile		f;
	COXml		oxml;

	string		filename = fileName(ref);

	if (!f.open(filename) || !oxml.init(&f))
		return false;

	try
	{
		serial(oxml);
	}
	catch (const Exception&)
	{
		return false;
	}

	return true;
}
示例#17
0
文件: main.cpp 项目: sythaeryn/pndrpg
// ***************************************************************************
void SaveInstanceGroup (const char* sFilename, CInstanceGroup *pIG)
{
	COFile file;

	if( file.open( sFilename ) )
	{
		try
		{
			pIG->serial (file);
		}
		catch (const Exception &e)
		{
			string stTmp = string(e.what()) ;
			outString(  stTmp );
		}
	}
	else
	{
		string stTemp = string("Couldn't create ") + string(sFilename) ;
		outString( stTemp );
	}
}
示例#18
0
/*
 * Save the ranges into a data file
 */
void				CRangeMirrorManager::saveRanges()
{
	try
	{
		COFile file;
		if ( file.open( RANGE_MANAGER_BACKUP_FILE ) )
		{
			COXml output;
			if ( output.init( &file, "1.0" ) )
			{
				output.serialCont( _RangeListByDataSet );
				output.flush();
			}
			file.close();
		}
		else
			throw EFileNotOpened( RANGE_MANAGER_BACKUP_FILE );
	}
	catch ( Exception& e )
	{
		nlwarning( "Can't save ranges: %s", e.what() );
	}
}
示例#19
0
bool CNelExport::exportSkeleton	(const char *sPath, INode* pNode, TimeValue time)
{
	// Result to return
	bool bRet=false;

	// Build the skeleton format
	CSkeletonShape *skeletonShape=new CSkeletonShape();
	TInodePtrInt mapId;
	_ExportNel->buildSkeletonShape (*skeletonShape, *pNode, NULL, mapId, time);

	// Open a file
	COFile file;
	if (file.open (sPath))
	{
		try
		{
			// Create a streamable shape
			CShapeStream shapeStream (skeletonShape);
			
			// Serial the shape
			shapeStream.serial (file);

			// All is good
			bRet=true;
		}
		catch (Exception &e)
		{
			nlwarning (e.what());
		}
	}

	// Delete the pointer
	delete skeletonShape;

	return bRet;
}
示例#20
0
// ***************************************************************************
void	makeAnimMeleeImpact(const std::string &animSetFile, const set<CAnimCombatSet> &combatAnimSets)
{
	// look if this animSetFile is in the combat list to patch
	string	shortName= CFile::getFilenameWithoutExtension(animSetFile);
	strlwr(shortName);
	CAnimCombatSet	key;
	key.Name= shortName;
	set<CAnimCombatSet>::const_iterator	it= combatAnimSets.find(key);
	if(it == combatAnimSets.end())
		return;

	const CAnimCombatSet	&currentCombatAnimSet= *it;

	InfoLog->displayRawNL("patching %s", animSetFile.c_str());


	// *** Read the animset file.
	CIFile	iFile;
	iFile.open(animSetFile, true);
	// Read all text
	static vector<string>	animSetText;
	animSetText.clear();
	while(!iFile.eof())
	{
		char	tmp[50000];
		iFile.getline(tmp, 50000);
		animSetText.push_back(tmp);
	}
	iFile.close();


	bool	someChangeDone= false;

	// *** Parse the animSet
	{
		// For each line of the animSet
		sint	structLevel= 0;
		sint	meleeImpactDelayLine= -1;
		string	currentStateName;
		for(uint j=0;j<animSetText.size();j++)
		{
			string	line= animSetText[j];
			string	lineLwr= toLower(line);

			// Find <LOG> TAg? => stop
			if(line.find("<LOG>")!=string::npos)
				break;

			// Find a STRUCT start?
			if(line.find("<STRUCT")!=string::npos)
			{
				// inc struct
				structLevel++;

				// if start a new State block
				if(structLevel==2)
				{
					// reset info for this state
					currentStateName.clear();
					meleeImpactDelayLine= -1;
					
					// try to get the name
					const string	tagStart= "name=\"";
					std::string::size_type	start= lineLwr.find(tagStart);
					if(start!=string::npos)
					{
						start+= tagStart.size();
						std::string::size_type	end= lineLwr.find("\"", start);
						if(end!=string::npos)
							currentStateName= lineLwr.substr(start, end-start);
					}
				}
			}

			// Find a STRUCT end?
			if(line.find("</STRUCT>")!=string::npos)
			{
				// if end a state block, may add or replace MeleeDelayImpact
				if(structLevel==2 && !currentStateName.empty())
				{
					// If the state is not in the combat state, no need to patch anything
					static CAnimCombatState		key;
					// must translate for instance "attack1" to "A1"
					key.StateCode= StateNameToStateCode[currentStateName];
					set<CAnimCombatState>::const_iterator		it= currentCombatAnimSet.States.find(key);
					if(it!=currentCombatAnimSet.States.end())
					{
						// else take the mean anim time
						string	format= "      <ATOM Name=\"MeleeImpactDelay\" Value=\"%.3f\"/>";
						string	newLine= toString(format.c_str(), it->MeanAnimTime * MeleeImpactTimeFactor);

						// melee impact delay doesn't exist?
						if(meleeImpactDelayLine==-1)
						{
							// add just before this line the Melee Impact Atom
							animSetText.insert(animSetText.begin()+j, newLine);
							j++;
							someChangeDone= true;
						}
						// else exist and want to replace?
						else if(ReplaceExistingMeleeImpactDelay)
						{
							animSetText[meleeImpactDelayLine]= newLine;
							someChangeDone= true;
						}
					}
				}

				// dec struct level
				structLevel--;
			}
				
			// if we are in level 2 structure, try to get the line to modify (if exist)
			if(structLevel==2)
			{
				if( line.find("Name=\"MeleeImpactDelay\"")!=string::npos )
					meleeImpactDelayLine= j;
			}
		}
	}

	// *** Write the animset file.
	if(someChangeDone)
	{
		COFile	oFile;
		oFile.open(animSetFile, false, true);
		// Write all text
		for(uint i=0;i<animSetText.size();i++)
		{
			string	str= animSetText[i];
			str+= "\n";
			oFile.serialBuffer((uint8*)str.c_str(), (uint)str.size());
		}
	}
}
// ***************************************************************************
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;
}
示例#22
0
文件: Browse.cpp 项目: mixxit/solinia
void Browse::OnExportBorder() 
{
	// Select a file
	CFileDialog sFile (false, NULL, NULL, OFN_ENABLESIZING,
		"Targa bitmap (*.tga)|*.tga|All files (*.*)|*.*||",NULL);
	if (sFile.DoModal()==IDOK)
	{
		// Get the border of the bank
		std::vector<NLMISC::CBGRA> array;

		// 256 or 128 ?
		int width, height;
		tileBank2.getTileSet (land)->getBorder128 (m_ctrl.Texture==1?CTile::diffuse:CTile::additive)->get (width, height, array);

		// Make a bitmap
		if (width&&height)
		{
			NLMISC::CBitmap bitmap;
			bitmap.resize (width, height, NLMISC::CBitmap::RGBA);

			// Get pixel
			CRGBA *pPixel=(CRGBA*)&bitmap.getPixels()[0];

			// Make a copy
			for (int i=0; i<width*height; i++)
			{
				// Copy the pixel
				pPixel->R=array[i].R;
				pPixel->G=array[i].G;
				pPixel->B=array[i].B;
				pPixel->A=array[i].A;
				pPixel++;
			}

			// Write the bitmap
			bool error=false;
			CString pathName=sFile.GetPathName();
			try
			{
				COFile file;
				if (file.open ((const char*)pathName))
				{
					// Export
					bitmap.writeTGA (file, 32);
				}
				else
					error=true;
			}
			catch (Exception& e)
			{
				const char *toto=e.what ();
				error=true;
			}

			// Error during export ?
			if (error)
			{
				// Error message
				char tmp[512];
				sprintf (tmp, "Can't write bitmap %s", (const char*)pathName);
				MessageBox (tmp, "Export border", MB_OK|MB_ICONEXCLAMATION);
			}
		}
	}
}
示例#23
0
bool CNelExport::exportLodCharacter (const char *sPath, INode& node, TimeValue time)
{
	// Result to return
	bool bRet=false;

	// Eval the object a time
	ObjectState os = node.EvalWorldState(time);

	// Object exist ?
	if (os.obj)
	{
		// Skeleton shape
		CSkeletonShape *skeletonShape=NULL;
		TInodePtrInt *mapIdPtr=NULL;
		TInodePtrInt mapId;

		// If model skinned ?
		if (CExportNel::isSkin (node))
		{
			// Create a skeleton
			INode *skeletonRoot=CExportNel::getSkeletonRootBone (node);

			// Skeleton exist ?
			if (skeletonRoot)
			{
				// Build a skeleton
				skeletonShape=new CSkeletonShape();

				// Add skeleton bind pos info
				CExportNel::mapBoneBindPos boneBindPos;
				CExportNel::addSkeletonBindPos (node, boneBindPos);

				// Build the skeleton based on the bind pos information
				_ExportNel->buildSkeletonShape (*skeletonShape, *skeletonRoot, &boneBindPos, mapId, time);

				// Set the pointer to not NULL
				mapIdPtr=&mapId;

				// Erase the skeleton
				if (skeletonShape)
					delete skeletonShape;
			}
		}

		// Conversion success ?
		CLodCharacterShapeBuild		lodBuild;
		if (_ExportNel->buildLodCharacter (lodBuild, node, time, mapIdPtr) )
		{
			// Open a file
			COFile file;
			if (file.open (sPath))
			{
				try
				{
					// Serial the shape
					lodBuild.serial (file);

					// All is good
					bRet=true;
				}
				catch (...)
				{
				}
			}
		}
	}
	return bRet;
}
示例#24
0
	// write that spell as a sheet
	void writeSheet(const std::string &sheetName)
	{
		COFile f;
		if (!f.open(sheetName, false, true))
		{
			nlwarning("Can't write %s", sheetName.c_str());
			return;
		}
		try
		{	
			COXml xmlStreamOut;
			xmlStreamOut.init(&f);
			xmlStreamOut.xmlPushBegin("FORM");

			IStream &xmlStream = xmlStreamOut;

				/*
				std::string revision = "$revision$";
				xmlStream.xmlSerial(revision, "Revision");
				std::string state = "modified";
				xmlStream.xmlSerial(state, "State");
				*/				
				xmlStream.xmlSetAttrib("Revision");
				std::string revision = "$revision$";
				xmlStream.serial(revision);
				xmlStream.xmlSetAttrib("State");
				std::string state = "modified";
				xmlStream.serial(state);								
			xmlStream.xmlPushEnd();
			// write parent list
			for(uint k = 0; k < Parents.size(); ++k)
			{
				xmlStream.xmlPushBegin("PARENT");					
					xmlStream.xmlSetAttrib("Filename");
					xmlStream.serial(Parents[k]);									
				xmlStream.xmlPushEnd();
				xmlStream.xmlPop();
			}
			if (!Projectile.empty() || !Impact.empty())
			{			
				xmlStream.xmlPush("STRUCT");
					if (!Projectile.empty())
					{
						xmlStream.xmlPushBegin("STRUCT");
							xmlStream.xmlSetAttrib("Name");
							std::string name = "Projectile";
							xmlStream.serial(name);					
						xmlStream.xmlPushEnd();			
							Projectile.serial(xmlStream);
						xmlStream.xmlPop();
					}
					if (!Impact.empty())
					{
						xmlStream.xmlPushBegin("STRUCT");										
							xmlStream.xmlSetAttrib("Name");
							std::string name = "Impact";
							xmlStream.serial(name);					
						xmlStream.xmlPushEnd();
							Impact.serial(xmlStream);
						xmlStream.xmlPop();
					}
				xmlStream.xmlPop();
			}
			else
			{
				xmlStream.xmlPush("STRUCT");
				xmlStream.xmlPop();
			}
			xmlStream.xmlPop();
		}
		catch(const EStream &)
		{
			nlwarning("Cant write %s", sheetName.c_str());
		}
	}
示例#25
0
bool CNelExport::exportMesh (const char *sPath, INode& node, TimeValue time)
{
	// Result to return
	bool bRet=false;

	// Eval the object a time
	ObjectState os = node.EvalWorldState(time);

	// Object exist ?
	if (os.obj)
	{
		// Skeleton shape
		CSkeletonShape *skeletonShape=NULL;
		TInodePtrInt *mapIdPtr=NULL;
		TInodePtrInt mapId;

		// If model skinned ?
		if (CExportNel::isSkin (node))
		{
			// Create a skeleton
			INode *skeletonRoot=CExportNel::getSkeletonRootBone (node);

			// Skeleton exist ?
			if (skeletonRoot)
			{
				// Build a skeleton
				skeletonShape=new CSkeletonShape();

				// Add skeleton bind pos info
				CExportNel::mapBoneBindPos boneBindPos;
				CExportNel::addSkeletonBindPos (node, boneBindPos);

				// Build the skeleton based on the bind pos information
				_ExportNel->buildSkeletonShape (*skeletonShape, *skeletonRoot, &boneBindPos, mapId, time);

				// Set the pointer to not NULL
				mapIdPtr=&mapId;

				// Erase the skeleton
				if (skeletonShape)
					delete skeletonShape;
			}
		}

		DWORD t = timeGetTime();
		if (InfoLog)
			InfoLog->display("Beg buildShape %s \n", node.GetName());
		// Export in mesh format
		IShape*	pShape=_ExportNel->buildShape (node, time, mapIdPtr, true);
		if (InfoLog)
			InfoLog->display("End buildShape in %d ms \n", timeGetTime()-t);

		// Conversion success ?
		if (pShape)
		{
			// Open a file
			COFile file;
			if (file.open (sPath))
			{
				try
				{
					// Create a streamable shape
					CShapeStream shapeStream (pShape);
					
					// Serial the shape
					shapeStream.serial (file);

					// All is good
					bRet=true;
				}
				catch (...)
				{
				}
			}

			// Delete the pointer
			delete pShape;
		}
	}
	return bRet;
}
示例#26
0
文件: misc.cpp 项目: AzyxWare/ryzom
//-----------------------------------------------
// dump :
// Create a file with information to debug.
//-----------------------------------------------
void dump(const std::string &name)
{
	// Write information to start as the version
	COFile fStart;
	if(fStart.open(name + "_start.rec", false, false))
	{
		CVectorD currentPos = UserEntity->pos();
		fStart.serialVersion(RecordVersion);
		fStart.serial(currentPos);
		// Close the File.
		fStart.close();
	}
	else
		nlwarning("dump: cannot open/create the file '%s_start.rec'.", name.c_str());

	// Write the DB
	IngameDbMngr.write(name + "_db.rec");
	// Open the file.
	COFile f;
	if(f.open(name + ".rec", false, false))
	{
		// Dump entities.
		EntitiesMngr.dump(f);

		// Dump Client CFG.
		ClientCfg.serial(f);

		// Close the File.
		f.close();
	}
	else
		nlwarning("dump: cannot open/create the file '%s.rec'.", name.c_str());


	// Open the file.
	if(f.open(name + ".xml", false, true))
	{
		// Create the XML stream
		COXml output;
		// Init
		if(output.init (&f, "1.0"))
		{
			// Open the XML Dump.
			output.xmlPush("XML");

			// Dump Client CFG.
			ClientCfg.serial(output);

			// Dump entities.
			EntitiesMngr.dumpXML(output);

			// Close the XML Dump.
			output.xmlPop();

			// Flush the stream, write all the output file
			output.flush();
		}
		else
			nlwarning("dump: cannot initialize '%s.xml'.", name.c_str());
		// Close the File.
		f.close();
	}
	else
		nlwarning("dump: cannot open/create the file '%s.xml'.", name.c_str());
}// dump //
示例#27
0
void CGeorgesTreeViewDialog::write( )
{

    COFile file;
    std::string s = CPath::lookup(loadedForm.toUtf8().constData(), false);
    if (file.open (s))
    {
        try
        {
            if (loadedForm.contains(".typ"))
            {
                //nlassert (Type != NULL);

                //// Write the file
                //// Modified ?
                //if (IsModified ())
                //{
                //	Type->Header.MinorVersion++;
                //	flushValueChange ();
                //}
                //Type->write (xmlStream.getDocument (), theApp.Georges4CVS);
                //modify (NULL, NULL, false);
                //flushValueChange ();
                //UpdateAllViews (NULL);
                //return TRUE;
            }
            else if (loadedForm.contains(".dfn"))
            {
                //nlassert (Dfn != NULL);

                //// Write the file
                //if (IsModified ())
                //{
                //	Dfn->Header.MinorVersion++;
                //	flushValueChange ();
                //}
                //Dfn->write (xmlStream.getDocument (), lpszPathName, theApp.Georges4CVS);
                //modify (NULL, NULL, false);
                //UpdateAllViews (NULL);
                //return TRUE;
            }
            else
            {
                nlassert (_form != NULL);

                // Write the file
                /*if (IsModified ())
                {
                ((CForm*)(UForm*)Form)->Header.MinorVersion++;
                }*/
                //((CForm*)(UForm*)Form)->write (xmlStream.getDocument (), lpszPathName, theApp.Georges4CVS);
                _form->write(file, false);
                setWindowTitle(windowTitle().remove("*"));
                _modified = false;
                //if (strcmp (xmlStream.getErrorString (), "") != 0)
                //{
                //	char message[512];
                //	smprintf (message, 512, "Error while saving file: %s", xmlStream.getErrorString ());
                //theApp.outputError (message);
                //}
                //modify (NULL, NULL, false);
                //flushValueChange ();
                //UpdateAllViews (NULL);

                // Get the left view
                //CView* pView = getLeftView ();
            }
        }
        catch (Exception &e)
        {
            nlerror("Error while loading file: %s", e.what());
        }
    }
    else
    {   //if (!file.open())
        nlerror("Can't open the file %s for writing.", s.c_str());
    }
}
// ***************************************************************************
int		main(int argc, char *argv[])
{
	// Filter addSearchPath
	NLMISC::createDebug();
	NLMISC::InfoLog->addNegativeFilter ("adding the path");

	if (argc != 3)
	{
		nlwarning("usage : %s hlsinfo_dir output_name ", argv[0]);
		exit(-1);
	}

	// get all .hlsinfo file in directory.
	vector<string>		files;
	vector<string>		hlsInfofiles;
	NLMISC::CPath::getPathContent(argv[1], false, false, true, files);
	hlsInfofiles.reserve(files.size());
	uint	k;
	for (k = 0;  k < files.size(); ++k)
	{
		std::string fileExt = NLMISC::strupr(NLMISC::CFile::getExtension(files[k]));						
		if(fileExt=="HLSINFO")
			hlsInfofiles.push_back(files[k]);
	}

	//  If none, quit.
	if(hlsInfofiles.empty())
		exit(-1);

	// Concat all hlsinfo in a Bank
	CHLSTextureBank		textBank;
	for (k = 0;  k < hlsInfofiles.size(); ++k)
	{
		printf("HLSBank Process [%2d]\r", (uint)(100*k/hlsInfofiles.size()));
		try
		{
			CIFile	f(hlsInfofiles[k]);
			CHLSBankTextureInfo	textInfo;
			f.serial(textInfo);
			addTextToBank(textInfo, textBank);
		}
		catch(Exception &e)
		{
			nlwarning("ERROR: Unable to process %s. Reason: %s. Processing next", hlsInfofiles[k].c_str(), e.what());
		}
	}

	// compile it
	textBank.compile();

	// save the bank.
	COFile	fOut;
	try
	{
		if(!fOut.open(argv[2]))
			throw int(0);
		fOut.serial(textBank);
		fOut.close();
	}
	catch(Exception &e)
	{
		nlwarning("ERROR: Unable to write HLS Bank %s: %s", argv[2], e.what());
		exit(-1);
	}
	catch(...)
	{
		nlwarning("ERROR: Unable to write HLS Bank %s.", argv[2]);
		exit(-1);
	}

	return 0;
}
// ***************************************************************************
void	CIgLighterLib::lightIg(CInstanceLighter &instanceLighter,
	const CInstanceGroup &igIn, CInstanceGroup &igOut, CInstanceLighter::CLightDesc &lightDesc, 
	CSurfaceLightingInfo &slInfo, const char *igName)
{
	sint				i;


	// Setup.
	//=======
	// Init
	instanceLighter.init();

	// For interiors ig, disable Sun contrib according to ig.
	lightDesc.DisableSunContribution= !igIn.getRealTimeSunContribution();
	// Copy it to igOut, just to keep same setup data for in and out.
	igOut.enableRealTimeSunContribution(!lightDesc.DisableSunContribution);


	// Add obstacles.
	std::vector<CInstanceLighter::CTriangle>	obstacles;
	// only if Shadowing On.
	if(lightDesc.Shadow)
	{
		// Map of shape to load
		std::map<string, IShape*> shapeMap;

		// For all instances of igIn.
		for(i=0; i<(sint)igIn.getNumInstance();i++)
		{
			// progress
			instanceLighter.progress("Loading Shapes obstacles", float(i)/igIn.getNumInstance());

			// Skip it?? IgLighterLib use the DontCastShadowForInterior flag. See doc of this flag
			if(igIn.getInstance(i).DontCastShadow || igIn.getInstance(i).DontCastShadowForInterior)
				continue;

			// Get the instance shape name
			string name= igIn.getShapeName(i);
			bool	shapeFound= true;

			// Try to find the shape in the UseShapeMap.
			std::map<string, IShape*>::const_iterator iteMap= lightDesc.UserShapeMap.find (name);

			// If not found in userShape map, try to load it from the temp loaded ShapeBank.
			if( iteMap == lightDesc.UserShapeMap.end() )
			{
				// Add a .shape at the end ?
				if (name.find('.') == std::string::npos)
					name += ".shape";

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

				// Find the shape in the bank
				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());
						shapeFound= false;
					}
				}
			}

			if(shapeFound)
			{
				CMatrix		matInst;
				matInst.setPos(igIn.getInstancePos(i));
				matInst.setRot(igIn.getInstanceRot(i));
				matInst.scale(igIn.getInstanceScale(i));
				// Add triangles of this shape
				CInstanceLighter::addTriangles(*iteMap->second, matInst, obstacles, i);
			}

		}

		// Clean Up shapes.
		//-----------
		std::map<string, IShape*>::iterator iteMap;
		iteMap= shapeMap.begin();
		while(iteMap!= shapeMap.end())
		{
			// delte shape
			delete	iteMap->second;
			// delete entry in map
			shapeMap.erase(iteMap);
			// next
			iteMap= shapeMap.begin();
		}
	}

	// Add pointLights of the IG.
	for(i=0; i<(sint)igIn.getPointLightList().size();i++)
	{
		instanceLighter.addStaticPointLight( igIn.getPointLightList()[i], igName );
	}


	// Setup a CIGSurfaceLightBuild if needed.
	//=======
	CIGSurfaceLightBuild	*igSurfaceLightBuild= NULL;
	CGlobalRetriever		*globalRetriever= slInfo.GlobalRetriever;
	CRetrieverBank			*retrieverBank= slInfo.RetrieverBank;
	float	cellSurfaceLightSize= slInfo.CellSurfaceLightSize;
	if(retrieverBank && globalRetriever)
	{
		igSurfaceLightBuild= new CIGSurfaceLightBuild;
		igSurfaceLightBuild->CellSize= cellSurfaceLightSize;
		// col Identifier.
		string	colIdent= slInfo.ColIdentifierPrefix + slInfo.IgFileName + slInfo.ColIdentifierSuffix;

		// For any retreiverInstance with this identifier.
		//----------------
		uint	numInstances= (uint)globalRetriever->getInstances().size();
		for(uint instanceId=0; instanceId<numInstances; instanceId++)
		{
			const CRetrieverInstance	&instance= globalRetriever->getInstance(instanceId);
			// If this instance is an interior
			if ( instance.getType() == CLocalRetriever::Interior )
			{
				uint					localRetrieverId= instance.getRetrieverId();
				const CLocalRetriever	&localRetriever= retrieverBank->getRetriever(localRetrieverId);
				// get the identifer of this localRetriever
				string	retIdent= localRetriever.getIdentifier();

				// Match the ident??
				if( retIdent.find(colIdent)!=string::npos )
				{
					// check CRetrieverLightGrid not already present
					CIGSurfaceLightBuild::ItRetrieverGridMap	itRgm;
					itRgm= igSurfaceLightBuild->RetrieverGridMap.find(localRetrieverId);
					if( itRgm != igSurfaceLightBuild->RetrieverGridMap.end() )
					{
						nlwarning ("ERROR Found 2 different collision retriever with same identifier: '%s'. The 2nd is discared\n", retIdent.c_str());
					}
					else
					{
						// Append CRetrieverLightGrid.
						itRgm= igSurfaceLightBuild->RetrieverGridMap.insert(
							make_pair(localRetrieverId, CIGSurfaceLightBuild::CRetrieverLightGrid() ) ).first;
						CIGSurfaceLightBuild::CRetrieverLightGrid	&rlg= itRgm->second;

						// Resize Grids.
						uint	numSurfaces= (uint)localRetriever.getSurfaces().size();
						rlg.Grids.resize( numSurfaces );

						// Compute the bbox for all surfaces. (NB: local to the localRetriever).
						vector<CAABBox>		surfaceBBoxes;
						localRetriever.buildInteriorSurfaceBBoxes(surfaceBBoxes);

						// For each surface, compute it.
						for(uint surfaceId=0; surfaceId<numSurfaces; surfaceId++)
						{
							// Progress.
							char	stmp[256];
							sprintf(stmp, "Sample surfaces of %s", retIdent.c_str());
							instanceLighter.progress(stmp, surfaceId / float(numSurfaces));

							// Compute surface and size of the grid.
							CIGSurfaceLightBuild::CSurface		&surfDst= rlg.Grids[surfaceId];

							// Snap Origin on cellSize
							surfDst.Origin= surfaceBBoxes[surfaceId].getMin();
							surfDst.Origin.x= floorf(surfDst.Origin.x/cellSurfaceLightSize) * cellSurfaceLightSize;
							surfDst.Origin.y= floorf(surfDst.Origin.y/cellSurfaceLightSize) * cellSurfaceLightSize;

							// Snap Width / Height on cellSize.
							float	sizex= surfaceBBoxes[surfaceId].getMax().x - surfDst.Origin.x;
							float	sizey= surfaceBBoxes[surfaceId].getMax().y - surfDst.Origin.y;
							surfDst.Width= (uint)floorf(sizex/cellSurfaceLightSize) + 2;
							surfDst.Height= (uint)floorf(sizey/cellSurfaceLightSize) + 2;
							// Get Zcenter.
							float	zCenter= surfaceBBoxes[surfaceId].getCenter().z;

							// Allocate elements.
							surfDst.Cells.resize(surfDst.Width * surfDst.Height);

							// For all elements
							for(sint yCell=0; yCell<(sint)surfDst.Height; yCell++)
							{
								for(sint xCell=0; xCell<(sint)surfDst.Width; xCell++)
								{
									// compute pos of the cell.
									ULocalPosition	localPos;
									localPos.Estimation.x= surfDst.Origin.x + xCell*cellSurfaceLightSize;
									localPos.Estimation.y= surfDst.Origin.y + yCell*cellSurfaceLightSize;
									localPos.Estimation.z= zCenter;

									// snap the pos to the surface.
									localPos.Surface= surfaceId;
									bool	snapped;
									localRetriever.snapToInteriorGround(localPos, snapped);

									// if snapped then this point is IN the surface.
									CIGSurfaceLightBuild::CCellCorner	&cell= 
										surfDst.Cells[yCell * surfDst.Width + xCell];
									cell.InSurface= snapped;

									// If ok, retrieve the global (ie world) position
									if(snapped)
									{
										// build a valid globalPosition.
										UGlobalPosition	globalPos;
										globalPos.InstanceId= instanceId;
										globalPos.LocalPosition= localPos;
										// retrieve from globalRetriever.
										cell.CenterPos= globalRetriever->getGlobalPosition(globalPos);
										// Add a delta to simulate entity center
										cell.CenterPos.z+= slInfo.CellRaytraceDeltaZ;

										// OverSample
										if(lightDesc.OverSampling==0)
										{
											// No OverSample, just add CenterPos to the samples.
											cell.NumOverSamples= 1;
											cell.OverSamples[0]= cell.CenterPos;
										}
										else
										{
											// OverSample.
											overSampleCell(cell, lightDesc.OverSampling, localRetriever, 
												*globalRetriever, instanceId, localPos, cellSurfaceLightSize, 
												slInfo.CellRaytraceDeltaZ);
											// it is possible that no samples lies in surfaces (small surface).
											// In this case, just copy CenterPos into samples.
											if(cell.NumOverSamples==0)
											{
												cell.NumOverSamples= 1;
												cell.OverSamples[0]= cell.CenterPos;
											}
										}
									}
									else
									{
										// For debug mesh only, get an approximate pos.
										cell.CenterPos= localPos.Estimation + instance.getOrigin();
										cell.CenterPos.z+= slInfo.CellRaytraceDeltaZ;
									}

									// Init cell defaults
									cell.Dilated= false;
									cell.SunContribution= 0;
								}
							}
						}
					}
				}
			}
		}

	}


	// Run.
	//=======
	instanceLighter.light(igIn, igOut, lightDesc, obstacles, NULL, igSurfaceLightBuild);

	// Output a debug mesh??
	if(igSurfaceLightBuild && slInfo.BuildDebugSurfaceShape && !igSurfaceLightBuild->RetrieverGridMap.empty() )
	{
		// Do it for the sun and point lights.
		for(uint i=0;i<2;i++)
		{
			// compute
			CMesh::CMeshBuild			meshBuild;
			CMeshBase::CMeshBaseBuild	meshBaseBuild;
			CVector	deltaPos= CVector::Null;
			deltaPos.z= - slInfo.CellRaytraceDeltaZ + 0.1f;
			// What kind of debug?
			if( i==0 )
				igSurfaceLightBuild->buildSunDebugMesh(meshBuild, meshBaseBuild, deltaPos);
			else
				igSurfaceLightBuild->buildPLDebugMesh(meshBuild, meshBaseBuild, deltaPos, igOut);

			// build
			CMesh	mesh;
			mesh.build(meshBaseBuild, meshBuild);

			// Save.
			CShapeStream	shapeStream;
			shapeStream.setShapePointer(&mesh);
			COFile		file;
			if( i==0 )
				file.open(slInfo.DebugSunName);
			else
				file.open(slInfo.DebugPLName);
			shapeStream.serial(file);
		}
	}


	// Clean.
	//=======
	if(igSurfaceLightBuild)
		delete igSurfaceLightBuild;
}
示例#30
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;
}