Beispiel #1
0
	//-----------------------------------------------------------------------------
	void Image::save(const String& filename)
	{
		if( !mBuffer )
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No image data loaded", 
				"Image::save");
		}

		String strExt;
		size_t pos = filename.find_last_of(".");
		if( pos == String::npos )
			OGRE_EXCEPT(
			Exception::ERR_INVALIDPARAMS, 
			"Unable to save image file '" + filename + "' - invalid extension.",
			"Image::save" );

		while( pos != filename.length() - 1 )
			strExt += filename[++pos];

		Codec * pCodec = Codec::getCodec(strExt);
		if( !pCodec )
			OGRE_EXCEPT(
			Exception::ERR_INVALIDPARAMS, 
			"Unable to save image file '" + filename + "' - invalid extension.",
			"Image::save" );

		ImageCodec::ImageData* imgData = OGRE_NEW ImageCodec::ImageData();
		imgData->format = mFormat;
		imgData->height = mHeight;
		imgData->width = mWidth;
		imgData->depth = mDepth;
		imgData->size = mBufSize;
		// Wrap in CodecDataPtr, this will delete
		Codec::CodecDataPtr codeDataPtr(imgData);
		// Wrap memory, be sure not to delete when stream destroyed
		MemoryDataStreamPtr wrapper(OGRE_NEW MemoryDataStream(mBuffer, mBufSize, false));

		pCodec->codeToFile(wrapper, filename, codeDataPtr);
	}
    //-----------------------------------------------------------------------
    void TextureUnitState::setAnimatedTextureName( const String& name, unsigned int numFrames, Real duration)
    {
		setContentType(CONTENT_NAMED);
		mTextureLoadFailed = false;

		String ext;
        String baseName;

        size_t pos = name.find_last_of(".");
        baseName = name.substr(0, pos);
        ext = name.substr(pos);

        mFrames.resize(numFrames);
		// resize pointers, but don't populate until needed
        mFramePtrs.resize(numFrames);
        mAnimDuration = duration;
        mCurrentFrame = 0;
        mCubic = false;

        for (unsigned int i = 0; i < mFrames.size(); ++i)
        {
			StringUtil::StrStreamType str;
            str << baseName << "_" << i << ext;
            mFrames[i] = str.str();
			mFramePtrs[i].setNull();
        }

        // Load immediately if Material loaded
        if (isLoaded())
        {
            _load();
        }
		// Tell parent to recalculate hash
		if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) )
		{
			mParent->_dirtyHash();
		}

    }
		void Cocos2dxFactory::loadTextureAtlasFile(const String &textureAtlasFile , const String &name)
		{
			dragonBones::XMLDataParser parser;
			// 载入皮肤数据
			dragonBones::XMLDocument doc;
			auto date = cocos2d::FileUtils::getInstance()->getDataFromFile(textureAtlasFile);
			doc.Parse(reinterpret_cast<char*>(date.getBytes()), date.getSize());

			int pos = textureAtlasFile.find_last_of("/");
			if (std::string::npos != pos){
				std::string base_path = textureAtlasFile.substr(0, pos + 1);
				
				std::string img_path = doc.RootElement()->Attribute(ConstValues::A_IMAGE_PATH.c_str());
				std::string new_img_path = base_path + img_path;

				doc.RootElement()->SetAttribute(ConstValues::A_IMAGE_PATH.c_str(), new_img_path.c_str());
			}

			// 解析皮肤数据
			TextureAtlasData *textureAtlasData = parser.parseTextureAtlasData(doc.RootElement());
			addTextureAtlas(new dragonBones::Cocos2dxTextureAtlas(textureAtlasData));

		}
Beispiel #4
0
bool parser::parse_include(const String & srcname, const String & includename)
{
	// 拼include的名字
	String dir = srcname;
	std::replace(dir.begin(), dir.end(), '\\', '/');
	int pos = dir.find_last_of('/');
	if (pos == -1)
	{
		dir = "";
	}
	else
	{
		dir = dir.substr(0, pos + 1);
	}
	dir += includename;

	// 解析
	if (!parse(dir.c_str()))
	{
		FKERR("parse_include %s fail", dir.c_str());
		return false;
	}
	return true;
}
Beispiel #5
0
void cv::glob(String pattern, std::vector<String>& result, bool recursive)
{
    CV_INSTRUMENT_REGION()

    result.clear();
    String path, wildchart;

    if (isDir(pattern, 0))
    {
        if(strchr(dir_separators, pattern[pattern.size() - 1]) != 0)
        {
            path = pattern.substr(0, pattern.size() - 1);
        }
        else
        {
            path = pattern;
        }
    }
    else
    {
        size_t pos = pattern.find_last_of(dir_separators);
        if (pos == String::npos)
        {
            wildchart = pattern;
            path = ".";
        }
        else
        {
            path = pattern.substr(0, pos);
            wildchart = pattern.substr(pos + 1);
        }
    }

    glob_rec(path, wildchart, result, recursive);
    std::sort(result.begin(), result.end());
}
 String AbstractFileManager::deleteExtension(const String& path) {
     size_t pos = path.find_last_of('.');
     if (pos == String::npos) return path;
     return path.substr(0, pos);
 }
Beispiel #7
0
//==============================================================================
String File::GetCanonicalPath(const String& path)
{
	//
	// Deal with the empty string right away
	//
	if(path.empty())
	{
		return String();
	}

	//
	// The prefix is copied to the output unchanged
	//
	size_t prefixLen = FileSystem::GetFileSystem()->getPrefixLength(path);
	String ret = path.substr(0, prefixLen);

	//
	// The remainder of the path represents a sequence of names
	// separated by the path separator character.
	//
	StringTokenizer tokenizer(path.substr(prefixLen), GetSeparator());
	String sequence;
	
	const CharType sep = GetSeparatorChar();
	
	while(tokenizer.hasMoreTokens())
	{
		const String& name = tokenizer.nextToken();
		if(name == QC_T("."))
		{
			continue;
		}
		else if(name == QC_T(".."))
		{
			size_t pos = sequence.find_last_of(sep);
			if(pos != String::npos)
			{
				sequence.erase(pos);
			}
			else
			{
				// This is an error.  We have a ".." with no preceding
				// name.  We've gone back as far as we could!
				sequence += sep;
				sequence += name;
			}
		}
		else
		{
			sequence += sep;
			sequence += name;
		}
	}

	if(!sequence.empty())
	{
		//
		// erase the trailing separator from the prefix (if any)
		//
		if(prefixLen && ret[prefixLen-1] == sep)
		{
			ret.erase(prefixLen-1);
		}
		ret += sequence;
	}

	return ret;
}
    void TerrainPaintInfoContainer::addTextureInfo( TextureInfo &info )
    {
        assert ( isTextureInfoOk(info) );

        String brushName = info.brushName;

        String pathName = info.ownerTextureName;

		addTexNameAndBrushMapInfo(pathName,brushName);

        size_t pos = pathName.find_last_of('/');

        if (pos != String::npos)
        {
            pathName.erase(pos+1);
            pathName.append(brushName);

            brushName = pathName;
        }

        String texTypeStr;

        // 找到该纹理的类型字符串
        StringTexTypeMap::iterator itForStringTexTypeMap = mStringTexTypeMap.begin();
        while ( itForStringTexTypeMap != mStringTexTypeMap.end() )
        {
            if (itForStringTexTypeMap->second == info.textureType)
            {
                texTypeStr = itForStringTexTypeMap->first;
                break;
            }
            ++itForStringTexTypeMap;
        }

        assert (itForStringTexTypeMap != mStringTexTypeMap.end());

        TextureInfoMap::iterator it = mTextureInfoMap.find(brushName);

        // 如果当前map中没有这个brush,说明是一组新的画刷
        if ( it == mTextureInfoMap.end() )
        {
            TextureInfos newInfos;            

            // 自动生成纹理名称,名称格式为 “组名|当前组的纹理序号|纹理类型”
            String textureName = info.brushName + "|"
                + Ogre::StringConverter::toString(newInfos.size()) + "|" + texTypeStr;

            info.textureName = textureName;

            newInfos.push_back(info);

            std::pair<TextureInfoMap::iterator, bool> inserted = 
                mTextureInfoMap.insert( TextureInfoMap::value_type(brushName, newInfos) );

            assert (inserted.second);
        }
        else
        {
            // 自动生成纹理名称
            String textureName = info.brushName + "|"
                + Ogre::StringConverter::toString(it->second.size()) + "|" + texTypeStr;

            info.textureName = textureName;

            it->second.push_back(info);
        }
    }
	//--------------------------------
	bool Utils::createDirectoryRecursive( const String &pathString )
	{
		if (pathString.length() == 0)
			return false;

		String path = pathString;

		if (path[path.length()-1] != '/' && path[path.length()-1] != '\\')
			path.push_back('\\');

		std::list<String> paths;
		size_t offset = String::npos;
		while ((offset != 0) && (offset = pathString.find_last_of("/\\", offset)) != String::npos)
		{
			paths.push_front(pathString.substr(0, offset + 1));
			if (offset !=0) --offset;
		}

		bool pathExists = true;

		SystemType type = getSystemType();

#ifdef COLLADABU_OS_WIN
		if( type != WINDOWS )
			return false;

		const char* currentPath = _getcwd(0, 0);

		for (std::list<String>::const_iterator iPath = paths.begin(); iPath != paths.end(); ++iPath)
		{
			// if path exists
			if (_chdir((*iPath).c_str()) == 0)
				continue;

			// path does not exist, try to create it
			_mkdir((*iPath).c_str());
			
			if (_chdir((*iPath).c_str()) != 0)
			{
				pathExists = false;
				break;
			}
		}

		// Restore current path
		_chdir(currentPath);
#else
		if( type != POSIX )
			return false;

		const char* currentPath = getcwd(0, 0);

		for (std::list<String>::const_iterator iPath = paths.begin(); iPath != paths.end(); ++iPath)
		{
			// if path exists
			if (chdir((*iPath).c_str()) == 0)
				continue;

			// path does not exist, try to create it
			mkdir((*iPath).c_str(), 0755);
			
			if (chdir((*iPath).c_str()) != 0)
			{
				pathExists = false;
				break;
			}
		}

		// Restore current path
		chdir(currentPath);
#endif
		return pathExists;
	}
Beispiel #10
0
Shader::Shader(String vertex, String frag, String geom)
{
	GLuint vertex_id = 0,frag_id = 0,geom_id = 0,program_id;
	GLint link = 0;
	GLint tailleErreur = 0;
	char *erreur = NULL;

	ready = false;

	if(vertex.empty() && frag.empty() && geom.empty())
		return;

	int beg = vertex.find_last_of("/") > 0 ? vertex.find_last_of("/") : 0;
	int end = vertex.find_last_of(".") > 0 ? vertex.find_last_of(".") : vertex.size()-1;
	programName = vertex.substr(beg+1,end);

	if(!vertex.empty())
		vertex_id = LoadShader(GL_VERTEX_SHADER,vertex.c_str());

	if(!geom.empty())
		geom_id = LoadShader(GL_GEOMETRY_SHADER_EXT,geom.c_str());

	if(!frag.empty())
		frag_id = LoadShader(GL_FRAGMENT_SHADER,frag.c_str());


	program_id = glCreateProgram();
	fragId = frag_id;
	geomId = geom_id;
	vertexId = vertex_id;
	programId = program_id;
	ready = false;

	if(vertex_id)
		glAttachShader(program_id, vertex_id);
	if(geom_id)
		glAttachShader(program_id, geom_id);
	if(frag_id)
		glAttachShader(program_id, frag_id);
	
	glLinkProgram(program_id);

	glGetProgramiv(program_id, GL_LINK_STATUS, &link);

	if(link != GL_TRUE)
	{

		glGetProgramiv(program_id, GL_INFO_LOG_LENGTH, &tailleErreur);

		erreur = new char[tailleErreur + 1];

		glGetProgramInfoLog(program_id, tailleErreur, &tailleErreur, erreur);
		erreur[tailleErreur] = '\0';

		printf("Erreur lors du link du program : %s",erreur);

		delete erreur;
		return;
	}
	ready = true;
	SetupUniform();
	SetupVertexAttribut();
}
Beispiel #11
0
bool XmlSchema::generateCode(const Char* filename, const Char* pchFilename) const
{
	String headerCode, sourceCode;

	if (!generateCodeForNode(this, headerCode, sourceCode))
	{
		return false;
	}

	String note =
T("///////////////////////////////////////////////////////////////////////////////////////////////////\r\n\
//this file is automatically generated, do not modify.\r\n\
///////////////////////////////////////////////////////////////////////////////////////////////////\r\n");

	String definition = filename;
	int pos1 = definition.find_last_of(T('/'));
	int pos2 = definition.find_last_of(T('\\'));
	int slashPos = std::max(pos1 == String::npos ? -1: pos1,
								pos2 == String::npos ? -1: pos2);
	definition = definition.substr(slashPos + 1, definition.size() - slashPos - 1);
	String headerInclude;
	headerInclude += T("#ifndef __XML_");
	headerInclude += definition;
	headerInclude += T("_H__\r\n#define __XML_");
	headerInclude += definition;
	headerInclude += T("_H__\r\n\r\n#include \"SlimXml.h\"\r\n#include <vector>\r\n\r\n");
	String nameSpace;
	nameSpace = T("namespace ");
	nameSpace += definition;
	nameSpace += T("\r\n{\r\n");

	headerCode = note + headerInclude + nameSpace + headerCode;
	headerCode += T("}\r\n\r\n");
	headerCode += T("#endif\r\n");

	String sourceInclude;
	if (pchFilename != NULL)
	{
		sourceInclude += T("#include \"");
		sourceInclude += pchFilename;
		sourceInclude += T("\"\r\n");
	}
	sourceInclude += T("#include \"");
	sourceInclude += definition;
	sourceInclude += T(".h\"\r\n#include <cassert>\r\n\r\nusing namespace slim;\r\n\r\n");

	sourceCode = note + sourceInclude + nameSpace + sourceCode;
	sourceCode += T("}\r\n");

	assert(filename != NULL);

	String filenameString = filename;
	filenameString += T(".h");

	//header
	std::fstream file;
	file.open(filenameString.c_str(), std::ios_base::out | std::ios_base::binary);
	if (!file.is_open())
	{
		return false;
	}

#ifdef SLIM_USE_WCHAR
	//always write in utf-8
	unsigned char bom[3];
	bom[0] = 0xef;
	bom[1] = 0xbb;
	bom[2] = 0xbf;
	size_t bufferSize = headerCode.size() * 4;
	char* buffer = new char[bufferSize];
	size_t characterCount = utf16toutf8(headerCode.c_str(), headerCode.size(), buffer, bufferSize);
	file.write((char*)bom, 3);
	file.write(buffer, characterCount);
	delete[] buffer;
#else
	file.write(headerCode.c_str(), headerCode.size());
#endif

	file.close();

	//cpp
	filenameString = filename;
	filenameString += T(".cpp");
	file.open(filenameString.c_str(), std::ios_base::out | std::ios_base::binary);
	if (!file.is_open())
	{
		return false;
	}

#ifdef SLIM_USE_WCHAR
	bufferSize = sourceCode.size() * 3;
	buffer = new char[bufferSize];
	characterCount = utf16toutf8(sourceCode.c_str(), sourceCode.size(), buffer, bufferSize);
	file.write((char*)bom, 3);
	file.write(buffer, characterCount);
	delete[] buffer;
#else
	file.write(sourceCode.c_str(), sourceCode.size());
#endif

	file.close();
	return true;
}
Beispiel #12
0
int main(int argc, char* argv[])
{
  CommandlineParser parpars("LigandFileSplitter", "split molecule files", VERSION, String(__DATE__), "Preparation");
	parpars.registerParameter("i", "input molecule file", INFILE, true);
  parpars.registerParameter("no", "Number of output files to be created", BALL::INT, false);
  parpars.registerParameter("mpf", "Number of molecules per output file", BALL::INT, false);
	parpars.registerParameter("outname_pattern", "Pattern that will be used to generate the names of the output files, see notes and examples below.", BALL::STRING, false);
	parpars.registerParameter("o", "Output filenames. If none are specified, input filename postfixed with IDs will be used", OUTFILELIST, false);
  
	String man =
	"LigandFileSplitter splits a molecule file into a given number of subsets.\n\n"

	"Examples:\n\n"

  "$ LigandFileSplitter -i Trypsin_actives.sdf -o batch_1 batch_2\n"
	"  will split the input file Trypsin_actives.sdf in the two output files batch_1.sdf and batch_2.sdf.\n\n"
	
  "$ LigandFileSplitter -i Trypsin_actives.sdf -no 3\n"
	"  will split the input file Trypsin_actives.sdf in three files named Trypsin_actives_0.sdf, Trypsin_actives_1.sdf and Trypsin_actives_2.sdf\n\n"
	
  "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 4\n"
	"  will split the input file ligands.sdf in as many files needed to fit at most 4 ligands per file.\n"
	"  The files will be named ligands_0.sdf, ligands_1.sdf ... ligands_N.sdf\n\n"
	
  "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 5 -outname_pattern split_ligands-%d.sdf\n"
	"  will split the input file ligands.sdf in as many files needed to fit at most 5 ligands per file.\n"
  "  The files will be named split_ligands-0.sdf, split_ligands-1.sdf, ... , split_ligands-N.sdf.\n\n"
			  
  "$ LigandFileSplitter -i ligands.sdf -outname_pattern split_ligands_%d.sdf -no 100\n"
	"  will split the input file ligands.sdf in 100 files using the following names:\n"
	"  split_ligands_0.sdf, split_ligands_1.sdf, ... , split_ligands_99.sdf.\n\n"
			
  "NOTES:\n"
	"- Molecules are not sorted in any way.\n"
	"- The tool is no format converter and the format of the output files will be the same as of the input file.\n"
	"- Output_name_pattern accepts a printf-like pattern, expecting exactly one decimal integer placeholder, %d.\n"
	"- The following are valid patterns: output_ligand.sdf_%d, split_%d.mol, %d_lig.drf\n"
	"- The following are invalid patterns: output_%f.sdf, ligands.drf_%u, %d_lig_%d.mol, molecules.sdf\n\n"
  
  "WARNING:\n"
	"- If the parameter outname_pattern is specified, the user is responsible for the occurrence of a valid file extension\n"
	"  in the outname_pattern, which has to be of the same file format as the input file.\n\n";
  
	parpars.setToolManual(man);
	parpars.setSupportedFormats("i","mol2,sdf,drf");
	parpars.setSupportedFormats("o","mol2,sdf,drf");
	parpars.setOutputFormatSource("o","i");
 	parpars.parse(argc, argv);
  
  
  // Check if parameter setting is valid and/or useful  
 	validateParameters(parpars);

  
  unsigned int n_molecules = 0;
  unsigned int n_outfiles = 0;
  unsigned int mpf = 0;
  
  String infile = parpars.get("i");
  String infile_name = infile.substr(0, infile.find_last_of('.'));
  String infile_type = infile.substr(infile.find_last_of('.') + 1, infile.length() - infile.find_last_of('.') - 1);
  
  vector<String> outfile_names;
  HashSet <String> conformation_ids;
  
  Molecule* mol;
 	GenericMolFile* input;
  GenericMolFile* output;

  DockResultFile* drf_input;
  DockResultFile* drf_output;  
  

	// Determine number of molecules in input files.
	// In case of DockResultFiles, we do not need to process all contained molecules 
	// in order to achieve this; we can simply count the result-section entries.
  
  input = MolFileFactory::open(infile);
	
  drf_input = NULL;
  drf_input = dynamic_cast<DockResultFile*>(input);
	if (drf_input)
	{
		n_molecules = drf_input->countConformations();
	}
	else
	{
 		Log.level(10) << "\rCount number of molecules in input file ..." << endl;
		for (mol = input->read(); mol; mol = input->read())
		{
			++n_molecules;
			delete mol;
		}
	}	
	
	Log.level(10) << "\r" << n_molecules << " molecules found." << endl << endl;

	input->close();
	delete input;

	
	// Check which split method should be applied
	
	if (parpars.has("o"))
	{
		// Option 1:
		// Number of output files specified by explicit name passing.
		// Parameter 'o' is specified
    
		list<String> tmp = parpars.getList("o");
    for (list<String>::iterator iter = tmp.begin(); iter != tmp.end(); ++iter)
    {
      outfile_names.push_back(*iter + "." + infile_type);
    }
    
		n_outfiles = outfile_names.size();
  
    if (n_molecules >= n_outfiles)
    {
      mpf = floor((double)n_molecules / n_outfiles);
    }
    else
    {
      Log.level(10) << "\rNOTE: Number of molecules in input file is smaller than number of specified output files." << endl;
      n_outfiles = n_molecules;
      mpf = 1;
    }
	}
  else
  {
    if (parpars.has("no"))
    {
      // Option 2:
		  // Number of output files is specified directly.
		  // Parameter 'no' is specified
      
      n_outfiles = parpars.get("no").toInt();
      
      if (n_molecules >= n_outfiles)
      {
        mpf = floor((double)n_molecules / n_outfiles);
      }
      else
      {
        Log.level(10) << "\rNOTE: Number of molecules in input file is smaller than specified number of output files." << endl;
        n_outfiles = n_molecules;
        mpf = 1;
      }
    }
    else
    {
      if (parpars.has("mpf"))
      {
        // Option 3:
        // Number of molecules per output file is specified directly.
        // Parameter 'mpf' is specified
      
        mpf = parpars.get("mpf").toInt();
        n_outfiles = ceil((double)n_molecules / (double)mpf);
      }
    }
    
    
    // Generate output file names
    
    if (parpars.has("outname_pattern"))
    {
      // Option 1: Generate output file names from specified pattern

      String pattern = parpars.get("outname_pattern");
      
      for (unsigned int i=0; i!= n_outfiles; ++i)
      {
        outfile_names.push_back(getOutputFileName(pattern, true, infile_type, i));
      }
    }
    else
    {
      // Option 2: Simple indexing of input file name
      
      for (unsigned int i=0; i!= n_outfiles; ++i)
      {
        outfile_names.push_back(getOutputFileName(infile_name, false, infile_type, i));
      }
    }
      
  }
  
  
  // Now do the splitting
  
  input = MolFileFactory::open(infile);

  drf_input = NULL;
	drf_input = dynamic_cast<DockResultFile*>(input);
	if (drf_input) 
  {
    drf_input->selectAllResultsForInput();
  }
  
  for (unsigned int i=0; i!=outfile_names.size(); ++i)
  {
    conformation_ids.clear();
    
    output = MolFileFactory::open(outfile_names[i], ios::out, infile_type);
    drf_output = dynamic_cast<DockResultFile*>(output);
    if (drf_input && drf_output)
    {
      drf_output->disableAutomaticResultCreation();
    }

    
    if (i < outfile_names.size()-1)
    {
      // Not the last file - so number of molecules is standard
      
      for (unsigned int j=0; j!=mpf; ++j)
      {
        mol = input->read();
        if (drf_input && drf_output && mol->hasProperty("Conformation_input_UID"))
        {
          conformation_ids.insert(mol->getProperty("Conformation_input_UID").toString());
        }

        output->write(*mol);
        delete mol;
      }
    }
    else
    {
      // Last output file - so write remaining molecules into it
      
      mol = input->read();
      while (mol)
      {
        if (drf_input && drf_output && mol->hasProperty("Conformation_input_UID"))
        {
          conformation_ids.insert(mol->getProperty("Conformation_input_UID").toString());
        }

        output->write(*mol);
        delete mol;
        mol = input->read();
      }
    }

    if (drf_input && drf_output)
    {
      const vector<Result*>* results = drf_input->getResults();
      for (unsigned int i = 0; i < results->size(); ++i)
      {
        Result* new_res = new Result(*(*results)[i], conformation_ids);
        drf_output->addResult(new_res);
      }
    }
    
    output->close();
    delete output;
  }  

  input->close();
  delete input;
  
  
  return 0;
}
Beispiel #13
0
String Environment::getFilePart( const String& fileName ) {
    return fileName.substr( fileName.find_last_of( PATH_SEPARATOR ) + 1 );
}
Beispiel #14
0
//---------------------------------------------------------------------------//
  String PathService::getFileExtension( const String& szFileName )
  {
    int iPos = szFileName.find_last_of( "." );
    return szFileName.substr( iPos + 1, szFileName.size() - iPos );
  }
 String AbstractFileManager::pathExtension(const String& path) {
     size_t pos = path.find_last_of('.');
     if (pos == String::npos) return "";
     return path.substr(pos + 1);
 }
 String AbstractFileManager::deleteLastPathComponent(const String& path) {
     if (path.empty()) return path;
     size_t sepPos = path.find_last_of(pathSeparator());
     if (sepPos == String::npos) return "";
     return path.substr(0, sepPos);
 }
Beispiel #17
0
// Update an options menu item
void Menu::updateOptionsItem(int i, bool change) {
	TextAreaOverlayElement *item = static_cast<TextAreaOverlayElement*>(OverlayManager::getSingleton().getOverlayElement(mMenuName + StringConverter::toString(i+1)));
	Viewport *vp = gameApp->getRenderWindow()->getViewport(0);
	String itemText = item->getCaption();
	itemText = itemText.substr(0, itemText.find_last_of(':'));
	itemText += ": ";
	String str;
	char volstr[16] = "";
	Real vol = 0;
	
	switch(i) {
		// Bloom effect
		case MENU_OPTIONS_BLOOM:
			str = gameApp->mGameConfig->GetValue("graphics", "bloom", "on");
			if(change) {
				if(str == "on") str = "off";
				else if(str == "off") str = "on";
				gameApp->mGameConfig->SetValue("graphics", "bloom", str.c_str());
				CompositorManager::getSingleton().setCompositorEnabled(vp, "Bloom", (str != "off"));
			}
			item->setCaption(itemText + ((str == "on") ? "ON" : "OFF"));
			break;

		// Shadows
		case MENU_OPTIONS_SHADOWS:
			str = gameApp->mGameConfig->GetValue("graphics", "shadows", "on");
			if(change) {
				if(str == "on") str = "off";
				else if(str == "off") str = "on";
				gameApp->mGameConfig->SetValue("graphics", "shadows", str.c_str());
				mSceneMgr->setShadowTechnique((str == "off") ? SHADOWTYPE_NONE : SHADOWTYPE_STENCIL_ADDITIVE);
			}
			item->setCaption(itemText + ((str == "on") ? "ON" : "OFF"));
			break;

		// Dynamic lights
		case MENU_OPTIONS_DYN_LIGHTS:
			str = gameApp->mGameConfig->GetValue("graphics", "dynamic_lights", "on");
			if(change) {
				if(str == "on") str = "off";
				else if(str == "off") str = "on";
				gameApp->mGameConfig->SetValue("graphics", "dynamic_lights", str.c_str());
			}
			item->setCaption(itemText + ((str == "on") ? "ON" : "OFF"));
			break;

		// Dynamic light cast shadows
		case MENU_OPTIONS_DYN_LIGHT_SHADOWS:
			str = gameApp->mGameConfig->GetValue("graphics", "dynamic_light_shadows", "on");
			if(change) {
				if(str == "on") str = "off";
				else if(str == "off") str = "on";
				gameApp->mGameConfig->SetValue("graphics", "dynamic_light_shadows", str.c_str());
			}
			item->setCaption(itemText + ((str == "on") ? "ON" : "OFF"));
			break;

		// Sound volume
		case MENU_OPTIONS_SOUND_VOL:
			str = gameApp->mGameConfig->GetValue("audio", "volume", "1.0");
			vol = StringConverter::parseReal(str);
			if(change) {
				vol += 0.1f;
				if((int)(vol*100.0f) > 100) vol = 0.0f;
				str = StringConverter::toString(vol);
				gameApp->mGameConfig->SetValue("audio", "volume", str.c_str());

				// Play a test sound
				SoundSystem::getSingleton().setSoundVolume(vol);
				SoundSystem::getSingleton().playSound("mushroom1");
			}

			//ivol = (int)(100 * vol);
			sprintf(volstr, "%.0f%%", vol*100.0f);
			item->setCaption(itemText + String(volstr));
			break;

		// Music volume
		case MENU_OPTIONS_MUSIC_VOL:
			str = gameApp->mGameConfig->GetValue("audio", "music_volume", "0.5");
			vol = StringConverter::parseReal(str);
			if(change) {
				vol += 0.1f;
				if((int)(vol*100.0f) > 100) vol = 0.0f;
				str = StringConverter::toString(vol);
				gameApp->mGameConfig->SetValue("audio", "music_volume", str.c_str());

				SoundSystem::getSingleton().setMusicVolume(vol);
			}

			//ivol = (int)(100 * vol);
			sprintf(volstr, "%.0f%%", vol*100.0f);
			item->setCaption(itemText + String(volstr));
			break;
	}
}
Beispiel #18
0
void PolycodePlayer::loadFile(const char *fileName) {
	
	String mainFile = "";
	String basePath = fileName;
	
	Number red = 0.2f;
	Number green = 0.2f;
	Number blue = 0.2f;
	
	String textureFiltering = "linear";
	
	frameRate = 60;
	
	Object configFile;

	String nameString = fileName;
		
	bool loadingArchive = false;

	if(nameString != "") {
	String ext = nameString.substr(nameString.length() - 8, nameString.length());
	
	Logger::log("Loading %s\n", fileName);
	
	String configPath;
	
	if(ext == ".polyapp" || _knownArchive) {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		rman->addArchive(nameString);
		configPath = "runinfo.polyrun";
		loadingArchive = true;
		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
	} else {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		
		String fileDir = "";
		std::vector<String> bits = String(fileName).split("/");
		for(int i=0; i <	 bits.size()-1; i++) {
			fileDir += "/"+bits[i];
		}
		
		rman->addArchive(fileDir);
		configPath = fileName;
		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
	}
	

	if(!configFile.loadFromXML(configPath)) {
		Logger::log("Error loading config file\n");
	} else {		
		
		if(configFile.root["entryPoint"]) {
			mainFile = configFile.root["entryPoint"]->stringVal;
		}		
		if(configFile.root["defaultWidth"]) {
			xRes = configFile.root["defaultWidth"]->intVal;
		}		
		if(configFile.root["defaultHeight"]) {
			yRes = configFile.root["defaultHeight"]->intVal;
		}		
		if(configFile.root["frameRate"]) {
			frameRate = configFile.root["frameRate"]->intVal;
		}		
		if(configFile.root["antiAliasingLevel"]) {
			aaLevel = configFile.root["antiAliasingLevel"]->intVal;
		}		
		if(configFile.root["fullScreen"]) {
			fullScreen = configFile.root["fullScreen"]->boolVal;
		}				
		if(configFile.root["textureFiltering"]) {
			textureFiltering = configFile.root["textureFiltering"]->stringVal;
		}		
	
		
		if(configFile.root["backgroundColor"]) {
			ObjectEntry *color = configFile.root["backgroundColor"];
			if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
				red = (*color)["red"]->NumberVal;
				green = (*color)["green"]->NumberVal;
				blue = (*color)["blue"]->NumberVal;
				
			}			
		}
		
		ObjectEntry *fonts = configFile.root["fonts"];
		if(fonts) {
			for(int i=0; i < fonts->length; i++) {			
				ObjectEntry *fontName = (*(*fonts)[i])["name"];				
				ObjectEntry *fontPath = (*(*fonts)[i])["path"];
				
				if(fontName && fontPath) {
					printf("REGISTERING FONT %s %s\n", fontName->stringVal.c_str(), fontPath->stringVal.c_str());
					CoreServices::getInstance()->getFontManager()->registerFont(fontName->stringVal, fontPath->stringVal);
				}

			}
		}
		
		ObjectEntry *modules = configFile.root["modules"];			
		if(modules) {
			for(int i=0; i < modules->length; i++) {			
				String moduleName = (*modules)[i]->stringVal;
				Logger::log("Loading module: %s\n", moduleName.c_str());				

#ifdef _WINDOWS
			TCHAR _tempPath[4098];
			TCHAR tempPath[4098];
			GetTempPathW(4098, _tempPath);
			GetLongPathNameW(_tempPath, tempPath, 4098);
			String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
			String moduleFileName = String("__lib/win/") + moduleName+ String(".dll");

#else
	#if defined(__APPLE__) && defined(__MACH__)
				String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
	#else
				String moduleFileName = String("__lib/linux/") + moduleName+ String(".so");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".so");
	#endif
#endif				
				OSFILE *inFile = OSBasics::open(moduleFileName, "rb");	
				if(inFile) {
					OSBasics::seek(inFile, 0, SEEK_END);	
					long progsize = OSBasics::tell(inFile);
					OSBasics::seek(inFile, 0, SEEK_SET);
					char *buffer = (char*)malloc(progsize+1);
					memset(buffer, 0, progsize+1);
					OSBasics::read(buffer, progsize, 1, inFile);
					
					OSFILE *outFile = OSBasics::open(moduleDestPath, "wb");						
					OSBasics::write(buffer, progsize, 1, outFile);
					OSBasics::close(outFile);	
					
					free(buffer);
					OSBasics::close(inFile);	
					
					loadedModules.push_back(moduleName);
				} else {
					Logger::log("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());									
				}
			}

		}			
	}
	
	Logger::log("Mainfile: %s\n", mainFile.c_str());
	
	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
	event->xRes = xRes;
	event->yRes = yRes;	
	
	}
	createCore();

	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
	core->getInput()->addEventListener(this, InputEvent::EVENT_KEYUP);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEMOVE);
	core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEUP);
					
	if(nameString == "") {
		return;
	}
	
	Logger::log("Core created...\n");

	CoreServices::getInstance()->getResourceManager()->addArchive("UIThemes.pak");
	CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/default/theme.xml");
	
	CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("Physics2D.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("Physics3D.pak");
	CoreServices::getInstance()->getResourceManager()->addArchive("UI.pak");			
	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];				
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				if(entryIsResource && entryPath) {
					if(entryIsResource->boolVal == true) {
						CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
					}
				}
			}
		}
	}
	
	
	core->setUserPointer(this);
	//core->addEventListener(this, Core::EVENT_CORE_RESIZE);
	core->setVideoMode(xRes, yRes, fullScreen, false, 0, aaLevel);
	
	if(textureFiltering == "nearest") {
		CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_NEAREST);
	} else {
		CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_LINEAR);
	}
				
	CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
	CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);


//	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
	
	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
//	CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
	srand(core->getTicks());
	
	if(loadingArchive) {
		fullPath = mainFile;
	} else {
		int lindex = basePath.find_last_of("/");
		fullPath = basePath.substr(0, lindex);	
		fullPath += mainFile;	
		Logger::log(fullPath.c_str());
	}
	
	remoteDebuggerClient = NULL;
	
	if(useDebugger) {
	
			
		remoteDebuggerClient = new PolycodeRemoteDebuggerClient();
		remoteDebuggerClient->addEventListener(this, Event::COMPLETE_EVENT);
		
		this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_PRINT);
		this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_ERROR);		
		remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_CLIENT_READY);
		remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_SERVER_DATA);
		
		debuggerTimer = new Timer(true, 5000);
		debuggerTimer->addEventListener(this, Timer::EVENT_TRIGGER);
	} else{
		runFile(fullPath);
	}
}
void PolycodeProjectGenerator::generateVS12(){
	OSFILE *slnF = bas.open("Projects/PolycodeProject12.sln", "r");
	OSFILE *vcxprojF = bas.open("Projects/PolycodeProject12.vcxproj", "r");
	OSFILE *mainF = bas.open("Projects/Source/mainWin.cpp", "r");
	OSFILE *appCF = bas.open("Projects/Source/PolycodeProject.cpp", "r");
	OSFILE *appHF = bas.open("Projects/Include/PolycodeProject.h", "r");

	String sln = loadFile(slnF), vcxproj = loadFile(vcxprojF), main = loadFile(mainF), appC = loadFile(appCF), appH = loadFile(appHF);

	bas.close(slnF);
	bas.close(vcxprojF);
	bas.close(mainF);
	bas.close(appCF);
	bas.close(appHF);

	String modulesInc, modulesLibD, modulesLibs, modulesLibsD, modulesIncH, extraCopy;

	if (physics2D->isChecked() || physics3D->isChecked() || ui->isChecked()){
		modulesInc = "Framework/Modules/include;";
		modulesLibD = "Framework/Modules/lib;";
		if (physics2D->isChecked() || physics3D->isChecked()){
			modulesInc += "Framework/Modules/Dependencies/include;";
			modulesLibD += "Framework/Modules/Dependencies/lib;";
			if (physics2D->isChecked()){
				modulesLibs = "Polycode2DPhysics.lib;Box2D.lib;";
				modulesLibsD = "Polycode2DPhysics_d.lib;Box2D_d.lib;";
				modulesIncH = "#include \"Physics2D.h\"\n";
			}
			if (physics3D->isChecked()){
				modulesInc += "Modules/Dependencies/include/bullet;";
				modulesLibs += "Polycode3DPhysics.lib;BulletDynamics.lib;BulletCollision.lib;LinearMath.lib;";
				modulesLibsD += "Polycode3DPhysics_d.lib;BulletDynamics_d.lib;BulletCollision_d.lib;LinearMath_d.lib;";
				modulesIncH += "#include \"Physics3D.h\"\n";
			}
		}
		if (ui->isChecked()){
			modulesLibs += "PolycodeUI.lib;";
			modulesLibsD += "PolycodeUI_d.lib;";
			modulesIncH += "#include \"PolycodeUI.h\"\n";
			extraCopy = "if not exist \"$(ProjectDir)UIThemes.pak\" copy \"$(PolycodeDir)Modules/Assets/UIThemes.pak\" \"$(ProjectDir)\"\n";
		}
	}

	String name = projName->getText();

	sln = sln.replace("--ProjectName--", name);

	vcxproj = vcxproj.replace("--ProjectName--", name);
	vcxproj = vcxproj.replace("--ModulesIncDir--", modulesInc);
	vcxproj = vcxproj.replace("--ModulesLibDir--", modulesLibD);
	vcxproj = vcxproj.replace("--ModulesDebug--", modulesLibsD);
	vcxproj = vcxproj.replace("--Modules--", modulesLibs);
	vcxproj = vcxproj.replace("--ExtraCopy--", extraCopy);

	main = main.replace("--ProjectName--", name);
	appC = appC.replace("--ProjectName--", name);
	appH = appH.replace("--ProjectName--", name);
	appH = appH.replace("--ModulesInc--", modulesIncH);

	String path = projPos->getText();

	if (!bas.isFolder(path))
		bas.createFolder(path);
	if (path.find_last_of("\\") != path.length() && path.find_last_of("/") != path.length()){
		path.append('/');
	}

	bas.createFolder(path + "Source");
	bas.createFolder(path + "Include");

	String buildPath = path + "Build";
	bas.createFolder(buildPath);
	buildPath += "/VS12";
	bas.createFolder(buildPath);
	buildPath.append('/');

	if (!bas.fileExists(buildPath + name + ".sln"))
		writeFile(buildPath + name + ".sln", sln);
	if (!bas.fileExists(buildPath + name + ".vcxproj"))
		writeFile(buildPath + name + ".vcxproj", vcxproj);
	if (!bas.fileExists(path + "Source/" + name + ".cpp"))
		writeFile(path + "Source/" + name + ".cpp", appC);
	if (!bas.fileExists(buildPath + "main.cpp"))
		writeFile(buildPath + "main.cpp", main);
	if (!bas.fileExists(path + "Include/" + name + ".h"))
		writeFile(path + "Include/" + name + ".h", appH);

}
Beispiel #20
0
/**
* Windows specific file dialog opener
*
*  @param fileName the name of the file to save (in case @param mode is FILEMODE_SAVE)
*  otherwise ignored.
*  @param mode either FILEMODE_SAVE or FILEMODE_OPEN depending on whether
*  the dialog should be "Save as.." og "Open file.."
*  @param owner handle to the owner window
*/
String Environment::LoadFileDialog( String fileName, UInt mode, HWND owner )
{
	char Filestring[4196];
	//reset Filestring
	for ( UInt i = 0; i < 4196; i++ )
		Filestring[i] = 0;
	String returnstring;
	OPENFILENAME opf;
	LPCTSTR filter;
	Vector<char> str2;

	if ( mode == FILEMODE_OPEN )
	{
		filter = "Fits files\0*.FITS;*.FIT;*.FTS;*.IMG;*.LBL;\0\0";
		opf.lpstrDefExt = "fit";
		
		
	
	}
	else if ( mode == FILEMODE_SAVE )
	{		
		filter = "Tiff files\0*.TIFF;*.TIF\0\0";
		opf.lpstrDefExt = "tif";
		//get the position of the last '.' which defines the file extension
		Int pos = fileName.find_last_of( ".", String::npos );
		if ( pos > 0 )
			fileName = fileName.substr( 0, pos );

		fileName = fileName + ".tif";

		fileName = Environment::getFilePart( fileName );
		
		
		fileName.copy( Filestring, fileName.length(), 0 );

		
	}
	
	opf.lpstrTitle = NULL;
	opf.hwndOwner = owner;
	opf.hInstance = NULL;
	opf.lpstrFilter = filter;
	opf.lpstrCustomFilter = NULL;
	opf.nMaxCustFilter = 0L;
	opf.nFilterIndex = 1L;
	opf.lpstrFile = Filestring;	
	opf.nMaxFile = 4196;
	opf.lpstrFileTitle = NULL;
	opf.nMaxFileTitle=50;
	opf.lpstrInitialDir = NULL;

	opf.nFileOffset = NULL;
	opf.nFileExtension = NULL;
	
	opf.lpfnHook = NULL; 
	opf.lCustData = NULL;
	opf.Flags = (OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT) & ~OFN_ALLOWMULTISELECT;  
	opf.lStructSize = sizeof(OPENFILENAME);
	opf.FlagsEx = 0; 
	if ( mode == FILEMODE_OPEN )
	{
		if(GetOpenFileName(&opf))    		        
			returnstring = opf.lpstrFile;
	}
	else if ( mode == FILEMODE_SAVE )
	{
		if(GetSaveFileName(&opf))    		        
			returnstring = opf.lpstrFile;
	}
	return returnstring;
}
void PolycodeProjectGenerator::generateMakefile(){
	OSFILE *makeF = bas.open("Projects/Makefile", "r");
	OSFILE *mainF = bas.open("Projects/Source/mainMakefile.cpp", "r");
	OSFILE *appCF = bas.open("Projects/Source/PolycodeProject.cpp", "r");
	OSFILE *appHF = bas.open("Projects/Include/PolycodeProject.h", "r");

	String make = loadFile(makeF), main = loadFile(mainF), appC = loadFile(appCF), appH = loadFile(appHF);

	bas.close(makeF);
	bas.close(mainF);
	bas.close(appCF);
	bas.close(appHF);

	String modulesInc, modulesLibs, modulesIncH, extraCopy;

	if (physics2D->isChecked() || physics3D->isChecked() || ui->isChecked()){
		modulesInc = "-IFramework/Modules/include ";
		if (physics2D->isChecked() || physics3D->isChecked()){
			modulesInc += "-IFramework/Modules/Dependencies/include ";
			if (physics2D->isChecked()){
				modulesLibs = "Framework/Modules/lib/libPolycode2DPhysics.a Framework/Modules/Dependencies/lib/libBox2D.a";
				modulesIncH = "#include \"Physics2D.h\"\n";
			}
			if (physics3D->isChecked()){
				modulesInc += "-IFramework/Modules/Dependencies/include/bullet ";
				modulesLibs += " Framework/Modules/lib/libPolycode3DPhysics.a Framework/Modules/Dependencies/lib/libBulletDynamics.a Framework/Modules/Dependencies/lib/libBulletCollision.a Framework/Modules/Dependencies/lib/libLinearMath.a";
				modulesIncH += "#include \"Physics3D.h\"\n";
			}
		}
		if (ui->isChecked()){
			modulesLibs += " Framework/Modules/lib/libPolycodeUI.a";
			modulesIncH += "#include \"PolycodeUI.h\"\n";
			extraCopy = "cp Framework/Modules/Assets/UIThemes.pak .";
		}
	}

	String name = projName->getText();

	make = make.replace("--ProjectName--", name);
	make = make.replace("--ModulesIncDir--", modulesInc);
	make = make.replace("--Modules--", modulesLibs);
	make = make.replace("--ExtraCopy--", extraCopy);

	main = main.replace("--ProjectName--", name);
	appC = appC.replace("--ProjectName--", name);
	appH = appH.replace("--ProjectName--", name);
	appH = appH.replace("--ModulesInc--", modulesIncH);


	String path = projPos->getText();

	if (!bas.isFolder(path))
		bas.createFolder(path);
	if (path.find_last_of("\\") != path.length() && path.find_last_of("/") != path.length()){
		path.append('/');
	}

	bas.createFolder(path + "Source");
	bas.createFolder(path + "Include");

	String buildPath = path + "Build";
	bas.createFolder(buildPath);
	buildPath += "/Linux";
	bas.createFolder(buildPath);
	buildPath.append('/');

	if (!bas.fileExists(buildPath + "Makefile"))
		writeFile(buildPath + "Makefile", make);
	if (!bas.fileExists(path + "Source/" + name + ".cpp"))
		writeFile(path + "Source/" + name + ".cpp", appC);
	if (!bas.fileExists(buildPath + "main.cpp"))
		writeFile(buildPath + "main.cpp", main);
	if (!bas.fileExists(path + "Include/" + name + ".h"))
		writeFile(path + "Include/" + name + ".h", appH);

}
Beispiel #22
0
void PolycodePlayer::loadFile(const char *fileName) {
	
	FILE *t = fopen("C:\\out.txt", "a");
	fwrite(fileName, strlen(fileName), 1, t);
	fclose(t);

	String mainFile = "";
	String basePath = fileName;
	
	Number red = 0.2f;
	Number green = 0.2f;
	Number blue = 0.2f;
	
	frameRate = 60;
	
	Object configFile;

	String nameString = fileName;
		
	bool loadingArchive = false;

	if(nameString != "") {
	String ext = nameString.substr(nameString.length() - 8, nameString.length());
	
	Logger::log("Loading %s\n", fileName);
	
	String configPath;
	
	if(ext == ".polyapp" || _knownArchive) {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		rman->addArchive(nameString);
		configPath = "runinfo.polyrun";
		loadingArchive = true;
		Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
	} else {
		ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
		
		String fileDir = "";
		vector<String> bits = String(fileName).split("/");
		for(int i=0; i <	 bits.size()-1; i++) {
			fileDir += "/"+bits[i];
		}
		
		rman->addArchive(fileDir);
		configPath = fileName;
		Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);		
	}
	

	if(!configFile.loadFromXML(configPath)) {
		Logger::log("Error loading config file\n");
	} else {		
		
		if(configFile.root["entryPoint"]) {
			mainFile = configFile.root["entryPoint"]->stringVal;
		}		
		if(configFile.root["defaultWidth"]) {
			xRes = configFile.root["defaultWidth"]->intVal;
		}		
		if(configFile.root["defaultHeight"]) {
			yRes = configFile.root["defaultHeight"]->intVal;
		}		
		if(configFile.root["frameRate"]) {
			frameRate = configFile.root["frameRate"]->intVal;
		}		
		if(configFile.root["antiAliasingLevel"]) {
			aaLevel = configFile.root["antiAliasingLevel"]->intVal;
		}		
		if(configFile.root["fullScreen"]) {
			fullScreen = configFile.root["fullScreen"]->boolVal;
		}		
		if(configFile.root["backgroundColor"]) {
			ObjectEntry *color = configFile.root["backgroundColor"];
			if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
				red = (*color)["red"]->NumberVal;
				green = (*color)["green"]->NumberVal;
				blue = (*color)["blue"]->NumberVal;
				
			}			
		}
		ObjectEntry *modules = configFile.root["modules"];			
		if(modules) {
			for(int i=0; i < modules->length; i++) {			
				String moduleName = (*modules)[i]->stringVal;
				Logger::log("Loading module: %s\n", moduleName.c_str());				

#ifdef _WINDOWS
			TCHAR _tempPath[4098];
			TCHAR tempPath[4098];
			GetTempPathW(4098, _tempPath);
			GetLongPathNameW(_tempPath, tempPath, 4098);
			String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
			String moduleFileName = String("__lib/win/") + moduleName+ String(".dll");

#else
				String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
				String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
#endif				
				OSFILE *inFile = OSBasics::open(moduleFileName, "rb");	
				if(inFile) {
					OSBasics::seek(inFile, 0, SEEK_END);	
					long progsize = OSBasics::tell(inFile);
					OSBasics::seek(inFile, 0, SEEK_SET);
					char *buffer = (char*)malloc(progsize+1);
					memset(buffer, 0, progsize+1);
					OSBasics::read(buffer, progsize, 1, inFile);
					
					OSFILE *outFile = OSBasics::open(moduleDestPath, "wb");						
					OSBasics::write(buffer, progsize, 1, outFile);
					OSBasics::close(outFile);	
					
					free(buffer);
					OSBasics::close(inFile);	
					
					loadedModules.push_back(moduleName);
				} else {
					Logger::log("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());									
				}
			}

		}			
	}
	
	Logger::log("Mainfile: %s\n", mainFile.c_str());
	
	PolycodeDebugEvent *event = new PolycodeDebugEvent();			
	event->xRes = xRes;
	event->yRes = yRes;	
	
	}
	createCore();

	if(nameString == "") {
		return;
	}
	
	Logger::log("Core created...\n");
	
	CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
	
	if(configFile.root["packedItems"]) {
		ObjectEntry *packed = configFile.root["packedItems"];
		if(packed) {
			for(int i=0; i < packed->length; i++) {
				ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];				
				ObjectEntry *entryPath = (*(*packed)[i])["path"];
				if(entryIsResource && entryPath) {
					if(entryIsResource->boolVal == true) {
						CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
					}
				}
			}
		}
	}
	
	
	core->setUserPointer(this);
	//core->addEventListener(this, Core::EVENT_CORE_RESIZE);
	core->setVideoMode(xRes, yRes, fullScreen, aaLevel);
		
	CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
	CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);


//	dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);		
	
	CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
//	CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
	srand(core->getTicks());
	
	String fullPath;
	
	if(loadingArchive) {
		fullPath = mainFile;
	} else {
		int lindex = basePath.find_last_of("/");
		fullPath = basePath.substr(0, lindex);	
		fullPath += mainFile;	
		Logger::log(fullPath.c_str());
	}
	
	runFile(fullPath);
}
Beispiel #23
0
  DescriptorReader(const String& zernike_filename, const String& texture_filename, const String& dc_filename) {
    std::ifstream fp(zernike_filename.c_str());

    String line;
    while (fp) {
      std::getline(fp, line);

      if (line.length() <= 0) continue;

      size_t idx = line.find(" ");

      if (idx != String::npos) {
        String meshname = line.substr(0,idx);
        String descriptorStr = line.substr(idx+1);

        meshname = meshname.substr(meshname.find_last_of('/')+1);
        String meshnamefull = "meerkat:///tahirazim/apiupload/" + meshname + "/optimized/0/" + meshname;

        mZernikeDescriptorMap[meshnamefull] = ZernikeDescriptor(descriptorStr);
 
        meshnamefull = "meerkat:///tahirazim/apiupload/" + meshname + "/original/0/" + meshname;
        mZernikeDescriptorMap[meshnamefull] = ZernikeDescriptor(descriptorStr);


      }
    }

    fp.close();

    std::ifstream fp2(texture_filename.c_str());
    while (fp2) {
      std::getline(fp2, line);

      if (line.length() <= 0) continue;

      size_t idx = line.find(" ");

      if (idx != String::npos) {
        String meshname = line.substr(0,idx);
        String descriptorStr = line.substr(idx+1);

        if (meshname.find("meerkat:///") != 0) {
          //meshname = meshname.substr(meshname.find_last_of('/')+1); //this is no longer needed with ~/all_csds.txt
          String meshnamefull = "meerkat:///tahirazim/apiupload/" + meshname + "/optimized/0/" + meshname;
          mTextureDescriptorMap[meshnamefull] = ZernikeDescriptor(descriptorStr);
          meshnamefull = "meerkat:///tahirazim/apiupload/" + meshname + "/original/0/" + meshname;
          mTextureDescriptorMap[meshnamefull] = ZernikeDescriptor(descriptorStr);
        }
        else {
          mTextureDescriptorMap[meshname] = ZernikeDescriptor(descriptorStr);
        }
      }
    }

    fp2.close();

    std::ifstream fp3(dc_filename.c_str());
    std::getline(fp3, line);
    while (fp3) {
      String meshname=line;
      std::getline(fp3, line);  //texname
      String texname = line;
      String fullname = meshname + ":" + texname;
      std::getline(fp3, line);  //texname again
      std::getline(fp3, line);  //size info
      std::getline(fp3, line);  // sc (spatial coherence info)
      std::getline(fp3, line);  //percentage, color value, color variance table head.

      String value="abcde";
      int r = 0, g = 0, b = 0;
      std::getline(fp3, value);

      int maxPercentage = 0;
      //parse next "value: " line.
      while (value.substr(0,6) == "value:") {

        bool currentIsMax = false;

        char valueline[1024];
        strncpy(valueline, value.c_str(), value.length()+1);
        const char* delim = " :|";
        char* p;
        char*save;
        int count = 0;

        //tokenize the line
#if LIBPROX_PLATFORM == PLATFORM_WINDOWS
#define strtok_threadsafe strtok_s
#else
#define strtok_threadsafe strtok_r
#endif
        for (p=strtok_threadsafe(valueline, delim, &save); p; p = strtok_threadsafe(NULL, delim, &save) ) {
          if (count == 1) {
            int percentValue = atoi(p);
            if (percentValue > maxPercentage && percentValue > 90) {
              maxPercentage = percentValue;
              currentIsMax = true;
            }
          } //end if

          if (currentIsMax) {
            if (count == 2) r = atoi(p);
            if (count == 3) g = atoi(p);
            if (count == 4) b = atoi(p);
          } //end if

          count++;
        } //end for

        std::getline(fp3, value);
      } //end while

      line = value;

      //quantize the r,g,b's
      r = ((r/32)*32) + 16;
      g = ((g/32)*32) + 16;
      b = ((b/32)*32) + 16;

      //add to map.
      std::vector<float> rgb;
      rgb.push_back(r);
      rgb.push_back(g);
      rgb.push_back(b);

      //std::cout << fullname << " : " << r << " " << g << " " << b << "\n";
      if (maxPercentage != 0)
        mDominantColorMap[fullname] = ZernikeDescriptor(rgb);

      //std::cout << fullname << " : " << mDominantColorMap[fullname].toString() << "\n";
    }
    fp3.close();
  }
bool CvCascadeClassifier::train( const String _cascadeDirName,
                                const String _posFilename,
                                const String _negFilename,
                                int _numPos, int _numNeg,
                                int _precalcValBufSize, int _precalcIdxBufSize,
                                int _numStages,
                                const CvCascadeParams& _cascadeParams,
                                const CvFeatureParams& _featureParams,
                                const CvCascadeBoostParams& _stageParams,
                                bool baseFormatSave )
{
    if( _cascadeDirName.empty() || _posFilename.empty() || _negFilename.empty() )
        CV_Error( CV_StsBadArg, "_cascadeDirName or _bgfileName or _vecFileName is NULL" );

    string dirName;
    if (_cascadeDirName.find_last_of("/\\") == (_cascadeDirName.length() - 1) )
        dirName = _cascadeDirName;
    else
        dirName = _cascadeDirName + '/';

    numPos = _numPos;
    numNeg = _numNeg;
    numStages = _numStages;
    if ( !imgReader.create( _posFilename, _negFilename, _cascadeParams.winSize ) )
    {
        cout << "Image reader can not be created from -vec " << _posFilename
                << " and -bg " << _negFilename << "." << endl;
        return false;
    }
    if ( !load( dirName ) )
    {
        cascadeParams = _cascadeParams;
        featureParams = CvFeatureParams::create(cascadeParams.featureType);
        featureParams->init(_featureParams);
        stageParams = new CvCascadeBoostParams;
        *stageParams = _stageParams;
        featureEvaluator = CvFeatureEvaluator::create(cascadeParams.featureType);
        featureEvaluator->init( (CvFeatureParams*)featureParams, numPos + numNeg, cascadeParams.winSize );
        stageClassifiers.reserve( numStages );
    }
    cout << "PARAMETERS:" << endl;
    cout << "cascadeDirName: " << _cascadeDirName << endl;
    cout << "vecFileName: " << _posFilename << endl;
    cout << "bgFileName: " << _negFilename << endl;
    cout << "numPos: " << _numPos << endl;
    cout << "numNeg: " << _numNeg << endl;
    cout << "numStages: " << numStages << endl;
    cout << "precalcValBufSize[Mb] : " << _precalcValBufSize << endl;
    cout << "precalcIdxBufSize[Mb] : " << _precalcIdxBufSize << endl;
    cascadeParams.printAttrs();
    stageParams->printAttrs();
    featureParams->printAttrs();

    int startNumStages = (int)stageClassifiers.size();
    if ( startNumStages > 1 )
        cout << endl << "Stages 0-" << startNumStages-1 << " are loaded" << endl;
    else if ( startNumStages == 1)
        cout << endl << "Stage 0 is loaded" << endl;

    double requiredLeafFARate = pow( (double) stageParams->maxFalseAlarm, (double) numStages ) /
                                (double)stageParams->max_depth;
    double tempLeafFARate;

    for( int i = startNumStages; i < numStages; i++ )
    {
        cout << endl << "===== TRAINING " << i << "-stage =====" << endl;
        cout << "<BEGIN" << endl;

        if ( !updateTrainingSet( tempLeafFARate ) )
        {
            cout << "Train dataset for temp stage can not be filled. "
                "Branch training terminated." << endl;
            break;
        }
        if( tempLeafFARate <= requiredLeafFARate )
        {
            cout << "Required leaf false alarm rate achieved. "
                 "Branch training terminated." << endl;
            break;
        }

        CvCascadeBoost* tempStage = new CvCascadeBoost;
        bool isStageTrained = tempStage->train( (CvFeatureEvaluator*)featureEvaluator,
                                                curNumSamples, _precalcValBufSize, _precalcIdxBufSize,
                                                *((CvCascadeBoostParams*)stageParams) );
        cout << "END>" << endl;

        if(!isStageTrained)
            break;

        stageClassifiers.push_back( tempStage );

        // save params
        if( i == 0)
        {
            std::string paramsFilename = dirName + CC_PARAMS_FILENAME;
            FileStorage fs( paramsFilename, FileStorage::WRITE);
            if ( !fs.isOpened() )
            {
                cout << "Parameters can not be written, because file " << paramsFilename
                        << " can not be opened." << endl;
                return false;
            }
            fs << FileStorage::getDefaultObjectName(paramsFilename) << "{";
            writeParams( fs );
            fs << "}";
        }
        // save current stage
        char buf[10];
        sprintf(buf, "%s%d", "stage", i );
        string stageFilename = dirName + buf + ".xml";
        FileStorage fs( stageFilename, FileStorage::WRITE );
        if ( !fs.isOpened() )
        {
            cout << "Current stage can not be written, because file " << stageFilename
                    << " can not be opened." << endl;
            return false;
        }
        fs << FileStorage::getDefaultObjectName(stageFilename) << "{";
        tempStage->write( fs, Mat() );
        fs << "}";
    }

    if(stageClassifiers.size() == 0)
    {
        cout << "Cascade classifier can't be trained. Check the used training parameters." << endl;
        return false;
    }

    cout << "Save to " << dirName + CC_CASCADE_FILENAME <<endl;
    save( dirName + CC_CASCADE_FILENAME, baseFormatSave );

    return true;
}
Beispiel #25
0
    //-----------------------------------------------------------------------
    void MapUtil::processOneMap()
    {   
        MapSplatter SplatMapper;
        MapLighter LightMapper;
        MapBlender Blender;
        MapSplitter Splitter;
        MapMergeModulater MergeModulater;

        mPageX = mWidth / mPageSize;
        mPageZ = mHeight / mPageSize;  

        Splitter.init ();

        if (mGenEqualize)
        { 
            MapEqualizer Equalizer;
            Equalizer.equalize ();
        }

        if (mGenInfiniteMap)
        { 
            MapInfinitizer Infinitizer;
            Infinitizer.Infinitize (static_cast <uint> (mHeight / 10), 
                                    0.0f, 
                                    0);
                    
        }

        const Real Blur = mHeightMapBlurFactor;
        if (Blur > 0.0f)
        {
            Convolver *c = new Convolver (int (Blur));
            c->blurReal (mData, mWidth, mHeight);
        }


        // 
        // Split Heightmap in 2^n + 1 part  
        // 
        if (mGenHeightMap)
        {
            Splitter.setRawSave (StringUtil::match(mExt, "raw", false));
            Splitter.saveAndSpaceAndSplitHeightData (mFileName, 
                                            mData, 
                                            mWidth, 
                                            mHeight); 
            Splitter.setRawSave (StringUtil::match(mTextureExt, "raw", false));
        }

/*        if (mGenMiniMap)
        {
            const uint W = MapUtil::getSingleton().getMapWidth ();
            const uint H  = MapUtil::getSingleton().getMapHeight ();
            const uint hn_map_size = W*H;
            uchar *data = new uchar[hn_map_size];            
            const Real divider = 1.0f / getMaxTheoHeight() * 256;
            Real *hdata = mData;
            for ( uint i = 0; i < hn_map_size; i++ )            
            { 
                data[i] = static_cast <uchar>  (hdata[i] * divider);
            }
            Image grayheightmap;
          
            grayheightmap.loadDynamicImage (data, 
                                            static_cast <size_t> (W),
                                            static_cast <size_t> (H), 
                                            1, PF_L8, true);


            const ushort wtiles = mGenMiniMapWidth;
            const ushort htiles = mGenMiniMapHeight; 

            grayheightmap.resize (wtiles, htiles);

            const String OutDirectory = mOutDirectory;

            char *olddir = ChangeToDir (const_cast< char * > (OutDirectory.c_str ()));
            Splitter.saveExt (mPureFilename + ".Small." + mExt, grayheightmap.getData(), 
                                static_cast <uint> (wtiles), 
                                static_cast <uint> (htiles),
                                1);
            RetablishDir (olddir);

            String MapName = mColorMapName;
            if (MapName != StringUtil::BLANK && MapName != "none")    
            {
                    if (MapName == mFileName)
                        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
                                "HeightMap File and ColorMap file cannot be the same file", 
                                "MapUtil::ProcessOneFile");
               
                    Image ExistingColorMap;

                    ExistingColorMap.load (MapName, mGroupName);

                    // Get codec according to filename extension
                    size_t colorpos = MapName.find_last_of(".");
                    String colormPureFilename = MapName.substr(0, colorpos + 1);
           
                    ExistingColorMap.resize (wtiles,htiles);

                    olddir = ChangeToDir (const_cast< char * > (OutDirectory.c_str ()));
                    Splitter.saveExt (colormPureFilename + ".Small." + mTextureExt, ExistingColorMap.getData(), 
                                 static_cast <uint> (wtiles), 
                                static_cast <uint> (htiles),
                                3);
                    RetablishDir (olddir);

            }


        }
*/
        // 
        // Split Normal Map + HeightMap in alpha channel in 2^n + 1 part  
        // 
 /*       if (mGenHeightNormalMap)
        {		
            const uint W = MapUtil::getSingleton().getMapWidth ();
            const uint H  = MapUtil::getSingleton().getMapHeight ();
            const uint hn_map_size = W*H;
            uchar *data = new uchar[hn_map_size];            
            const Real divider = 1.0f / getMaxTheoHeight() * 256;
            Real *hdata = mData;
            for ( uint i = 0; i < hn_map_size; i++ )            
            { 
                data[i] = static_cast <uchar>  (hdata[i] * divider);
            }
            Image grayheightmap;
          
            grayheightmap.loadDynamicImage (data, static_cast <size_t> (W),
                                            static_cast <size_t> (H), 1, PF_L8, true);

            Image *NormalMap = MergeModulater.MergeGrayAndRgbInRgba (&grayheightmap,
                                                                NormalMapper.getNormalMap ());
              
            Splitter.saveAndSpaceAndSplitMap (mPureFilename + ".HN." + mExt,
                                                NormalMap);
            delete NormalMap;
        }   */
          
        // 
        // If we does calculate Light or slope We need Normals.
        // 
        if (mGenCoverageMap ||
            mGenBaseMap || 
            mGenRGBMaps || 
            mGenAlphaMaps || 
            mGenAlphaSplatRGBAMaps || 
            mGenAlphaSplatLightMaps || 
            mGenLightMap || 
            mGenShadowMap ||
            mGenLitColorMapGenerate ||
            mGenLitColorMapSplit ||
            mGenLitBaseMap)
        {
            mNormalMap = NormalMapper.getNormalMap ();
            mNormalMapBpp = PixelUtil::getNumElemBytes (mNormalMap->getFormat ());
            mNormalMapData = mNormalMap->getData();
            mNormalMapDataSize = static_cast <uint> (mNormalMap->getSize());
        }

        // 
        // Split Normal Map in 2^n  part  
        // 
        if (mGenNormalMap)
        {
                Splitter.saveAndSpaceAndSplitMap (mPureFilename + String(".N.") + mTextureExt,
                                                    mNormalMap);
        } // if (mGenNormalMap)

        // 
        // Split Light Map in 2^n  part  
        // 
        if (mGenLightMap)
            Splitter.saveAndSplitMap (mPureFilename + String(".Light.") + mTextureExt,
                                    LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur));
        // 
        // Split Shadow Map in 2^n  part (shadow is light map inverted.)
        // 
        if (mGenShadowMap)
            Splitter.saveAndSplitMap (mPureFilename + String(".Shadow.") + mTextureExt,
                                    LightMapper.getShadowMap (mSun, mAmb, mDiff, mBlur));

        // 
        // Generate a Color Map in 2^n  part 
        // 
        if (mGenColorMapGenerate)
            Splitter.saveAndSplitMap (mPureFilename + String(".Color.") + mTextureExt,
                                    SplatMapper.getColorMap ());

        // 
        // Lit Generated Color Map in 2^n  part 
        // 
        if (mGenLitColorMapGenerate)
        { 
            // does modify color map.
            MergeModulater.ModulateGrayAndRgbInRgb (LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur),
                                                    SplatMapper.getColorMap (),
                                                    2);
            Splitter.saveAndSplitMap (mPureFilename + String(".LitColor.") + mTextureExt,
                                    SplatMapper.getColorMap ());
        }


        // 
        // If user want to use its Own Color Map
        //
        if (mGenColorMapSplit || 
            mGenLitColorMapSplit)
        {
            Image ExistingColorMap;

            String MapName = mColorMapName;
            if (MapName == mFileName)
                 OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, 
                        "HeightMap File and ColorMap file cannot be the same file", 
                        "MapUtil::ProcessOneFile");
       
            ExistingColorMap.load (MapName, mGroupName);
            // Get codec according to filename extension
            size_t colorpos = MapName.find_last_of(".");
            String colormPureFilename = MapName.substr(0, colorpos + 1);

            const uint oldheight = mHeight;
            const uint oldwidth = mWidth;

            ExistingColorMap.resize(static_cast <ushort> (ExistingColorMap.getWidth ()+1), 
                                    static_cast <ushort> (ExistingColorMap.getHeight ()+1));

            mHeight = static_cast <uint> (ExistingColorMap.getHeight ());
            mWidth = static_cast <uint> (ExistingColorMap.getWidth ());

            Splitter.init ();
            Splitter.setRawSave (StringUtil::match(mTextureExt, "raw", false));
            // 
            // Split User Color Map in 2^n  part 
            // 
            if (mGenColorMapSplit)
            {
              Splitter.saveAndSplitMap (colormPureFilename + "." + mTextureExt,
                                        &ExistingColorMap);
            }
            // 
            // Lit User Color Map  in 2^n  part 
            // 
            if (mGenLitColorMapSplit)
            { 
                // does modify colormap.
                MergeModulater.ModulateGrayAndRgbInRgb (LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur),
                                                        &ExistingColorMap,
                                                        2);
                Splitter.saveAndSplitMap (colormPureFilename + String(".Lit.") + mTextureExt,
                                        &ExistingColorMap);
            }   

            mHeight = oldheight;
            mWidth = oldwidth;
            Splitter.init ();
            Splitter.setRawSave (StringUtil::match(mTextureExt, "raw", false));
        }

       
        // 
        // Split Base Map in 2^n  part 
        // 
        if (mGenBaseMap)
            Splitter.saveAndSplitMap (mPureFilename + String(".Base.") + mTextureExt,
                                    SplatMapper.getBaseMap ());
        // 
        // Split Coverage Map in 2^n  part 
        // 
        if (mGenCoverageMap)
        {
            //MapBlurrer Blurrer;

            // blur.
            //Blurrer.gaussianBlur (SplatMapper.getCoverageMap (), 2);

            Splitter.saveAndSplitMap (mPureFilename + String(".Coverage.") + mTextureExt,
                                    SplatMapper.getCoverageMap ());
        }
        // 
        // Split Lit Base Map in 2^n  part 
        // 
        if (mGenLitBaseMap)
        { 
                // does modify Base Map.
                MergeModulater.ModulateGrayAndRgbaInRgba (LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur),
                                                    SplatMapper.getBaseMap (),
                                                    2);

                Splitter.saveAndSplitMap (mPureFilename + String(".LitBase.") + mTextureExt,
                                            SplatMapper.getBaseMap ());
        }

       

        // 
        // Split Alpha Map in 2^n  part 
        // (each alpha is a color channel of coverage Map)
        //
        if (mGenAlphaMaps)
            for (uint i = 0; i < 4; i++)
        {
                String alphaname =  mPureFilename + String(".Alpha.") + 
                                            StringConverter::toString(i) + 
                                            String(".") + mTextureExt;
                Splitter.saveAndSplitMap (alphaname, 
                                        SplatMapper.getAlphaMap (i));
        }

        // 
        // Merge Alpha Map and an empty RGBA map
        // Split it in 2^n  part 
        //
        if (mGenAlphaSplatRGBAMaps)
        {            
            const uint W = MapUtil::getSingleton().getMapWidth ();
            const uint H  = MapUtil::getSingleton().getMapHeight ();
            const uint size = W*H * 3;
            uchar *data = new uchar[size];  
            memset (data, 0, size);

            Image RgbImage;
            RgbImage.loadDynamicImage  (data, static_cast <size_t>(W), 
                static_cast <size_t>(H), 1, PF_BYTE_RGB, true); 
            
            for (uint i = 0; i < 4; i++)
            {
                String alphaname =  mPureFilename + String(".AlphaSplatRGBAMaps.") + StringConverter::toString(i) + 
                    String(".") + mTextureExt;
                // does not modify AlphaMap, allocate a new image
                mAlphaMap[i] = MergeModulater.MergeGrayAndRgbInRgba (
                                                SplatMapper.getAlphaMap (i),
                                                &RgbImage);
                Splitter.saveAndSplitMap (alphaname, 
                                            mAlphaMap[i]);
                if (!mGenAlphaSplatLightMaps)
                    delete mAlphaMap[i];                
            }
        }

        // 
        // Merge Alpha Map and Light map
        // Split it in 2^n  part 
        //
        if (mGenAlphaSplatLightMaps)
            {
                for (uint i = 0; i < 4; i++)
                {
                    String alphaname =  mPureFilename + String(".AlphaSplatLightMaps.") + StringConverter::toString(i) + 
                        String(".") + mTextureExt;
                    // does not modify AlphaMap, allocate a new image
                    // does prepare a new AlphaMap for merging.
                    if (!mGenAlphaSplatRGBAMaps)
                        mAlphaMap[i] = MergeModulater.MergeAlphaAndRgbInRgba (LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur),
                                                SplatMapper.getAlphaMap (i));

                    // does modify mAlphaMap[i]
                    MergeModulater.MergeGrayAndRgbaInRgba (LightMapper.getLightMap (mSun, mAmb, mDiff, mBlur),
                                                            mAlphaMap[i]);

                    Splitter.saveAndSplitMap (alphaname, 
                                                mAlphaMap[i]); 
                    delete mAlphaMap[i];   
                }
            }

        // 
        // Split RGB Map in 2^n  part 
        //       
        if (mGenRGBMaps)
            for (uint i = 0; i < 4; i++)
            {
                String RGBname =  mPureFilename + String(".RGB.") + StringConverter::toString(i) + 
                    String(".") + mTextureExt;
                Splitter.saveAndSplitMap (RGBname, 
                    SplatMapper.getRGBMap (i));
            }


        // 
        // create a Potential Visibility Set map 
        //    
        if (mGenPVSMap)
        {
            MapVis PVSMapper;

            PVSMapper.calc (32, 20);
            PVSMapper.save (const_cast< char * > ((mPureFilename + String(".vis")).c_str()));
        }

       
        // 
        // create a Horizon map 
        // That let us calculate mountains shadows
        //    
        MapHorizon HorizonMapper;
        //MapHorizon2 HorizonMapper;// maybe prettier

        if (mGenHorizonMap)
        {

            uint horizon_samples = 2;
            uint vscale = 7;
            uint steps = 8;
            //vscale = 20; step = 16; horizon_samples = 16;
            //HorizonMapper.calcHorizon3DMap (vscale, horizon_samples, steps);

            //vscale = 7; step = 16; horizon_samples = 128;
            HorizonMapper.calcHorizon3DMap (vscale, horizon_samples, steps);//2
            for (uint k = 0; k < horizon_samples; k++) 
            {  
                String HCMname = mPureFilename + String(".HCM_") + StringConverter::toString(k) + String(".")  + mTextureExt;

                MapBlurrer Blurrer;

                // blur.
                //Blurrer.gaussianBlur (HorizonMapper.getHorizon3DMap (k), 2);

                Splitter.saveAndSplitMap (HCMname, 
                                            HorizonMapper.getHorizon3DMap (k));
            }
        }

        // 
        // create an Elevation Map
        // Used as lookup table to get shadows position 
        //    
        if (mGenElevationMap)
        { 
            HorizonMapper.calcElevationCubeMap (256);

            const String cubename[6] = 
            {
                "rt", "lf", 
                "up", "dn", 
                "fr", "bk"
            };


            for (uint k = 0; k < 6; k++) 
            {
                String Elevname = mPureFilename + String(".Elev_") + cubename[k] + String(".png");
                Splitter.saveAndSplitMap (Elevname, 
                                            HorizonMapper.getElevationCubeMap (k));

            }  
        }

    //
    ////  let us calculate mountains shadows
    ////    
        if (mGenZHorizon)
        {  
            MapHorizon3 HorizonMapper3;

            HorizonMapper3.calcHorizonMap ();
            String hname = mPureFilename + String(".HS.") + mTextureExt;
            Splitter.saveAndSplitMap (hname, HorizonMapper3.getHorizonMap ());

            HorizonMapper3.calcLightMap ();
            String lname = mPureFilename + String(".L.") + mTextureExt;
            Splitter.saveAndSplitMap (lname, HorizonMapper3.getLightMap ());
        }       

        NormalMapper.reset();

#ifndef _MAPEDITOR
        mHeightdata->unload();
        delete mHeightdata;
#endif // _MAPEDITOR
    }