Beispiel #1
0
int main(int argc, char **argv)
{
	int i, err;
	static char filename[4096];

	lua_State *L = luaL_newstate();
	luaL_openlibs(L);
	lua_newtable(L);
	for(i = 0; i < argc; i++)
	{
		lua_pushinteger(L, i + 1);
		lua_pushstring(L, argv[i]);
		lua_settable(L, -3);
	}
	lua_setglobal(L, "args");
	lua_settop(L, 0);

	/* Temporarily initialize PhysicsFS so that we can append the base directory to package.cpath */
	PHYSFS_init(argv[0]);
	lua_getglobal(L, "package");
	lua_pushstring(L, PHYSFS_getBaseDir());
	lua_pushstring(L, "?.so;");
	lua_pushstring(L, PHYSFS_getDirSeparator());
	lua_pushstring(L, "?.so;");
	lua_getfield(L, -5, "cpath");
	lua_concat(L, 5);
	lua_setfield(L, -2, "cpath");
	lua_pushstring(L, PHYSFS_getBaseDir());
	lua_pushstring(L, "?.dll;");
	lua_pushstring(L, PHYSFS_getDirSeparator());
	lua_pushstring(L, "?.dll;");
	lua_getfield(L, -5, "cpath");
	lua_concat(L, 5);
	lua_setfield(L, -2, "cpath");
	lua_pop(L, 1);
	sprintf(filename, "%s%s%s", PHYSFS_getBaseDir(), PHYSFS_getDirSeparator(), "server");
	PHYSFS_deinit();

	if((err = luaL_dofile(L, filename)))
	{
		const char *message = lua_tostring(L, -1);
		fprintf(stderr, "Error: %s\n", message);
		return err;
	}
	lua_getglobal(L, "init");
	if((err = lua_pcall(L, 0, 0, 0)))
	{
		const char *message = lua_tostring(L, -1);

		fprintf(stderr, "Error: %s\n", message);

		return err;
	}

	return 0;
}
Beispiel #2
0
std::string getWZInstallPrefix()
{
	const std::string dirSeparator(PHYSFS_getDirSeparator());
	ASSERT(dirSeparator.length() > 0, "PHYSFS_getDirSeparator returned an empty string");

	// Construct the install PREFIX path
	std::string prefixDir(PHYSFS_getBaseDir());
	while (!prefixDir.empty() && (prefixDir.rfind(dirSeparator, std::string::npos) == (prefixDir.length() - dirSeparator.length())))
	{
		prefixDir.resize(prefixDir.length() - dirSeparator.length()); // Remove trailing path separators
	}
	size_t binDirComponentsCount = 1;
#ifdef WZ_BINDIR
	// Trim off as many path components as are in WZ_BINDIR
	std::string binDir(WZ_BINDIR);
	std::vector<std::string> binDirComponents = splitAtAnyDelimiter(binDir, "/");
	binDirComponentsCount = std::count_if(binDirComponents.begin(), binDirComponents.end(), [](const std::string &s) { return !s.empty() && (s != "."); });
	ASSERT(binDirComponentsCount > 0, "WZ_BINDIR unexpectedly has zero components?: \"%s\"", WZ_BINDIR);
#endif
	for (size_t i = 0; i < binDirComponentsCount; ++i)
	{
		size_t lastSlash = prefixDir.rfind(dirSeparator, std::string::npos);
		if (lastSlash != std::string::npos)
		{
			prefixDir = prefixDir.substr(0, lastSlash); // Trim off the last path component
		}
	}

	return prefixDir;
}
Beispiel #3
0
util::VersionInfo Application::initPhysFS(const std::string& arg0)
{
    PHYSFS_Version ver;
    PHYSFS_init(arg0.c_str());
    PHYSFS_addToSearchPath(PHYSFS_getBaseDir(),0);
    PHYSFS_getLinkedVersion(&ver);
    return util::VersionInfo(ver.major, ver.minor, ver.patch);
}
Beispiel #4
0
// ----------------------------------------------------------------------------
void Editor::readConfigFile(IFileSystem* file_system)
{
    IXMLReader* xml_reader = file_system->createXMLReader(path(PHYSFS_getBaseDir())
                                                                    + "config.xml");

    if (!xml_reader)
    {
        path dir = PHYSFS_getUserDir();
        m_config_loc = dir + "/.stk-te";
        xml_reader = file_system->createXMLReader(m_config_loc + "/config.xml");
        if (!xml_reader)
        {
            PHYSFS_setWriteDir(dir.c_str());
            PHYSFS_mkdir(".stk-te");
            return;
        }
    }
    else m_config_loc = PHYSFS_getBaseDir();

    const stringw node_name(L"data_dir");
    const stringw res(L"res");
    const stringw exe(L"exe");
    while (xml_reader->read())
    {
        if (xml_reader->getNodeType() == EXN_ELEMENT)
        {
            if (res.equals_ignore_case(xml_reader->getNodeName()))
            {
                m_screen_size = dimension2du(
                    atol(((stringc)xml_reader->getAttributeValueSafe(L"x")).c_str()),
                    atol(((stringc)xml_reader->getAttributeValueSafe(L"y")).c_str()));
            }
            else  if (node_name.equals_ignore_case(xml_reader->getNodeName()))
            {
                m_data_loc = xml_reader->getAttributeValueSafe(L"path");
                m_icons_loc = m_data_loc + "editor/icons/";
            }
            else if (exe.equals_ignore_case(xml_reader->getNodeName()))
            {
                m_exe_loc = xml_reader->getAttributeValueSafe(L"path");
            }
        }
    }
    xml_reader->drop();
} // readConfigFile
Beispiel #5
0
Path GetPhysFSWorkingDirectory()
{
	std::string workingDirStr = PHYSFS_getBaseDir();
	Path workingDirectory(workingDirStr);

	if (workingDirectory.has_filename())
		workingDirectory = workingDirectory.parent_path();

	return workingDirectory;
}
Beispiel #6
0
void initI18n(void)
{
	const char *textdomainDirectory = NULL;

	if (!setLanguage("")) // set to system default
	{
		// no system default?
		debug(LOG_ERROR, "initI18n: No system language found");
	}
#if defined(WZ_OS_WIN)
	{
		// Retrieve an absolute path to the locale directory
		char localeDir[PATH_MAX];
		sstrcpy(localeDir, PHYSFS_getBaseDir());
		sstrcat(localeDir, "\\" LOCALEDIR);

		// Set locale directory and translation domain name
		textdomainDirectory = bindtextdomain(PACKAGE, localeDir);
	}
#else
	#ifdef WZ_OS_MAC
	{
		char resourcePath[PATH_MAX];
		CFURLRef resourceURL = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
		if( CFURLGetFileSystemRepresentation( resourceURL, true, (UInt8 *) resourcePath, PATH_MAX) )
		{
			sstrcat(resourcePath, "/locale");
			textdomainDirectory = bindtextdomain(PACKAGE, resourcePath);
		}
		else
		{
			debug( LOG_ERROR, "Could not change to resources directory." );
		}

		if (resourceURL != NULL)
		{
			CFRelease(resourceURL);
		}

		debug(LOG_INFO, "resourcePath is %s", resourcePath);
	}
	#else
	textdomainDirectory = bindtextdomain(PACKAGE, LOCALEDIR);
	#endif
#endif
	if (!textdomainDirectory)
	{
		debug(LOG_ERROR, "initI18n: bindtextdomain failed!");
	}

	(void)bind_textdomain_codeset(PACKAGE, "UTF-8");
	(void)textdomain(PACKAGE);
}
Beispiel #7
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());
    }
};
Beispiel #8
0
int main(int argc, char *argv[])
{

    printf("Init physfs\n");
    PHYSFS_init(argv[0]);
    PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 1);
    PHYSFS_addToSearchPath("data.7z", 1);
    printf("Init physfs end\n");

	Main main;
	main.Execute();
	return 0;
}
Beispiel #9
0
void Client::initRootDir()
{
    mRootDir = PHYSFS_getBaseDir();
#ifdef _WIN32
    std::string portableName = mRootDir + "portable.xml";
    struct stat statbuf;

    if (!stat(portableName.c_str(), &statbuf) && S_ISREG(statbuf.st_mode))
    {
        std::string dir;
        Configuration portable;
        portable.init(portableName);

        logger->log("Portable file: %s", portableName.c_str());

        if (mOptions.localDataDir.empty())
        {
            dir = portable.getValue("dataDir", "");
            if (!dir.empty())
            {
                mOptions.localDataDir = mRootDir + dir;
                logger->log("Portable data dir: %s",
                    mOptions.localDataDir.c_str());
            }
        }

        if (mOptions.configDir.empty())
        {
            dir = portable.getValue("configDir", "");
            if (!dir.empty())
            {
                mOptions.configDir = mRootDir + dir;
                logger->log("Portable config dir: %s",
                    mOptions.configDir.c_str());
            }
        }

        if (mOptions.screenshotDir.empty())
        {
            dir = portable.getValue("screenshotDir", "");
            if (!dir.empty())
            {
                mOptions.screenshotDir = mRootDir + dir;
                logger->log("Portable screenshot dir: %s",
                    mOptions.screenshotDir.c_str());
            }
        }
    }
#endif
}
Beispiel #10
0
void FS_Init(const char *argv0) {
	int err = PHYSFS_init(argv0);

	if (err == 0) {
		Con_Errorf(ERR_FATAL, "Error in PHYSFS_init: %s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
		return;
	}

	const char *baseDir = PHYSFS_getBaseDir();
	fs_basepath = Con_GetVarDefault("fs.basepath", baseDir, CONVAR_STARTUP);
	fs_basegame = Con_GetVarDefault("fs.basegame", "base", CONVAR_STARTUP);
	fs_game = Con_GetVarDefault("fs.game", DEFAULT_GAME, CONVAR_STARTUP);

	bool modLoaded = fs_game->string[0] != '\0';

	char **baseFiles, **gameFiles;

	// get the file listing for the basegame dir, then immediately unmount
	const char *fullBasePath = tempstr("%s/%s", fs_basepath->string, fs_basegame->string);
	PHYSFS_mount(fullBasePath, "/", 1);
	baseFiles = PHYSFS_enumerateFiles("/");
	PHYSFS_removeFromSearchPath(fullBasePath);

	// if fs_game is set, do the same thing for the fs_game dir
	if (modLoaded) {
		const char *fullGamePath = tempstr("%s/%s", fs_basepath->string, fs_game->string);
		PHYSFS_mount(fullGamePath, "/", 1);
		gameFiles = PHYSFS_enumerateFiles("/");
		PHYSFS_removeFromSearchPath(fullGamePath);

		// mount the mod dir first, then mount mod PK3s
		PHYSFS_mount(tempstr("%s/%s", fs_basepath->string, fs_game->string), "/", 1);
		FS_AddPaksFromList(gameFiles, fs_basepath->string, fs_game->string);
		PHYSFS_freeList(gameFiles);
	}

	// then mount the base game dir, then the mount base game PK3s
	PHYSFS_mount(tempstr("%s/%s", fs_basepath->string, fs_basegame->string), "/", 1);
	FS_AddPaksFromList(baseFiles, fs_basepath->string, fs_basegame->string);
	PHYSFS_freeList(baseFiles);

	// print all the files we've found in order of priority
	Con_Printf("Current filesystem search path:\n");
	PHYSFS_getSearchPathCallback(printSearchPath, NULL);
	Con_Printf("\n");

	// add command handler for dir to view virtual filesystem
	Con_AddCommand("dir", Cmd_Dir_f);
}
Beispiel #11
0
int main(int argc,char * argv[])
{
	#ifndef EE_NOPHYS_IN_LOADER
	PHYSFS_init(argv[0]);//init physfs
	//PHYSFS_addToSearchPath("D:\\warnch\\Simple\\Simple\\edy",1);
	PHYSFS_addToSearchPath(PHYSFS_getBaseDir(),1);//add things around exe to search path
	#endif
	sf::RenderWindow app(sf::VideoMode(600,480),"LuaInterface");
	app.setFramerateLimit(60);
	app.resetGLStates();
	sfg::SFGUI sfgui;
	sfg::Desktop desk;//usuall sfg setup procedure..

	edy::gui::InterfaceLoader loader;//create instance of the loader
	loader.setCreationCallback(std::bind(fun2,std::placeholders::_2));//bind creation callback
	loader.load("test.lua");//load from that file(internally open via physfs)
	auto& it=loader.getWindows();//get vector of resuting windows
	for(unsigned i=0;i<it.size();++i) desk.Add(it[i]);//add them to desktop

	loader.setCallCallback(std::bind(fun,std::placeholders::_2));//set messages callback

	sf::Clock clo;//typicall loop:
	while(app.isOpen())
	{
		sf::Event eve;
		while(app.pollEvent(eve))
		{
			desk.HandleEvent(eve);
			if(eve.type==sf::Event::Closed) app.close();
		}
		desk.Update(clo.restart().asSeconds());
		app.clear();
		sfgui.Display(app);
		app.display();
	}
	#ifndef EE_NOPHYS_IN_LOADER
	PHYSFS_deinit();//deinit physfs
	#endif
}
Beispiel #12
0
// Initialise PhysicsFS, set up basic search paths and add arguments from .ini file.
// The .ini file can be in either the user directory or the same directory as the program.
// The user directory is searched first.
void PHYSFSX_init(int argc, char *argv[])
{
#if defined(__unix__)
	const char *path = NULL;
#endif
#ifdef macintosh	// Mac OS 9
	char base_dir[PATH_MAX];
	int bundle = 0;
#else
#define base_dir PHYSFS_getBaseDir()
#endif
	
	PHYSFS_init(argv[0]);
	atexit(PHYSFSX_deinit);
	PHYSFS_permitSymbolicLinks(1);
	
#ifdef macintosh
	strcpy(base_dir, PHYSFS_getBaseDir());
	if (strstr(base_dir, ".app:Contents:MacOSClassic"))	// the Mac OS 9 program is still in the .app bundle
	{
		char *p;
		
		bundle = 1;
		if (base_dir[strlen(base_dir) - 1] == ':')
			base_dir[strlen(base_dir) - 1] = '\0';
		p = strrchr(base_dir, ':'); *p = '\0';	// path to 'Contents'
		p = strrchr(base_dir, ':'); *p = '\0';	// path to bundle
		p = strrchr(base_dir, ':'); *p = '\0';	// path to directory containing bundle
	}
#endif
	
#if (defined(__APPLE__) && defined(__MACH__))	// others?
	chdir(base_dir);	// make sure relative hogdir paths work
#endif
	
#if defined(__unix__)
	char fullPath[PATH_MAX + 5];
# if !(defined(__APPLE__) && defined(__MACH__))
	path = "~/.d2x-rebirth/";
# else
	path = "~/Library/Preferences/D2X Rebirth/";
# endif
	
	if (path[0] == '~') // yes, this tilde can be put before non-unix paths.
	{
		const char *home = PHYSFS_getUserDir();
		
		strcpy(fullPath, home); // prepend home to the path
		path++;
		if (*path == *PHYSFS_getDirSeparator())
			path++;
		strncat(fullPath, path, PATH_MAX + 5 - strlen(home));
	}
	else
		strncpy(fullPath, path, PATH_MAX + 5);
	
	PHYSFS_setWriteDir(fullPath);
	if (!PHYSFS_getWriteDir())
	{                                               // need to make it
		char *p;
		char ancestor[PATH_MAX + 5];    // the directory which actually exists
		char child[PATH_MAX + 5];               // the directory relative to the above we're trying to make
		
		strcpy(ancestor, fullPath);
		while (!PHYSFS_getWriteDir() && ((p = strrchr(ancestor, *PHYSFS_getDirSeparator()))))
		{
			if (p[1] == 0)
			{                                       // separator at the end (intended here, for safety)
				*p = 0;                 // kill this separator
				if (!((p = strrchr(ancestor, *PHYSFS_getDirSeparator()))))
					break;          // give up, this is (usually) the root directory
			}
			
			p[1] = 0;                       // go to parent
			PHYSFS_setWriteDir(ancestor);
		}
		
		strcpy(child, fullPath + strlen(ancestor));
		for (p = child; (p = strchr(p, *PHYSFS_getDirSeparator())); p++)
			*p = '/';
		PHYSFS_mkdir(child);
		PHYSFS_setWriteDir(fullPath);
	}
	
	PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 1);
#endif
	
	PHYSFS_addToSearchPath(base_dir, 1);
	InitArgs( argc,argv );
	PHYSFS_removeFromSearchPath(base_dir);
	
	if (!PHYSFS_getWriteDir())
	{
		PHYSFS_setWriteDir(base_dir);
		if (!PHYSFS_getWriteDir())
			Error("can't set write dir: %s\n", PHYSFS_getLastError());
		else
			PHYSFS_addToSearchPath(PHYSFS_getWriteDir(), 0);
	}
	
	//tell PHYSFS where hogdir is
	if (GameArg.SysHogDir)
		PHYSFS_addToSearchPath(GameArg.SysHogDir,1);
#if defined(__unix__)
	else if (!GameArg.SysNoHogDir)
		PHYSFS_addToSearchPath(SHAREPATH, 1);
#endif
	
	PHYSFSX_addRelToSearchPath("data", 1);	// 'Data' subdirectory
	
	// For Macintosh, add the 'Resources' directory in the .app bundle to the searchpaths
#if defined(__APPLE__) && defined(__MACH__)
	{
		ProcessSerialNumber psn = { 0, kCurrentProcess };
		FSRef fsref;
		OSStatus err;
		
		err = GetProcessBundleLocation(&psn, &fsref);
		if (err == noErr)
			err = FSRefMakePath(&fsref, (ubyte *)fullPath, PATH_MAX);
		
		if (err == noErr)
		{
			strncat(fullPath, "/Contents/Resources/", PATH_MAX + 4 - strlen(fullPath));
			fullPath[PATH_MAX + 4] = '\0';
			PHYSFS_addToSearchPath(fullPath, 1);
		}
	}
#elif defined(macintosh)
	if (bundle)
	{
		base_dir[strlen(base_dir)] = ':';	// go back in the bundle
		base_dir[strlen(base_dir)] = ':';	// go back in 'Contents'
		strncat(base_dir, ":Resources:", PATH_MAX - 1 - strlen(base_dir));
		base_dir[PATH_MAX - 1] = '\0';
		PHYSFS_addToSearchPath(base_dir, 1);
	}
#endif
}
Beispiel #13
0
static int l_filesystem_getSource(lua_State* state)
{
  lua_pushstring(state, PHYSFS_getBaseDir());
  return 1;
}
Beispiel #14
0
    ResourceManager::ResourceManager(const std::string &path)
    {
        mDefaultBody = 0;
        mDefaultFemale = 0;
        mDefaultHair = 0;
        mDefaultChest = 0;
        mDefaultLegs = 0;
        mDefaultFeet = 0;
        mBodyWidth = 0;
        mBodyHeight = 0;
        mNumParts = 5; // TODO: Calculate based on body.cfg
        std::string datapath = "";
        std::string error;
        std::string dirName;

        // physfs code
        PHYSFS_init(path.c_str());

        // add paths
        // writable first, since thats where updates will go to
#if defined __unix__
        mWriteDataPath = PHYSFS_getUserDir();
#elif defined __APPLE__
		mWriteDataPath = PHYSFS_getUserDir();
		mWriteDataPath.append("Library/Application Support/");
#elif defined _WIN32
        TCHAR writePath[MAX_PATH+1];
        SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, writePath);
		int length = _tcslen(writePath);
        mWriteDataPath.assign(&writePath[0], &writePath[length]);
#endif

#ifndef __unix__
        dirName = "townslife";
#else
        dirName = ".townslife";
#endif
        PHYSFS_setWriteDir(mWriteDataPath.c_str());

        if (!doesExist(dirName))
        {
			if (PHYSFS_mkdir(dirName.c_str()) == 0)
			{
			    error = PHYSFS_getLastError();
			}
        }
        mWriteDataPath.append("/" + dirName);
        PHYSFS_setWriteDir(mWriteDataPath.c_str());
        mWriteDataPath.append("/");
        addPath(mWriteDataPath);

        // now add cfg and /data directory
#if defined __unix__
        datapath = PHYSFS_getBaseDir();
        addPath(datapath);
        addPath(datapath + "data/");
#elif defined __APPLE__
        CFBundleRef mainBundle = CFBundleGetMainBundle();
		CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
		char resPath[PATH_MAX];
		CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)resPath, PATH_MAX);
		CFRelease(resourcesURL);
		addPath(resPath);
#elif defined _WIN32
        TCHAR exePath[MAX_PATH+1];
        GetModuleFileName(0, exePath, MAX_PATH);
		length = _tcslen(exePath);
        datapath.append(&exePath[0], &exePath[length]);
        datapath = datapath.substr(0, datapath.find_last_of("\\") + 1);
        addPath(datapath);
        addPath(datapath + "data\\");
#endif
    }
Beispiel #15
0
const char *fs_base_dir(void)
{
    return PHYSFS_getBaseDir();
}
Beispiel #16
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;
}
Beispiel #17
0
void FS_Init(lua_State *L, char *argv[], char **pFilename) {
	#ifdef __MACOSX__
		char *ch = NULL;
		const char *basedir;
	#endif
	FILE *fh;
	char magic[4] = "000"; /* array for the magic bytes used to recognize a zip archive */
	char *dir = NULL;
	char *base = NULL;
	char appdata[4096];
//	char **search_path = NULL;
//	char **copy;

	/* initialize PhysFS */
	if (PHYSFS_init(argv[0]) ==0) {
		error(L, "Error: Could not initialize PhysFS: %s.", PHYSFS_getLastError());
	}

	/* allow symlinks */
	PHYSFS_permitSymbolicLinks(1);

	/*	on Mac OS X applications are packed inside a folder with the ending .app;
		try to set the search path to this folder;
		if a file is not found in the base dir (the dir containing the app bundle)
		it is searched inside the bundle */
	#ifdef __MACOSX__
		ch = strstr(argv[0], "/Contents/MacOS");
		if (ch != NULL) {
			/* substite the 'C' of 'Contents/MacOS' with a string terminator */
			*(ch+1) = '\0';
			if (*pFilename == NULL) {
				/* if no filename was selected */
				chdir(argv[0]);
			}
			/* append app folder to search path */
			if (PHYSFS_addToSearchPath(argv[0], 1) == 0) {
				error(L,	"Error: Could not add application folder"
							"to search path: %s.", PHYSFS_getLastError());
			}
			*(ch+1) = 'C';
		} else {
			basedir = PHYSFS_getBaseDir();
			if (*pFilename == NULL) {
				chdir(basedir);
			}
			if (PHYSFS_addToSearchPath(basedir, 1) == 0) {
				error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError());
			}
		}
	#else
		/* check whether we are on Linux or Unix */
		#ifndef __WIN32__
			/* on Linux or Unix: Try to append the share directory */
			#ifdef SHARE_DIR
			PHYSFS_addToSearchPath(SHARE_DIR, 1);
			#endif

		#endif
		/* on every system but OS X, prepend base dir to search path */
		if (PHYSFS_addToSearchPath(PHYSFS_getBaseDir(), 0) == 0) {
			error(L, "Error: Could not add base dir to search path: %s.", PHYSFS_getLastError());
		}
	#endif

	/*
	 * if a Lua file is given, try to mount the parent directory and change
	 * the working directory
	 * if an archive or directory is given, try to mount it
	 */
	if (*pFilename == NULL) {
		*pFilename = (char *)DEFAULT_FILE;
		if (PHYSFS_exists(*pFilename) == 0) {
			/* if default file not exists */
			if (PHYSFS_exists(DEFAULT_ARCHIVE) != 0) {
				/* if default archive exists, prepend to search path */
				if (PHYSFS_addToSearchPath(DEFAULT_ARCHIVE, 0) == 0) {
					error(L,	"Error: Could not add default archive '"
								DEFAULT_ARCHIVE "' to search path: %s",
								PHYSFS_getLastError());
				}
			} else {
				error(L,	"Error: "
							"Neither the default Lua file '" DEFAULT_FILE
							"' nor the default archive '" DEFAULT_ARCHIVE
							"' could be found.");
			}
		}
	} else {
		/* try to change the working directory (only successful if directory is given) */
		if (chdir(*pFilename) == 0) {
			/* prepend the new working directory to the search path */
			if (PHYSFS_addToSearchPath(".", 0) == 0) {
				error(L, "Error: Could not add directory '%s' to search path: %s", argv[1], PHYSFS_getLastError());
			}
			*pFilename = (char *)DEFAULT_FILE;
		} else {
			/* chdir was unsuccessful -> archive or Lua file was probably given on command line */
			splitPath(*pFilename, &dir, &base);
			/* change the working directory to the directory with the archive or the Lua file */
			chdir(dir);
			/* check if it's an archive; only zip is supported, so we check for the magic numbers */
			fh = fopen(base, "r");
			if (fh == NULL) {
				error(L, "Error: Could not open file '%s' for reading.", argv[1]);
			}
			fread(magic, 1, 4, fh);
			fclose(fh);
			/* look for the four signature bytes that every zip file has */
			if (magic[0] == 0x50 && magic[1] == 0x4B && magic[2] == 0x03 && magic[3] == 0x04) {
//				fprintf(stdout, "Found zip archive: %s\n", base);
				if (PHYSFS_addToSearchPath(base, 0) == 0) {
					error(L, "Error: Could not add archive '%s' to search path: %s", argv[1], PHYSFS_getLastError());
				}
				*pFilename = (char *)DEFAULT_FILE;
			} else {
//				fprintf(stdout, "Found Lua file: %s\n", base);
				/* prepend the new working directory to the search path */
				if (PHYSFS_addToSearchPath(".", 0) == 0) {
					error(L, 	"Error: Could not add directory containing '%s' to search path: %s",
								base, PHYSFS_getLastError());
				}
				/* change the filename to its basename -> later call to FS_runLuaFile will find it in the path */
				*pFilename = base;
			}
		}
	}
	

  //  char * xdgdatahome = getenv("XDG_DATA_HOME");

    //if (!xdgdatahome)
    //{
        strcpy(appdata, PHYSFS_getUserDir());
		#ifdef __GNUC__
			strcat(appdata, "/.local/share/");
		#else
			strcat(appdata, "Application Data");
		#endif
    //}
    //else
    //    strcpy(appdata, xdgdatahome);

//    printf("%s", appdata);
    if(!PHYSFS_setWriteDir(appdata))
        error(L, "Error: Could not set write directory '%s': %s",
								appdata, PHYSFS_getLastError());
    strcat(appdata, "/Scriptum Plus/");
//    strcat(appdata, appName);
    //char * relative_path = strcat("./Scriptum Plus/", appName);
	if(!PHYSFS_mkdir("/Scriptum Plus/"))
        error(L, "Error: Could not create write directory '%s': %s",
								appdata, PHYSFS_getLastError());

    if(!PHYSFS_setWriteDir(appdata))
        error(L, "Error: Could not set write directory '%s': %s",
								appdata, PHYSFS_getLastError());
    PHYSFS_addToSearchPath(appdata, 0);

	atexit(FS_Quit);

//	search_path = PHYSFS_getSearchPath();
//	copy = search_path;
//	while (*copy != NULL) {
//		printf("search path: %s\n", *copy++);
//	}
//	PHYSFS_freeList(search_path);
}
Beispiel #18
0
const char *ex_fsys_app_dir () { return PHYSFS_getBaseDir(); }
static int cmd_getbasedir(char *args)
{
    (void)args;
    printf("Base dir is [%s].\n", PHYSFS_getBaseDir());
    return(1);
} /* cmd_getbasedir */
Beispiel #20
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;
}
void initialize(const char* argv0, const char* ,
                            const char* application)
{
    if(!PHYSFS_init(argv0))
        throw Exception("failure while initialising physfs: %s",
                        PHYSFS_getLastError());

    const char* basedir = PHYSFS_getBaseDir();
    const char* userdir = PHYSFS_getUserDir();
    const char* dirsep = PHYSFS_getDirSeparator();
    char* writedir = new char[strlen(userdir) + strlen(application) + 2];

    sprintf(writedir, "%s.%s", userdir, application);
    if(!PHYSFS_setWriteDir(writedir)) {
        // try to create the directory...
        char* mkdir = new char[strlen(application)+2];
        sprintf(mkdir, ".%s", application);
        if(!PHYSFS_setWriteDir(userdir) || ! PHYSFS_mkdir(mkdir)) {
            delete[] writedir;
            delete[] mkdir;
            throw Exception("failed creating configuration directory: '%s': %s",
                            writedir, PHYSFS_getLastError());
        }
        delete[] mkdir;

        if (!PHYSFS_setWriteDir(writedir)) {
            throw Exception("couldn't set configuration directory to '%s': %s",
                            writedir, PHYSFS_getLastError());
        }
    }

    PHYSFS_addToSearchPath(writedir, 0);
    PHYSFS_addToSearchPath(basedir, 1);

    delete[] writedir;

    /* Root out archives, and add them to search path... */
    char* archiveExt = "zip";
    if (archiveExt != NULL) {
        char **rc = PHYSFS_enumerateFiles("/");
        char **i;
        size_t extlen = strlen(archiveExt);
        char *ext;

        for (i = rc; *i != NULL; i++) {
            size_t l = strlen(*i);
            if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
                ext = (*i) + (l - extlen);
                if (strcasecmp(ext, archiveExt) == 0) {
                    const char *d = PHYSFS_getRealDir(*i);
                    char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
                    sprintf(str, "%s%s%s", d, dirsep, *i);
                    PHYSFS_addToSearchPath(str, 1);
                    delete[] str;
                } /* if */
            } /* if */
        } /* for */

        PHYSFS_freeList(rc);
    } /* if */
}
Beispiel #22
0
bool Resources::Open(PString & argv0, PString & application) {
    if(!PHYSFS_init(argv0.GetPointer())) {
        PError << "failure while initialising physfs: " << PHYSFS_getLastError() << endl;
        return PFalse;
    } else {
        PTRACE(5, "successful initialize physfs");
    }
    const char* basedir = PHYSFS_getBaseDir();
    const char* userdir = PHYSFS_getUserDir();
    const char* dirsep = PHYSFS_getDirSeparator();
    char* writedir = new char[strlen(userdir) + application.GetLength() + 2];
    sprintf(writedir, "%s.%s", userdir, application.GetPointer());
    PTRACE(5, "physfs base directory: " << basedir);
    PTRACE(5, "physfs user directory: " << userdir);
    PTRACE(5, "physfs write directory: " << writedir);

    if(!PHYSFS_setWriteDir(writedir)) {
        // try to create the directory...
        char* mkdir = new char[application.GetLength()+2];
        sprintf(mkdir, ".%s", application.GetPointer());
        if(!PHYSFS_setWriteDir(userdir) || ! PHYSFS_mkdir(mkdir)) {
            delete[] writedir;
            delete[] mkdir;
            PError << "failed creating configuration directory: '" << writedir << "': " << PHYSFS_getLastError() << endl;
            return PFalse;
        }
        delete[] mkdir;

        if (!PHYSFS_setWriteDir(writedir)) {
            PError << "couldn't set configuration directory to '" << writedir << "': " << PHYSFS_getLastError() << endl;
            return PFalse;
        }
    }

    PHYSFS_addToSearchPath(writedir, 0);
    PHYSFS_addToSearchPath(basedir, 1);

    delete[] writedir;

    /* Root out archives, and add them to search path... */
    if (resourceExt != NULL) {
        char **rc = PHYSFS_enumerateFiles("/");
        char **i;
        size_t extlen = strlen(resourceExt);
        char *ext;

        for (i = rc; *i != NULL; i++) {
            size_t l = strlen(*i);
            if ((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
                ext = (*i) + (l - extlen);
                if (strcasecmp(ext, resourceExt) == 0) {
                    PTRACE(5, "Add resource '" << *i << "' to search path");
                    const char *d = PHYSFS_getRealDir(*i);
                    char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
                    sprintf(str, "%s%s%s", d, dirsep, *i);
                    addToSearchPath(str, 1);
                    delete[] str;
                };
            };
        };
        PHYSFS_freeList(rc);
    }
    return PTrue;
}
Beispiel #23
0
static void getPlatformUserDir(char * const tmpstr, size_t const size)
{
#if defined(WZ_OS_WIN)
//  When WZ_PORTABLE is passed, that means we want the config directory at the same location as the program file
	DWORD dwRet;
	wchar_t tmpWStr[MAX_PATH];
#ifndef WZ_PORTABLE
	if ( SUCCEEDED( SHGetFolderPathW( NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, tmpWStr ) ) )
	{
#else
	if (dwRet = GetCurrentDirectoryW(MAX_PATH, tmpWStr))
	{
		if(dwRet > MAX_PATH)
		{
			debug(LOG_FATAL, "Buffer exceeds maximum path to create directory. Exiting.");
			exit(1);
		}
#endif
		if (WideCharToMultiByte(CP_UTF8, 0, tmpWStr, -1, tmpstr, size, NULL, NULL) == 0)
		{
			debug(LOG_FATAL, "Config directory encoding conversion error.");
			exit(1);
		}
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
#elif defined(WZ_OS_MAC)
	FSRef fsref;
	OSErr error = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &fsref);
	if (!error)
		error = FSRefMakePath(&fsref, (UInt8 *) tmpstr, size);
	if (!error)
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	else
#endif
	if (PHYSFS_getUserDir())
	{
		strlcpy(tmpstr, PHYSFS_getUserDir(), size); // Use PhysFS supplied UserDir (As fallback on Windows / Mac, default on Linux)
	}
	// If PhysicsFS fails (might happen if environment variable HOME is unset or wrong) then use the current working directory
	else if (getCurrentDir(tmpstr, size))
	{
		strlcat(tmpstr, PHYSFS_getDirSeparator(), size);
	}
	else
	{
		debug(LOG_FATAL, "Can't get UserDir?");
		abort();
	}
}


static void initialize_ConfigDir(void)
{
	char tmpstr[PATH_MAX] = { '\0' };

	if (strlen(configdir) == 0)
	{
		getPlatformUserDir(tmpstr, sizeof(tmpstr));

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		if (!PHYSFS_mkdir(WZ_WRITEDIR)) // s.a.
		{
			debug(LOG_FATAL, "Error creating directory \"%s\": %s",
			      WZ_WRITEDIR, PHYSFS_getLastError());
			exit(1);
		}

		// Append the Warzone subdir
		sstrcat(tmpstr, WZ_WRITEDIR);
		sstrcat(tmpstr, PHYSFS_getDirSeparator());

		if (!PHYSFS_setWriteDir(tmpstr))
		{
			debug( LOG_FATAL, "Error setting write directory to \"%s\": %s",
			tmpstr, PHYSFS_getLastError() );
			exit(1);
		}
	}
	else
	{
		sstrcpy(tmpstr, configdir);

		// Make sure that we have a directory separator at the end of the string
		if (tmpstr[strlen(tmpstr) - 1] != PHYSFS_getDirSeparator()[0])
			sstrcat(tmpstr, PHYSFS_getDirSeparator());

		debug(LOG_WZ, "Using custom configuration directory: %s", tmpstr);

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		// NOTE: This is currently only used for mingw builds for now.
#if defined (WZ_CC_MINGW)
		if (!OverrideRPTDirectory(tmpstr))
		{
			// since it failed, we just use our default path, and not the user supplied one.
			debug(LOG_ERROR, "Error setting exception hanlder to use directory %s", tmpstr);
		}
#endif
	}

	// User's home dir first so we allways see what we write
	PHYSFS_addToSearchPath( PHYSFS_getWriteDir(), PHYSFS_PREPEND );

	PHYSFS_permitSymbolicLinks(1);

	debug(LOG_WZ, "Write dir: %s", PHYSFS_getWriteDir());
	debug(LOG_WZ, "Base dir: %s", PHYSFS_getBaseDir());
}
Beispiel #24
0
int main(int argc, char ** argv)
{
    // number of arguments to skip before the script's real arguments
    int skip_arg = 1;

    // init physfs
    if(!PHYSFS_init(argv[0]))
    {
        fprintf(stderr, "physfs init failed: %s", PHYSFS_getLastError());
        return 1;
    }

    // get executable path
    const char *directory = PHYSFS_getBaseDir();
    const char *executable = basename(argv[0]);
    char *path = malloc(strlen(directory) + strlen(executable) + 1);
    strcpy(path, directory);
    strcat(path, executable);
    // try to mount the executable as an archive, on failure try to mount the
    // first argument instead
    if(!PHYSFS_mount(path, "/", 0))
    {
        skip_arg = skip_arg + 1;
        if(argc < 2 || !PHYSFS_mount(argv[1], "/", 0))
        {
            fprintf(stderr, "no archive found in the executable nor in the "
                    "first argument\n");
            return 1;
        }
    }
    free(path);

    // load lua and libraries
    lua_State *L = lua_open();
    luaL_openlibs(L);
    init_physfs_loader(L);
    init_preloaders(L);
    
    // load arguments (and pre-arguments) into a global 'arg' table
    lua_newtable(L);
    for(int i = 0; i < argc; i++)
    {
        lua_pushstring(L, argv[i]);
        lua_rawseti(L, -2, i - skip_arg + 1);
    }
    lua_setglobal(L, "arg");

    // open app, with error reporting
    lua_getglobal(L, "debug");
    lua_getfield(L, -1, "traceback");

    lua_pushcfunction(L, seed_loadfile);
    lua_pushstring(L, "init.lua");
    int error = lua_pcall(L, 1, 1, 0); // load file

    if(!error)
    {
        // load command-line arguments as function arguments
        lua_checkstack(L, argc - skip_arg);
        for(int i = 1; i <= argc - skip_arg; i++)
            lua_pushstring(L, argv[i + skip_arg - 1]);
        error = lua_pcall(L, argc - skip_arg, 0, -2);  // run the result
    }

    if(error)
        fprintf(stderr, "%s\n", lua_tostring(L, -1));

    lua_close(L);
    PHYSFS_deinit();
    return error;
}
void initPhysfs(const char* argv0)
{
    if(!PHYSFS_init(argv0)) {
        std::stringstream msg;
        msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
        throw std::runtime_error(msg.str());
    }

    // Initialize physfs (this is a slightly modified version of
    // PHYSFS_setSaneConfig
    const char* application = /* PACKAGE_NAME */ "lincity";
    const char* userdir = PHYSFS_getUserDir();
    const char* dirsep = PHYSFS_getDirSeparator();
    char* writedir = new char[strlen(userdir) + strlen(application) + 2];

    // Set configuration directory
    sprintf(writedir, "%s.%s", userdir, application);
    if(!PHYSFS_setWriteDir(writedir)) {
        // try to create the directory
        char* mkdir = new char[strlen(application) + 2];
        sprintf(mkdir, ".%s", application);
        if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
            std::ostringstream msg;
            msg << "Failed creating configuration directory '" <<
                writedir << "': " << PHYSFS_getLastError();
            delete[] writedir;
            delete[] mkdir;
            throw std::runtime_error(msg.str());
        }
        delete[] mkdir;

        if(!PHYSFS_setWriteDir(writedir)) {
            std::ostringstream msg;
            msg << "Failed to use configuration directory '" <<            
                writedir << "': " << PHYSFS_getLastError();
            delete[] writedir;
            throw std::runtime_error(msg.str());
        }
    }
    PHYSFS_addToSearchPath(writedir, 0);
    delete[] writedir;
   
    // Search for archives and add them to the search path
    const char* archiveExt = "zip";
    char** rc = PHYSFS_enumerateFiles("/");
    size_t extlen = strlen(archiveExt);

    for(char** i = rc; *i != 0; ++i) {
        size_t l = strlen(*i);
        if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
            const char* ext = (*i) + (l - extlen);
            if(strcasecmp(ext, archiveExt) == 0) {
                const char* d = PHYSFS_getRealDir(*i);
                char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
                sprintf(str, "%s%s%s", d, dirsep, *i);
                PHYSFS_addToSearchPath(str, 1);
                delete[] str;
            }
        }
    }

    PHYSFS_freeList(rc);
            
    // when started from source dir...
    std::string dir = PHYSFS_getBaseDir();
    dir += "/data";
    std::string testfname = dir;
    testfname += "/images/tiles/images.xml";
    FILE* f = fopen(testfname.c_str(), "r");
    if(f) {
        fclose(f);
        if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
#ifdef DEBUG
            std::cout << "Warning: Couldn't add '" << dir << 
                "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
#endif
        }
    }

#if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
    std::string datadir;
#ifdef ENABLE_BINRELOC
    BrInitError error;
    if (br_init (&error) == 0 && error != BR_INIT_ERROR_DISABLED) {
        printf ("Warning: BinReloc failed to initialize (error code %d)\n",
                error);
        printf ("Will fallback to hardcoded default path.\n");
    }
    
    char* brdatadir = br_find_data_dir("/usr/local/share");
    datadir = brdatadir;
    datadir += "/" PACKAGE_NAME;
    free(brdatadir);
#else
    datadir = APPDATADIR;
#endif
    
    if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
        std::cout << "Couldn't add '" << datadir
            << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
    }
#endif

    // allow symbolic links
    PHYSFS_permitSymbolicLinks(1);

    //show search Path 
    for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
        printf("[%s] is in the search path.\n", *i);

    // ugly: set LINCITY_HOME environment variable
    const char* lincityhome = PHYSFS_getRealDir("colour.pal");
    if(lincityhome == 0) {
        throw std::runtime_error("Couldn't locate lincity data (colour.pal).");
    }
    std::cout << "LINCITY_HOME: " << lincityhome << "\n";
    char tmp[256];
    snprintf(tmp, sizeof(tmp), "LINCITY_HOME=%s", lincityhome);
    putenv(tmp);
}
Beispiel #26
0
 const char *getBaseDir()
 {
     return PHYSFS_getBaseDir();
 }
Beispiel #27
0
string getBaseDir() {
	return PHYSFS_getBaseDir();
}
Beispiel #28
0
static void init_physfs(const char* argv0)
{
  if(!PHYSFS_init(argv0)) {
    std::stringstream msg;
    msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
    throw std::runtime_error(msg.str());
  }

  // Initialize physfs (this is a slightly modified version of
  // PHYSFS_setSaneConfig
  const char* application = PACKAGE_NAME;
  const char* userdir = PHYSFS_getUserDir();
  const char* dirsep = PHYSFS_getDirSeparator();
  char* writedir = new char[strlen(userdir) + strlen(application) + 2];

  // Set configuration directory
  sprintf(writedir, "%s.%s", userdir, application);
  if(!PHYSFS_setWriteDir(writedir)) {
    // try to create the directory
    char* mkdir = new char[strlen(application) + 2];
    sprintf(mkdir, ".%s", application);
    if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
      std::ostringstream msg;
      msg << "Failed creating configuration directory '" 
          << writedir << "': " << PHYSFS_getLastError();
      delete[] writedir;
      delete[] mkdir;
      throw std::runtime_error(msg.str());
    }
    delete[] mkdir;
    
    if(!PHYSFS_setWriteDir(writedir)) {
      std::ostringstream msg;
      msg << "Failed to use configuration directory '" 
          <<  writedir << "': " << PHYSFS_getLastError();
      delete[] writedir;
      throw std::runtime_error(msg.str());
    }
  }
  PHYSFS_addToSearchPath(writedir, 0);
  delete[] writedir;

  // Search for archives and add them to the search path
  const char* archiveExt = "zip";
  char** rc = PHYSFS_enumerateFiles("/");
  size_t extlen = strlen(archiveExt);

  for(char** i = rc; *i != 0; ++i) {
    size_t l = strlen(*i);
    if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
      const char* ext = (*i) + (l - extlen);
      if(strcasecmp(ext, archiveExt) == 0) {
        const char* d = PHYSFS_getRealDir(*i);
        char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
        sprintf(str, "%s%s%s", d, dirsep, *i);
        PHYSFS_addToSearchPath(str, 1);
        delete[] str;
      }
    }
  }
  
  PHYSFS_freeList(rc);

  // when started from source dir...
  std::string dir = PHYSFS_getBaseDir();
  dir += "/data";
  std::string testfname = dir;
  testfname += "/credits.txt";
  bool sourcedir = false;
  FILE* f = fopen(testfname.c_str(), "r");
  if(f) {
    fclose(f);
    if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
      log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
    } else {
      sourcedir = true;
    }
  }

#ifdef MACOSX
  // when started from Application file on Mac OS X...
  dir = PHYSFS_getBaseDir();
  dir += "SuperTux.app/Contents/Resources/data";
  testfname = dir + "/credits.txt";
  sourcedir = false;
  f = fopen(testfname.c_str(), "r");
  if(f) {
    fclose(f);
    if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
      msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
    } else {
      sourcedir = true;
    }
  }
#endif

  if(!sourcedir) {
#if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
    std::string datadir;
#ifdef ENABLE_BINRELOC
    char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
    datadir = brdatadir;
    free(brdatadir);
#else
    datadir = APPDATADIR;
#endif
    if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
      log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
    }
#endif
  }

  // allow symbolic links
  PHYSFS_permitSymbolicLinks(1);

  //show search Path
  for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
    log_info << "[" << *i << "] is in the search path" << std::endl;
}
Beispiel #29
0
/*!
 * \brief Adds default data dirs
 *
 * Priority:
 * Lower loads first. Current:
 * -datadir > User's home dir > source tree data > AutoPackage > BaseDir > DEFAULT_DATADIR
 *
 * Only -datadir and home dir are allways examined. Others only if data still not found.
 *
 * We need ParseCommandLine, before we can add any mods...
 *
 * \sa rebuildSearchPath
 */
static void scanDataDirs( void )
{
	char tmpstr[PATH_MAX], prefix[PATH_MAX];
	char* separator;

#if defined(WZ_OS_MAC)
	// version-independent location for video files
	registerSearchPath("/Library/Application Support/Warzone 2100/", 1);
#endif

	// Find out which PREFIX we are in...
	sstrcpy(prefix, PHYSFS_getBaseDir());

	separator = strrchr(prefix, *PHYSFS_getDirSeparator());
	if (separator)
	{
		*separator = '\0'; // Trim ending '/', which getBaseDir always provides

		separator = strrchr(prefix, *PHYSFS_getDirSeparator());
		if (separator)
		{
			*separator = '\0'; // Skip the last dir from base dir
		}
	}

	// Commandline supplied datadir
	if( strlen( datadir ) != 0 )
		registerSearchPath( datadir, 1 );

	// User's home dir
	registerSearchPath( PHYSFS_getWriteDir(), 2 );
	rebuildSearchPath( mod_multiplay, true );

	if( !PHYSFS_exists("gamedesc.lev") )
	{
		// Data in source tree
		sstrcpy(tmpstr, prefix);
		sstrcat(tmpstr, "/data/");
		registerSearchPath( tmpstr, 3 );
		rebuildSearchPath( mod_multiplay, true );

		if( !PHYSFS_exists("gamedesc.lev") )
		{
			// Relocation for AutoPackage
			sstrcpy(tmpstr, prefix);
			sstrcat(tmpstr, "/share/warzone2100/");
			registerSearchPath( tmpstr, 4 );
			rebuildSearchPath( mod_multiplay, true );

			if( !PHYSFS_exists("gamedesc.lev") )
			{
				// Program dir
				registerSearchPath( PHYSFS_getBaseDir(), 5 );
				rebuildSearchPath( mod_multiplay, true );

				if( !PHYSFS_exists("gamedesc.lev") )
				{
					// Guessed fallback default datadir on Unix
					registerSearchPath( WZ_DATADIR, 6 );
					rebuildSearchPath( mod_multiplay, true );
				}
			}
		}
	}

#ifdef WZ_OS_MAC
	if( !PHYSFS_exists("gamedesc.lev") ) {
		CFURLRef resourceURL = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
		char resourcePath[PATH_MAX];
		if( CFURLGetFileSystemRepresentation( resourceURL, true,
							(UInt8 *) resourcePath,
							PATH_MAX) ) {
			chdir( resourcePath );
			registerSearchPath( "data", 7 );
			rebuildSearchPath( mod_multiplay, true );
		} else {
			debug( LOG_ERROR, "Could not change to resources directory." );
		}

		if( resourceURL != NULL ) {
			CFRelease( resourceURL );
		}
	}
#endif

	/** Debugging and sanity checks **/

	printSearchPath();

	if( PHYSFS_exists("gamedesc.lev") )
	{
		debug( LOG_WZ, "gamedesc.lev found at %s", PHYSFS_getRealDir( "gamedesc.lev" ) );
	}
	else
	{
		debug( LOG_FATAL, "Could not find game data. Aborting." );
		exit(1);
	}
}
Beispiel #30
0
static void initialize_ConfigDir(void)
{
	char tmpstr[PATH_MAX] = { '\0' };

	if (strlen(configdir) == 0)
	{
		getPlatformUserDir(tmpstr, sizeof(tmpstr));

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		if (!PHYSFS_mkdir(WZ_WRITEDIR)) // s.a.
		{
			debug(LOG_FATAL, "Error creating directory \"%s\": %s",
			      WZ_WRITEDIR, PHYSFS_getLastError());
			exit(1);
		}

		// Append the Warzone subdir
		sstrcat(tmpstr, WZ_WRITEDIR);
		sstrcat(tmpstr, PHYSFS_getDirSeparator());

		if (!PHYSFS_setWriteDir(tmpstr))
		{
			debug( LOG_FATAL, "Error setting write directory to \"%s\": %s",
			tmpstr, PHYSFS_getLastError() );
			exit(1);
		}
	}
	else
	{
		sstrcpy(tmpstr, configdir);

		// Make sure that we have a directory separator at the end of the string
		if (tmpstr[strlen(tmpstr) - 1] != PHYSFS_getDirSeparator()[0])
			sstrcat(tmpstr, PHYSFS_getDirSeparator());

		debug(LOG_WZ, "Using custom configuration directory: %s", tmpstr);

		if (!PHYSFS_setWriteDir(tmpstr)) // Workaround for PhysFS not creating the writedir as expected.
		{
			debug(LOG_FATAL, "Error setting write directory to \"%s\": %s",
			      tmpstr, PHYSFS_getLastError());
			exit(1);
		}

		// NOTE: This is currently only used for mingw builds for now.
#if defined (WZ_CC_MINGW)
		if (!OverrideRPTDirectory(tmpstr))
		{
			// since it failed, we just use our default path, and not the user supplied one.
			debug(LOG_ERROR, "Error setting exception hanlder to use directory %s", tmpstr);
		}
#endif
	}

	// User's home dir first so we allways see what we write
	PHYSFS_addToSearchPath( PHYSFS_getWriteDir(), PHYSFS_PREPEND );

	PHYSFS_permitSymbolicLinks(1);

	debug(LOG_WZ, "Write dir: %s", PHYSFS_getWriteDir());
	debug(LOG_WZ, "Base dir: %s", PHYSFS_getBaseDir());
}