From f2068ddb2fbed6c6bf6bffc3648327435886e603 Mon Sep 17 00:00:00 2001 From: Ekaitz Zarraga Date: Thu, 17 Nov 2022 13:00:52 +0100 Subject: Add a simple resource manager --- src/main.cpp | 21 +++++++++++++++++--- src/resourceManager.h | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 3 deletions(-) create mode 100644 src/resourceManager.h (limited to 'src') diff --git a/src/main.cpp b/src/main.cpp index 94bf125..bd330fc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,6 +5,7 @@ #include "graphics/animation.h" #include "entity.h" +#include "resourceManager.h" namespace gph = Graphics; @@ -34,8 +35,8 @@ class Unit: Entity{ sf::Vector2f speed; - Unit(){ - spritesheet_.loadFromFile("assets/img/Player/Player Angle 1 Sheet.png"); + Unit(sf::Texture& spritesheet){ + spritesheet_ = spritesheet; standing_animation = gph::Animation(spritesheet_, 6, 60, 44, 48, 0); walking_animation = gph::Animation(spritesheet_, 8, 60, 44, 48, 1); shooting_animation = gph::FlippedAnimation(spritesheet_, 6, 60, 44, 48, 2); @@ -66,16 +67,30 @@ class Unit: Entity{ sprite.setScale(8,8); sprite.setTextureRect(current_animation->next(dt)); sprite.setPosition(position.x, position.y); + sprite = sprite; } }; + +enum class TextureId{ + Angle1, + Angle2, + Front, + Back, + Side +}; + int main() { sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "Demo Game"); sf::Event event; sf::Clock clock; - Unit unit; + + ResourceManager TextureManager; + TextureManager.load( TextureId::Angle1, "assets/img/Player/Player Angle 1 Sheet.png"); + + Unit unit = Unit(TextureManager.get(TextureId::Angle1)); renderWindow.setFramerateLimit(60); diff --git a/src/resourceManager.h b/src/resourceManager.h new file mode 100644 index 0000000..be6e250 --- /dev/null +++ b/src/resourceManager.h @@ -0,0 +1,54 @@ +#ifndef RESOURCE_MANAGER_H +#define RESOURCE_MANAGER_H + +#include +#include +#include +#include +#include + +template +class ResourceManager{ + private: + std::map> resourceMap; + public: + void load(Identifier id, const std::string& path); + Resource& get(Identifier id); + const Resource& get(Identifier id) const; +}; + +template +void +ResourceManager::load(Identifier id, + const std::string& path){ + auto resource = std::make_unique(); + if( !resource->loadFromFile(path) ){ + throw("ResoureManager::load - Failed to load filename: " + path); + } + auto inserted = resourceMap.insert( + std::make_pair(id, std::move(resource)) + ); + assert(inserted.second); +} + +template +Resource& +ResourceManager::get(Identifier id) +{ + auto found = resourceMap.find(id); + assert(found != resourceMap.end()); + + return *found->second; +} + +template +const Resource& +ResourceManager::get(Identifier id) const +{ + auto found = resourceMap.find(id); + assert(found != resourceMap.end()); + + return *found->second; +} + +#endif // RESOURCE_MANAGER_H -- cgit v1.2.3