farmlands/src/storage/ResourceManager.cpp

121 lines
2.3 KiB
C++

/*
* ResourceManager.cpp
*
* Created on: Nov 7, 2016
* Author: tibi
*/
#include "ResourceManager.h"
#include "Resources.h"
#define FONTID(id,size) (id * 1000 + size)
#define FONTID_SIZE(fontid) (fontid % 1000)
#define FONTID_ID(fontid) (fontid / 1000)
namespace farmlands
{
namespace storage
{
ResourceManager::ResourceManager()
{
}
ResourceManager::~ResourceManager()
{
}
void ResourceManager::loadMainMenu()
{
}
void ResourceManager::loadGame(SDL_Renderer* renderer)
{
loadTextures(renderer);
}
void ResourceManager::loadTextures(SDL_Renderer* renderer)
{
for (size_t i = 0; i < sizeof(Resources_Textures) / sizeof(Resources_Textures[0]); i++)
{
SDL_Surface* surface = IMG_Load(Resources_Textures[i]);
m_surfaces.push_back(surface);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
m_textures.push_back(texture);
}
}
TTF_Font* ResourceManager::font(const char* name, int pointSize)
{
int id = fontId(name);
return font(id, pointSize);
}
TTF_Font* ResourceManager::font(int id, int pointSize)
{
// Open from cache
auto it = m_fontCache.find(FONTID(id, pointSize));
if (it != m_fontCache.end())
return it->second;
// Open font
TTF_Font* font = TTF_OpenFont(Resources_Fonts[id], pointSize);
m_fontCache.emplace(FONTID(id, pointSize), font);
return font;
}
int ResourceManager::fontId(const char* name)
{
// Find in cache
auto it = m_fontIdCache.find(std::string(name));
if (it != m_fontIdCache.end())
return it->second;
for (size_t i = 0; i < sizeof(Resources_Fonts) / sizeof(Resources_Fonts[0]); i++)
{
// Extract name from file name
std::string fontName = Resources_Fonts[i];
size_t nameStart = fontName.find_last_of('/');
if (nameStart == std::string::npos)
nameStart = 0;
else
++nameStart;
size_t nameEnd = fontName.find_last_of('.');
size_t nameLen = (nameEnd != std::string::npos) ? nameEnd - nameStart : std::string::npos;
fontName = fontName.substr(nameStart, nameLen);
// Found?
if (fontName == name) {
m_fontIdCache.emplace(fontName, i);
return i;
}
}
return -1;
}
SDL_Texture* ResourceManager::texture(const char* name)
{
return NULL;
}
SDL_Texture* ResourceManager::texture(int id)
{
return m_textures[id];
}
int ResourceManager::textureId(const char* name)
{
return -1;
}
} /* namespace storage */
} /* namespace farmlands */