Example #1
0
// Add a new zip file or folder
bool j1FileSystem::AddPath(const char* path_or_zip, const char* mount_point)
{
	bool ret = false;

	if(PHYSFS_mount(path_or_zip, mount_point, 1) == 0)
		LOG("File System error while adding a path or zip(%s): %s\n", path_or_zip, PHYSFS_getLastError());
	else
		ret = true;

	return ret;
}
Example #2
0
void Filesystem::addPath(const char *s)
{
    if (!PHYSFS_isInit()) {
        throw_error;
    }

    int success = PHYSFS_mount(s, NULL, 0);

    if (!success) {
        throw_error;
    }
}
Example #3
0
 bool Mount(std::string path, std::string fsPath) {
     if (!IsLoaded()) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "FS not loaded" << Logger::end();
         assert(false);
         return false;
     }
     int result = PHYSFS_mount(path.c_str(), fsPath.c_str(), 1);
     if (result == 0) {
         Logger::begin("Filesystem", Logger::LogLevel_Error) << "Error Mounting " << PHYSFS_getLastError() << Logger::end();
     }
     return result > 0;
 }
Example #4
0
bool buildMapList()
{
	if (!loadLevFile("gamedesc.lev", mod_campaign, false, nullptr))
	{
		return false;
	}
	loadLevFile("addon.lev", mod_multiplay, false, nullptr);
	WZ_Maps.clear();
	MapFileList realFileNames = listMapFiles();
	for (auto &realFileName : realFileNames)
	{
		bool mapmod = false;
		struct WZmaps CurrentMap;
		std::string realFilePathAndName = PHYSFS_getRealDir(realFileName.c_str()) + realFileName;

		PHYSFS_mount(realFilePathAndName.c_str(), NULL, PHYSFS_APPEND);

		char **filelist = PHYSFS_enumerateFiles("");
		for (char **file = filelist; *file != nullptr; ++file)
		{
			std::string checkfile = *file;
			size_t len = strlen(*file);
			if (len > 10 && !strcasecmp(*file + (len - 10), ".addon.lev"))  // Do not add addon.lev again
			{
				loadLevFile(*file, mod_multiplay, true, realFileName.c_str());
			}
			// add support for X player maps using a new name to prevent conflicts.
			if (len > 13 && !strcasecmp(*file + (len - 13), ".xplayers.lev"))
			{
				loadLevFile(*file, mod_multiplay, true, realFileName.c_str());
			}
		}
		PHYSFS_freeList(filelist);

		if (WZ_PHYSFS_unmount(realFilePathAndName.c_str()) == 0)
		{
			debug(LOG_ERROR, "Could not unmount %s, %s", realFilePathAndName.c_str(), WZ_PHYSFS_getLastError());
		}

		mapmod = CheckInMap(realFilePathAndName.c_str(), "WZMap", "WZMap");
		if (!mapmod)
		{
			mapmod = CheckInMap(realFilePathAndName.c_str(), "WZMap", "WZMap/multiplay");
		}

		CurrentMap.MapName = realFileName;
		CurrentMap.isMapMod = mapmod;
		WZ_Maps.push_back(CurrentMap);
	}

	return true;
}
Example #5
0
FileSystem::FileSystem(const char * argv)
{
	std::string path = argv;

	path = WorkaroundVisualStudio(path);

	PHYSFS_init(path.c_str());
	m_workingDirectory = GetPhysFSWorkingDirectory();
	auto test = m_workingDirectory.generic_string();
	auto cstr = test.c_str();
	PHYSFS_mount(cstr, NULL, 0);
	PHYSFS_permitSymbolicLinks(1);
}
bool FileSystem::addSearchPath(const char *path_or_zip, const char *mount_point)
{
	bool ret = true;

	if (PHYSFS_mount(path_or_zip, mount_point, 1) == 0)
	{
		LOG("%s %s", "Failure on mounting or adding path", path_or_zip);
		LOG("%s", "Error:", PHYSFS_getLastError());
		ret = false;
	}

	return ret;
}
Example #7
0
static int l_filesystem_set_requireDir(lua_State* state)
{
  if(!lua_isstring(state, 1))
    return luaL_error(state, "The argument must be a string.");

  const char* dir = lua_tostring(state, 1);

  int m = PHYSFS_mount(dir, "/", 1);
  if(!m)
    printf("%s %s \n", "No folder/.zip named ", dir);

  return 1;
}
Example #8
0
void FileSystem::addPath(const char *path)
{
	/* Try the normal mount first */
	if (!PHYSFS_mount(path, 0, 1))
	{
		/* If it didn't work, try mounting via a wrapped
		 * SDL_RWops */
		PHYSFS_Io *io = createSDLRWIo(path);

		if (io)
			PHYSFS_mountIo(io, path, 0, 1);
	}
}
Example #9
0
	bool mount(const std::string_view file, const std::string_view mountPoint,
		bool appendToSearchPath)
	{
		int append = appendToSearchPath == true ? 1 : 0;
		try
		{
			std::filesystem::path path(file);

			if (PHYSFS_mount(path.u8string().c_str(), mountPoint.data(), append) != 0)
			{
				return true;
			}
			if (path.has_extension() == true)
			{
				path = path.replace_extension();
				if (PHYSFS_mount(path.u8string().c_str(), mountPoint.data(), append) != 0)
				{
					return true;
				}
			}
			path = path.replace_extension(".mpq");
			if (PHYSFS_mount(path.u8string().c_str(), mountPoint.data(), append) != 0)
			{
				return true;
			}
			path = path.replace_extension(".zip");
			if (PHYSFS_mount(path.u8string().c_str(), mountPoint.data(), append) != 0)
			{
				return true;
			}
			path = path.replace_extension(".7z");
			if (PHYSFS_mount(path.u8string().c_str(), mountPoint.data(), append) != 0)
			{
				return true;
			}
		}
		catch (std::exception&) {}
		return false;
	}
Example #10
0
static int cmd_mount(char *args)
{
    char *ptr;
    char *mntpoint = NULL;
    int appending = 0;

    if (*args == '\"')
    {
        args++;
        ptr = strchr(args, '\"');
        if (ptr == NULL)
        {
            printf("missing string terminator in argument.\n");
            return(1);
        } /* if */
        *(ptr) = '\0';
    } /* if */
    else
    {
        ptr = strchr(args, ' ');
        *ptr = '\0';
    } /* else */

    mntpoint = ptr + 1;
    if (*mntpoint == '\"')
    {
        mntpoint++;
        ptr = strchr(mntpoint, '\"');
        if (ptr == NULL)
        {
            printf("missing string terminator in argument.\n");
            return(1);
        } /* if */
        *(ptr) = '\0';
    } /* if */
    else
    {
        ptr = strchr(mntpoint, ' ');
        *(ptr) = '\0';
    } /* else */
    appending = atoi(ptr + 1);

    /*printf("[%s], [%s], [%d]\n", args, mntpoint, appending);*/

    if (PHYSFS_mount(args, mntpoint, appending))
        printf("Successful.\n");
    else
        printf("Failure. reason: %s.\n", PHYSFS_getLastError());

    return(1);
} /* cmd_mount */
Example #11
0
  void find_datadir() const
  {
    std::string datadir;
    if (m_forced_datadir)
    {
      datadir = *m_forced_datadir;
    }
    else if (const char* env_datadir = getenv("SUPERTUX2_DATA_DIR"))
    {
      datadir = env_datadir;
    }
    else
    {
      // check if we run from source dir
      char* basepath_c = SDL_GetBasePath();
      std::string basepath = basepath_c ? basepath_c : "./";
      SDL_free(basepath_c);

      if (FileSystem::exists(FileSystem::join(BUILD_DATA_DIR, "credits.stxt")))
      {
        datadir = BUILD_DATA_DIR;
        // Add config dir for supplemental files
        PHYSFS_mount(boost::filesystem::canonical(BUILD_CONFIG_DATA_DIR).string().c_str(), NULL, 1);
      }
      else
      {
        // if the game is not run from the source directory, try to find
        // the global install location
        datadir = basepath.substr(0, basepath.rfind(INSTALL_SUBDIR_BIN));
        datadir = FileSystem::join(datadir, INSTALL_SUBDIR_SHARE);
      }
    }

    if (!PHYSFS_mount(boost::filesystem::canonical(datadir).string().c_str(), NULL, 1))
    {
      log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastErrorCode() << std::endl;
    }
  }
Example #12
0
bool FileSystem::AddSearchDirectory(const Path & path)
{
	auto posixPath = MakePosix(path);
	auto genericString = posixPath.generic_string();
	int32_t status = PHYSFS_mount(genericString.c_str(), NULL, 0);

	if (status == 0)
	{
		return false;
	}

	m_searchDirectories.push_back(path);
	return true;
}
Example #13
0
FileSystem::FileSystem(std::vector<UString> paths)
{
	// FIXME: Is this the right thing to do that?
	LogInfo("Registering external archivers...");
	PHYSFS_registerArchiver(getCueArchiver());
	// Paths are supplied in inverse-search order (IE the last in 'paths' should be the first
	// searched)
	for (auto &p : paths)
	{
		if (!PHYSFS_mount(p.cStr(), "/", 0))
		{
			LogInfo("Failed to add resource dir \"%s\", error: %s", p,
			        PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
			continue;
		}
		else
			LogInfo("Resource dir \"%s\" mounted to \"%s\"", p, PHYSFS_getMountPoint(p.cStr()));
	}
	this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME);
	LogInfo("Setting write directory to \"%s\"", this->writeDir);
	PHYSFS_setWriteDir(this->writeDir.cStr());
	// Finally, the write directory trumps all
	PHYSFS_mount(this->writeDir.cStr(), "/", 0);
}
Example #14
0
  void find_datadir()
  {
    std::string datadir;
    if (m_forced_datadir)
    {
      datadir = *m_forced_datadir;
    }
    else if (const char* env_datadir = getenv("SUPERTUX2_DATA_DIR"))
    {
      datadir = env_datadir;
    }
    else
    {
      // check if we run from source dir
      char* basepath_c = SDL_GetBasePath();
      std::string basepath = basepath_c ? basepath_c : "./";
      SDL_free(basepath_c);

      // If we are on windows, the data directory is one directory above the binary
#ifdef WIN32
      const std::array<std::string, 2> subdirs = { { "data", "../data" } };
#else
      const std::array<std::string, 1> subdirs = { { "data" } };
#endif
      bool found = false;
      for (const std::string &subdir : subdirs)
      {
        datadir = FileSystem::join(basepath, subdir);
        if (FileSystem::exists(FileSystem::join(datadir, "credits.txt")))
        {
          found = true;
          break;
        }
      }
      if (!found)
      {
        // if the game is not run from the source directory, try to find
        // the global install location
        datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
        datadir = FileSystem::join(datadir, INSTALL_SUBDIR_SHARE);
      }
    }

    if (!PHYSFS_mount(datadir.c_str(), NULL, 1))
    {
      log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
    }
  }
Example #15
0
static void PostProcessGameArg()
{
	if (CGameArg.SysMaxFPS < MINIMUM_FPS)
		CGameArg.SysMaxFPS = MINIMUM_FPS;
	else if (CGameArg.SysMaxFPS > MAXIMUM_FPS)
		CGameArg.SysMaxFPS = MAXIMUM_FPS;
#if PHYSFS_VER_MAJOR >= 2
	if (!CGameArg.SysMissionDir.empty())
		PHYSFS_mount(CGameArg.SysMissionDir.c_str(), MISSION_DIR, 1);
#endif

	static char sdl_disable_lock_keys[] = "SDL_DISABLE_LOCK_KEYS=0";
	if (CGameArg.CtlNoStickyKeys) // Must happen before SDL_Init!
		sdl_disable_lock_keys[sizeof(sdl_disable_lock_keys) - 2] = '1';
	SDL_putenv(sdl_disable_lock_keys);
}
Example #16
0
void
AddonManager::mount_old_addons()
{
  std::string mountpoint;
  for (auto& addon : m_installed_addons) {
    if (addon->get_format() == Addon::ORIGINAL &&
        addon->get_type() != Addon::LANGUAGEPACK &&
        addon->is_enabled()) {
      if (PHYSFS_mount(addon->get_install_filename().c_str(), mountpoint.c_str(), 0) == 0)
      {
        log_warning << "Could not add " << addon->get_install_filename() << " to search path: "
                    << PHYSFS_getLastError() << std::endl;
      }
    }
  }
}
Example #17
0
void FS_AddPaksFromList(char **list, const char *basePath, const char *gamePath) {
	static const char *archiveExt = "pk3";
	size_t extlen = strlen(archiveExt);

	char **i;
	char *ext;

	for (i = list; *i != NULL; i++) {
		size_t l = strlen(*i);
		if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
			ext = (*i) + (l - extlen);
			if (strcasecmp(ext, archiveExt) == 0) {
				PHYSFS_mount(tempstr("%s/%s/%s", basePath, gamePath, *i), "/", 1);
			}
		}
	}
}
Example #18
0
void kp::file::init(const char* argv0)
{
    if(PHYSFS_init(argv0) == 0)
    {
        //kp::debug::fatal("PHYSFS_init: %s", PHYSFS_getLastError());
    }

#ifdef __APPLE__
    std::string formatted = boost::str(boost::format("%s/%s") % PHYSFS_getBaseDir() % "Contents/Resources");
    const char* directory = formatted.c_str();
#else
    const char* directory = PHYSFS_getBaseDir();
#endif
    
    //printf("%c", kp::string::format("%s/%s", PHYSFS_getBaseDir(), "Contents/Resources"));

    if(PHYSFS_mount(directory, NULL, 1) == 0)
    {
        //kp::debug::fatal("PHYSFS_mount(%c): %s", directory, PHYSFS_getLastError());
    }
};
Example #19
0
// Mount the archive under the mountpoint, and enumerate the archive according to lookin
static bool CheckInMap(const char *archive, const char *mountpoint,const char *lookin)
{
	bool mapmod = false;

	if (!PHYSFS_mount(archive, mountpoint, PHYSFS_APPEND))
	{
		// We already checked to see if this was valid before, and now, something went seriously wrong.
		debug(LOG_FATAL, "Could not mount %s, because: %s. Please delete the file, and run the game again. Game will now exit.", archive, PHYSFS_getLastError());
		exit(-1);
	}

	std::string checkpath = lookin;
	checkpath.append("/");
	char **filelist = PHYSFS_enumerateFiles(lookin);
	for (char **file = filelist; *file != NULL; ++file)
	{
		std::string checkfile = *file;
		if (PHYSFS_isDirectory((checkpath+checkfile).c_str()))
		{
			if (checkfile.compare("wrf")==0 || checkfile.compare("stats")==0 ||checkfile.compare("components")==0
				|| checkfile.compare("anims")==0 || checkfile.compare("effects")==0 ||checkfile.compare("messages")==0
				|| checkfile.compare("audio")==0 || checkfile.compare("sequenceaudio")==0 ||checkfile.compare("misc")==0
				|| checkfile.compare("features")==0 || checkfile.compare("script")==0 ||checkfile.compare("structs")==0
				|| checkfile.compare("tileset")==0 || checkfile.compare("images")==0 || checkfile.compare("texpages")==0
				|| checkfile.compare("skirmish")==0 )
			{
				debug(LOG_WZ, "Detected: %s %s" , archive, checkfile.c_str());
				mapmod = true;
				break;
			}
		}
	}
	PHYSFS_freeList(filelist);

	if (!PHYSFS_removeFromSearchPath(archive))
	{
		debug(LOG_ERROR, "Could not unmount %s, %s", archive, PHYSFS_getLastError());
	}
	return mapmod;
}
Example #20
0
void
AddonManager::enable_addon(const AddonId& addon_id)
{
  log_debug << "enabling addon " << addon_id << std::endl;
  auto& addon = get_installed_addon(addon_id);
  if (addon.is_enabled())
  {
    log_warning << "Tried enabling already enabled Add-on" << std::endl;
  }
  else
  {
    log_debug << "Adding archive \"" << addon.get_install_filename() << "\" to search path" << std::endl;
    //int PHYSFS_mount(addon.installed_install_filename.c_str(), "addons/", 0)

    std::string mountpoint;
    switch (addon.get_format()) {
      case Addon::ORIGINAL:
        mountpoint = "";
        break;
      default:
        mountpoint = "custom/" + addon_id;
        break;
    }

    if (PHYSFS_mount(addon.get_install_filename().c_str(), mountpoint.c_str(), 0) == 0)
    {
      log_warning << "Could not add " << addon.get_install_filename() << " to search path: "
                  << PHYSFS_getLastError() << std::endl;
    }
    else
    {
      if(addon.get_type() == Addon::LANGUAGEPACK)
      {
        PHYSFS_enumerateFilesCallback(addon.get_id().c_str(), add_to_dictionary_path, NULL);
      }
      addon.set_enabled(true);
    }
  }
}
Example #21
0
void
AddonManager::add_installed_archive(const std::string& archive, const std::string& md5)
{
  const char* realdir = PHYSFS_getRealDir(archive.c_str());
  if (!realdir)
  {
    log_warning << "PHYSFS_getRealDir() failed for " << archive << ": "
                << PHYSFS_getLastError() << std::endl;
  }
  else
  {
    std::string os_path = FileSystem::join(realdir, archive);

    PHYSFS_mount(os_path.c_str(), NULL, 0);

    std::string nfo_filename = scan_for_info(os_path);

    if (nfo_filename.empty())
    {
      log_warning << "Couldn't find .nfo file for " << os_path << std::endl;
    }
    else
    {
      try
      {
        std::unique_ptr<Addon> addon = Addon::parse(nfo_filename);
        addon->set_install_filename(os_path, md5);
        m_installed_addons.push_back(std::move(addon));
      }
      catch (const std::runtime_error& e)
      {
        log_warning << "Could not load add-on info for " << archive << ": " << e.what() << std::endl;
      }
    }

    PHYSFS_unmount(os_path.c_str());
  }
}
Example #22
0
bool vfs::mount(
    std::string const& path,
    std::string const& mountPoint,
    int flags)
{
    if (flags & writeDirectory) {
        boost::filesystem::create_directories(path);
        CALL_PHYSFS(PHYSFS_setWriteDir, path.c_str());
    }

    if (!PHYSFS_mount(path.c_str(), mountPoint.c_str(), flags & appendPath)) {
        Error err("", false);
        if (flags & logWarnings || !(flags & mountOptional)) {
            err = Error("Mounting \"" + path + "\" failed");
            if (flags & logWarnings)
                LOG_W(err.what());
        }
        if (flags & mountOptional)
            return false;
        throw err;
    }
    return true;
}
Example #23
0
/**
**  The main program: initialise, parse options and arguments.
**
**  @param argc  Number of arguments.
**  @param argv  Vector of arguments.
*/
int stratagusMain(int argc, char **argv)
{
#ifdef USE_BEOS
	//  Parse arguments for BeOS
	beos_init(argc, argv);
#endif
#ifdef USE_WIN32
	SetUnhandledExceptionFilter(CreateDumpFile);
#endif
#if defined(USE_WIN32) && ! defined(REDIRECT_OUTPUT)
	SetupConsole();
#endif
	//  Setup some defaults.
#ifndef MAC_BUNDLE
	StratagusLibPath = ".";
#else
	freopen("/tmp/stdout.txt", "w", stdout);
	freopen("/tmp/stderr.txt", "w", stderr);
	// Look for the specified data set inside the application bundle
	// This should be a subdir of the Resources directory
	CFURLRef pluginRef = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
												 CFSTR(MAC_BUNDLE_DATADIR), NULL, NULL);
	CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef,  kCFURLPOSIXPathStyle);
	const char *pathPtr = CFStringGetCStringPtr(macPath, CFStringGetSystemEncoding());
	Assert(pathPtr);
	StratagusLibPath = pathPtr;
#endif

#ifdef USE_PHYSFS
	if (PHYSFS_init(argv[0])) {
		PHYSFS_mount(PHYSFS_DATAFILE, "/", 0);
	}
#endif

#ifdef USE_STACKTRACE
	try {
#endif
	Parameters &parameters = Parameters::Instance;
	parameters.SetDefaultValues();
	parameters.SetLocalPlayerNameFromEnv();

#ifdef REDIRECT_OUTPUT
	RedirectOutput();
#endif

	if (argc > 0) {
		parameters.applicationName = argv[0];
	}

	// FIXME: Parse options before or after scripts?
	ParseCommandLine(argc, argv, parameters);
	// Init the random number generator.
	InitSyncRand();

	makedir(parameters.GetUserDirectory().c_str(), 0777);

	// Init Lua and register lua functions!
	InitLua();
	LuaRegisterModules();

	// Initialise AI module
	InitAiModule();

	LoadCcl(parameters.luaStartFilename, parameters.luaScriptArguments);

	PrintHeader();
	PrintLicense();

	// Setup video display
	InitVideo();

	// Setup sound card
	if (!InitSound()) {
		InitMusic();
	}

#ifndef DEBUG			// For debug it's better not to have:
	srand(time(NULL));	// Random counter = random each start
#endif

	//  Show title screens.
	SetDefaultTextColors(FontYellow, FontWhite);
	LoadFonts();
	SetClipping(0, 0, Video.Width - 1, Video.Height - 1);
	Video.ClearScreen();
	ShowTitleScreens();

	// Init player data
	ThisPlayer = NULL;
	//Don't clear the Players structure as it would erase the allowed units.
	// memset(Players, 0, sizeof(Players));
	NumPlayers = 0;

	UnitManager.Init();	// Units memory management
	PreMenuSetup();		// Load everything needed for menus

	MenuLoop();

	Exit(0);
#ifdef USE_STACKTRACE
	} catch (const std::exception &e) {
		fprintf(stderr, "Stratagus crashed!\n");
		//Wyrmgus start
//		fprintf(stderr, "Please send this call stack to our bug tracker: https://github.com/Wargus/stratagus/issues\n");
		fprintf(stderr, "Please send this call stack to our bug tracker: https://github.com/Andrettin/Wyrmgus/issues\n");
		//Wyrmgus end
		fprintf(stderr, "and tell us what caused this bug to occur.\n");
		fprintf(stderr, " === exception state traceback === \n");
		fprintf(stderr, "%s", e.what());
		exit(1);
	}
#endif
	return 0;
}
Example #24
0
File: fsys.c Project: exdev/exsdk
int ex_fsys_mount ( const char *_dir, const char *_mount_point, bool _append ) {
    __PHYSFS_CHECK( PHYSFS_mount ( _dir, _mount_point, _append ) );
    return 0;
}
Example #25
0
		void Init(const char* argv0) {
			PHYSFS_init(argv0);
			Logger::begin("Filesystem", Logger::LogLevel_Log) << "Filesystem Loaded" << Logger::end();
			PHYSFS_mount("res", "/", 1);
		}
Example #26
0
int flubPhysfsInit(const char *appPath) {
    char working_dir[512];
    int k;

    if(_physfsCtx.init) {
        warning("Ignoring attempt to re-initialize physfs.");
        return 1;
    }

    if(!logValid()) {
        // The logger has not been initiated!
        return 0;
    }

    logDebugRegister("file", DBG_FILE, "general", DBG_FILE_DTL_GENERAL);

    debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "Initializing PHYSFS");

    if(!PHYSFS_init(appPath)) {
        fatal("Failed to initialize the virtual file system.");
        return 0;
    } else {
        if(!PHYSFS_mount(getcwd(working_dir, sizeof(working_dir)), NULL, 1)) {
            fatalf("Failed to mount the current working directory (%s).", working_dir);
            return 0;
        } else {
            infof("Mounted current working directory: %s", working_dir);
        }
        if(!PHYSFS_mount(PHYSFS_getBaseDir(), NULL, 1)) {
            fatalf("Failed to mount the application's base dir (%s).",
                   PHYSFS_getBaseDir());
            return 0;
        } else {
            infof("Mounted base directory: %s", PHYSFS_getBaseDir());
        }
        if(appDefaults.archiveFile != NULL) {
            infof("Mounting app archive file \"%s\".", appDefaults.archiveFile);
            if(!PHYSFS_mount(appDefaults.archiveFile, NULL, 1)) {
                fatalf("Failed to mount the application's archive file: %s", PHYSFS_getLastError());
                return 0;
            }
        } else {
            debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "No application archive file specified.");
        }
        for(k = 0; _flubMemfileResources[k].name != NULL; k++) {
            if(!PHYSFS_mount(PHYSFS_getMemfileName(_flubMemfileResources[k].memfile), NULL, 1)) {
                errorf("Failed to mount %s", _flubMemfileResources[k].name);
            } else {
                debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "Mounted flub resource file image [%s].", _flubMemfileResources[k].name);
            }
        }
        if(appDefaults.resources != NULL) {
            for(k = 0; appDefaults.resources[k].name != NULL; k++) {
                if(!PHYSFS_mount(PHYSFS_getMemfileName(appDefaults.resources[k].memfile), NULL, 1)) {
                    errorf("Failed to mount %s", appDefaults.resources[k].name);
                } else {
                    debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "Mounted application resource file image [%s].", appDefaults.resources[k].name);
                }
            }
        } else {
            debugf(DBG_FILE, DBG_FILE_DTL_GENERAL, "No application resource file images specified.");
        }
        debug(DBG_FILE, DBG_FILE_DTL_GENERAL, "Virtual file system started.");
    }

    _physfsCtx.init = 1;

    return 1;
}
Example #27
0
int Flamingo::_Init(int argc, char *argv[]) {

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        return -1;
    }

    // Initialize SDL_GL Attributes
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
     
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,32);
     
    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 8);
     
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
    

    // Create window
    _displaySize = (SDL_Rect){0, 0, 1024, 768};
    if ((_display = SDL_SetVideoMode(_displaySize.w, _displaySize.h, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_OPENGL)) == NULL) {
        return -1;
    }

    // OpenGL settings
    glClearColor(0, 0, 0, 0);
    glClearDepth(1.0f);
    glEnable(GL_TEXTURE_2D);

    // Flamingo
    PHYSFS_init(argv[0]);
    PHYSFS_mount(PHYSFS_getBaseDir(), "/", 0);
    ilInit();

    std::cout << "PHYSFS Base Dir: " << PHYSFS_getBaseDir() << "\n";
    
    //// Python
    Py_Initialize();
    pythonDir = "python/";
    PHYSFS_mount(pythonDir.c_str(), "python", 0);
    AddPythonPath(pythonDir);

    _eventManager = new EventManager();
    _entityManager = new EntityManager(_eventManager);
    inputSystem = new InputSystem(_eventManager, _entityManager);

    _masterClock = new Clock();

    // Register Components
    REGISTER_COMPONENT(PositionComp, FL_COMPTYPE_POSITION);
    REGISTER_COMPONENT(ScreenComp, FL_COMPTYPE_SCREEN);
    REGISTER_COMPONENT(SpriteComp, FL_COMPTYPE_SPRITE);

    ScreenComp *_s = (ScreenComp *)_entityManager->factory->CreateInstance(FL_COMPTYPE_SCREEN);
    std::cout << _s->local_rect.x << "\n";

    //// Screens
    screenSystem = new ScreenSystem(_eventManager, _entityManager);
	SDL_Rect r = {0, 100, 640, 240};
	SDL_Rect r2 = {100, 200, 800, 480};

	Entity *e = _entityManager->CreateEntity();
    _entityManager->AddComponent(e, new PositionComp());
    //ScreenComp *s = new ScreenComp(&_displaySize);
    ScreenComp *s = new ScreenComp(&r2);
    s->LoadScript("scripts/testscript.py", "testscript");
	_entityManager->AddComponent(e, s);

	e = _entityManager->CreateEntity();
    _entityManager->AddComponent(e, new PositionComp());
	_entityManager->AddComponent(e, new ScreenComp(&r));
    //_entityManager->DestroyEntity(e);

    int res = this->Init(argc, argv);
    
    // Test DB dump
    _entityManager->Dump("database.db");
    
    return res;
}
Example #28
0
void mount(const string& newDir, const string& mountPoint, bool appendToPath) {
	PHYSFS_mount(newDir.c_str(), mountPoint.c_str(), appendToPath);
}
Example #29
0
// Initializes the the GDATA struct
_Bool data_init(void)
{
    // Create a window to display things on: 800x600 pixels
    al_set_new_display_flags(ALLEGRO_RESIZABLE | ALLEGRO_OPENGL);
    al_set_new_display_refresh_rate(60);
    data->display = al_create_display(res_width, res_height);
    if(data->display == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Display Error:", "Failed to create window!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Sets the physfs file interface to be used for loading files
    al_set_physfs_file_interface();
    PHYSFS_mount("images", NULL, 1);
    PHYSFS_mount("fonts", NULL, 1);
    PHYSFS_mount("buttons", NULL, 1);

    // Well, looks like we're gonna have to draw our own mouse *SIGH*
    al_hide_mouse_cursor(data->display);
    data->cursor = al_load_bitmap("cursor_darkgrey.png");
    if(data->cursor == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Cursor Error:", "Failed to locate cursor!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Set the title of the window
    al_set_window_title(data->display, "SpeedRun!");

    // Sets the window's icon
    data->icon = al_load_bitmap("speedrundisplayicon.png");
    if(data->icon == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Icon Error:", "Failed to locate icon!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }
    al_set_display_icon(data->display, data->icon);

    // Load a font
    data->font = al_load_ttf_font("times.ttf", 25, 0);
    data->b_font = al_load_ttf_font("impact.ttf", 25, 0);
    if(data->font == NULL || data->b_font == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Font Error:", "Failed to load font!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Make and set a color to draw with
    data->text_color = al_map_rgba(80, 112, 255, 255);

    // Set background color
    data->background_color = al_map_rgba(0, 0, 0, 0);

    // Install the keyboard handler
    if(!al_install_keyboard())
    {
        al_show_native_message_box(data->display, "Error!", "Keyboard Error:", "Failed to install keyboard handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Install the mouse handler
    if(!al_install_mouse())
    {
        al_show_native_message_box(data->display, "Error!", "Mouse Error:", "Failed to install mouse handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Detect and set refresh rate
    int refresh_rate = al_get_display_refresh_rate(data->display);
    if(refresh_rate == 0)
    {
        refresh_rate = 60;
    }

    // Install timer with refresh rate
    data->timer = al_create_timer(1.0/refresh_rate);
    if(data->timer == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Timer Error:", "Failed to initialize timer!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return 1;
    }
    al_start_timer(data->timer);


    // Start the event queues to handle keyboard input, mouse input, display input and timer input
    data->queue = al_create_event_queue();
    al_register_event_source(data->queue, (ALLEGRO_EVENT_SOURCE*)data->timer);
    data->queue2 = al_create_event_queue();
    al_register_event_source(data->queue2, al_get_keyboard_event_source());
    al_register_event_source(data->queue2, (ALLEGRO_EVENT_SOURCE*)data->display);
    al_register_event_source(data->queue2, al_get_mouse_event_source());

    // Set the quit and gamestarted flags to false initially
    data->exit = false;
    data->gamestarted = false;
    data->options = false;
    data->highscores = false;
    data->howtoplay = false;

    al_start_timer(data->timer);

    return true;
}
Example #30
0
bool buildMapList()
{
	if (!loadLevFile("gamedesc.lev", mod_campaign, false, NULL))
	{
		return false;
	}
	loadLevFile("addon.lev", mod_multiplay, false, NULL);
	WZ_Maps.clear();
	MapFileList realFileNames = listMapFiles();
	for (MapFileList::iterator realFileName = realFileNames.begin(); realFileName != realFileNames.end(); ++realFileName)
	{
		bool mapmod = false;
		struct WZmaps CurrentMap;
		std::string realFilePathAndName = PHYSFS_getRealDir(realFileName->c_str()) + *realFileName;

		PHYSFS_addToSearchPath(realFilePathAndName.c_str(), PHYSFS_APPEND);

		char **filelist = PHYSFS_enumerateFiles("");
		for (char **file = filelist; *file != NULL; ++file)
		{
			std::string checkfile = *file;
			size_t len = strlen(*file);
			if (len > 10 && !strcasecmp(*file + (len - 10), ".addon.lev"))  // Do not add addon.lev again
			{
				loadLevFile(*file, mod_multiplay, true, realFileName->c_str());
			}
			// add support for X player maps using a new name to prevent conflicts.
			if (len > 13 && !strcasecmp(*file + (len - 13), ".xplayers.lev"))
			{
				loadLevFile(*file, mod_multiplay, true, realFileName->c_str());
			}
		}
		PHYSFS_freeList(filelist);

		if (PHYSFS_removeFromSearchPath(realFilePathAndName.c_str()) == 0)
		{
			debug(LOG_ERROR, "Could not unmount %s", PHYSFS_getLastError());
		}
		// check what kind of map it is
		if (!PHYSFS_mount(realFilePathAndName.c_str(), "WZMap", PHYSFS_APPEND))
		{
			debug(LOG_FATAL, "Could not mount %s, because: %s. Please delete the file, and run the game again. Game will now exit.", realFilePathAndName.c_str(), PHYSFS_getLastError());
			exit(-1);
		}

		filelist = PHYSFS_enumerateFiles("WZMap");
		for (char **file = filelist; *file != NULL; ++file)
		{
			if (PHYSFS_isDirectory(*file))
			{
				std::string checkfile = *file;
				if (checkfile.compare("wrf")==0 || checkfile.compare("stats")==0 ||checkfile.compare("components")==0
					|| checkfile.compare("anims")==0 || checkfile.compare("effects")==0 ||checkfile.compare("messages")==0
					|| checkfile.compare("audio")==0 || checkfile.compare("sequenceaudio")==0 ||checkfile.compare("misc")==0
					|| checkfile.compare("features")==0 || checkfile.compare("script")==0 ||checkfile.compare("structs")==0
					|| checkfile.compare("tileset")==0 || checkfile.compare("images")==0 || checkfile.compare("texpages")==0 )
				{
					mapmod = true;
					break;
				}
			}
		}
		PHYSFS_freeList(filelist);

		CurrentMap.MapName = realFileName->c_str();
		CurrentMap.isMapMod = mapmod;
		WZ_Maps.push_back(CurrentMap);

		if (PHYSFS_removeFromSearchPath(realFilePathAndName.c_str()) == 0)
		{
			debug(LOG_ERROR, "Could not unmount %s", PHYSFS_getLastError());
		}
	}

	return true;
}