Пример #1
0
/**  The constructor sets the view to the size of the window
*  and centers the view on the center of the window.
*/
GameStateMapEditor::GameStateMapEditor(Game* game) {
  this->game = game;

  	trackMapEvents = new TrackMapInput_c(Game::map);

	sf::Vector2f position = sf::Vector2f(this->game->game_window.getSize());
	this->_gameView.setSize(position);
	this->_guiView.setSize(position);

	sf::Vector2f center_position = 0.5f * position;
	this->_gameView.setCenter(center_position);
	this->_guiView.setCenter(center_position);
	
	initializeButtonMap();
	tileSelector = Tile::EMPTY;
	returnToMenu = false;
	pauseSave = false;
	pauseLoad = false;
	font.loadFromFile("resources/helveticaneue-webfont.ttf");

	mapBackdrop.load("resources/images/MapBackdrop.png");
	mapBackdrop.setPosition(0*32,0*32);
	mapX = Map::MAX_MAP_WIDTH;
	mapY = Map::MAX_MAP_HEIGHT;
	displayXsize.setString(std::to_string(mapX));
	displayYsize.setString(std::to_string(mapY));
	mapFiles = getFilesInDir("resources/maps/");
}
Пример #2
0
u64 GameInfo::GetInstallDataSizeInBytes() {
	if (fileType == FILETYPE_PSP_SAVEDATA_DIRECTORY || fileType == FILETYPE_PPSSPP_SAVESTATE) {
		return 0;
	}
	std::vector<std::string> saveDataDir = GetSaveDataDirectories();

	u64 totalSize = 0;
	u64 filesSizeInDir = 0;
	for (size_t j = 0; j < saveDataDir.size(); j++) {
		std::vector<FileInfo> fileInfo;
		getFilesInDir(saveDataDir[j].c_str(), &fileInfo);
		// Note: getFileInDir does not fill in fileSize properly.
		for (size_t i = 0; i < fileInfo.size(); i++) {
			FileInfo finfo;
			getFileInfo(fileInfo[i].fullName.c_str(), &finfo);
			if (!finfo.isDirectory)
				filesSizeInDir += finfo.size;
		}
		if (filesSizeInDir >= 0xA00000) { 
			// HACK: Generally the savedata size in a dir shouldn't be more than 10MB.
			// This is probably GameInstall data.
			totalSize += filesSizeInDir;
		}
		filesSizeInDir = 0;
	}
	return totalSize;
}
Пример #3
0
void ProfileLoader::loadProfiles( const std::string& avProfilesPath )
{
	std::string realAvProfilesPath = avProfilesPath;
	if( realAvProfilesPath.empty() )
	{
		// get custom profiles location from AVPROFILES environment variable
		if( std::getenv( "AVPROFILES" ) )
			realAvProfilesPath = std::getenv( "AVPROFILES" );
		// else get default profiles location
		else
			realAvProfilesPath = AVTRANSCODER_DEFAULT_AVPROFILES;
	}

	std::vector< std::string > paths;
	split( paths, realAvProfilesPath, ":" );
	for( std::vector< std::string >::iterator dirIt = paths.begin(); dirIt != paths.end(); ++dirIt )
	{
		std::vector< std::string > files;
		if( getFilesInDir( *dirIt, files ) != 0 )
			continue;

		for( std::vector< std::string >::iterator fileIt = files.begin(); fileIt != files.end(); ++fileIt )
		{
			const std::string absPath = ( *dirIt ) + "/" + ( *fileIt );
			try
			{
				loadProfile( absPath );
			}
			catch( const std::exception& e )
			{
				LOG_WARN( e.what() )
			}
		}
	}
}
Пример #4
0
u32 DiskCachingFileLoaderCache::CountCachedFiles() {
	std::string dir = cacheDir_;
	if (dir.empty()) {
		dir = GetSysDirectory(DIRECTORY_CACHE);
	}

	std::vector<FileInfo> files;
	return (u32)getFilesInDir(dir.c_str(), &files, "ppdc:");
}
Пример #5
0
bool DirectoryAssetReader::GetFileListing(const char *path, std::vector<FileInfo> *listing, const char *filter = 0)
{
	char new_path[256] = {0};
	// Check if it already contains the path
	if (strlen(path) > strlen(path_) && 0 == memcmp(path, path_, strlen(path_))) {
	}
	else {
		strcpy(new_path, path_);
	}
	strcat(new_path, path);
	getFilesInDir(new_path, listing, filter);
	return true;
}
Пример #6
0
  // Returns true if successful, false otherwise
  bool FeatureMatcher::loadRecognitionSet(string country)
  {
    std::ostringstream out;
    out << config->getKeypointsRuntimeDir() << "/" << country << "/";
    string country_dir = out.str();

    if (DirectoryExists(country_dir.c_str()))
    {
      vector<Mat> trainImages;
      vector<string> plateFiles = getFilesInDir(country_dir.c_str());

      for (unsigned int i = 0; i < plateFiles.size(); i++)
      {
        if (hasEnding(plateFiles[i], ".jpg") == false)
          continue;

        string fullpath = country_dir + plateFiles[i];
        Mat img = imread( fullpath );

        // convert to gray and resize to the size of the templates
        cvtColor(img, img, CV_BGR2GRAY);
        resize(img, img, getSizeMaintainingAspect(img, config->stateIdImageWidthPx, config->stateIdimageHeightPx));

        if( img.empty() )
        {
          cout << "Can not read images" << endl;
          return -1;
        }

        Mat descriptors;

        vector<KeyPoint> keypoints;
        detector->detect( img, keypoints );
        extractor->compute(img, keypoints, descriptors);

        if (descriptors.cols > 0)
        {
          billMapping.push_back(plateFiles[i].substr(0, 2));
          trainImages.push_back(descriptors);
          trainingImgKeypoints.push_back(keypoints);
        }
      }

      this->descriptorMatcher->add(trainImages);
      this->descriptorMatcher->train();

      return true;
    }

    return false;
  }
Пример #7
0
std::vector<std::string> GameInfo::GetSaveDataDirectories() {
	std::string memc = GetSysDirectory(DIRECTORY_SAVEDATA);

	std::vector<FileInfo> dirs;
	getFilesInDir(memc.c_str(), &dirs);

	std::vector<std::string> directories;
	for (size_t i = 0; i < dirs.size(); i++) {
		if (startsWith(dirs[i].name, id)) {
			directories.push_back(dirs[i].fullName);
		}
	}

	return directories;
}
Пример #8
0
bool GameInfo::DeleteAllSaveData() {
	std::vector<std::string> saveDataDir = GetSaveDataDirectories();
	for (size_t j = 0; j < saveDataDir.size(); j++) {
		std::vector<FileInfo> fileInfo;
		getFilesInDir(saveDataDir[j].c_str(), &fileInfo);

		u64 totalSize = 0;
		for (size_t i = 0; i < fileInfo.size(); i++) {
			deleteFile(fileInfo[i].fullName.c_str());
		}

		deleteDir(saveDataDir[j].c_str());
	}
	return true;
}
Пример #9
0
static int64_t GetDirectoryRecursiveSize(std::string path) {
	std::vector<FileInfo> fileInfo;
	getFilesInDir(path.c_str(), &fileInfo);
	int64_t sizeSum = 0;
	// Note: getFileInDir does not fill in fileSize properly.
	for (size_t i = 0; i < fileInfo.size(); i++) {
		FileInfo finfo;
		getFileInfo(fileInfo[i].fullName.c_str(), &finfo);
		if (!finfo.isDirectory)
			sizeSum += finfo.size;
		else
			sizeSum += GetDirectoryRecursiveSize(finfo.fullName);
	}
	return sizeSum;
}
Пример #10
0
void DiskCachingFileLoaderCache::GarbageCollectCacheFiles(u64 goalBytes) {
	// We attempt to free up at least enough files from the cache to get goalBytes more space.
	const std::vector<std::string> usedPaths = DiskCachingFileLoader::GetCachedPathsInUse();
	std::set<std::string> used;
	for (std::string path : usedPaths) {
		used.insert(MakeCacheFilename(path));
	}

	std::string dir = cacheDir_;
	if (dir.empty()) {
		dir = GetSysDirectory(DIRECTORY_CACHE);
	}

	std::vector<FileInfo> files;
	getFilesInDir(dir.c_str(), &files, "ppdc:");

	u64 remaining = goalBytes;
	// TODO: Could order by LRU or etc.
	for (FileInfo file : files) {
		if (file.isDirectory) {
			continue;
		}
		if (used.find(file.name) != used.end()) {
			// In use, must leave alone.
			continue;
		}

#ifdef _WIN32
		const std::wstring w32path = ConvertUTF8ToWString(file.fullName);
		bool success = DeleteFileW(w32path.c_str()) != 0;
#else
		bool success = unlink(file.fullName.c_str()) == 0;
#endif

		if (success) {
			if (file.size > remaining) {
				// We're done, huzzah.
				break;
			}

			// A little bit more.
			remaining -= file.size;
		}
	}

	// At this point, we've done all we can.
}
Пример #11
0
u64 GameInfo::GetSaveDataSizeInBytes() {
	std::vector<std::string> saveDataDir = GetSaveDataDirectories();

	u64 totalSize = 0;
	for (size_t j = 0; j < saveDataDir.size(); j++) {
		std::vector<FileInfo> fileInfo;
		getFilesInDir(saveDataDir[j].c_str(), &fileInfo);
		// Note: getFileInDir does not fill in fileSize properly.
		for (size_t i = 0; i < fileInfo.size(); i++) {
			FileInfo finfo;
			getFileInfo(fileInfo[i].fullName.c_str(), &finfo);
			if (!finfo.isDirectory)
				totalSize += finfo.size;
		}
	}
	return totalSize;
}
Пример #12
0
u32 SimpleXP3::addFileFromDisk(const s8* diskFilePath, const s8* archiveFileName, bool compress)
{
    if (!diskFilePath)
    {
        return XP3_NOSUCHFILE;
    }

    //check if this is a directory
    if (isDir(diskFilePath))
    {
        std::list<std::string> files = getFilesInDir(diskFilePath);
        for (std::list<std::string>::iterator it = files.begin();
                it != files.end();
                it++)
        {
            addFileFromDisk((*it).c_str());
        }
        return XP3_OK;
    }


    //get file size
    unique_file f = unique_file(fopen(diskFilePath,"rb"));
    fseek(f.get(), 0, SEEK_END);
    u64 fileSize = ftell(f.get());
    fseek(f.get(), 0, SEEK_SET);

    u32 ret = XP3_OK;
    if (fileSize > 0)
    {
        unique_buffer<u8> buffer = unique_buffer<u8>(fileSize);
        READ_ARRAY_DYN(f.get(),buffer.get(),fileSize);

        ret = addFileFromMemory(archiveFileName ? archiveFileName : diskFilePath,
                          buffer.get(),
                          fileSize,
                          compress); //TODO: check file extension to selectively enable
    }
    else
    {
        ret = addEmptyFile(diskFilePath);
    }

    return ret;
}
Пример #13
0
void PathBrowser::GetListing(std::vector<FileInfo> &fileInfo, const char *filter) {
#ifdef _WIN32
    if (path_ == "/") {
        // Special path that means root of file system.
        std::vector<std::string> drives = getWindowsDrives();
        for (auto drive = drives.begin(); drive != drives.end(); ++drive) {
            FileInfo fake;
            fake.fullName = *drive;
            fake.name = *drive;
            fake.isDirectory = true;
            fake.exists = true;
            fake.size = 0;
            fake.isWritable = false;
            fileInfo.push_back(fake);
        }
    }
#endif

    getFilesInDir(path_.c_str(), &fileInfo, filter);
}
Пример #14
0
void
FsWatcher::ScanDirectory_NotifyRemovals_Execute(QString dirPath)
{
  _LOG_DEBUG("Triggered DirPath: " << dirPath.toStdString());

  fs::path absPathTriggeredDir(dirPath.toStdString());
  dirPath.remove(0, m_dirPath.size());

  fs::path triggeredDir(dirPath.toStdString());

  /*
  FileItemsPtr files = m_fileState->LookupFilesInFolderRecursively(triggeredDir.relative_path().generic_string());
  for (std::list<FileItem>::iterator file = files->begin(); file != files->end(); file ++)
    {
      fs::path testFile = fs::path(m_dirPath.toStdString()) / file->filename();
      _LOG_DEBUG("Check file for deletion [" << testFile.generic_string() << "]");

      if (!fs::exists(testFile))
        {
          if (removeIncomplete || file->is_complete())
            {
              _LOG_DEBUG("Notifying about removed file [" << file->filename() << "]");
              m_onDelete(file->filename());
            }
        }
    }
    */

  std::vector<std::string> files;
  getFilesInDir(triggeredDir.relative_path(), files);
  for (std::vector<std::string>::iterator file = files.begin(); file != files.end(); file++) {
    fs::path targetFile = fs::path(m_dirPath.toStdString()) / *file;
    if (!fs::exists(targetFile)) {
      deleteFile(*file);
      m_onDelete(*file);
    }
  }
}
Пример #15
0
u64 GameInfo::GetSaveDataSizeInBytes() {
	std::vector<std::string> saveDataDir = GetSaveDataDirectories();

	u64 totalSize = 0;
	u64 filesSizeInDir = 0;
	for (size_t j = 0; j < saveDataDir.size(); j++) {
		std::vector<FileInfo> fileInfo;
		getFilesInDir(saveDataDir[j].c_str(), &fileInfo);
		// Note: getFileInDir does not fill in fileSize properly.
		for (size_t i = 0; i < fileInfo.size(); i++) {
			FileInfo finfo;
			getFileInfo(fileInfo[i].fullName.c_str(), &finfo);
			if (!finfo.isDirectory)
				filesSizeInDir += finfo.size;
		}
		if (filesSizeInDir < 0xA00000) {
			//Generally the savedata size in a dir shouldn't be more than 10MB.
			totalSize += filesSizeInDir;
		}
		filesSizeInDir = 0;
	}
	return totalSize;
}
Пример #16
0
bool DirectoryAssetReader::GetFileListing(const char *path, std::vector<FileInfo> *listing, const char *filter = 0)
{
	char new_path[1024] = {0};
	// Check if it already contains the path
	if (strlen(path) > strlen(path_) && 0 == memcmp(path, path_, strlen(path_))) {
	}
	else {
		strcpy(new_path, path_);
	}
	strcat(new_path, path);
	FileInfo info;
	if (!getFileInfo(new_path, &info))
		return false;

	if (info.isDirectory)
	{
		getFilesInDir(new_path, listing, filter);
		return true;
	}
	else
	{
		return false;
	}
}
Пример #17
0
//============================================================================
// MAIN PROGRAM
//============================================================================
int main( int argc, char** argv )
{
    if ( parseArgs(argc,argv) != 0 ) return 1;

    // Initialize the Python environment. Will clean it up when destroyed.
    UsingPython usingPython;

    // Load the readline module if available
    if (isatty(fileno(stdin)))
    {
        PyObject *v;
        v = PyImport_ImportModule("readline");
        if (v==NULL)
        {
            PyErr_Clear();
        }
        else
        {
            Py_DECREF(v);
        }
    }

    SPELLlog::instance().setLogFile("SHELL","SHELL");
    SPELLlog::instance().enableLog(true);
    SPELLlog::instance().enableTraces(true);

    // Install log support
    Log_Install();

    try
    {
        // Setup the execution environment
    	std::cerr << "Loading SPELL framework" << std::endl;
        SPELLpythonHelper::instance().loadFramework();
        // Load the SPELL configuration (will fail with exception if there is an error)
    	std::cerr << "Loading configuration" << std::endl;
        SPELLconfiguration::instance().loadConfig(configFile);
        // Load the configuration on python side for the language and drivers
        SPELLconfiguration::instance().loadPythonConfig(configFile);
        // Load user libraries
    	std::cerr << "Loading user libraries" << std::endl;
    	SPELLprocedureManager::instance().setup(contextName);
    	std::string libPath = SPELLprocedureManager::instance().getLibPath();
        if (isDirectory(libPath))
        {
            SPELLpythonHelper::instance().addToPath(libPath);
            std::list<std::string> files = getFilesInDir(libPath);
            std::list<std::string>::iterator it;
            std::list<std::string>::iterator end = files.end();
            for( it = files.begin(); it != end; it++)
            {
                std::string filename = (*it);
                if (filename == "__init__.py" ) continue;
                std::size_t idx = filename.find(".py");
                if ((idx != std::string::npos) && (idx>0))
                {
                	std::cerr << "    - library " << filename << std::endl;
                    std::string module = filename.substr(0,idx);
                    SPELLpythonHelper::instance().importAllFrom(module);
                }
            }
        }

    }
    catch(SPELLcoreException& ex)
    {
        std::cerr << "FATAL ERROR: cannot initialize: " << ex.what() << std::endl;
        return 1;
    }

    // Will cleanup the driver manager when destroyed
    UsingDriver usingDriver;

    try
    {
        // Load the driver
        SPELLdriverManager::instance().setup(contextName);
    }
    catch(SPELLcoreException& ex)
    {
        std::cerr << "FATAL ERROR: cannot setup driver: " << ex.what() << std::endl;
        return 1;
    }

    // Load predefined databases and interfaces
    PyObject* dbMgr = SPELLregistry::instance().get("DBMGR");
    if (dbMgr == NULL)
    {
        std::cerr << "WARNING: cannot install DB manager" << std::endl;
    }
    else
    {
        // Install the runtime databases
    	SPELLdatabaseManager::instance().loadBuiltinDatabases();
    }


    signal(SIGABRT, signalHandler);
    signal(SIGTERM, signalHandler);

    SPELLexecutorIF* executor = new SPELLshellExecutor();
    SPELLcif* cif = new SPELLshellCif();
    SPELLschedulerIF* scheduler = new SPELLscheduler(true);
    SPELLcontrollerIF* controller = new SPELLshellController();
    SPELLcallstackIF* callstack = new SPELLshellCallstack();
    executor->initialize( cif, controller, scheduler, callstack, NULL );
    SPELLexecutor::setInstance(executor);

    ShellExecutor_Install();
    ShellClientIF_Install( cif );

    // Launch the interactive loop
    int status = 0;
    try
    {
        status = PyRun_AnyFileExFlags( stdin, "<stdin>", 0, NULL );
    }
    catch(SPELLcoreException& ex)
    {
        std::cerr << "FATAL ERROR: " << ex.what() << std::endl;
        status = ex.getCode();
    }

    return status;
}
Пример #18
0
void GameStateMapEditor::buttonCommandLibrary(){
	if(sf::Mouse::isButtonPressed(sf::Mouse::Left)){
		if(buttonMap["startTileBtn"].spriteContains(localPosition))
			tileSelector = Tile::START;
		else if(buttonMap["endTileBtn"].spriteContains(localPosition))
			tileSelector = Tile::END;
		else if(buttonMap["pathTileBtn"].spriteContains(localPosition))
			tileSelector = Tile::PATH;
		else if(buttonMap["sceneryTileBtn"].spriteContains(localPosition))
			tileSelector = Tile::SCENERY;
		else if(buttonMap["deadTileBtn"].spriteContains(localPosition))
			tileSelector = Tile::DEAD;
		else if(buttonMap["fillMapBtn"].spriteContains(localPosition))
		{
			this->game->map.fillMap();
			trackMapEvents->recordFillMap( );
		}
		else if(buttonMap["resetMapBtn"].spriteContains(localPosition))
		{
			this->game->map.blankMap();
			trackMapEvents->recordResetMap();
		}
		else if(buttonMap["UndoBtn"].spriteContains(localPosition))
		{
			trackMapEvents->undo();
		}
		else if(buttonMap["RedoBtn"].spriteContains(localPosition))
		{
			trackMapEvents->redo();
		}

		else if(buttonMap["saveBtn"].spriteContains(localPosition)){
			if(!pauseSave){
				pauseSave = true;
				pauseLoad = false;
				systemOutput.setString("Please type in a name for the map (without the .xml extension) and then click save again:\n");
			}
			else if(pauseSave){
				pauseSave = false;
				this->game->map.save(userInput);
				systemOutput.setString("");
				mapFiles = getFilesInDir("resources/maps/");
			}
		}
		else if(buttonMap["loadBtn"].spriteContains(localPosition)){
			if(!pauseLoad){
				pauseLoad = true;
				pauseSave = false;
				string tempString = "Here are the available map files, please type in the full extension of the map and click load again:\n";
				for(int i = 0 ; i < int(mapFiles.size()) ; ++i){
					tempString.append(mapFiles[i] + "\n");
				}
				systemOutput.setString(tempString);
			}
			else if (pauseLoad){
				pauseLoad = false;
				this->game->map.load(userInput);
				systemOutput.setString("");
			}
		}
		else if(buttonMap["playBtn"].spriteContains(localPosition)){
			if(game->map.isMapValid())
				this->game->pushState(new GameStatePlay(this->game));
			else
				cout << "map is not valid, cannot play" << endl;
		}
		else if(buttonMap["menuBtn"].spriteContains(localPosition)){
			returnToMenu = true;
			this->game->popState();
		}
		else if(buttonMap["validateMapBtn"].spriteContains(localPosition)){
			if(this->game->map.isMapValid())
				cout << "map is valid" << endl;
			else
				cout << "map not valid" << endl;
		}
		else if(buttonMap["setMapSizeBtn"].spriteContains(localPosition)){
			this->game->map.resetMap();
			this->game->map.setMapSize(mapX, mapY);
			this->game->map.blankMap();
		}
		else if(buttonMap["plusSizeBtnX"].spriteContains(localPosition)){
			if(mapX < Map::MAX_MAP_WIDTH){
				++mapX;
				displayXsize.setString(std::to_string(mapX));
			}
		}
		else if(buttonMap["minusSizeBtnX"].spriteContains(localPosition)){
			if(mapX > 0){
				--mapX;
				displayXsize.setString(std::to_string(mapX));
			}
		}
		else if(buttonMap["plusSizeBtnY"].spriteContains(localPosition)){
			if(mapY < Map::MAX_MAP_HEIGHT){
				++mapY;
				displayYsize.setString(std::to_string(mapY));
			}
		}
		else if(buttonMap["minusSizeBtnY"].spriteContains(localPosition)){
			if(mapY > 0){
				--mapY;
				displayYsize.setString(std::to_string(mapY));
			}
		}
	}
}
Пример #19
0
void FileSelectScreen::updateListing() {
    listing_.clear();
    getFilesInDir(currentDirectory_.c_str(), &listing_, options_.filter);
    g_Config.currentDirectory = currentDirectory_;
    list_.contentChanged();
}
Пример #20
0
//============================================================================
// FUNCTION:    SPELLutils::dumpInterpreterInfo()
//============================================================================
void SPELLutils::dumpInterpreterInfo( const std::string& id )
{
	LOG_INFO("Begin dump");
	// Cleanup previous files
	std::string dataDir = getSPELL_DATA() + PATH_SEPARATOR + "Runtime" + PATH_SEPARATOR;
	std::list<std::string> files = getFilesInDir(dataDir);
	std::list<std::string>::iterator it;
	for( it = files.begin(); it != files.end(); it++)
	{
		std::string fileName = (*it);
		if (fileName.find( id + "_interpreter_state") != std::string::npos )
		{
			deleteFile( dataDir + fileName );
		}
		if (fileName.find( id + "_thread_state") != std::string::npos )
		{
			deleteFile( dataDir + fileName );
		}
		if (fileName.find( id + "_frame_state") != std::string::npos )
		{
			deleteFile( dataDir + fileName );
		}
	}

	LOG_INFO("Get interpreter head");
	PyInterpreterState* currIS = PyInterpreterState_Head();

	// Count the interpreter state
	int numIS = 0;
	// For each interpreter state
	while(currIS != NULL)
	{
		LOG_INFO("Dump information for interpreter state " + ISTR(numIS));
		std::string filename = dataDir + id + "_interpreter_state_" + ISTR(numIS) + ".dump";
		std::ofstream dumpFile;
		dumpFile.open( filename.c_str() , std::ios::out );

		// Main data
		dumpFile << "INTERPRETER STATE " << numIS << " DATA" << std::endl;
		dumpFile << "--------------------------------------" << std::endl;
		dumpFile << "Address     : " << PSTR(currIS) << std::endl;
		dumpFile << "Next address: " << PSTR(currIS->next) << std::endl;
		dumpFile << "Modules     : " << PYSIZE(currIS->modules)  << " items." << std::endl;
		dumpFile << "Sysdict     : " << PYSIZE(currIS->sysdict)  << " items." << std::endl;
		dumpFile << "Builtins    : " << PYSIZE(currIS->builtins) << " items." << std::endl;
		dumpFile << "Reloading   : " << PYSIZE(currIS->modules_reloading)  << " items." << std::endl;
		dumpFile << "Search path : " << PYSIZE(currIS->codec_search_path)  << " items." << std::endl;
		dumpFile << "Search cache: " << PYSIZE(currIS->codec_search_cache) << " items." << std::endl;
		dumpFile << "Error regst.: " << PYSIZE(currIS->codec_error_registry) << " items." << std::endl;
		dumpFile << "DL flags    : " << currIS->dlopenflags << std::endl;

		// Count thread states
		int numTS = 0;
		PyThreadState* currTS = currIS->tstate_head;
		while( currTS != NULL )
		{
			dumpThreadStateInfo( id, currTS, numIS, numTS );
			numTS++;
			currTS = currTS->next;
		}
		dumpFile << "Thr. states : " << numTS << std::endl;

		// Close the interpreter state dump, no more to add
		dumpFile.flush();
		dumpFile.close();

		// Next interpreter state
		currIS = currIS->next;
		numIS++;
	}
	LOG_INFO("Finish dump");
}
Пример #21
0
int main( int argc, const char** argv )
{
    std::string filename;
    std::string configFile = "";
    bool outputJson = false;
    int seektoms = 0;
    bool detectRegion = false;
    std::string templateRegion;
    std::string country;
    int topn;

    TCLAP::CmdLine cmd("OpenAlpr Command Line Utility", ' ', Alpr::getVersion());

    TCLAP::UnlabeledValueArg<std::string>  fileArg( "image_file", "Image containing license plates", false, "", "image_file_path"  );


    TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe).  Default=us",false, "us" ,"country_code");
    TCLAP::ValueArg<int> seekToMsArg("","seek","Seek to the specied millisecond in a video file. Default=0",false, 0 ,"integer_ms");
    TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file",false, "" ,"config_file");
    TCLAP::ValueArg<std::string> templateRegionArg("t","template_region","Attempt to match the plate number against a region template (e.g., md for Maryland, ca for California)",false, "" ,"region code");
    TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return.  Default=10",false, 10 ,"topN");

    TCLAP::SwitchArg jsonSwitch("j","json","Output recognition results in JSON format.  Default=off", cmd, false);
    TCLAP::SwitchArg detectRegionSwitch("d","detect_region","Attempt to detect the region of the plate image.  Default=off", cmd, false);
    TCLAP::SwitchArg clockSwitch("","clock","Measure/print the total time to process image and all plates.  Default=off", cmd, false);

    try
    {
        cmd.add( templateRegionArg );
        cmd.add( seekToMsArg );
        cmd.add( topNArg );
        cmd.add( configFileArg );
        cmd.add( fileArg );
        cmd.add( countryCodeArg );


        if (cmd.parse( argc, argv ) == false)
        {
            // Error occured while parsing.  Exit now.
            return 1;
        }

        filename = fileArg.getValue();

        country = countryCodeArg.getValue();
        seektoms = seekToMsArg.getValue();
        outputJson = jsonSwitch.getValue();
        configFile = configFileArg.getValue();
        detectRegion = detectRegionSwitch.getValue();
        templateRegion = templateRegionArg.getValue();
        topn = topNArg.getValue();
        measureProcessingTime = clockSwitch.getValue();
    }
    catch (TCLAP::ArgException &e)    // catch any exceptions
    {
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
        return 1;
    }


    cv::Mat frame;

    Alpr alpr(country, configFile);
    alpr.setTopN(topn);

    if (detectRegion)
        alpr.setDetectRegion(detectRegion);

    if (templateRegion.empty() == false)
        alpr.setDefaultRegion(templateRegion);

    if (alpr.isLoaded() == false)
    {
        std::cerr << "Error loading OpenALPR" << std::endl;
        return 1;
    }

    if (filename.empty())
    {
        std::string filename;
        while (std::getline(std::cin, filename))
        {
            if (fileExists(filename.c_str()))
            {
                frame = cv::imread( filename );
                detectandshow( &alpr, frame, "", outputJson);
            }
            else
            {
                std::cerr << "Image file not found: " << filename << std::endl;
            }

        }
    }
    else if (filename == "webcam")
    {
        int framenum = 0;
        cv::VideoCapture cap(0);
        if (!cap.isOpened())
        {
            std::cout << "Error opening webcam" << std::endl;
            return 1;
        }

        while (cap.read(frame))
        {
            detectandshow(&alpr, frame, "", outputJson);
            usleep(1000);
            framenum++;
        }
    }
    else if (startsWith(filename, "http://") || startsWith(filename, "https://"))
    {
        int framenum = 0;

        VideoBuffer videoBuffer;

        videoBuffer.connect(filename, 5);

        cv::Mat latestFrame;

        while (program_active)
        {
            int response = videoBuffer.getLatestFrame(&latestFrame);

            if (response != -1)
            {
                detectandshow( &alpr, latestFrame, "", outputJson);
            }

            // Sleep 10ms
            usleep(10000);
        }

        videoBuffer.disconnect();

        std::cout << "Video processing ended" << std::endl;
    }
    else if (hasEndingInsensitive(filename, ".avi") || hasEndingInsensitive(filename, ".mp4") || hasEndingInsensitive(filename, ".webm") ||
             hasEndingInsensitive(filename, ".flv") || hasEndingInsensitive(filename, ".mjpg") || hasEndingInsensitive(filename, ".mjpeg"))
    {
        if (fileExists(filename.c_str()))
        {
            int framenum = 0;

            cv::VideoCapture cap=cv::VideoCapture();
            cap.open(filename);
            cap.set(CV_CAP_PROP_POS_MSEC, seektoms);

            while (cap.read(frame))
            {
                if (SAVE_LAST_VIDEO_STILL)
                {
                    cv::imwrite(LAST_VIDEO_STILL_LOCATION, frame);
                }
                std::cout << "Frame: " << framenum << std::endl;

                detectandshow( &alpr, frame, "", outputJson);
                //create a 1ms delay
                usleep(1000);
                framenum++;
            }
        }
        else
        {
            std::cerr << "Video file not found: " << filename << std::endl;
        }
    }
    else if (hasEndingInsensitive(filename, ".png") || hasEndingInsensitive(filename, ".jpg") ||
             hasEndingInsensitive(filename, ".jpeg") || hasEndingInsensitive(filename, ".gif"))
    {
        if (fileExists(filename.c_str()))
        {
            frame = cv::imread( filename );

            detectandshow( &alpr, frame, "", outputJson);
        }
        else
        {
            std::cerr << "Image file not found: " << filename << std::endl;
        }
    }
    else if (DirectoryExists(filename.c_str()))
    {
        std::vector<std::string> files = getFilesInDir(filename.c_str());

        std::sort( files.begin(), files.end(), stringCompare );

        for (int i = 0; i< files.size(); i++)
        {
            if (hasEndingInsensitive(files[i], ".jpg") || hasEndingInsensitive(files[i], ".png"))
            {
                std::string fullpath = filename + "/" + files[i];
                std::cout << fullpath << std::endl;
                frame = cv::imread( fullpath.c_str() );
                if (detectandshow( &alpr, frame, "", outputJson))
                {
                    //while ((char) cv::waitKey(50) != 'c') { }
                }
                else
                {
                    //cv::waitKey(50);
                }
            }
        }
    }
    else
    {
        std::cerr << "Unknown file type" << std::endl;
        return 1;
    }

    return 0;
}
Пример #22
0
void LoadPostShaderInfo(std::vector<std::string> directories) {
	shaderInfo.clear();
	ShaderInfo off;
	off.name = "Off";
	off.section = "Off";
	off.outputResolution = false;
	off.isUpscalingFilter = false;
	shaderInfo.push_back(off);

	for (size_t d = 0; d < directories.size(); d++) {
		std::vector<FileInfo> fileInfo;
		getFilesInDir(directories[d].c_str(), &fileInfo, "ini:");

		if (fileInfo.size() == 0) {
			// TODO: Really gotta fix the filter, now it's gonna open shaders as ini files..
			VFSGetFileListing(directories[d].c_str(), &fileInfo, "ini:");
		}

		for (size_t f = 0; f < fileInfo.size(); f++) {
			IniFile ini;
			bool success = false;
			std::string name = fileInfo[f].fullName;
			std::string path = directories[d];
			// Hack around Android VFS path bug. really need to redesign this.
			if (name.substr(0, 7) == "assets/")
				name = name.substr(7);
			if (path.substr(0, 7) == "assets/")
				path = path.substr(7);

			if (ini.LoadFromVFS(name) || ini.Load(fileInfo[f].fullName)) {
				success = true;
				// vsh load. meh.
			}
			if (!success)
				continue;

			// Alright, let's loop through the sections and see if any is a shader.
			for (size_t i = 0; i < ini.Sections().size(); i++) {
				IniFile::Section &section = ini.Sections()[i];
				if (section.Exists("Fragment") && section.Exists("Vertex")) {
					// Valid shader!
					ShaderInfo info;
					std::string temp;
					info.section = section.name();
					section.Get("Name", &info.name, section.name().c_str());
					section.Get("Fragment", &temp, "");
					info.fragmentShaderFile = path + "/" + temp;
					section.Get("Vertex", &temp, "");
					info.vertexShaderFile = path + "/" + temp;
					section.Get("OutputResolution", &info.outputResolution, false);
					section.Get("Upscaling", &info.isUpscalingFilter, false);

					// Let's ignore shaders we can't support. TODO: Not a very good check
					if (gl_extensions.IsGLES && !gl_extensions.GLES3) {
						bool requiresIntegerSupport;
						section.Get("RequiresIntSupport", &requiresIntegerSupport, false);
						if (requiresIntegerSupport)
							continue;
					}

					auto beginErase = std::find(shaderInfo.begin(), shaderInfo.end(), info.name);
					if (beginErase != shaderInfo.end()) {
						shaderInfo.erase(beginErase, shaderInfo.end());
					}
					shaderInfo.push_back(info);
				}
			}
		}
	}
}