Example #1
0
const rho::String& CRhodesModule::getAppName()
{
    if ( m_strAppName.length() == 0 )
    {
#if defined(APP_BUILD_CAPABILITY_SHARED_RUNTIME)
        bool bRE1App = false;
        if (!rho_wmimpl_get_is_version2())
            bRE1App = true;
        if ( bRE1App )
            m_strAppName = convertToStringA( rho_wmimpl_sharedconfig_getvalue( L"General\\Name" ) );
        else
        {
            String path = getRhoRootPath();
            String_replace(path, '/', '\\');

            int nEnd = path.find_last_of('\\');
            nEnd = path.find_last_of('\\', nEnd-1)-1;

            int nStart = path.find_last_of('\\', nEnd) +1;
            m_strAppName = path.substr( nStart, nEnd-nStart+1);
        }
#else
        m_strAppName = get_app_build_config_item("name");
#endif
    }

    return m_strAppName;
}
 void Cocos2dxFactory::loadTextureAtlasFile(const String &textureAtlasFile , const String &name)
 {
     dragonBones::XMLDataParser parser;
     unsigned long dummySize;
     
     dragonBones::XMLDocument doc;
     unsigned char* texture_data = CCFileUtils::sharedFileUtils()->
     getFileData(textureAtlasFile.c_str(), "rb", &dummySize);
     doc.Parse(reinterpret_cast<char*>(texture_data), dummySize);
     delete[] texture_data;
     
     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));
     
 }
Example #3
0
    //-----------------------------------------------------------------------
    void DynLib::load()
    {
        // Log library load
        LogManager::getSingleton().logMessage("Loading library " + mName);

        String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN
        if (name.find(".js") == String::npos)
            name += ".js";
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
        // dlopen() does not add .so to the filename, like windows does for .dll
        if (name.find(".so") == String::npos)
        {
            name += ".so.";
            name += StringConverter::toString(OGRE_VERSION_MAJOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_MINOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_PATCH);
        }
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        // dlopen() does not add .dylib to the filename, like windows does for .dll
        if(name.substr(name.find_last_of(".") + 1) != "dylib")
            name += ".dylib";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
        // Although LoadLibraryEx will add .dll itself when you only specify the library name,
        // if you include a relative path then it does not. So, add it to be sure.
        if(name.substr(name.find_last_of(".") + 1) != "dll")
            name += ".dll";
#endif
        mInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        if(!mInst)
        {
            name = mName;
            if(name.substr(name.find_last_of(".") + 1) != "framework")
                name += ".framework";
            // Try again as a framework
            mInst = (DYNLIB_HANDLE)FRAMEWORK_LOAD( name );
        }
#endif
        if( !mInst )
            OGRE_EXCEPT(
                Exception::ERR_INTERNAL_ERROR, 
                "Could not load dynamic library " + mName + 
                ".  System Error: " + dynlibError(),
                "DynLib::load" );
    }
Example #4
0
//-----------------------------------------------------------------------
void GLSLESProgram::checkAndFixInvalidDefaultPrecisionError( String &message )
{
    String precisionQualifierErrorString = ": 'Default Precision Qualifier' : invalid type Type for default precision qualifier can be only float or int";
    vector< String >::type linesOfSource = StringUtil::split(mSource, "\n");
    if( message.find(precisionQualifierErrorString) != String::npos )
    {
        LogManager::getSingleton().logMessage("Fixing invalid type Type for default precision qualifier by deleting bad lines the re-compiling");

        // remove relevant lines from source
        vector< String >::type errors = StringUtil::split(message, "\n");

        // going from the end so when we delete a line the numbers of the lines before will not change
        for(int i = static_cast<int>(errors.size()) - 1 ; i != -1 ; i--)
        {
            String & curError = errors[i];
            size_t foundPos = curError.find(precisionQualifierErrorString);
            if(foundPos != String::npos)
            {
                String lineNumber = curError.substr(0, foundPos);
                size_t posOfStartOfNumber = lineNumber.find_last_of(':');
                if (posOfStartOfNumber != String::npos)
                {
                    lineNumber = lineNumber.substr(posOfStartOfNumber + 1, lineNumber.size() - (posOfStartOfNumber + 1));
                    if (StringConverter::isNumber(lineNumber))
                    {
                        int iLineNumber = StringConverter::parseInt(lineNumber);
                        linesOfSource.erase(linesOfSource.begin() + iLineNumber - 1);
                    }
                }
            }
        }
        // rebuild source
        StringStream newSource;
        for(size_t i = 0; i < linesOfSource.size()  ; i++)
        {
            newSource << linesOfSource[i] << "\n";
        }
        mSource = newSource.str();

        const char *source = mSource.c_str();
        OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL));

        if (compile())
        {
            LogManager::getSingleton().logMessage("The removing of the lines fixed the invalid type Type for default precision qualifier error.");
        }
        else
        {
            LogManager::getSingleton().logMessage("The removing of the lines didn't help.");
        }
    }
}
URI::URI(const String& uriStr, bool nofrag) {
    initialize();

    if (nofrag) {
        size_t pos = uriStr.find_last_of('#');
        if (pos != String::npos) {
            set(uriStr.substr(0, pos));
            return;
        }
    }

    set(uriStr);
}
Example #6
0
String Path::ReplaceExtension(String path, String newExt)
{
	newExt.TrimFront('.');

	// Remove everything in the extension and the dot
	size_t dotPos = path.find_last_of(".");
	if(dotPos != -1)
	{
		path.erase(path.begin() + dotPos, path.end());
	}

	if(newExt.empty())
		return path;

	path.push_back('.');
	path += newExt;

	return path;
}
Example #7
0
    //-----------------------------------------------------------------------
    void StringUtil::splitFilename(const String& qualifiedName, 
        String& outBasename, String& outPath)
    {
        String path = qualifiedName;
        // Replace \ with / first
        std::replace( path.begin(), path.end(), '\\', '/' );
        // split based on final /
        size_t i = path.find_last_of('/');

        if (i == String::npos)
        {
            outPath.clear();
			outBasename = qualifiedName;
        }
        else
        {
            outBasename = path.substr(i+1, path.size() - i - 1);
            outPath = path.substr(0, i+1);
        }

    }
		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));

		}
Example #9
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;
}
Example #10
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;
}
Example #11
0
String Environment::getFilePart( const String& fileName ) {
    return fileName.substr( fileName.find_last_of( PATH_SEPARATOR ) + 1 );
}
Example #12
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);
	}
}
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;
}