The Table Engine
resourcemanager.cpp
Go to the documentation of this file.
1 #include <string>
2 #include <unordered_map>
3 #include <iostream>
4 
5 #include "resourcemanager.h"
6 #include <SDL2/SDL.h>
7 #include <SDL2/SDL_mixer.h>
8 
10 {
11  return m_renderer;
12 }
13 
14 void ResourceManager::setRenderer(SDL_Renderer* renderer)
15 {
16  m_renderer = renderer;
17 }
18 
19 // for images
20 SDL_Texture* ResourceManager::loadTexture(std::string path)
21 {
22  if (m_imageResourceMap.find(path) != m_imageResourceMap.end())
23  {
24  return m_imageResourceMap[path];
25  }
26 
27  if (SDL_LoadBMP(path.c_str()) == NULL)
28  {
29  std::cout << "Error loading image: " << path << std::endl;
30  return NULL;
31  }
32 
33  SDL_Surface* surface = SDL_LoadBMP(path.c_str());
34  SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer, surface);
35  SDL_FreeSurface(surface);
36 
37  m_imageResourceMap[path] = texture;
38  return texture;
39 }
40 
41 // for fonts
42 SDL_Texture* ResourceManager::loadText(std::string font_path, std::string text, SDL_Color color, int font_size)
43 {
44  TTF_Font* font = NULL;
45  std::string textKey = text + std::to_string(font_size);
46 
47  if (m_fontMap[textKey] != NULL)
48  {
49  font = m_fontMap[textKey];
50  }
51  else
52  {
53  font = TTF_OpenFont(font_path.c_str(), font_size);
54  if (font == NULL)
55  {
56  std::cout << "Error loading font: " << font_path << std::endl;
57  return NULL;
58  }
59  m_fontMap[textKey] = font;
60  }
61 
62  SDL_Surface* surface = TTF_RenderText_Solid(font, text.c_str(), color);
63  SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer, surface);
64  SDL_FreeSurface(surface);
65 
66  return texture;
67 }
68 
69 // for sounds
70 // Sound* ResourceManager::loadSound(std::string path)
71 // {
72 // Sound* sound = new Sound(path);
73 // return sound;
74 // }
void setRenderer(SDL_Renderer *renderer)
Sets the renderer for resource management.
SDL_Renderer * m_renderer
Renderer used to render game objects.
SDL_Texture * loadText(std::string font_path, std::string text, SDL_Color color, int font_size=20)
Loads a text as a texture using a specified TTF font.
SDL_Renderer * getRenderer()
Gets the current renderer.
std::unordered_map< std::string, SDL_Texture * > m_imageResourceMap
Cache of texture resources.
SDL_Texture * loadTexture(std::string path)
Loads a texture from a specified file path.
std::unordered_map< std::string, TTF_Font * > m_fontMap
Cache of font resources.
Manages resources such as textures, fonts, and potentially sounds for a game engine.