Ejemplo n.º 1
0
bool vfs::CVirtualFileSystem::removeFileFromFS(vfs::Path const& sFilePath)
{
	vfs::Path sPath,sFile;
	sFilePath.splitLast(sPath,sFile);
	vfs::CVirtualProfile *pProf = m_oProfileStack.getWriteProfile();
	if(pProf)
	{
		vfs::IBaseLocation *pBL = pProf->getLocation(sPath);
		if(pBL && pBL->implementsWritable())
		{
			vfs::TDirectory<vfs::IWritable> *pDir = dynamic_cast<vfs::TDirectory<vfs::IWritable>*>(pBL);
			if(pDir)
			{
				bool bSuccess = false;
				// remove file from virtual structures first
				vfs::IBaseFile* file = pDir->getFile(sFilePath);
				if(file)
				{
					vfs::Path sDir,sFile;
					sFilePath.splitLast(sDir,sFile);
					vfs::CVirtualLocation *pVLoc = this->getVirtualLocation(sDir);
					if(pVLoc)
					{
						bSuccess = pVLoc->removeFile(file);
					}
				}
				// delete actual file
				return bSuccess && pDir->deleteFileFromDirectory(sFilePath);
			}
		}
	}
	return false;
}
Ejemplo n.º 2
0
void vfs::Path::splitFirst(vfs::Path &rsFirst, vfs::Path &rsTail) const
{
	pathSplitFirst(_path, rsFirst._path, rsTail._path, _sep.first, _sep.last);
	getFirstLastSeparator(rsFirst.c_str(), rsFirst._sep.first, rsFirst._sep.last);
	getFirstLastSeparator(rsTail.c_str(), rsTail._sep.first, rsTail._sep.last);
	// no need to check, as the original path is already checked
	//rPath.doCheck();
	//rFile.doCheck();
}
Ejemplo n.º 3
0
/**
 * Downloads a single file from the specified server.
 */
bool GetOneFile(
  const launcher::Settings &settings,
  const std::string &filename, const Signature crc) {

  Trace("Attempting to download " << filename);

  core::net::NetClient client(core::net::eConnectionMode::TCP_ASYNC);
  std::string hostName;
  for (auto server = settings.get_patch_server_begin(); server != settings.get_patch_server_end(); ++server) {
    client.start(settings.get_patch_server(0));
    if (client.valid()) {
      hostName = wrappers::net::http::Uri(server->get_dns_name()).getHost();
      break;
    }
  }

  if (!client.valid()) {
    Log(LL::Error) << "Unable to connect to any servers." << std::endl;
    return false;
  }

  wrappers::net::http::HttpHeader header = wrappers::net::http::HttpHeader::Builder()
      .setRequestType(wrappers::net::http::HttpHeader::eRequestType::HTTP_REQUEST_GET)
      .setRequestPath(std::string("/") + settings.get_server_patch_dir() + filename)
      .addHeader("host", hostName)
      .build();

  if (!header.valid()) {
    return false;
  }
  client.send(header.asBlob());

  const vfs::Path outputPath = GetOutputPath(filename);
  vfs::ofstream outfile(outputPath, std::ios::binary | std::ios::out);
  if (!outfile.is_open()) {
    Log(LL::Error) << "Unable to open file: " << outputPath.str() << std::endl;
    return false;
  }
  wrappers::net::http::HttpFileHandler fileHandler(outfile);
  while (client.valid() && !fileHandler.done()) {
    client.update(fileHandler);
    core::thread::thisthread::yield();
  }
  client.stop();
  outfile.flush();

  if (!fileHandler.success()) {
    return false;
  }

  return CheckSignature(outputPath, crc);
}
Ejemplo n.º 4
0
IniFilePtr IniFile::ConstructFromFile(vfs::Path filename)
{
	// Start parsing
	std::ifstream iniFile(filename.toString().c_str());

	if (!iniFile)
	{
		Logger::warning( "[IniFile]: Cannot open file " + filename.toString() );
		return IniFilePtr();
	}

	return ConstructFromStream(iniFile);
}
Ejemplo n.º 5
0
void IniFile::ExportToFile(vfs::Path file, const std::string& headerComments) const
{
	std::ofstream stream(file.toString().c_str());

	if (!headerComments.empty())
	{
		// Split the header text into lines and export it as INI comment
		std::vector<std::string> lines = StringHelper::split( headerComments, "\n" );

		for (std::size_t i = 0; i < lines.size(); ++i)
		{
			stream << "# " << lines[i] << std::endl;
		}

		// add some additional line break after the header
		stream << std::endl;
	}

	for (Sections::const_iterator i = _settings.begin(); i != _settings.end(); ++i)
	{
		stream << "[" << i->first << "]" << std::endl;

		for (Options::const_iterator kv = i->second.begin(); kv != i->second.end(); ++kv)
		{
			stream << kv->key << " = " << kv->value << std::endl;
		}
		
		stream << std::endl;
	}
}
Ejemplo n.º 6
0
VariantMap SaveAdapter::load( const vfs::Path& filename )
{
  Logger::warning( "SaveAdapter: try load model from " + filename.toString() );
  NFile f = NFile::open( filename );

  return load( f );
}
Ejemplo n.º 7
0
bool vfs::CVirtualFileSystem::createNewFile(vfs::Path const& sFilename)
{
	vfs::Path sPath,sFile;
	sFilename.splitLast(sPath,sFile);
	vfs::CVirtualProfile *pProf = m_oProfileStack.getWriteProfile();
	if(pProf)
	{
		bool bIsExclusive = false;
		bool bNewLocation = false;
		vfs::IBaseLocation *pProfLoc = pProf->getLocation(sPath);
		if(!pProfLoc)
		{
			// try to find closest match
			vfs::Path sTemp, sCreateDir, sRight, sLeft = sPath;
			while(!pProfLoc && !sLeft.empty())
			{
				sLeft.splitLast(sTemp,sRight);
				sLeft = sTemp;
				sCreateDir = sRight + sCreateDir;
				pProfLoc = pProf->getLocation(sLeft);
			}
			// see if the closest match is exclusive
			// if yes, then the the new path is a subdirectory and has to be exclusive too
			vfs::CVirtualLocation *pVLoc = this->getVirtualLocation(sLeft,true);
			if(pVLoc)
			{
				bIsExclusive = pVLoc->getIsExclusive();
			}
			//else
			//{
			//	VFS_THROW(L"location (closest match) should exist");
			//}
			bNewLocation = true;
		}
		if(pProfLoc && pProfLoc->implementsWritable())
		{
			// create file and add to location
			vfs::TDirectory<vfs::IWritable> *pDir = dynamic_cast<vfs::TDirectory<vfs::IWritable>*>(pProfLoc);
			vfs::IBaseFile* pFile = pDir->addFile(sFilename);
			if(bNewLocation)
			{
				pProf->addLocation(pProfLoc);
			}
			if(pFile)
			{
				CVirtualLocation* pLoc = this->getVirtualLocation(sPath,true);
				if(bIsExclusive)
				{
					pLoc->setIsExclusive(bIsExclusive);
				}
				pLoc->addFile(pFile,pProf->cName);
				return true;
			}
		}
	}
	// throw ?
	return false;
}
Ejemplo n.º 8
0
bool Addon::open(vfs::Path path)
{
# ifdef CAESARIA_PLATFORM_WIN
  _d->library = ::LoadLibraryA(path.toString().c_str());
# else
  _d->library = ::dlopen(path.toString().c_str(), RTLD_LAZY);
# endif

  if( _d->library != 0 )
  {
    _d->isOpened = true;
    _d->funcInit = _d->initFunction<addonInitFunctor>( "initialize" );
    _d->funcGetVersion = _d->initFunction<addonGetVersionFunctor>( "getVersion" );
    _d->funcGetLevel = _d->initFunction<addonGetLevelFunctor>( "getLevel" );
  }

  return _d->isOpened;
}
Ejemplo n.º 9
0
void PictureBank::Impl::loadAtlas(const vfs::Path& filePath)
{
  if( !filePath.exist() )
  {
    Logger::warning( "PictureBank: cant find atlas " + filePath.toString() );
    return;
  }

  VariantMap info = config::load( filePath );

  vfs::Path texturePath = info.get( "texture" ).toString();

  vfs::NFile file = vfs::NFile::open( texturePath );

  Picture mainTexture;
  if( file.isOpen() )
  {
    mainTexture = PictureLoader::instance().load( file );
  }
  else
  {
    Logger::warning( "PictureBank: load atlas failed for texture" + texturePath.toString() );
    mainTexture = Picture::getInvalid();
  }

  //SizeF mainRectSize = mainTexture.size().toSizeF();
  if( !info.empty() )
  {
    VariantMap items = info.get( framesSection ).toMap();
    for( auto& i : items )
    {
      VariantList rInfo = i.second.toList();
      Picture pic = mainTexture;
      Point start( rInfo.get( 0 ).toInt(), rInfo.get( 1 ).toInt() );
      Size size( rInfo.get( 2 ).toInt(), rInfo.get( 3 ).toInt() );

      pic.setOriginRect( Rect( start, size ) );
      setPicture( i.first, pic );
    }
  }
}
Ejemplo n.º 10
0
/**
 * @return true if the {@code crc} is 0, or matches the computed CRC of the file
 */
bool CheckSignature(const vfs::Path &filePath, const Signature crc) {
  Trace("Checking signature matches [" << crc << "] for file " << filePath.str());
  vfs::ifstream infile(filePath, std::ios::binary | std::ios::in);
  if (!infile.is_open()) {
    return false;
  }
  const Signature downloadCrc = core::hash::CRC32(
                                  std::istreambuf_iterator<char>(infile.rdbuf()),
                                  std::istreambuf_iterator<char>());
  Trace("Crc was: " << downloadCrc);
  return (crc == 0 || crc == downloadCrc);
}
Ejemplo n.º 11
0
UpdateController::UpdateController(IUpdateView& view, vfs::Path executableName, UpdaterOptions& options) :
	_view(view),
	_curStep(Init),
	_updater(options, executableName.baseName()),
	_abortFlag(false),
	_differentialUpdatePerformed(false)
{
	_progress = ProgressHandlerPtr( new ProgressHandler(_view) );
	_progress->drop();

	_updater.SetDownloadProgressCallback( ptr_cast<Updater::DownloadProgress>( _progress ));
	_updater.SetFileOperationProgressCallback( ptr_cast<Updater::FileOperationProgress>( _progress ));
}
Ejemplo n.º 12
0
int BmFontUtil::main() {
  g_inputFile.checkSet();
  g_outputFile.checkSet();

  vfs::Mount("./", "./", std::ios::in | std::ios::out | std::ios::binary);

  const vfs::Path filename(g_inputFile.get());
  const vfs::Path rootPath(filename.dir());

  std::string content;
  if (!appshared::parseFileToString(filename, content)) {
    Log(LL::Error) << "Unable to open input font set: " << g_inputFile.get() << std::endl;
    return eExitCode::BAD_FILE;
  }

  XmlNode doc;
  if (!doc.parse(content)) {
    Log(LL::Error) << "Unable to parse XML document." << std::endl;
    return eExitCode::BAD_DATA;
  }

  u32 nodeIndex;
  if (!doc.getChild("font", nodeIndex)) {
    Log(LL::Error) << "XML is not a valid font file. Missing top level 'font' node." << std::endl;
    return eExitCode::BAD_DATA;
  }

  FontDef def;
  if (!ParseDocument(def, rootPath, doc.getChild(nodeIndex), g_exportAsDistanceFont.get())) {
    return eExitCode::BAD_DATA;
  }

  if (!appshared::serializeProtoToFile(vfs::Path(g_outputFile.get()), def)) {
    Log(LL::Error) << "Unable to write output." << std::endl;
    return eExitCode::EXCEPTION;
  }
  return eExitCode::OK;
}
Ejemplo n.º 13
0
vfs::CVirtualFileSystem::CMatchingIterator::CMatchingIterator(vfs::Path const& sPattern, vfs::CVirtualFileSystem* pVFS)
: tBaseClass(), m_VFS(pVFS)
{
	if(sPattern() == vfs::Const::STAR())
	{
		m_sLocPattern =  vfs::Path(vfs::Const::STAR());
		m_sFilePattern = vfs::Path(vfs::Const::STAR());
	}
	else
	{
		sPattern.splitLast(m_sLocPattern,m_sFilePattern);
	}

	_vloc_iter = m_VFS->m_mapFS.begin();
	while(_vloc_iter != m_VFS->m_mapFS.end())
	{
		if( matchPattern(m_sLocPattern(),_vloc_iter->second->cPath()) )
		{
			bool bExclusiveVLoc = _vloc_iter->second->getIsExclusive();
			_vfile_iter = _vloc_iter->second->iterate();
			while(!_vfile_iter.end())
			{
				vfs::IBaseFile* pFile = NULL;
				if(bExclusiveVLoc)
				{
					pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_STOP_ON_WRITABLE_PROFILE);
				}
				else
				{
					pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_TOP);
				}
				if(pFile)
				{
					vfs::Path const& filename = pFile->getName();
					if( matchPattern(m_sFilePattern(),filename()) )
					{
						return;
					}
				}
				_vfile_iter.next();
			}
		}
		_vloc_iter++;
	}
}
Ejemplo n.º 14
0
void FontCollection::addFont(const int key, const std::string& name, vfs::Path pathFont, const int size, const NColor& color )
{
  TTF_Font* ttf = TTF_OpenFont(pathFont.toCString(), size);
  if( ttf == NULL )
  {
    std::string errorStr( TTF_GetError() );
#ifdef CAESARIA_PLATFORM_WIN
    errorStr += "\n Is it only latin symbols in path to game?";
#endif
    OSystem::error( "CRITICAL!!! ", errorStr );
    THROW( errorStr );
  }

  Font font0;
  font0._d->ttfFont = ttf;

  SDL_Color c = { color.red(), color.green(), color.blue(), color.alpha() };
  font0._d->color = c;
  setFont( key, name, font0);
}
Ejemplo n.º 15
0
void Saver::save(const vfs::Path& filename, const Game& game )
{
  VariantMap vm;
  vm[ SaverOptions::version ] = 1;
  vm[ "timemultiplier" ] = game.timeMultiplier();

  VariantMap vm_scenario;
  vm_scenario[ "date" ] = game::Date::current();
  vm_scenario[ "events" ] = events::Dispatcher::instance().save();
  vm_scenario[ "translation" ] = SETTINGS_VALUE( lastTranslation );
  vm_scenario[ "climate" ] = (int)game.city()->climate();

  vm[ "scenario" ] = vm_scenario;
  vm[ SaverOptions::restartFile ] = Variant( _restartFile );

  VariantMap vm_empire;
  game.empire()->save( vm_empire );
  vm[ "empire" ] = vm_empire;

  VariantMap plm;
  game.player()->save( plm );
  vm[ "player" ] = plm;

  VariantMap vm_city;
  game.city()->save( vm_city );
  vm[ "city" ] = vm_city;

  VariantMap vm_pantheon;
  religion::rome::Pantheon::instance().save( vm_pantheon );
  vm[ "pantheon" ] = vm_pantheon;

  gui::Minimap* minimap = gui::findChildA<gui::Minimap*>( true, game.gui()->rootWidget() );
  if( minimap )
  {
    vfs::Path imgPath = filename.changeExtension( "png" );
    minimap->saveImage( imgPath.toString() );
  }

  config::save( vm, filename );
}
Ejemplo n.º 16
0
void PictureInfoBank::initialize(vfs::Path filename)
{
  Logger::warning( "PictureInfoBank: start load offsets from " + filename.toString() );
  VariantMap m = config::load( filename );

  foreach( it, m )
  {
    Variant v = it->second;
    Logger::warning( "Set offset for " + it->first );
    if( v.type() == Variant::Map )
    {
      VariantMap vm = v.toMap();
      int startIndex = vm[ "start" ];
      int stopIndex = vm[ "stop" ];
      std::string rc = vm[ "rc" ].toString();
      Point offset = vm[ "offset" ].toPoint();
      _d->setRange( rc.empty() ? it->first : rc, startIndex, stopIndex, offset );
    }
    else if( v.type() == Variant::List )
    {
      VariantList vl = v.toList();
      _d->setOne( it->first, vl.get( idxIndex ), vl.get( idxXOffset ), vl.get( idxYOffset ) );
    }
  }
Ejemplo n.º 17
0
bool operator==(vfs::Path const& p1, const vfs::String::char_t* p2)
{
	return vfs::StrCmp::Equal(p1.c_str(), p2);
}
Ejemplo n.º 18
0
bool operator==(vfs::Path const& p1, vfs::String::str_t const& p2)
{
	return vfs::StrCmp::Equal(p1.c_str(), p2);
}
Ejemplo n.º 19
0
void Game::Impl::initFontCollection( vfs::Path resourcePath )
{
    Logger::warning( "Game: load fonts" );
    std::string fontname = SETTINGS_STR( font );
    FontCollection::instance().initialize( resourcePath.toString(), fontname );
}
Ejemplo n.º 20
0
iResourceLoader::eLoadState::type FontFromFile::postload() {
  if (m_fontDef.get_texture_size() == 0) {
    Log(LL::Error) << "Font has no textures in it." << std::endl;
    return eLoadState::LOAD_FAILURE;
  }

  // Load material
  if (!m_material.getHandle().isValid()) {
    MaterialDef::Builder materialBuilder;

    // Create temp textures
    for (u32 i = 0; i < m_fontDef.get_texture_size(); ++i) {
      const vfs::Path filename = vfs::Path("memfile/")
                                 + vfs::Path(vfs::Path(m_fontDef.get_texture(i).get_filename()).file());
      const std::string &data = m_fontDef.get_texture(i).get_image_data();

      vfs::getStaticMemFileSystem()->create(filename, core::memory::ConstBlob((const u8 *) data.data(), data.size()));
      materialBuilder.add_textures(filename.str());
    }

    if (m_fontDef.get_texture(0).get_is_distancefield()) {
      materialBuilder.set_alpha_test(fsengine::render::eAlphaTestMode::ALPHA_TEST_GEQUAL);
      materialBuilder.set_alpha_cutoff(0.5f);
      materialBuilder.set_blend_mode(fsengine::render::eBlendMode::BLEND_NONE);
      materialBuilder.set_name("font");
      materialBuilder.set_shader("data/shaders/tex0cutoffcolor");
    } else {
      materialBuilder.set_blend_mode(fsengine::render::eBlendMode::BLEND_NORMAL);
      materialBuilder.set_name("font");
      materialBuilder.set_shader("data/shaders/tex0color");
    }

    {
      const MaterialDef materialDef = materialBuilder.build();
      const vfs::Path filename = vfs::Path("memfile/")
                                 + vfs::Path(vfs::Path(m_id + "_mat").file());
      const size_t sz = materialDef.byte_size();
      m_materialData.resize(sz, ' ');
      core::memory::Blob blob((u8 *) &m_materialData[0], sz);
      core::base::BlobSink sink(blob);
      sink << materialBuilder.build();
      vfs::getStaticMemFileSystem()->create(filename, core::memory::ConstBlob((const u8 *) m_materialData.data(), m_materialData.size()));
      m_material = m_pLoader->asyncLoadResource<Material, MaterialFromFile>(filename.str());
    }
  }

  if (!m_material) {
    if (m_material.getManager()->isValidOrLocked(m_material.getHandle())) {
      return eLoadState::LOAD_DEPENDENCY;
    } else {
      return eLoadState::LOAD_FAILURE;
    }
  }

  // Create font
  if (!m_pResource->loadFromDef(m_fontDef)) {
    return eLoadState::LOAD_FAILURE;
  }

  // cleanup
  for (u32 i = 0; i < m_fontDef.get_texture_size(); ++i) {
    m_pResource->setTexture(i, m_material->m_pTexture[i]);

    const vfs::Path filename = vfs::Path("memfile/")
                               + vfs::Path(vfs::Path(m_fontDef.get_texture(i).get_filename()).file());
    vfs::util::Remove(filename);
  }
  const vfs::Path filename = vfs::Path("memfile/")
                             + vfs::Path(vfs::Path(m_id + "_mat").file());
  vfs::util::Remove(filename);

  m_pResource->setMaterial(m_material);

  return eLoadState::LOAD_SUCCESS;
}
Ejemplo n.º 21
0
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".tga")
bool PictureLoaderPng::isALoadableFileExtension(const vfs::Path& filename) const
{
    return filename.isMyExtension( ".png" );
}