Example #1
0
// saves the currently loaded map to a file
void EditableMap::save(char *filename)
{
	std::ofstream mapFile(getResourcePath(filename));

	std::cout << "Saving the map index \"" << filename << "\" ... ";

	// verify that the file was opened correctly before reading
	if(mapFile.bad())
	{
		std::cout << "FAILED!\n";
		return;
	}

	// sets the width and height of the map
	mapFile << w << "\n";
	mapFile << h << "\n";

	// write the information about every tile on the map
	for(int i=0;i<w;i++)
	{
		for(int j=0;j<h;j++)
		{
			mapFile << ts[i][j].b << " " << ts[i][j].f << " " << ((ts[i][j].isWalkable)?"Y":"N") << "\n";
		}
	}
	mapFile.close();
	std::cout << "Successful!\n";
}
Example #2
0
    bool AnimatedPicture::addFrame(const std::string& filename, sf::Time frameDuration)
    {
        // Check if the filename is empty
        if (filename.empty())
            return false;

        Texture tempTexture;

        // Try to load the texture from the file
        if (TGUI_TextureManager.getTexture(getResourcePath() + filename, tempTexture))
        {
            // If this is the first frame then set it as the current displayed frame
            if (m_Textures.empty())
            {
                m_CurrentFrame = 0;

                // Remember the size of this image
                m_Size = sf::Vector2f(tempTexture.getSize());
            }

            // Add the texture
            tempTexture.sprite.setColor(sf::Color(255, 255, 255, m_Opacity));
            m_Textures.push_back(tempTexture);

            // Store the frame duration
            m_FrameDuration.push_back(frameDuration);

            // Return true to indicate that nothing went wrong
            return m_Loaded = true;
        }
        else // The texture was not loaded
            return m_Loaded = false;
    }
Example #3
0
//constructor
Menu::Menu(SDL_Window *sentWindow){
  	window = sentWindow;

  	//creates the renderer to be used
  	ren = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  	if (ren == nullptr){
    	SDL_DestroyWindow(window);
	    std::cout << "SDL_CreateMenuRenderer Error: " << SDL_GetError() << std::endl;
	    SDL_Quit();
  	}

  	//creates the menu's textures
  	const string menuPath = getResourcePath("magicworm") + "menu.bmp";
  	SDL_Surface *bmp = SDL_LoadBMP(menuPath.c_str());
  	if (bmp == nullptr){
    	SDL_DestroyRenderer(ren);
    	SDL_DestroyWindow(window);
    	std::cout << "SDL_LoadMenuBMP Error: " << SDL_GetError() << std::endl;
    	SDL_Quit();
  	}

  	menTex = SDL_CreateTextureFromSurface(ren, bmp);
  	SDL_FreeSurface(bmp);
  	if (menTex == nullptr){
  	  	SDL_DestroyRenderer(ren);
  	  	SDL_DestroyWindow(window);
  	  	std::cout << "SDL_CreateMenuTextureFromSurface Error: " << SDL_GetError() << std::endl;
  	  	SDL_Quit();
  	}

  	mainMenu();
}
Example #4
0
void ReplayBuilder::copyReplayResource(const char *resource,
                                       const char *targetDir) {
  FileManager fileManager;
  char *localResource = new char[strlen(resource) + 1];
  strcpy(localResource, resource);
  fileManager.fixSlashes(localResource);
  char *filename = fileManager.parseFilename(localResource);
  delete localResource;
  char *targetPath = fileManager.getFilePath(targetDir, filename);
  delete filename;

  if (!fileManager.fileExists(targetPath)) {
    char *resourcePath = getResourcePath(resource);
    if (resourcePath != 0) {
      char *s = 0;
      try {
        s = fileManager.readFile(resourcePath);
      } catch (FileNotFoundException *e) {
        delete e;
      }
      
      if (s != 0) {
        fileManager.writeFile(targetPath, s);
        delete s;
      }
      delete resourcePath;
    }
  }
  delete targetPath;
}
Example #5
0
/** Searches all help pages for the phrase the Search box.
 *  Fills treeSearch with documents containing matches and sets the
 *  status bar text appropriately.
 */
void
HelpBrowser::search()
{
  /* Clear the list */
  ui.treeSearch->clear();
  
  /* Don't search if invalid document or blank search phrase */
  if (ui.lineSearch->text().isEmpty()) {
    return;
  }
    
  HelpTextBrowser browser;
  QTextCursor found;
  QTextDocument::FindFlags flags = QTextDocument::FindWholeWords;

  _lastSearch = ui.lineSearch->text();

  /* Search through all the pages looking for the phrase */
  for (int i=0; i < _elementList.size(); ++i) {
    /* Load page data into browser */
    browser.setSource(QUrl(getResourcePath(_elementList[i])));
      
    /* Search current document */
    found = browser.document()->find(ui.lineSearch->text(), 0, flags);

    /* If found, add page to tree */
    if (!found.isNull()) {
      ui.treeSearch->addTopLevelItem(createTopicTreeItem(_elementList[i], 0));
    }
  }

  /* Set the status bar text */
  this->statusBar()->showMessage(tr("Found %1 results")
                                .arg(ui.treeSearch->topLevelItemCount()));
}
Example #6
0
int main()
{
  if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
    std::cout << "SDL_Init ERROR: " << SDL_GetError() << std::endl;
    return 1;
  }
  std::cout << "Resource path is: " << getResourcePath() << std::endl;

  SDL_Window *win = SDL_CreateWindow("Hello World", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
  if (win == nullptr){
    std::cout << "SDL_CreatingWindow Error: " << SDL_GetError() << std::endl;
    SDL_Quit();
    return 1;
  }

  SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (ren == nullptr){
    cleanup(win);
    std::cout << "SDL_CreateRendere Error: " << SDL_GetError() << std::endl;
    SDL_Quit();
    return 1;
  } 

  SDL_Quit();
  return 0;
}
Example #7
0
	void TheGame::initScripting()
	{
		GameScript::setResourcePath(getResourcePath());
		GameScript::setAssetManager(assets);
		GameScript::setClock(gameTime);
		GameScript::setWindow(window);
		GameScript::setSettings(gameSettings);
	}
Example #8
0
    void Picture::setTexture(const sf::String& filename, bool fullyClickable)
    {
        m_fullyClickable = fullyClickable;
        m_loadedFilename = getResourcePath() + filename;

        m_texture.load(m_loadedFilename);
        m_texture.setSize(getSize());
    }
void AudioMeteringDemo::initialize()
{
    m_timeSinceLastClip = 0;
    m_waveBankHandle = kwlWaveBankLoad(getResourcePath("music.kwb"));
    m_eventHandle = kwlEventGetHandle("music/music_stereo_ogg");
    m_timeSinceLastClip = 100000;
    kwlEventStart(m_eventHandle);
}
Example #10
0
bool ezCursor::loadImage()
{
    
    if(img.loadFromFile(getResourcePath(1)+"pointer.bmp"))
        return true;
   
    return false;
}
Example #11
0
void ResourceWeb::showResource()
{
	Logger::getInstance()->writeToFile("ResourceWeb::~showResource");
	QString path = getResourcePath();
	if (path.isEmpty())
		path = "https://www.qt.io";
	mWebView.load(QUrl(path));
	mWebView.show();
}
Example #12
0
	void TheGame::loadAssets()
	{
		assets.loadResourceFolder(getResourcePath() / "anims");
		assets.loadResourceFolder(getResourcePath() / "dicts");
		assets.loadResourceFolder(getResourcePath() / "fonts");
		assets.loadResourceFolder(getResourcePath() / "maps");
		assets.loadResourceFolder(getResourcePath() / "music");
		assets.loadResourceFolder(getResourcePath() / "scripts");
		assets.loadResourceFolder(getResourcePath() / "sounds");
		assets.loadResourceFolder(getResourcePath() / "textures");
		assets.loadMods(getResourcePath() / "../mods");

		// make log file a little prettier
		swift::Logger::get() << '\n';
	}
Example #13
0
void Map::parseIndex(char *filename)
{
	int mapW, mapH, newF, newB;
	char newW;

	std::ifstream mapFile(getResourcePath(filename));

	std::cout << "Opening map index \"" << filename << "\" ... ";

	// verify that the file was opened correctly before reading 
	if(mapFile.bad()) 
	{ 
		std::cout << "FAILED!\n";
		return; 
	}
	std::cout << "Successful!\n";

	// get the width and height of the map (according to its index)
	mapFile >> mapW;
	mapFile >> mapH;

	w = mapW;
	h = mapH;

	// check if the bounding window is larger than the map
	if(limitWTiles > w)
		limitWTiles = w;
	if(limitHTiles > h)
		limitHTiles = h;


	// initialize 2D array of tiles which will represent the map
	ts = new Tile*[mapW];
	for (int k = 0; k < mapW; k++)
		ts[k] = new Tile[mapH];


	std::cout << "Initializing map, W: "<<mapW<<" tiles, H: "<< mapH <<" tiles ... ";

	// read the input index file, initializing the tiles
	for(int i=0;i<w;i++)
	{
		for(int j=0;j<h;j++)
		{
			mapFile >> newB;
			mapFile >> newF;
			mapFile >> newW;

			ts[i][j].b = newB;
			ts[i][j].f = newF;
			ts[i][j].isWalkable = (newW=='Y')?true:false;
		}
	}
	mapFile.close();
	std::cout << "Successful!\n";
}
Example #14
0
	Game::Game(const std::string& t, unsigned tps)
	:	running(false),
		fullscreen(false),
		verticalSync(false),
		resolution({800, 600}),
		title(t),
		ticksPerSecond(tps)
	{
		getResourcePath();
	}
Example #15
0
/** Creates a new element to be inserted into the topic tree. */
QTreeWidgetItem*
HelpBrowser::createTopicTreeItem(const QDomElement &topicElement, 
                                 QTreeWidgetItem *parent)
{
  QTreeWidgetItem *topic = new QTreeWidgetItem(parent);
  topic->setText(0, topicElement.attribute(ATTRIBUTE_TOPIC_NAME));
  topic->setData(0, ROLE_TOPIC_ID, topicElement.attribute(ATTRIBUTE_TOPIC_ID));
  topic->setData(0, ROLE_TOPIC_QRC_PATH, getResourcePath(topicElement));
  return topic;
}
Example #16
0
	Path buildResourcePath( const string& filename )
	{
	  Path result = getResourcePath() / filename;

	  FILE *l_filecheck = fopen(result.string().c_str(), "r");
	  if (l_filecheck != NULL) fclose(l_filecheck);
	    else ASSERT(false, string("Couldn't find resource '"+ result.string() +"', does it exist in your resources directory? Is the spelling correct?").c_str());

	  return result;
	}
Example #17
0
void SampleClockDemo::initialize()
{
    m_frameCount = 0;
    m_waveBankHandle = 
        kwlWaveBankLoad(getResourcePath("music.kwb"));
    m_eventHandle = kwlEventGetHandle("music/la_romance_quoi_120bpm_loop");
    kwlEventStartFade(m_eventHandle, 3.0f);
    m_currentBeatIndex = 0;
    m_mixerPaused = false;
}
Example #18
0
int main (int argc,char** argv){
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0){
		std::cerr << "SDL init error" << SDL_GetError() << std::endl;
		return 1;
	}else{
		std::cout << "Inited" << std::endl;
	} 
	std::cout << "Ressource path is " << getResourcePath() << std::endl;
	SDL_Quit();
	return 0;
}
Example #19
0
int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    std::cout << "Resource path is: " << getResourcePath() << std::endl;

    SDL_Quit();
    return 0;
}
Example #20
0
	TheGame::TheGame(int argc, char** argv)
	:	Game("TheGame", 60),
		soundLevel(100),
		musicLevel(75)
	{
		// init Logger first
		swift::Logger::setFile(getResourcePath() / "TheGame.log");
		
		// get System Info
		swift::Logger::get()	<< "OS:\t\t" << swift::getOSName() << '\n'
								<< "Version:\t" << swift::getOSVersion() << '\n'
								<< "Arch:\t\t" << swift::getOSArch() << '\n'
								<< "Total Mem:\t" << swift::getTotalMem() << '\n'
								<< "CPU:\t\t" << swift::getCPUModel() << '\n'
								<< "Video Vendor:\t" << swift::getVideoVendor() << '\n'
								<< "Video Card:\t" << swift::getVideoCard() << '\n'
								<< "Video Driver:\t" << swift::getVideoDriver() << "\n\n";
		
		// get settings to initialize engine
		loadSettings(getResourcePath() / "settings.ini");
		
		// arguments override settings
		handleArgs(argc, argv);
		
		// get stuff so we can do stuff
		loadAssets();
		
		// gotta set this if you want any text to display
		defaultFont = assets.getFont("segoeuisl.ttf");
		
		//window.setIcon(SwiftEngineIcon.width, SwiftEngineIcon.height, SwiftEngineIcon.pixel_data);	// need to figure out icon stuff
		
		// can't do anything without state (well, in this case)
		initState();
		
		// scripting if you want it
		initScripting();
		
		// set saves directory for saving/loading
		swift::SaveManager::setResourcePath(getResourcePath());
	}
Example #21
0
bool Resource::Id::verifyPaths() const
{
	if (getResourcePath().empty()) {
//		DS_LOG_ERROR_M("resource_id (" << *this << ") missing resource path", ds::GENERAL_LOG);
		return false;
	}
	if (getDatabasePath().empty()) {
//		DS_LOG_ERROR_M("resource_id (" << *this << ") missing database path", ds::GENERAL_LOG);
		return false;
	}
	return true;
}
int NativeImageViewObject::setImage(TiObject* obj)
{
    QString imagePath;
    int error = NativeControlObject::getString(obj, imagePath);
    if (error != NATIVE_ERROR_OK)
    {
        return error;
    }

    imagePath = getResourcePath(imagePath);
    imageView_->setImage(QUrl(imagePath));
    return NATIVE_ERROR_OK;
}
Example #23
0
    void DefaultThemeLoader::readFile(const std::string& filename, std::stringstream& contents) const
    {
        std::string fullFilename = getResourcePath() + filename;

    #ifdef SFML_SYSTEM_ANDROID
        // If the file does not start with a slash then load it from the assets
        if (!fullFilename.empty() && (fullFilename[0] != '/'))
        {
            /// TODO: Workaround until SFML makes native activity publicly accessible
            /// When this happens, extra SFML folder in include can be removed as well.
            ANativeActivity* activity = sf::priv::getActivity(NULL)->activity;

            JNIEnv* env = 0;
            activity->vm->AttachCurrentThread(&env, NULL);
            jclass clazz = env->GetObjectClass(activity->clazz);

            jmethodID methodID = env->GetMethodID(clazz, "getAssets", "()Landroid/content/res/AssetManager;");
            jobject assetManagerObject = env->CallObjectMethod(activity->clazz, methodID);
            jobject globalAssetManagerRef = env->NewGlobalRef(assetManagerObject);
            AAssetManager* assetManager = AAssetManager_fromJava(env, globalAssetManagerRef);
            assert(assetManager);

            AAsset* asset = AAssetManager_open(assetManager, fullFilename.c_str(), AASSET_MODE_UNKNOWN);
            if (!asset)
                throw Exception{ "Failed to open theme file '" + fullFilename + "' from assets." };

            off_t assetLength = AAsset_getLength(asset);

            char* buffer = new char[assetLength + 1];
            AAsset_read(asset, buffer, assetLength);
            buffer[assetLength] = 0;

            contents << buffer;

            AAsset_close(asset);
            delete[] buffer;

            activity->vm->DetachCurrentThread();
        }
        else
    #endif
        {
            std::ifstream file{fullFilename};
            if (!file.is_open())
                throw Exception{ "Failed to open theme file '" + fullFilename + "'." };

            contents << file.rdbuf();
            file.close();
        }
    }
Example #24
0
void StartScreen::init()
{
	std::string musicPath = getResourcePath(MUSIC_INTRO);
	startMusic = Mix_LoadMUS(musicPath.c_str());
	musicStarted = false;

	background = loadImage(START_SCREEN_BACKDROP);

	//buttons
	btnStartGame = Rect(14*TILE_SIZE,18*TILE_SIZE,22*TILE_SIZE,3*TILE_SIZE);
	btnCreateNewLevel = Rect(14*TILE_SIZE,22*TILE_SIZE,22*TILE_SIZE,3*TILE_SIZE);
	btnEditLevel1 = Rect(17*TILE_SIZE,26*TILE_SIZE,16*TILE_SIZE,3*TILE_SIZE);
	btnEditLevel2 = Rect(17*TILE_SIZE,30*TILE_SIZE,16*TILE_SIZE,3*TILE_SIZE);
}
Example #25
0
EnemyProjectile::EnemyProjectile(sf::Vector2f position, 
								   sf::Vector2f velocity, Projectile::Direction direction, 
								   Player *p, Character *own) : Projectile(position, velocity, direction, own)
{
	player = p;
	if(!buffer.loadFromFile(getResourcePath("Assets/Sounds/")+"Enemy shoot.wav"))
	{
        std::cout << "ERROR unable to load sound Enemy shoot.wav in EnemyProjectile.cpp."<< std::endl;
    }
	fire.setBuffer(buffer);
	fire.play();
    range = own->stats["projectileRange"];
    damage = own->stats["projectileDamage"];
}
Example #26
0
// Format of saved replay file:
// | replay version
// | stage name length | stage name | stage width | stage height
// | num walls | <walls>
// | num zones | <zones>
// | num ships | <ship properties>
// | num ship adds | <ship adds>
// | num ship removes | <ship removes>
// | num ship show names | <show names>
// | num ship hide names | <hide names>
// | num ship show energys | <show energys>
// | num ship hide energys | <hide energys>
// | num ship ticks | <ship ticks>
// | num laser starts | <laser starts>
// | num laser ends | <laser ends>
// | num laser sparks | <laser sparks>
// | num torpedo starts | <torpedo starts>
// | num torpedo ends | <torpedo ends>
// | num torpedo blasts | <torpedo blasts>
// | num torpedo debris | <torpedo debris>
// | num ship destroys | <ship destroys>
// | num texts | <texts>
// | num log entries | <log entries>
// | num results | <results>
void ReplayBuilder::saveReplay(const char *dir, const char *filename) {
  // TODO: throw exceptions for failing to save replay, don't silently fail

  FileManager fileManager;
  char *replayTemplate = 0;
  char *templatePath = getResourcePath(REPLAY_TEMPLATE);
  if (templatePath != 0) {
    try {
      replayTemplate = fileManager.readFile(templatePath);
    } catch (FileNotFoundException *e) {
      delete e;
    }
    delete templatePath;
  }

  if (replayTemplate != 0) {
    copyReplayResource(KINETIC_JS, dir);
    copyReplayResource(BBREPLAY_JS, dir);

    std::string replayHtml(replayTemplate);
    std::string title = htmlTitle();
    size_t i;
    size_t len = strlen(REPLAY_TITLE_PLACEHOLDER);
    i = replayHtml.find(REPLAY_TITLE_PLACEHOLDER, 0);
    if (i != std::string::npos) {
      replayHtml.replace(i, len, htmlTitle());
    }

    len = strlen(REPLAY_DATA_PLACEHOLDER);
    i = replayHtml.find(REPLAY_DATA_PLACEHOLDER, 0);
    if (i != std::string::npos) {
      replayHtml.replace(i, len, buildReplayDataString());
    }

    len = strlen(EXTRA_JS_PLACEHOLDER);
    i = replayHtml.find(EXTRA_JS_PLACEHOLDER, 0);
    if (i != std::string::npos) {
      replayHtml.replace(i, len, extraJavascript_ == 0 ? "" : extraJavascript_);
    }

    char *filePath = fileManager.getFilePath(dir, filename);
    char *absFilename = fileManager.getAbsFilePath(filePath);
    delete filePath;
    fileManager.writeFile(absFilename, replayHtml.c_str());
    delete absFilename;
    delete replayTemplate;
  }
}
Example #27
0
    void AnimatedPicture::addFrame(const std::string& filename, sf::Time frameDuration)
    {
        // Try to load the texture from the file
        Texture tempTexture;
        tempTexture.load(getResourcePath() + filename);

        // If this is the first frame then set it as the current displayed frame
        if (m_textures.empty())
        {
            m_currentFrame = 0;

            // Remember the size of this image
            setSize(tempTexture.getSize());
        }

        // Add the texture and store its duration
        m_textures.push_back(tempTexture);
        m_frameDuration.push_back(frameDuration);
    }
Example #28
0
bool android_fcheck(const char* filename)
{
	bool ret = false;
	char* resPath = getResourcePath();
	if ( strstr(filename, (const char*)getResourcePath) )
	{
		if (access(filename, R_OK) == 0)
		{
			ret = true;
		}
		else
		{
			char name[128] = {0,};
			char temp[256] = {0,};
			char* p = NULL;
			const char* delim = "/";
			strcpy(temp, filename);
			p = strtok((char*)temp, delim);
			if (p) {
				strcpy(name, p);
			}
			while (p) {
				p = strtok(NULL, delim);
				if (p) {
					strcpy(name, p);
				}
			}

			if (fileCopy(name, filename)) {
				ret = true;
			} else {
				ret = false;
			}
		}
	}

	//LOGD("android_fcheck() filename: %s, ret: %x", filename, ret);

	return ret;
}
Example #29
0
bool CApp::OnInit() {
  // We don't HAVE to initialize everything, but it is convenient.
  if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
    return false;
  }
  
  _window.reset(SDL_CreateWindow("Tim Jones Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0));
  
  if (_window == nullptr) {
    return false;
  }
  
  if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
    return false;
  }

  _renderer.reset(SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED));
  if (_renderer == nullptr) {
    return false;
  }
  
  std::string startingPath = getResourcePath();
  
  if (_yoshiRight.OnLoad(_renderer.get(), startingPath + "yoshi.bmp", 64, 64, 8) == false) {
    return false;
  }
  
  if (_yoshiLeft.OnLoad(_renderer.get(), startingPath + "yoshiLeft.bmp", 64, 64, 8) == false) {
    return false;
  }
  
  _yoshiLeft.SetX(100.f);
  
  CEntity::_entityList.push_back(&_yoshiRight);
  CEntity::_entityList.push_back(&_yoshiLeft);
  
  return true;
}
Example #30
0
bool
ResourceFinder::unbundleResource(QString resourceCat, QString fileName)
{
    QString path = getResourcePath(resourceCat, fileName);
    
    if (!path.startsWith(':')) return true;

    // This is the lowest-priority alternative path for this
    // resource, so we know that there must be no installed copy.
    // Install one to the user location.
    RG_DEBUG << "ResourceFinder::unbundleResource: File " << fileName << " is bundled, un-bundling it" << endl;
    QString target = getResourceSavePath(resourceCat, fileName);
    QFile file(path);
    if (!file.copy(target)) {
        std::cerr << "ResourceFinder::unbundleResource: ERROR: Failed to un-bundle resource file \"" << fileName << "\" to user location \"" << target << "\"" << std::endl;
        return false;
    }

    // Now since the file is in the user's editable space, the user should get
    // to edit it.  The chords.xml file I unbundled came out 444 instead of 644
    // which won't do.  Rather than put the chmod code there, I decided to put
    // it here, because I think it will always be appropriate to make unbundled
    // files editable.  That's rather the point in many cases, and for the rest,
    // nobody will likely notice they could have edited their font files or what
    // have you that were unbundled to improve performance.  (Dissenting
    // opinions welcome.  We can always shuffle this somewhere else if
    // necessary.  There are many possibilities.)
    QFile chmod(target);
    chmod.setPermissions(QFile::ReadOwner |
                         QFile::ReadUser  | /* for potential platform-independence */
                         QFile::ReadGroup |
                         QFile::ReadOther |
                         QFile::WriteOwner|
                         QFile::WriteUser); /* for potential platform-independence */

    return true;
}