示例#1
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__) || defined(__APPLE__) || defined(__MACH__)
	char fullPath[PATH_MAX + 5];
#endif
#if defined(__unix__)
	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]);
	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__)
# if !(defined(__APPLE__) && defined(__MACH__))
	path = "~/.d2x-retro/";
# else
	path = "~/Library/Preferences/D2X Retro/";
# 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
}
示例#2
0
文件: fsys.c 项目: exdev/exsdk
int ex_fsys_set_write_path ( const char *_new_dir ) { 
    __PHYSFS_CHECK( PHYSFS_setWriteDir(_new_dir) );
    return 0;
}
示例#3
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());
}
示例#4
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);
		}
	}

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


	// 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());
}
示例#5
0
  void find_userdir() const
  {
    std::string userdir;
    if (m_forced_userdir)
    {
      userdir = *m_forced_userdir;
    }
    else if (const char* env_userdir = getenv("SUPERTUX2_USER_DIR"))
    {
      userdir = env_userdir;
    }
    else
    {
		userdir = PHYSFS_getPrefDir("SuperTux","supertux2");
    }
	//Kept for backwards-compatability only, hence the silence
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
	std::string physfs_userdir = PHYSFS_getUserDir();
#pragma GCC diagnostic pop

#ifdef _WIN32
	std::string olduserdir = FileSystem::join(physfs_userdir, PACKAGE_NAME);
#else
	std::string olduserdir = FileSystem::join(physfs_userdir, "." PACKAGE_NAME);
#endif
	if (FileSystem::is_directory(olduserdir)) {
	  boost::filesystem::path olduserpath(olduserdir);
	  boost::filesystem::path userpath(userdir);

	  boost::filesystem::directory_iterator end_itr;

	  bool success = true;

	  // cycle through the directory
	  for (boost::filesystem::directory_iterator itr(olduserpath); itr != end_itr; ++itr) {
		try
		{
		  boost::filesystem::rename(itr->path().string().c_str(), userpath / itr->path().filename());
		}
		catch (const boost::filesystem::filesystem_error& err)
		{
		  success = false;
		  log_warning << "Failed to move contents of config directory: " << err.what() << std::endl;
		}
	  }
	  if (success) {
	    try
		{
		  boost::filesystem::remove_all(olduserpath);
		}
		catch (const boost::filesystem::filesystem_error& err)
		{
		  success = false;
		  log_warning << "Failed to remove old config directory: " << err.what();
		}
	  }
	  if (success) {
	    log_info << "Moved old config dir " << olduserdir << " to " << userdir << std::endl;
	  }
	}

    if (!FileSystem::is_directory(userdir))
    {
	  FileSystem::mkdir(userdir);
	  log_info << "Created SuperTux userdir: " << userdir << std::endl;
    }

    if (!PHYSFS_setWriteDir(userdir.c_str()))
    {
      std::ostringstream msg;
      msg << "Failed to use userdir directory '"
          <<  userdir << "': " << PHYSFS_getLastErrorCode();
      throw std::runtime_error(msg.str());
    }

    PHYSFS_mount(userdir.c_str(), NULL, 0);
  }
示例#6
0
bool ResourceManager::setWriteDir(const std::string &path)
{
    return (bool) PHYSFS_setWriteDir(path.c_str());
}
示例#7
0
int main(int argc, char **argv)
{
    int rc;
    char buf[128];
    PHYSFS_file *f;

    if (!PHYSFS_init(argv[0]))
    {
        con_printf(CON_CRITICAL, "PHYSFS_init(): %s\n", PHYSFS_getLastError());
        return(1);
    } /* if */

    if (!PHYSFS_addToSearchPath(".", 1))
    {
        con_printf(CON_CRITICAL, "PHYSFS_addToSearchPath(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    if (!PHYSFS_setWriteDir("."))
    {
        con_printf(CON_CRITICAL, "PHYSFS_setWriteDir(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    if (!PHYSFS_mkdir("/a/b/c"))
    {
        con_printf(CON_CRITICAL, "PHYSFS_mkdir(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    if (!PHYSFS_mkdir("/a/b/C"))
    {
        con_printf(CON_CRITICAL, "PHYSFS_mkdir(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    f = PHYSFS_openWrite("/a/b/c/x.txt");
    PHYSFS_close(f);
    if (f == NULL)
    {
        con_printf(CON_CRITICAL, "PHYSFS_openWrite(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    f = PHYSFS_openWrite("/a/b/C/X.txt");
    PHYSFS_close(f);
    if (f == NULL)
    {
        con_printf(CON_CRITICAL, "PHYSFS_openWrite(): %s\n", PHYSFS_getLastError());
        PHYSFS_deinit();
        return(1);
    } /* if */

    strcpy(buf, "/a/b/c/x.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0))
        con_printf(CON_DEBUG,"test 1 failed\n");

    strcpy(buf, "/a/B/c/x.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0))
        con_printf(CON_DEBUG,"test 2 failed\n");

    strcpy(buf, "/a/b/C/x.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != 0) || (strcmp(buf, "/a/b/C/X.txt") != 0))
        con_printf(CON_DEBUG,"test 3 failed\n");

    strcpy(buf, "/a/b/c/X.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != 0) || (strcmp(buf, "/a/b/c/x.txt") != 0))
        con_printf(CON_DEBUG,"test 4 failed\n");

    strcpy(buf, "/a/b/c/z.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != -1) || (strcmp(buf, "/a/b/c/z.txt") != 0))
        con_printf(CON_DEBUG,"test 5 failed\n");

    strcpy(buf, "/A/B/Z/z.txt");
    rc = PHYSFSEXT_locateCorrectCase(buf);
    if ((rc != -2) || (strcmp(buf, "/a/b/Z/z.txt") != 0))
        con_printf(CON_DEBUG,"test 6 failed\n");

    con_printf(CON_DEBUG,"Testing completed.\n");
    con_printf(CON_DEBUG,"  If no errors were reported, you're good to go.\n");

    PHYSFS_delete("/a/b/c/x.txt");
    PHYSFS_delete("/a/b/C/X.txt");
    PHYSFS_delete("/a/b/c");
    PHYSFS_delete("/a/b/C");
    PHYSFS_delete("/a/b");
    PHYSFS_delete("/a");
    PHYSFS_deinit();
    return(0);
} /* main */
示例#8
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;
}
示例#9
0
// ----------------------------------------------------------------------------
void Track::build()
{
    IrrlichtDevice* device = Editor::getEditor()->getDevice();

    PHYSFS_setWriteDir(Editor::getEditor()->getTrackDir().c_str());
    PHYSFS_mkdir(m_file_name.c_str());

    path p = Editor::getEditor()->getTrackDir() + m_file_name;

    CMeshBuffer<S3DVertex2TCoords>* mb = m_terrain->build(p);
    SMesh smesh;
    smesh.addMeshBuffer(mb);

    for (u32 i = 1; i < m_roads.size(); i++)
    {
        IRoad* r = m_roads[i];
        if (r->getSpline()->getPointNum()>1)
            smesh.addMeshBuffer(((Road*)r)->getMeshBuffer());
    }

    B3DMeshWriter* writer = new B3DMeshWriter(device->getFileSystem());
    IWriteFile *file;
    file = device->getFileSystem()->createAndWriteFile((p + "/track.b3d").c_str());
    writer->writeMesh(file, &smesh);
    file->drop();
    delete writer;

    m_driveline->build(p);

    std::ofstream mat;
    mat.open((p + "/materials.xml").c_str());
    mat << "<materials>\n";
    mat << "  <material name=\"splatt.png\" shader=\"splatting\"";
    SMaterial m = m_terrain->getMaterial(0);
    for (int i = 1; i < 5; i++)
    {
        mat << " splatting-texture-" << i << "=\"";
        mat << Editor::toRelative(m.getTexture(i+1)->getName()).c_str();
        mat << "\"";
    }
    mat << "/>\n";

    if (m_gravity_road)
    {
        for (u32 i = 1; i < m_roads.size(); i++)
        {
            stringc tex = m_roads[i]->getTexName();
            if (tex.size()>0)
            {
                mat << "  <material name=\"";
                mat << tex.c_str();
                mat << "\" has-gravity=\"yes\" />\n";
            }
        } // roads
    } // gravity road mode

    mat <<"</materials>\n";
    mat.close();

    stringw track;
    track += "<track  name           = \"";
    track += m_track_name + L"\"\n";
    track += "        version        = \"6\"\n";
    track += "        groups         = \"made-by-STK-TE\"\n";
    track += "        designer       = \"";
    track += m_designer + "\"\n";
    track += "        music          = \"";
    track += m_music.c_str();
    track += "\"\n";
    track += "        screenshot     = \"screenshot.jpg\"\n";
    track += "        smooth-normals = \"true\"\n";
    track += "        default-number-of-laps = \"3\"\n";
    track += "        reverse        = \"Y\"\n";
    track += "        bloom          = \"Y\"\n";
    track += "        bloom-threshold = \"0.75\"\n";
    track += "        clouds         = \"N\"\n";
    track += "        shadows        = \"Y\"\n>\n";
    track += "</track>\n";

    PHYSFS_uint64 len = 4 * track.size();
    char*         dst = new char[len];
#if defined(_WIN32) || defined(WIN32)
    PHYSFS_utf8FromUcs2((PHYSFS_uint16*)track.c_str(),dst,len);
#else
    PHYSFS_utf8FromUcs4((PHYSFS_uint32*)track.c_str(), dst, len);
#endif

    FILE* f;
    f = fopen((p + "/track.xml").c_str(), "wb");
    fwrite(dst, sizeof(char), strlen(dst), f);
    fclose(f);
    delete[] dst;


    std::ofstream scene;
    scene.open((p + "/scene.xml").c_str());
    scene << "<scene>\n";
    scene << "  <track model=\"track.b3d\" x=\"0\" y=\"0\" z=\"0\">\n";

    exportElements(scene, true);
    scene << "  </track>\n";
    exportElements(scene, false);


    ISceneManager* sm = Editor::getEditor()->getSceneManager();
    ISceneNode* node;
    int i = 1;
    stringc name;
    while ((node = sm->getSceneNodeFromId(MAGIC_NUMBER + i)))
    {
        name = node->getName();
        vector3df pos;
        if (node->isVisible() && (name == "banana" || name == "item"
            || name == "small-nitro" || name == "big-nitro"))
        {
            pos = node->getPosition();
            scene << "  <" << name.c_str() << " x=\"" << pos.X << "\" y=\"" << pos.Y
                  << "\" z=\"" << pos.Z << "\" />\n";
        }
        i++;
    }

    scene << Viewport::get()->getSky()->getXmlString().c_str();

    Viewport::get()->printCheckLine(&scene);

    scene << "  <default-start   karts-per-row = \"3\"\n";
    scene << "                   forwards-distance =\"1.50\"\n";
    scene << "                   sidewards-distance=\"3.00\"\n";
    scene << "                   upwards-distance  =\"0.10\"/>\n";

    scene << "</scene>\n";
    scene.close();

    MsgWndw::get()->showMsg(_("Track exported!"));

} // build
示例#10
0
Data::Data(Framework &fw, std::vector<UString> paths, int imageCacheSize, int imageSetCacheSize,
           int voxelCacheSize)
{
	for (auto &imageBackend : *registeredImageBackends)
	{
		auto t = imageBackend.first;
		ImageLoader *l = imageBackend.second->create();
		if (l)
		{
			this->imageLoaders.emplace_back(l);
			LogInfo("Initialised image loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load image loader %s", t.c_str());
	}

	for (auto &sampleBackend : *registeredSampleLoaders)
	{
		auto t = sampleBackend.first;
		SampleLoader *s = sampleBackend.second->create(fw);
		if (s)
		{
			this->sampleLoaders.emplace_back(s);
			LogInfo("Initialised sample loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load sample loader %s", t.c_str());
	}

	for (auto &musicLoader : *registeredMusicLoaders)
	{
		auto t = musicLoader.first;
		MusicLoader *m = musicLoader.second->create(fw);
		if (m)
		{
			this->musicLoaders.emplace_back(m);
			LogInfo("Initialised music loader %s", t.c_str());
		}
		else
			LogWarning("Failed to load music loader %s", t.c_str());
	}
	this->writeDir = PHYSFS_getPrefDir(PROGRAM_ORGANISATION, PROGRAM_NAME);
	LogInfo("Setting write directory to \"%s\"", this->writeDir.c_str());
	PHYSFS_setWriteDir(this->writeDir.c_str());
	for (int i = 0; i < imageCacheSize; i++)
		pinnedImages.push(nullptr);
	for (int i = 0; i < imageSetCacheSize; i++)
		pinnedImageSets.push(nullptr);
	for (int i = 0; i < voxelCacheSize; i++)
		pinnedLOFVoxels.push(nullptr);

	// 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.c_str(), "/", 0))
		{
			LogWarning("Failed to add resource dir \"%s\"", p.c_str());
			continue;
		}
		else
			LogInfo("Resource dir \"%s\" mounted to \"%s\"", p.c_str(),
			        PHYSFS_getMountPoint(p.c_str()));
	}
	// Finally, the write directory trumps all
	PHYSFS_mount(this->writeDir.c_str(), "/", 0);
}
示例#11
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;
}
 void setWriteDir(const std::string& dir)
 {
   if (!PHYSFS_setWriteDir(dir.c_str()))
     throw Exception(PHYSFS_getLastError());
 }
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... */
    const 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 */
}