CS4850 Final Project
Loading...
Searching...
No Matches
ResourceManager.hpp
1#pragma once
2
3#include <SDL2/SDL.h>
4#include <SDL2/SDL_image.h>
5#include <unordered_map>
6#include <string>
7#include <memory>
8
9//Functor
11 void operator()(SDL_Texture* texture) const {
12 SDL_DestroyTexture(texture);
13 }
14};
15
16std::shared_ptr<SDL_Texture> make_shared_texture(SDL_Renderer* renderer, SDL_Surface* pixels);
17
23
30 if (nullptr == mInstance) {
31 mInstance = new ResourceManager;
32 }
33
34 return *mInstance;
35 }
36
44 std::shared_ptr<SDL_Texture> LoadTexture(SDL_Renderer* renderer, std::string filepath) {
45 if (!mTextureResources.contains(filepath)) {
46 // Load the image
47 auto extension = filepath.substr(filepath.find_last_of(".") + 1);
48 int imgFlags;
49 SDL_Surface* pixels;
50
51 if (extension == "bmp") {
52 pixels = SDL_LoadBMP(filepath.c_str());
53 } else {
54 if (extension == "png") {
55 imgFlags = IMG_INIT_PNG;
56 } else if (extension == "jpg" || extension == "jpeg") {
57 imgFlags = IMG_INIT_JPG;
58 } else if (extension == "avif") {
59 imgFlags = IMG_INIT_AVIF;
60 } else if (extension == "jxl") {
61 imgFlags = IMG_INIT_JXL;
62 } else if (extension == "tif") {
63 imgFlags = IMG_INIT_TIF;
64 } else if (extension == "webp") {
65 imgFlags = IMG_INIT_WEBP;
66 } else {
67 SDL_Log("Unsupported image format %s", extension.c_str());
68 return nullptr;
69 }
70 if( !(IMG_Init(imgFlags) & imgFlags)) {
71 SDL_Log( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
72 return nullptr;
73 }
74 pixels = IMG_Load(filepath.c_str());
75 }
76
77 if (!pixels) {
78 SDL_Log("Failed to load image %s", filepath.c_str());
79 return nullptr;
80 }
81 SDL_SetColorKey(pixels, SDL_TRUE, SDL_MapRGB(pixels->format,0xFF,0,0xFF));
82 std::shared_ptr<SDL_Texture> texture = make_shared_texture(renderer, pixels);
83 mTextureResources.insert({filepath, texture});
84 SDL_FreeSurface(pixels);
85 SDL_Log("Created new resource %s", filepath.c_str());
86 } else {
87 SDL_Log("Reused resource %s", filepath.c_str());
88 }
89
90 return mTextureResources[filepath];
91 }
92
93 private:
95 }
96
97 inline static ResourceManager* mInstance {nullptr};
98 std::unordered_map<std::string, std::shared_ptr<SDL_Texture>> mTextureResources;
99};
Singleton class to manage resources.
Definition ResourceManager.hpp:22
static ResourceManager & Instance()
Get the instance of the resource manager.
Definition ResourceManager.hpp:29
std::shared_ptr< SDL_Texture > LoadTexture(SDL_Renderer *renderer, std::string filepath)
Load a texture from a file.
Definition ResourceManager.hpp:44
Definition ResourceManager.hpp:10