Unificar Encoding.
Revisado que todos los archivos son UTF-8 y espacios como indentación.
This commit is contained in:
@@ -9,48 +9,48 @@ using json = nlohmann::ordered_json;
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
/* All types of Assets that can be loadedand stored by an AssetManager */
|
/* All types of Assets that can be loadedand stored by an AssetManager */
|
||||||
enum class AssetType
|
enum class AssetType
|
||||||
{
|
{
|
||||||
Texture = 0, Font, Sound, Other, Unvalid = 15
|
Texture = 0, Font, Sound, Other, Unvalid = 15
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Asset struct. Contains info regarding Assets para ser cargados. */
|
/* Asset struct. Contains info regarding Assets para ser cargados. */
|
||||||
struct Asset
|
struct Asset
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
Asset() {};
|
Asset() {};
|
||||||
|
|
||||||
Asset(std::string name,
|
Asset(std::string name,
|
||||||
std::string path,
|
std::string path,
|
||||||
AssetType type)
|
AssetType type)
|
||||||
: _name(name), _path(path), _type(type) {}
|
: _name(name), _path(path), _type(type) {}
|
||||||
|
|
||||||
|
|
||||||
std::string _name = "";
|
std::string _name = "";
|
||||||
std::string _path = "";
|
std::string _path = "";
|
||||||
|
|
||||||
AssetType _type = AssetType::Unvalid;
|
AssetType _type = AssetType::Unvalid;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Conversi�n de una struct Asset a JSON */
|
/* Conversi�n de una struct Asset a JSON */
|
||||||
inline void to_json(nlohmann::ordered_json& j, const Asset& as)
|
inline void to_json(nlohmann::ordered_json& j, const Asset& as)
|
||||||
{
|
{
|
||||||
j = nlohmann::ordered_json
|
j = nlohmann::ordered_json
|
||||||
{
|
{
|
||||||
{"name", as._name},
|
{"name", as._name},
|
||||||
{"Path", as._path},
|
{"Path", as._path},
|
||||||
{"Type", as._type},
|
{"Type", as._type},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Conversi�n de un JSON a una struct Asset */
|
/* Conversi�n de un JSON a una struct Asset */
|
||||||
inline void from_json(const nlohmann::ordered_json& j, Asset& as)
|
inline void from_json(const nlohmann::ordered_json& j, Asset& as)
|
||||||
{
|
{
|
||||||
j.at("name").get_to(as._name);
|
j.at("name").get_to(as._name);
|
||||||
j.at("Path").get_to(as._path);
|
j.at("Path").get_to(as._path);
|
||||||
j.at("Type").get_to(as._type);
|
j.at("Type").get_to(as._type);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,20 +62,20 @@ namespace UE
|
|||||||
/* Conversi�n de un Struct SDL_Rect a JSON */
|
/* Conversi�n de un Struct SDL_Rect a JSON */
|
||||||
inline void to_json(nlohmann::ordered_json& j, const SDL_Rect& rect)
|
inline void to_json(nlohmann::ordered_json& j, const SDL_Rect& rect)
|
||||||
{
|
{
|
||||||
j = nlohmann::ordered_json
|
j = nlohmann::ordered_json
|
||||||
{
|
{
|
||||||
{"posX", rect.x},
|
{"posX", rect.x},
|
||||||
{"posY", rect.y},
|
{"posY", rect.y},
|
||||||
{"sizeX", rect.w},
|
{"sizeX", rect.w},
|
||||||
{"sizeY", rect.h}
|
{"sizeY", rect.h}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Conversi�n de un JSON a un struct SDL_Rect */
|
/* Conversi�n de un JSON a un struct SDL_Rect */
|
||||||
inline void from_json(const nlohmann::ordered_json& j, SDL_Rect& rect)
|
inline void from_json(const nlohmann::ordered_json& j, SDL_Rect& rect)
|
||||||
{
|
{
|
||||||
j.at("posX").get_to(rect.x);
|
j.at("posX").get_to(rect.x);
|
||||||
j.at("posY").get_to(rect.y);
|
j.at("posY").get_to(rect.y);
|
||||||
j.at("sizeX").get_to(rect.w);
|
j.at("sizeX").get_to(rect.w);
|
||||||
j.at("sizeY").get_to(rect.h);
|
j.at("sizeY").get_to(rect.h);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
#include "Logging/Logger.h"
|
#include "Logging/Logger.h"
|
||||||
@@ -10,188 +10,186 @@
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
void AssetManager::InitAssetManager()
|
void AssetManager::InitAssetManager()
|
||||||
{
|
{
|
||||||
UE_LOG_INFO("AssetManager Iniciado con éxito.");
|
UE_LOG_INFO("AssetManager Iniciado con éxito.");
|
||||||
}
|
}
|
||||||
|
|
||||||
void AssetManager::CleanAssetManager()
|
void AssetManager::CleanAssetManager()
|
||||||
{
|
{
|
||||||
//Destruye todas las texturas de SDL.
|
//Destruye todas las texturas de SDL.
|
||||||
for (auto i = _textures.begin(); i != _textures.end(); i++)
|
for (auto i = _textures.begin(); i != _textures.end(); i++)
|
||||||
{
|
{
|
||||||
i->second->~Texture();
|
i->second->~Texture();
|
||||||
}
|
}
|
||||||
|
|
||||||
//Limpiamos las fuentes.
|
//Limpiamos las fuentes.
|
||||||
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
|
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
|
||||||
{
|
{
|
||||||
//Limpiamos las fuentes.
|
//Limpiamos las fuentes.
|
||||||
delete i->second;
|
delete i->second;
|
||||||
}
|
}
|
||||||
|
|
||||||
//CPP se debería de encargar de ellos, pero bueno.
|
//CPP se debería de encargar de ellos, pero bueno.
|
||||||
_assetQueue.clear();
|
_assetQueue.clear();
|
||||||
_textures.clear();
|
_textures.clear();
|
||||||
|
|
||||||
UE_LOG_INFO("AssetManager Cleaned");
|
UE_LOG_INFO("AssetManager Cleaned");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void AssetManager::LoadAssetsFromFile(std::string filePath)
|
||||||
|
{
|
||||||
|
std::fstream file(filePath.c_str());
|
||||||
|
|
||||||
|
if (!file.is_open())
|
||||||
|
{
|
||||||
|
UE_LOG_ERROR("No se ha podido abrir la lista de assets: {0}", filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
//Load Asset data from JSON.
|
||||||
|
json jread = json::parse(file);
|
||||||
|
|
||||||
|
json Textures = jread["Textures"];
|
||||||
|
json Fonts = jread["Fonts"];
|
||||||
|
json Sounds = jread["Sounds"];
|
||||||
|
json Others = jread["Others"];
|
||||||
|
|
||||||
|
/* Add assets struct to asset map. */
|
||||||
|
for (int i = 0; i < Textures.size(); i++)
|
||||||
|
{
|
||||||
|
_assetQueue.push_back(Textures.at(i));
|
||||||
|
}
|
||||||
|
for (int i = 0; i < Fonts.size(); i++)
|
||||||
|
{
|
||||||
|
_assetQueue.push_back(Fonts.at(i));
|
||||||
|
}
|
||||||
|
for (int i = 0; i < Sounds.size(); i++)
|
||||||
|
{
|
||||||
|
_assetQueue.push_back(Sounds.at(i));
|
||||||
|
}
|
||||||
|
for (int i = 0; i < Others.size(); i++)
|
||||||
|
{
|
||||||
|
_assetQueue.push_back(Others.at(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
file.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void AssetManager::LoadAsset(Asset& as)
|
||||||
|
{
|
||||||
|
_assetQueue.push_back(as);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void AssetManager::ProcessAssetQueue(int amount)
|
||||||
|
{
|
||||||
|
int cantidad = amount;
|
||||||
|
|
||||||
|
if (amount == -1 || cantidad >= _assetQueue.size())
|
||||||
|
cantidad = _assetQueue.size();
|
||||||
|
|
||||||
|
//Load Assets from files, depending on the type.
|
||||||
|
for (int i = 0; i < cantidad; i++)
|
||||||
|
{
|
||||||
|
Asset& as = _assetQueue.front();
|
||||||
|
switch (as._type)
|
||||||
|
{
|
||||||
|
case AssetType::Texture:
|
||||||
|
{
|
||||||
|
LoadTexture(as._name, as._path);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case AssetType::Font:
|
||||||
|
{
|
||||||
|
LoadFont(as._name, as._path);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
{
|
||||||
|
UE_LOG_WARN("Asset {0}, Type {1} Cannot be loaded from {2}", as._name, as._type, as._path);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_assetQueue.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadAssetsFromFile(std::string filePath)
|
void AssetManager::LoadTexture(std::string name, std::string txPath)
|
||||||
{
|
{
|
||||||
std::fstream file(filePath.c_str());
|
Texture* tx = new Texture(txPath, _SDL_Renderer);
|
||||||
|
_textures.insert(std::make_pair(name, tx));
|
||||||
|
|
||||||
if (!file.is_open())
|
//std::fstream file(txPath.c_str());
|
||||||
{
|
|
||||||
UE_LOG_ERROR("No se ha podido abrir la lista de assets: {0}", filePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
//Load Asset data from JSON.
|
//json jread = json::parse(file);
|
||||||
json jread = json::parse(file);
|
//std::string path = jread["TexturePath"];
|
||||||
|
|
||||||
json Textures = jread["Textures"];
|
////Cargamos la textura.
|
||||||
json Fonts = jread["Fonts"];
|
//SDL_Surface* loadSurface = IMG_Load(path.c_str());
|
||||||
json Sounds = jread["Sounds"];
|
//SDL_Texture* tx = SDL_CreateTextureFromSurface(_mainRenderer, loadSurface);
|
||||||
json Others = jread["Others"];
|
//_textures.insert(std::make_pair(name, tx));
|
||||||
|
//SDL_FreeSurface(loadSurface);
|
||||||
|
|
||||||
/* Add assets struct to asset map. */
|
////Almacenamos los Rects (sprites) de esa textura.
|
||||||
for (int i = 0; i < Textures.size(); i++)
|
//json textureRects = jread["TextureRects"];
|
||||||
{
|
|
||||||
_assetQueue.push_back(Textures.at(i));
|
//_textureRects.insert(std::make_pair(name, std::vector<SDL_Rect>()));
|
||||||
}
|
//std::vector<SDL_Rect>& vector = _textureRects.at(name);
|
||||||
for (int i = 0; i < Fonts.size(); i++)
|
|
||||||
{
|
//for (int i = 0; i < textureRects.size(); i++)
|
||||||
_assetQueue.push_back(Fonts.at(i));
|
//{
|
||||||
}
|
// //json rectData = textureRects.at(i);
|
||||||
for (int i = 0; i < Sounds.size(); i++)
|
// //SDL_Rect rect;
|
||||||
{
|
// //rect.x = rectData.at()
|
||||||
_assetQueue.push_back(Sounds.at(i));
|
|
||||||
}
|
// vector.push_back(textureRects.at(i).get<SDL_Rect>());
|
||||||
for (int i = 0; i < Others.size(); i++)
|
//}
|
||||||
{
|
|
||||||
_assetQueue.push_back(Others.at(i));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
file.close();
|
//file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadAsset(Asset& as)
|
void AssetManager::RemoveTexture(std::string name)
|
||||||
{
|
{
|
||||||
_assetQueue.push_back(as);
|
//Se supone que el erase del map llama al destructor del objeto...
|
||||||
}
|
//Pero no lo he comprobado del todo.
|
||||||
|
_textures.erase(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::ProcessAssetQueue(int amount)
|
void AssetManager::LoadFont(std::string name, std::string fontPath)
|
||||||
{
|
{
|
||||||
int cantidad = amount;
|
Font* fo = new Font(fontPath);
|
||||||
|
_fonts.insert(std::make_pair(name, fo));
|
||||||
|
|
||||||
if (amount == -1 || cantidad >= _assetQueue.size())
|
}
|
||||||
cantidad = _assetQueue.size();
|
|
||||||
|
|
||||||
//Load Assets from files, depending on the type.
|
|
||||||
for (int i = 0; i < cantidad; i++)
|
|
||||||
{
|
|
||||||
Asset& as = _assetQueue.front();
|
|
||||||
switch (as._type)
|
|
||||||
{
|
|
||||||
case AssetType::Texture:
|
|
||||||
{
|
|
||||||
LoadTexture(as._name, as._path);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case AssetType::Font:
|
|
||||||
{
|
|
||||||
LoadFont(as._name, as._path);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
{
|
|
||||||
UE_LOG_WARN("Asset {0}, Type {1} Cannot be loaded from {2}", as._name, as._type, as._path);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_assetQueue.pop_front();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
void AssetManager::RemoveFont(std::string name)
|
||||||
|
{
|
||||||
|
//Se supone que el erase del map llama al destructor del objeto...
|
||||||
|
//Pero no lo he comprobado del todo.
|
||||||
|
_fonts.erase(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadTexture(std::string name, std::string txPath)
|
//////////DEBUG//////////
|
||||||
{
|
|
||||||
Texture* tx = new Texture(txPath, _SDL_Renderer);
|
|
||||||
_textures.insert(std::make_pair(name, tx));
|
|
||||||
|
|
||||||
//std::fstream file(txPath.c_str());
|
|
||||||
|
|
||||||
//json jread = json::parse(file);
|
|
||||||
//std::string path = jread["TexturePath"];
|
|
||||||
|
|
||||||
////Cargamos la textura.
|
|
||||||
//SDL_Surface* loadSurface = IMG_Load(path.c_str());
|
|
||||||
//SDL_Texture* tx = SDL_CreateTextureFromSurface(_mainRenderer, loadSurface);
|
|
||||||
//_textures.insert(std::make_pair(name, tx));
|
|
||||||
//SDL_FreeSurface(loadSurface);
|
|
||||||
|
|
||||||
////Almacenamos los Rects (sprites) de esa textura.
|
|
||||||
//json textureRects = jread["TextureRects"];
|
|
||||||
|
|
||||||
//_textureRects.insert(std::make_pair(name, std::vector<SDL_Rect>()));
|
|
||||||
//std::vector<SDL_Rect>& vector = _textureRects.at(name);
|
|
||||||
|
|
||||||
//for (int i = 0; i < textureRects.size(); i++)
|
|
||||||
//{
|
|
||||||
// //json rectData = textureRects.at(i);
|
|
||||||
// //SDL_Rect rect;
|
|
||||||
// //rect.x = rectData.at()
|
|
||||||
|
|
||||||
// vector.push_back(textureRects.at(i).get<SDL_Rect>());
|
|
||||||
//}
|
|
||||||
|
|
||||||
|
|
||||||
//file.close();
|
void AssetManager::PrintAssetInfo()
|
||||||
}
|
{
|
||||||
|
std::cout << "AM - Debug INFO: " << std::endl;
|
||||||
|
for (int i = 0; i < _assetQueue.size(); i++) {
|
||||||
|
std::cout << _assetQueue[i]._name << " - " << _assetQueue[i]._path << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/////////////////////////
|
||||||
void AssetManager::RemoveTexture(std::string name)
|
|
||||||
{
|
|
||||||
//Se supone que el erase del map llama al destructor del objeto...
|
|
||||||
//Pero no lo he comprobado del todo.
|
|
||||||
_textures.erase(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::LoadFont(std::string name, std::string fontPath)
|
|
||||||
{
|
|
||||||
Font* fo = new Font(fontPath);
|
|
||||||
_fonts.insert(std::make_pair(name, fo));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::RemoveFont(std::string name)
|
|
||||||
{
|
|
||||||
//Se supone que el erase del map llama al destructor del objeto...
|
|
||||||
//Pero no lo he comprobado del todo.
|
|
||||||
_fonts.erase(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
//////////DEBUG//////////
|
|
||||||
|
|
||||||
|
|
||||||
void AssetManager::PrintAssetInfo()
|
|
||||||
{
|
|
||||||
std::cout << "AM - Debug INFO: " << std::endl;
|
|
||||||
for (int i = 0; i < _assetQueue.size(); i++) {
|
|
||||||
std::cout << _assetQueue[i]._name << " - " << _assetQueue[i]._path << std::endl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/////////////////////////
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,11 +19,11 @@ using json = nlohmann::ordered_json;
|
|||||||
|
|
||||||
|
|
||||||
///
|
///
|
||||||
/// TODO:
|
/// TODO:
|
||||||
/// - Modificar las funciones de Carga para quitar la queue o implementar una que tenga sentido.
|
/// - Modificar las funciones de Carga para quitar la queue o implementar una que tenga sentido.
|
||||||
/// Por ejemplo, se puede crear una cola (std::deque) y cargar un asset cada gameLoop en vez de
|
/// Por ejemplo, se puede crear una cola (std::deque) y cargar un asset cada gameLoop en vez de
|
||||||
/// procesar toda la cola de golpe. Optimizar�a la carga de assets.
|
/// procesar toda la cola de golpe. Optimizar�a la carga de assets.
|
||||||
/// - Terminar la implementaci�n del tipo de carga (queue/now).
|
/// - Terminar la implementaci�n del tipo de carga (queue/now).
|
||||||
/// - Modificar los for en la carga de archivo, as� como la estructura del archivo JSON. El tipo de Asset est� repetido.
|
/// - Modificar los for en la carga de archivo, as� como la estructura del archivo JSON. El tipo de Asset est� repetido.
|
||||||
/// - Logging.
|
/// - Logging.
|
||||||
/// - ERROR HANDLING
|
/// - ERROR HANDLING
|
||||||
@@ -32,151 +32,151 @@ using json = nlohmann::ordered_json;
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
/* Gestiona todos assets primitivos, almacenando sus ptrs en un lugar seguro. */
|
/* Gestiona todos assets primitivos, almacenando sus ptrs en un lugar seguro. */
|
||||||
class AssetManager
|
class AssetManager
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
/* Constructor. */
|
/* Constructor. */
|
||||||
AssetManager(SDL_Renderer* SDLrenderer)
|
AssetManager(SDL_Renderer* SDLrenderer)
|
||||||
: _SDL_Renderer(SDLrenderer) {}
|
: _SDL_Renderer(SDLrenderer) {}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Init AssetManager y todo lo necesario para funcionar correctamente.
|
* Init AssetManager y todo lo necesario para funcionar correctamente.
|
||||||
* - Inicia SDL_IMG.
|
* - Inicia SDL_IMG.
|
||||||
*/
|
*/
|
||||||
void InitAssetManager();
|
void InitAssetManager();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Clean AssetManager Data on exit
|
* Clean AssetManager Data on exit
|
||||||
* - Elimina todos los assets de sus contenedores.
|
* - Elimina todos los assets de sus contenedores.
|
||||||
* - Descarga SDL_IMG
|
* - Descarga SDL_IMG
|
||||||
*/
|
*/
|
||||||
void CleanAssetManager();
|
void CleanAssetManager();
|
||||||
|
|
||||||
|
|
||||||
/* Carga de Assets */
|
/* Carga de Assets */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Carga los datos de los Assets desde un fichero JSON seg�n par�metros.
|
* Carga los datos de los Assets desde un fichero JSON seg�n par�metros.
|
||||||
*
|
*
|
||||||
* \param filePath: Ubicaci�n del archivo JSON.
|
* \param filePath: Ubicaci�n del archivo JSON.
|
||||||
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
|
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void LoadAssetsFromFile(std::string filePath);
|
void LoadAssetsFromFile(std::string filePath);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Carga el Asset pasado por par�metro.
|
* Carga el Asset pasado por par�metro.
|
||||||
*
|
*
|
||||||
* \param as: Asset que cargar.
|
* \param as: Asset que cargar.
|
||||||
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
|
* \param loadMethod: Forma de carga. Procesado al momento o a�adido a la cola de carga.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void LoadAsset(Asset& as);
|
void LoadAsset(Asset& as);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Procesa la cola de carga de Assets.
|
* Procesa la cola de carga de Assets.
|
||||||
*
|
*
|
||||||
* \param Amount: N�mero de Assets de la cola a procesar. Si vale -1 se procesar�n todos.
|
* \param Amount: N�mero de Assets de la cola a procesar. Si vale -1 se procesar�n todos.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void ProcessAssetQueue(int amount = -1);
|
void ProcessAssetQueue(int amount = -1);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Devuelve la cantidad de Assets que quedan sin procesar en la cola.
|
* Devuelve la cantidad de Assets que quedan sin procesar en la cola.
|
||||||
* De esta forma, se puede hacer un bucle hasta que la cola sea <= 0.
|
* De esta forma, se puede hacer un bucle hasta que la cola sea <= 0.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
inline int GetAssetQueueSize() { return _assetQueue.size(); }
|
inline int GetAssetQueueSize() { return _assetQueue.size(); }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Comprueba si la cola de carga de Assets est� vac�a.
|
/// Comprueba si la cola de carga de Assets est� vac�a.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>El resultado de la cola.</returns>
|
/// <returns>El resultado de la cola.</returns>
|
||||||
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
|
inline bool IsAssetQueueEmpty() { return _assetQueue.empty(); }
|
||||||
|
|
||||||
|
|
||||||
/*--------------------------------------/
|
/*--------------------------------------/
|
||||||
* M�todos para manejar las texturas. *
|
* M�todos para manejar las texturas. *
|
||||||
*--------------------------------------*/
|
*--------------------------------------*/
|
||||||
|
|
||||||
//Crea una textura de SDL y la a�ade al mapa de texturas identificada por su nombre.
|
//Crea una textura de SDL y la a�ade al mapa de texturas identificada por su nombre.
|
||||||
void LoadTexture(std::string name, std::string txPath);
|
void LoadTexture(std::string name, std::string txPath);
|
||||||
|
|
||||||
//Elimina una textura del mapa a partir de su nombre.
|
//Elimina una textura del mapa a partir de su nombre.
|
||||||
void RemoveTexture(std::string name);
|
void RemoveTexture(std::string name);
|
||||||
|
|
||||||
//Obtiene una textura del mapa a partir de su nombre.
|
//Obtiene una textura del mapa a partir de su nombre.
|
||||||
//inline SDL_Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
|
//inline SDL_Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
|
||||||
inline Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
|
inline Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
|
||||||
|
|
||||||
//inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
|
//inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
|
||||||
|
|
||||||
|
|
||||||
/*------------------------------------/
|
/*------------------------------------/
|
||||||
* M�todos para manejar las fuentes. *
|
* M�todos para manejar las fuentes. *
|
||||||
*------------------------------------*/
|
*------------------------------------*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Crea un objeto UE:Font y lo a�ade al mapa de fuentes.
|
* Crea un objeto UE:Font y lo a�ade al mapa de fuentes.
|
||||||
*
|
*
|
||||||
* @param name : Nombre del asset (key para el mapa de fuentes).
|
* @param name : Nombre del asset (key para el mapa de fuentes).
|
||||||
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
|
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void LoadFont(std::string name, std::string fontPath);
|
void LoadFont(std::string name, std::string fontPath);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Elimina una fuente (y en teor�a limpia la fuente) dado su nombre de Asset.
|
* Elimina una fuente (y en teor�a limpia la fuente) dado su nombre de Asset.
|
||||||
*
|
*
|
||||||
* @param name : Nombre del Asset (key del mapa de fuentes).
|
* @param name : Nombre del Asset (key del mapa de fuentes).
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
void RemoveFont(std::string name);
|
void RemoveFont(std::string name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
|
* Obtiene y devuelve el ptr a una fuente dado su nombre de asset.
|
||||||
*
|
*
|
||||||
* @param fontName : Nombre del Asset.
|
* @param fontName : Nombre del Asset.
|
||||||
* @return UE::Font* : El ptr a la fuente solicitada.
|
* @return UE::Font* : El ptr a la fuente solicitada.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
inline Font* GetFont(std::string fontName) { return _fonts.at(fontName); }
|
inline Font* GetFont(std::string fontName) { return _fonts.at(fontName); }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
///////DEBUG////////
|
///////DEBUG////////
|
||||||
void PrintAssetInfo();
|
void PrintAssetInfo();
|
||||||
///////////////////
|
///////////////////
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
//----------------------
|
//----------------------
|
||||||
//VARIABLES
|
//VARIABLES
|
||||||
//---------------------
|
//---------------------
|
||||||
|
|
||||||
|
|
||||||
//std::string _assetPath;
|
//std::string _assetPath;
|
||||||
|
|
||||||
//std::vector<UE::Asset> _assets = {};
|
//std::vector<UE::Asset> _assets = {};
|
||||||
std::deque<UE::Asset> _assetQueue = {};
|
std::deque<UE::Asset> _assetQueue = {};
|
||||||
|
|
||||||
/* Almacenes de asssets */
|
/* Almacenes de asssets */
|
||||||
|
|
||||||
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
|
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
|
||||||
//std::unordered_map<std::string, SDL_Texture*> _textures = {};
|
//std::unordered_map<std::string, SDL_Texture*> _textures = {};
|
||||||
//std::unordered_map<std::string, std::vector<SDL_Rect>> _textureRects = {};
|
//std::unordered_map<std::string, std::vector<SDL_Rect>> _textureRects = {};
|
||||||
std::unordered_map <std::string, Texture*> _textures = {};
|
std::unordered_map <std::string, Texture*> _textures = {};
|
||||||
|
|
||||||
//Almacen de TTF_Fonts* (Para las fuentes de SDL_TTF).
|
//Almacen de TTF_Fonts* (Para las fuentes de SDL_TTF).
|
||||||
std::unordered_map<std::string, Font*> _fonts = {};
|
std::unordered_map<std::string, Font*> _fonts = {};
|
||||||
|
|
||||||
|
|
||||||
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
|
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
|
||||||
SDL_Renderer* _SDL_Renderer = NULL;
|
SDL_Renderer* _SDL_Renderer = NULL;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,70 +10,70 @@ using json = nlohmann::ordered_json;
|
|||||||
|
|
||||||
TTF_Font* UE::Font::GetFont(int size)
|
TTF_Font* UE::Font::GetFont(int size)
|
||||||
{
|
{
|
||||||
TTF_Font* font;
|
TTF_Font* font;
|
||||||
|
|
||||||
auto it = _fonts.find(size);
|
auto it = _fonts.find(size);
|
||||||
if (it == _fonts.end())
|
if (it == _fonts.end())
|
||||||
{
|
{
|
||||||
//El tama�o pedido no est� disponible.
|
//El tama�o pedido no est� disponible.
|
||||||
//La creamos nueva.
|
//La creamos nueva.
|
||||||
font = CreateFontSize(size);
|
font = CreateFontSize(size);
|
||||||
return font;
|
return font;
|
||||||
}
|
}
|
||||||
//En caso de estar disponible, lo retornamos.
|
//En caso de estar disponible, lo retornamos.
|
||||||
font = it->second;
|
font = it->second;
|
||||||
return font;
|
return font;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Font::InitFont()
|
void UE::Font::InitFont()
|
||||||
{
|
{
|
||||||
//Cargamos los datos desde el archivo.
|
//Cargamos los datos desde el archivo.
|
||||||
std::fstream file(_dataPath.c_str());
|
std::fstream file(_dataPath.c_str());
|
||||||
|
|
||||||
if (!file.is_open())
|
if (!file.is_open())
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de fuente: {0}", _fontPath);
|
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de fuente: {0}", _fontPath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
json jread = json::parse(file);
|
json jread = json::parse(file);
|
||||||
|
|
||||||
_fontPath = jread["FontPath"].get<std::string>();
|
_fontPath = jread["FontPath"].get<std::string>();
|
||||||
|
|
||||||
//Obtenemos los tama�os que crear de inicio.
|
//Obtenemos los tama�os que crear de inicio.
|
||||||
std::vector<int> vect = jread["FontSizes"].get<std::vector<int>>();
|
std::vector<int> vect = jread["FontSizes"].get<std::vector<int>>();
|
||||||
for (auto it : vect)
|
for (auto it : vect)
|
||||||
{
|
{
|
||||||
CreateFontSize(it);
|
CreateFontSize(it);
|
||||||
}
|
}
|
||||||
|
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Font::CleanFont()
|
void UE::Font::CleanFont()
|
||||||
{
|
{
|
||||||
//Eliminamos todos los tama�os de las fuentes.
|
//Eliminamos todos los tama�os de las fuentes.
|
||||||
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
|
for (auto i = _fonts.begin(); i != _fonts.end(); i++)
|
||||||
{
|
{
|
||||||
TTF_CloseFont(i->second);
|
TTF_CloseFont(i->second);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
TTF_Font* UE::Font::CreateFontSize(int size)
|
TTF_Font* UE::Font::CreateFontSize(int size)
|
||||||
{
|
{
|
||||||
//Creamos la fuente del tama�o requerido.
|
//Creamos la fuente del tama�o requerido.
|
||||||
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
|
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
|
||||||
if (font == nullptr)
|
if (font == nullptr)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
//La a�adimos al mapa.
|
//La a�adimos al mapa.
|
||||||
_fonts.insert(std::make_pair(size, font));
|
_fonts.insert(std::make_pair(size, font));
|
||||||
|
|
||||||
UE_LOG_TRACE("Font: {0} se ha creado con tamanho: {1}", _fontPath, size);
|
UE_LOG_TRACE("Font: {0} se ha creado con tamanho: {1}", _fontPath, size);
|
||||||
|
|
||||||
return font;
|
return font;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,79 +7,79 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Clase Wrapper para las SDL_Fonts.
|
* Clase Wrapper para las SDL_Fonts.
|
||||||
* También sirve de "cache" para los diferentes tamaños de la fuente, de esta forma
|
* Tambi�n sirve de "cache" para los diferentes tama�os de la fuente, de esta forma
|
||||||
* reducimos las veces que generamos las fuentes y podemos utilizar múltiples tamaños de forma sencilla.
|
* reducimos las veces que generamos las fuentes y podemos utilizar m�ltiples tama�os de forma sencilla.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
class Font
|
class Font
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//----- Constructor -----
|
//----- Constructor -----
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
Font(std::string dataPath)
|
Font(std::string dataPath)
|
||||||
: _dataPath(dataPath)
|
: _dataPath(dataPath)
|
||||||
{
|
{
|
||||||
InitFont();
|
InitFont();
|
||||||
}
|
}
|
||||||
|
|
||||||
~Font()
|
~Font()
|
||||||
{
|
{
|
||||||
CleanFont();
|
CleanFont();
|
||||||
}
|
}
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------- Methods -------
|
//------- Methods -------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Devuelve la fuente del tamaño pedido.
|
* Devuelve la fuente del tama�o pedido.
|
||||||
* En caso de no estar disponible, la genera y la añade al cache antes de devolverla.
|
* En caso de no estar disponible, la genera y la a�ade al cache antes de devolverla.
|
||||||
*
|
*
|
||||||
* @param size : tamaño de la fuente.
|
* @param size : tama�o de la fuente.
|
||||||
* @return TTF_Font* : Fuente del tamaño solicitado.
|
* @return TTF_Font* : Fuente del tama�o solicitado.
|
||||||
*/
|
*/
|
||||||
TTF_Font* GetFont(int size);
|
TTF_Font* GetFont(int size);
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/**
|
/**
|
||||||
* Crea la fuente a partir del archivo de datos.
|
* Crea la fuente a partir del archivo de datos.
|
||||||
*/
|
*/
|
||||||
void InitFont();
|
void InitFont();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Limpia la fuente, eliminando todos sus tamaños y vaciando toda la memoria.
|
* Limpia la fuente, eliminando todos sus tama�os y vaciando toda la memoria.
|
||||||
*/
|
*/
|
||||||
void CleanFont();
|
void CleanFont();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Se encarga de generar el tamaño de fuente deseado.
|
* Se encarga de generar el tama�o de fuente deseado.
|
||||||
*
|
*
|
||||||
* @param size : tamaño a generar.
|
* @param size : tama�o a generar.
|
||||||
* @return TTF_Font* : Ptr al nuevo tamaño generado. Hay que guardarlo en algún sitio.
|
* @return TTF_Font* : Ptr al nuevo tama�o generado. Hay que guardarlo en alg�n sitio.
|
||||||
*/
|
*/
|
||||||
TTF_Font* CreateFontSize(int size);
|
TTF_Font* CreateFontSize(int size);
|
||||||
|
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------ Variables ------
|
//------ Variables ------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
private:
|
private:
|
||||||
//Ubicación del archivo de datos (.json).
|
//Ubicaci�n del archivo de datos (.json).
|
||||||
std::string _dataPath = "";
|
std::string _dataPath = "";
|
||||||
|
|
||||||
//Ubicación de la tipografía (.ttf).
|
//Ubicaci�n de la tipograf�a (.ttf).
|
||||||
std::string _fontPath = "";
|
std::string _fontPath = "";
|
||||||
|
|
||||||
//Caché de los diferentes tamaños de la fuente.
|
//Cach� de los diferentes tama�os de la fuente.
|
||||||
std::unordered_map<int, TTF_Font*> _fonts = {};
|
std::unordered_map<int, TTF_Font*> _fonts = {};
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -10,61 +10,61 @@ using json = nlohmann::ordered_json;
|
|||||||
|
|
||||||
SDL_Rect* UE::Texture::GetTextureRect(int i)
|
SDL_Rect* UE::Texture::GetTextureRect(int i)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
SDL_Rect* rect = &_txRects.at(i);
|
SDL_Rect* rect = &_txRects.at(i);
|
||||||
return rect;
|
return rect;
|
||||||
}
|
}
|
||||||
catch (const std::out_of_range&)
|
catch (const std::out_of_range&)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
|
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
|
||||||
return &_txRects.at(0);
|
return &_txRects.at(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::InitTexture()
|
void UE::Texture::InitTexture()
|
||||||
{
|
{
|
||||||
std::fstream file(_dataPath);
|
std::fstream file(_dataPath);
|
||||||
//Comprobamos si el archivo se ha abierto.
|
//Comprobamos si el archivo se ha abierto.
|
||||||
if (!file.is_open())
|
if (!file.is_open())
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
json jread = json::parse(file);
|
json jread = json::parse(file);
|
||||||
_txPath = jread["TexturePath"].get<std::string>();
|
_txPath = jread["TexturePath"].get<std::string>();
|
||||||
|
|
||||||
//Creamos la textura.
|
//Creamos la textura.
|
||||||
CreateTexture();
|
CreateTexture();
|
||||||
|
|
||||||
//Cargamos los Rects.
|
//Cargamos los Rects.
|
||||||
json textureRects = jread["TextureRects"];
|
json textureRects = jread["TextureRects"];
|
||||||
|
|
||||||
for (int i = 0; i < textureRects.size(); i++)
|
for (int i = 0; i < textureRects.size(); i++)
|
||||||
{
|
{
|
||||||
AddRect(textureRects.at(i).get<SDL_Rect>());
|
AddRect(textureRects.at(i).get<SDL_Rect>());
|
||||||
}
|
}
|
||||||
|
|
||||||
file.close();
|
file.close();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::CleanTexture()
|
void UE::Texture::CleanTexture()
|
||||||
{
|
{
|
||||||
SDL_DestroyTexture(_texture);
|
SDL_DestroyTexture(_texture);
|
||||||
_txRects.clear();
|
_txRects.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::CreateTexture()
|
void UE::Texture::CreateTexture()
|
||||||
{
|
{
|
||||||
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
|
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
|
||||||
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
|
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
|
||||||
SDL_FreeSurface(loadSurface);
|
SDL_FreeSurface(loadSurface);
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Texture::AddRect(SDL_Rect newRect)
|
void UE::Texture::AddRect(SDL_Rect newRect)
|
||||||
{
|
{
|
||||||
_txRects.push_back(newRect);
|
_txRects.push_back(newRect);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,93 +9,93 @@
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
class Texture
|
class Texture
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//----- Constructor -----
|
//----- Constructor -----
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
Texture(std::string dataPath, SDL_Renderer* renderer)
|
Texture(std::string dataPath, SDL_Renderer* renderer)
|
||||||
: _dataPath(dataPath), _SDL_Renderer(renderer)
|
: _dataPath(dataPath), _SDL_Renderer(renderer)
|
||||||
{
|
{
|
||||||
InitTexture();
|
InitTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
~Texture()
|
~Texture()
|
||||||
{
|
{
|
||||||
CleanTexture();
|
CleanTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------- Methods -------
|
//------- Methods -------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna la textura.
|
* Retorna la textura.
|
||||||
*/
|
*/
|
||||||
inline SDL_Texture* GetTexture() { return _texture; }
|
inline SDL_Texture* GetTexture() { return _texture; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna los Rects de la textura.
|
* Retorna los Rects de la textura.
|
||||||
*/
|
*/
|
||||||
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
|
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retorna el Rect pedido. Comprobando que está disponible.
|
* Retorna el Rect pedido. Comprobando que est� disponible.
|
||||||
* Si no está disponible, devuelve el rect de index 0 (que debería ser el por defecto).
|
* Si no est� disponible, devuelve el rect de index 0 (que deber�a ser el por defecto).
|
||||||
*
|
*
|
||||||
* @param i : Índice del rect.
|
* @param i : �ndice del rect.
|
||||||
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
|
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
|
||||||
*/
|
*/
|
||||||
SDL_Rect* GetTextureRect(int i);
|
SDL_Rect* GetTextureRect(int i);
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/**
|
/**
|
||||||
* Carga los datos desde el archivo de datos y crea la textura y sus rects.
|
* Carga los datos desde el archivo de datos y crea la textura y sus rects.
|
||||||
*/
|
*/
|
||||||
void InitTexture();
|
void InitTexture();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Limpia todos los datos guardados.
|
* Limpia todos los datos guardados.
|
||||||
*/
|
*/
|
||||||
void CleanTexture();
|
void CleanTexture();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Método encargado de generar la textura a partir de los valores de la clase.
|
* M�todo encargado de generar la textura a partir de los valores de la clase.
|
||||||
*/
|
*/
|
||||||
void CreateTexture();
|
void CreateTexture();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Método que añade un SDL_Rect al vector correspondiente.
|
* M�todo que a�ade un SDL_Rect al vector correspondiente.
|
||||||
* @param newRect : Nuevo Rect que añadir al vector de Rects.
|
* @param newRect : Nuevo Rect que a�adir al vector de Rects.
|
||||||
*/
|
*/
|
||||||
void AddRect(SDL_Rect newRect);
|
void AddRect(SDL_Rect newRect);
|
||||||
|
|
||||||
//-----------------------
|
//-----------------------
|
||||||
//------ Variables ------
|
//------ Variables ------
|
||||||
//-----------------------
|
//-----------------------
|
||||||
|
|
||||||
private:
|
private:
|
||||||
//Ubicación del archivo de datos (.json).
|
//Ubicaci�n del archivo de datos (.json).
|
||||||
std::string _dataPath = "";
|
std::string _dataPath = "";
|
||||||
|
|
||||||
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
|
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
|
||||||
SDL_Renderer* _SDL_Renderer = nullptr;
|
SDL_Renderer* _SDL_Renderer = nullptr;
|
||||||
|
|
||||||
//Ubicación de la textura (.png).
|
//Ubicaci�n de la textura (.png).
|
||||||
std::string _txPath = "";
|
std::string _txPath = "";
|
||||||
|
|
||||||
//La propia textura.
|
//La propia textura.
|
||||||
SDL_Texture* _texture = nullptr;
|
SDL_Texture* _texture = nullptr;
|
||||||
//Conjunto de rects que hay en la textura.
|
//Conjunto de rects que hay en la textura.
|
||||||
std::vector<SDL_Rect> _txRects = {};
|
std::vector<SDL_Rect> _txRects = {};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -9,45 +9,45 @@
|
|||||||
|
|
||||||
void UE::Sprite::SetTextureRect(int textureID)
|
void UE::Sprite::SetTextureRect(int textureID)
|
||||||
{
|
{
|
||||||
SDL_Rect* newRect = _texture->GetTextureRect(textureID);
|
SDL_Rect* newRect = _texture->GetTextureRect(textureID);
|
||||||
|
|
||||||
if (newRect != nullptr)
|
if (newRect != nullptr)
|
||||||
{
|
{
|
||||||
_actualTxRect = newRect;
|
_actualTxRect = newRect;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Sprite::SetActive(bool active)
|
void UE::Sprite::SetActive(bool active)
|
||||||
{
|
{
|
||||||
isActive = active;
|
isActive = active;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool UE::Sprite::IsActive()
|
bool UE::Sprite::IsActive()
|
||||||
{
|
{
|
||||||
return isActive;
|
return isActive;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void UE::Sprite::Draw(Renderer* renderer)
|
void UE::Sprite::Draw(Renderer* renderer)
|
||||||
{
|
{
|
||||||
//Convertimos a ScreenCoords.
|
//Convertimos a ScreenCoords.
|
||||||
glm::ivec2 screenCoords = renderer->WorldToSreenCoords(_pos);
|
glm::ivec2 screenCoords = renderer->WorldToSreenCoords(_pos);
|
||||||
|
|
||||||
SDL_Rect position = { screenCoords.x, screenCoords.y, _size.x, _size.y };
|
SDL_Rect position = { screenCoords.x, screenCoords.y, _size.x, _size.y };
|
||||||
|
|
||||||
//destination.x = _pos.x;
|
//destination.x = _pos.x;
|
||||||
//destination.y = _pos.y;
|
//destination.y = _pos.y;
|
||||||
//
|
//
|
||||||
//destination.w = _size.x;
|
//destination.w = _size.x;
|
||||||
//destination.h = _size.y;
|
//destination.h = _size.y;
|
||||||
|
|
||||||
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
|
//std::cout << "Sprite Rendered to: " << destination.x << "-" << destination.y << std::endl;
|
||||||
renderer->QueueDrawCall(_renderLayer, position, _texture->GetTexture(), *_actualTxRect);
|
renderer->QueueDrawCall(_renderLayer, position, _texture->GetTexture(), *_actualTxRect);
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_Rect UE::Sprite::getPositionRect()
|
SDL_Rect UE::Sprite::getPositionRect()
|
||||||
{
|
{
|
||||||
SDL_Rect position = { _pos.x, _pos.y, _size.x, _size.y };
|
SDL_Rect position = { _pos.x, _pos.y, _size.x, _size.y };
|
||||||
return position;
|
return position;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,80 +21,80 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
class Renderer;
|
class Renderer;
|
||||||
|
|
||||||
class Sprite : public Drawable, public Transformable
|
class Sprite : public Drawable, public Transformable
|
||||||
{
|
{
|
||||||
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// --------------
|
// --------------
|
||||||
// Constructores.
|
// Constructores.
|
||||||
// --------------
|
// --------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Se establecen todos los par�metos.
|
Se establecen todos los par�metos.
|
||||||
La textura es obligatoria, y puede ha de darse:
|
La textura es obligatoria, y puede ha de darse:
|
||||||
- En SDL_Texture* -> Sin m�s, se entiende.
|
- En SDL_Texture* -> Sin m�s, se entiende.
|
||||||
En ambos casos se llama al m�todo SetTexturePtr.
|
En ambos casos se llama al m�todo SetTexturePtr.
|
||||||
Los dem�s par�metros tienen un valor por defecto.
|
Los dem�s par�metros tienen un valor por defecto.
|
||||||
|
|
||||||
\param texturePtr: El pointer a la textura de SDL.
|
\param texturePtr: El pointer a la textura de SDL.
|
||||||
\param textureRects: El pointer al conjunto de SDL_Rects de la textura.
|
\param textureRects: El pointer al conjunto de SDL_Rects de la textura.
|
||||||
\param textureRectID: El n�mero de Rect del conjunto de rects.
|
\param textureRectID: El n�mero de Rect del conjunto de rects.
|
||||||
\param renderLayer: La Layer en que se renderizar�.
|
\param renderLayer: La Layer en que se renderizar�.
|
||||||
*/
|
*/
|
||||||
Sprite(UE::Texture* texture,
|
Sprite(UE::Texture* texture,
|
||||||
int textureRectID = 0,
|
int textureRectID = 0,
|
||||||
int renderLayer = 1,
|
int renderLayer = 1,
|
||||||
glm::vec2 position = glm::vec2(0, 0),
|
glm::vec2 position = glm::vec2(0, 0),
|
||||||
glm::vec2 size = glm::vec2(100, 100))
|
glm::vec2 size = glm::vec2(100, 100))
|
||||||
|
|
||||||
: _texture(texture)
|
: _texture(texture)
|
||||||
{
|
{
|
||||||
SetTextureRect(textureRectID);
|
SetTextureRect(textureRectID);
|
||||||
|
|
||||||
SetLayer(renderLayer);
|
SetLayer(renderLayer);
|
||||||
|
|
||||||
SetPosition(position);
|
SetPosition(position);
|
||||||
SetSize(size);
|
SetSize(size);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
~Sprite() {}
|
~Sprite() {}
|
||||||
|
|
||||||
|
|
||||||
//-----------
|
//-----------
|
||||||
//- Setters -
|
//- Setters -
|
||||||
//-----------
|
//-----------
|
||||||
|
|
||||||
|
|
||||||
void SetTextureRect(int textureID);
|
void SetTextureRect(int textureID);
|
||||||
|
|
||||||
void SetActive(bool active);
|
void SetActive(bool active);
|
||||||
bool IsActive();
|
bool IsActive();
|
||||||
|
|
||||||
//Implementa el Draw de Drawable.
|
//Implementa el Draw de Drawable.
|
||||||
void Draw(Renderer* renderer) override;
|
void Draw(Renderer* renderer) override;
|
||||||
|
|
||||||
SDL_Rect getPositionRect();
|
SDL_Rect getPositionRect();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
//Datos de la textura. Sirven para pedirla al AssetManager.
|
//Datos de la textura. Sirven para pedirla al AssetManager.
|
||||||
|
|
||||||
UE::Texture* _texture = nullptr;
|
UE::Texture* _texture = nullptr;
|
||||||
|
|
||||||
//El que se va a renderizar.
|
//El que se va a renderizar.
|
||||||
SDL_Rect* _actualTxRect = nullptr;
|
SDL_Rect* _actualTxRect = nullptr;
|
||||||
|
|
||||||
bool isActive = true;
|
bool isActive = true;
|
||||||
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -5,28 +5,28 @@
|
|||||||
|
|
||||||
void UE::TextBox::SetText(std::string newText)
|
void UE::TextBox::SetText(std::string newText)
|
||||||
{
|
{
|
||||||
_text = newText;
|
_text = newText;
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::TextBox::SetSize(int newSize)
|
void UE::TextBox::SetSize(int newSize)
|
||||||
{
|
{
|
||||||
_textSize = newSize;
|
_textSize = newSize;
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void UE::TextBox::SetColor(UE_Color newColor)
|
void UE::TextBox::SetColor(UE_Color newColor)
|
||||||
{
|
{
|
||||||
_textColor = newColor;
|
_textColor = newColor;
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::TextBox::SetColor(int r, int g, int b, int a)
|
void UE::TextBox::SetColor(int r, int g, int b, int a)
|
||||||
{
|
{
|
||||||
UE_Color c = UE_Color(r, g, b, a);
|
UE_Color c = UE_Color(r, g, b, a);
|
||||||
_textColor = c;
|
_textColor = c;
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -34,56 +34,56 @@ void UE::TextBox::SetColor(int r, int g, int b, int a)
|
|||||||
|
|
||||||
void UE::TextBox::Draw(Renderer* renderer)
|
void UE::TextBox::Draw(Renderer* renderer)
|
||||||
{
|
{
|
||||||
//Si a�n no tenemos renderer, lo guardamos y procesamos.
|
//Si a�n no tenemos renderer, lo guardamos y procesamos.
|
||||||
if (_sdlRenderer == nullptr)
|
if (_sdlRenderer == nullptr)
|
||||||
{
|
{
|
||||||
_sdlRenderer = renderer->GetSDLRenderer();
|
_sdlRenderer = renderer->GetSDLRenderer();
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
if (_textTexture == nullptr)
|
if (_textTexture == nullptr)
|
||||||
{
|
{
|
||||||
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
|
UE_LOG_WARN("El texto: {0} ; No se est� renderizando. La textura no existe.", _text);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Generamos el SDL_Rect destino.
|
//Generamos el SDL_Rect destino.
|
||||||
SDL_Rect dest = { _pos.x, _pos.y, _size.x, _size.y };
|
SDL_Rect dest = { _pos.x, _pos.y, _size.x, _size.y };
|
||||||
|
|
||||||
renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
|
renderer->QueueDrawCall(_renderLayer, dest, _textTexture);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::TextBox::RenderTextTexture()
|
void UE::TextBox::RenderTextTexture()
|
||||||
{
|
{
|
||||||
//No podemos continuar hasta que no tengamos un renderer.
|
//No podemos continuar hasta que no tengamos un renderer.
|
||||||
if (_sdlRenderer == nullptr) { return; }
|
if (_sdlRenderer == nullptr) { return; }
|
||||||
|
|
||||||
SDL_DestroyTexture(_textTexture);
|
SDL_DestroyTexture(_textTexture);
|
||||||
|
|
||||||
//Creamos el SDL_Color a partir del vec4 que contiene el color.
|
//Creamos el SDL_Color a partir del vec4 que contiene el color.
|
||||||
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
|
SDL_Color color = { _textColor.x,_textColor.y, _textColor.z, _textColor.w };
|
||||||
|
|
||||||
//Tomamos la TTF_Font del tama�o que queremos de UE::Font.
|
//Tomamos la TTF_Font del tama�o que queremos de UE::Font.
|
||||||
TTF_Font* fn = _font->GetFont(_textSize);
|
TTF_Font* fn = _font->GetFont(_textSize);
|
||||||
|
|
||||||
SDL_Surface* loader = TTF_RenderText_Solid(fn, _text.c_str(), color);
|
SDL_Surface* loader = TTF_RenderText_Solid(fn, _text.c_str(), color);
|
||||||
if (loader == NULL)
|
if (loader == NULL)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido crear el texto: {0} ; Error: {1}",
|
UE_LOG_ERROR("No se ha podido crear el texto: {0} ; Error: {1}",
|
||||||
_text, TTF_GetError());
|
_text, TTF_GetError());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_textTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
|
_textTexture = SDL_CreateTextureFromSurface(_sdlRenderer, loader);
|
||||||
if (_textTexture == NULL)
|
if (_textTexture == NULL)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
|
UE_LOG_ERROR("No se ha podido crear la textura del texto: {0} ; Error: {1}",
|
||||||
_text, SDL_GetError());
|
_text, SDL_GetError());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_size.x = loader->w;
|
_size.x = loader->w;
|
||||||
_size.y = loader->h;
|
_size.y = loader->h;
|
||||||
|
|
||||||
SDL_FreeSurface(loader);
|
SDL_FreeSurface(loader);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -14,57 +14,57 @@
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
typedef glm::tvec4<int> UE_Color;
|
typedef glm::tvec4<int> UE_Color;
|
||||||
|
|
||||||
class TextBox : public Drawable, public Transformable
|
class TextBox : public Drawable, public Transformable
|
||||||
{
|
{
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
|
|
||||||
TextBox(UE::Font* font,
|
TextBox(UE::Font* font,
|
||||||
std::string text = "Texto por defecto",
|
std::string text = "Texto por defecto",
|
||||||
int textSize = 18,
|
int textSize = 18,
|
||||||
UE_Color textColor = UE_Color(0, 0, 0, 255),
|
UE_Color textColor = UE_Color(0, 0, 0, 255),
|
||||||
int renderLayer = 1,
|
int renderLayer = 1,
|
||||||
glm::vec2 position = glm::vec2(0, 0))
|
glm::vec2 position = glm::vec2(0, 0))
|
||||||
: _font(font), _text(text), _textSize(textSize)
|
: _font(font), _text(text), _textSize(textSize)
|
||||||
{
|
{
|
||||||
SetColor(textColor);
|
SetColor(textColor);
|
||||||
|
|
||||||
SetLayer(renderLayer);
|
SetLayer(renderLayer);
|
||||||
SetPosition(position);
|
SetPosition(position);
|
||||||
|
|
||||||
RenderTextTexture();
|
RenderTextTexture();
|
||||||
}
|
}
|
||||||
|
|
||||||
//Se generar� una textura y todo eso...
|
//Se generar� una textura y todo eso...
|
||||||
void SetText(std::string newText);
|
void SetText(std::string newText);
|
||||||
void SetSize(int newSize);
|
void SetSize(int newSize);
|
||||||
|
|
||||||
void SetColor(UE_Color newColor);
|
void SetColor(UE_Color newColor);
|
||||||
void SetColor(int r, int g, int b, int a);
|
void SetColor(int r, int g, int b, int a);
|
||||||
|
|
||||||
|
|
||||||
//Implementa el Draw de Drawable.
|
//Implementa el Draw de Drawable.
|
||||||
void Draw(Renderer* renderer) override;
|
void Draw(Renderer* renderer) override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void RenderTextTexture();
|
void RenderTextTexture();
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
UE::Font* _font = nullptr;
|
UE::Font* _font = nullptr;
|
||||||
std::string _text = "Texto por defecto";
|
std::string _text = "Texto por defecto";
|
||||||
int _textSize = 18;
|
int _textSize = 18;
|
||||||
UE_Color _textColor;
|
UE_Color _textColor;
|
||||||
|
|
||||||
SDL_Texture* _textTexture = nullptr;
|
SDL_Texture* _textTexture = nullptr;
|
||||||
|
|
||||||
//Esto est� muy mal hecho, no deber�a de ser as�.
|
//Esto est� muy mal hecho, no deber�a de ser as�.
|
||||||
//Necesito un renderer para crear la textura del texto, pero no puedo conseguirlo con la arquitectura actual.
|
//Necesito un renderer para crear la textura del texto, pero no puedo conseguirlo con la arquitectura actual.
|
||||||
//No quiero regenerar la textura en cada frame de forma innecesaria...
|
//No quiero regenerar la textura en cada frame de forma innecesaria...
|
||||||
//Por ello, me toca forzar un poco el sistema.
|
//Por ello, me toca forzar un poco el sistema.
|
||||||
SDL_Renderer* _sdlRenderer = nullptr;
|
SDL_Renderer* _sdlRenderer = nullptr;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -5,18 +5,18 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
std::shared_ptr<spdlog::logger> Logger::_engineLogger;
|
std::shared_ptr<spdlog::logger> Logger::_engineLogger;
|
||||||
std::shared_ptr<spdlog::logger> Logger::_gameLogger;
|
std::shared_ptr<spdlog::logger> Logger::_gameLogger;
|
||||||
|
|
||||||
void Logger::InitLogger()
|
void Logger::InitLogger()
|
||||||
{
|
{
|
||||||
spdlog::set_pattern("%^[%T]: %l - %n: %v %$");
|
spdlog::set_pattern("%^[%T]: %l - %n: %v %$");
|
||||||
|
|
||||||
_engineLogger = spdlog::stdout_color_mt("UberEngine");
|
_engineLogger = spdlog::stdout_color_mt("UberEngine");
|
||||||
_engineLogger->set_level(spdlog::level::trace);
|
_engineLogger->set_level(spdlog::level::trace);
|
||||||
|
|
||||||
_gameLogger = spdlog::stdout_color_mt("UberGame1");
|
_gameLogger = spdlog::stdout_color_mt("UberGame1");
|
||||||
_gameLogger->set_level(spdlog::level::trace);
|
_gameLogger->set_level(spdlog::level::trace);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,35 +7,35 @@
|
|||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
class Logger
|
class Logger
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
static void InitLogger();
|
static void InitLogger();
|
||||||
|
|
||||||
inline static std::shared_ptr<spdlog::logger>& GetGameLogger() { return _gameLogger; }
|
inline static std::shared_ptr<spdlog::logger>& GetGameLogger() { return _gameLogger; }
|
||||||
inline static std::shared_ptr<spdlog::logger>& GetEngineLogger() { return _engineLogger; }
|
inline static std::shared_ptr<spdlog::logger>& GetEngineLogger() { return _engineLogger; }
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static std::shared_ptr<spdlog::logger> _engineLogger;
|
static std::shared_ptr<spdlog::logger> _engineLogger;
|
||||||
static std::shared_ptr<spdlog::logger> _gameLogger;
|
static std::shared_ptr<spdlog::logger> _gameLogger;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//Macros para el Logging. Es más cómodo que estar poniendo la línea entera cada vez...
|
//Macros para el Logging. Es más cómodo que estar poniendo la línea entera cada vez...
|
||||||
#define UE_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
|
#define UE_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
|
||||||
#define UE_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
|
#define UE_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
|
||||||
#define UE_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
|
#define UE_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
|
||||||
#define UE_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
|
#define UE_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
|
||||||
#define UE_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
|
#define UE_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
|
||||||
#define UE_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
|
#define UE_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
|
||||||
|
|
||||||
#define GAME_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
|
#define GAME_LOG_TRACE(...) ::UE::Logger::GetEngineLogger()->trace(__VA_ARGS__)
|
||||||
#define GAME_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
|
#define GAME_LOG_DEBUG(...) ::UE::Logger::GetEngineLogger()->debug(__VA_ARGS__)
|
||||||
#define GAME_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
|
#define GAME_LOG_INFO(...) ::UE::Logger::GetEngineLogger()->info(__VA_ARGS__)
|
||||||
#define GAME_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
|
#define GAME_LOG_WARN(...) ::UE::Logger::GetEngineLogger()->warn(__VA_ARGS__)
|
||||||
#define GAME_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
|
#define GAME_LOG_ERROR(...) ::UE::Logger::GetEngineLogger()->error(__VA_ARGS__)
|
||||||
#define GAME_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
|
#define GAME_LOG_CRITICAL(...) ::UE::Logger::GetEngineLogger()->critical(__VA_ARGS__)
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -2,26 +2,26 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
class Renderer;
|
class Renderer;
|
||||||
|
|
||||||
class Drawable
|
class Drawable
|
||||||
{
|
{
|
||||||
|
|
||||||
public:
|
public:
|
||||||
Drawable() {}
|
Drawable() {}
|
||||||
virtual ~Drawable() {};
|
virtual ~Drawable() {};
|
||||||
|
|
||||||
//Get-Set del renderLayer.
|
//Get-Set del renderLayer.
|
||||||
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
|
inline void SetLayer(int newLayer) { _renderLayer = newLayer; }
|
||||||
inline int GetLayer() { return _renderLayer; }
|
inline int GetLayer() { return _renderLayer; }
|
||||||
|
|
||||||
public:
|
public:
|
||||||
virtual void Draw(Renderer* renderer) = 0;
|
virtual void Draw(Renderer* renderer) = 0;
|
||||||
|
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//renderLayer usada en el renderer como "profundidad".
|
//renderLayer usada en el renderer como "profundidad".
|
||||||
int _renderLayer = 0;
|
int _renderLayer = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
+186
-186
@@ -13,246 +13,246 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
int Renderer::InitRenderer()
|
int Renderer::InitRenderer()
|
||||||
{
|
{
|
||||||
//Configuramos los par�metros de la ventana de SDL.
|
//Configuramos los par�metros de la ventana de SDL.
|
||||||
Uint32 windowFlags = (SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE);
|
Uint32 windowFlags = (SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE);
|
||||||
|
|
||||||
//Creamos la ventana de SDL.
|
//Creamos la ventana de SDL.
|
||||||
_window = SDL_CreateWindow("UberGame1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenSize.x, screenSize.y, windowFlags);
|
_window = SDL_CreateWindow("UberGame1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenSize.x, screenSize.y, windowFlags);
|
||||||
if (_window == NULL)
|
if (_window == NULL)
|
||||||
{
|
{
|
||||||
UE_LOG_CRITICAL("Renderer - CreateWindow: No se ha podido crear la ventana con OpenGL: {0}", SDL_GetError());
|
UE_LOG_CRITICAL("Renderer - CreateWindow: No se ha podido crear la ventana con OpenGL: {0}", SDL_GetError());
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Creamos el Renderer de SDL.
|
//Creamos el Renderer de SDL.
|
||||||
main_Renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
|
main_Renderer = SDL_CreateRenderer(_window, -1, SDL_RENDERER_ACCELERATED);
|
||||||
if (main_Renderer == NULL)
|
if (main_Renderer == NULL)
|
||||||
{
|
{
|
||||||
UE_LOG_CRITICAL("Renderer - SDL_Renderer: No se ha podido crear el Renderer de SDL: {0}", SDL_GetError());
|
UE_LOG_CRITICAL("Renderer - SDL_Renderer: No se ha podido crear el Renderer de SDL: {0}", SDL_GetError());
|
||||||
return -2;
|
return -2;
|
||||||
}
|
}
|
||||||
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
SDL_SetRenderDrawColor(main_Renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||||
|
|
||||||
|
|
||||||
#pragma region ImGui.
|
#pragma region ImGui.
|
||||||
|
|
||||||
IMGUI_CHECKVERSION();
|
IMGUI_CHECKVERSION();
|
||||||
ImGui::CreateContext();
|
ImGui::CreateContext();
|
||||||
ImGuiIO& io = ImGui::GetIO();
|
ImGuiIO& io = ImGui::GetIO();
|
||||||
(void)io; //Evita que de un Warning por variable no usada.
|
(void)io; //Evita que de un Warning por variable no usada.
|
||||||
|
|
||||||
ImGui::StyleColorsDark();
|
ImGui::StyleColorsDark();
|
||||||
|
|
||||||
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
|
ImGui_ImplSDL2_InitForSDLRenderer(_window, main_Renderer);
|
||||||
ImGui_ImplSDLRenderer_Init(main_Renderer);
|
ImGui_ImplSDLRenderer_Init(main_Renderer);
|
||||||
|
|
||||||
#pragma endregion
|
#pragma endregion
|
||||||
|
|
||||||
|
|
||||||
//Init layers.
|
//Init layers.
|
||||||
for (int i = 0; i <= LAYER_AMOUNT; i++)
|
for (int i = 0; i <= LAYER_AMOUNT; i++)
|
||||||
{
|
{
|
||||||
renderLayers.push_back(std::vector<DrawCall>());
|
renderLayers.push_back(std::vector<DrawCall>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::CleanRenderer()
|
void Renderer::CleanRenderer()
|
||||||
{
|
{
|
||||||
renderQueue.empty();
|
renderQueue.empty();
|
||||||
|
|
||||||
ImGui_ImplSDLRenderer_Shutdown();
|
ImGui_ImplSDLRenderer_Shutdown();
|
||||||
ImGui_ImplSDL2_Shutdown();
|
ImGui_ImplSDL2_Shutdown();
|
||||||
ImGui::DestroyContext();
|
ImGui::DestroyContext();
|
||||||
|
|
||||||
SDL_DestroyRenderer(main_Renderer);
|
SDL_DestroyRenderer(main_Renderer);
|
||||||
SDL_DestroyWindow(_window);
|
SDL_DestroyWindow(_window);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void Renderer::RenderFrame()
|
void Renderer::RenderFrame()
|
||||||
{
|
{
|
||||||
NewFrame();
|
NewFrame();
|
||||||
RenderData();
|
RenderData();
|
||||||
EndFrame();
|
EndFrame();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Renderer::NewFrame()
|
void Renderer::NewFrame()
|
||||||
{
|
{
|
||||||
SDL_RenderClear(main_Renderer);
|
SDL_RenderClear(main_Renderer);
|
||||||
|
|
||||||
ImGui_ImplSDLRenderer_NewFrame();
|
ImGui_ImplSDLRenderer_NewFrame();
|
||||||
ImGui_ImplSDL2_NewFrame();
|
ImGui_ImplSDL2_NewFrame();
|
||||||
ImGui::NewFrame();
|
ImGui::NewFrame();
|
||||||
|
|
||||||
//Quiz�s deber�amos limpiar la cola y las Layers aqu� para eliminar residuos...
|
//Quiz�s deber�amos limpiar la cola y las Layers aqu� para eliminar residuos...
|
||||||
//callCounter = 0;
|
//callCounter = 0;
|
||||||
//rendererCounter = 0;
|
//rendererCounter = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::RenderData()
|
void Renderer::RenderData()
|
||||||
{
|
{
|
||||||
//Add items to their layer.
|
//Add items to their layer.
|
||||||
for (int i = 0; i < renderQueue.size(); i++)
|
for (int i = 0; i < renderQueue.size(); i++)
|
||||||
{
|
{
|
||||||
DrawCall item = renderQueue.at(i);
|
DrawCall item = renderQueue.at(i);
|
||||||
|
|
||||||
//Add item i to layer number i.layer.
|
//Add item i to layer number i.layer.
|
||||||
if (item.layer > LAYER_AMOUNT)
|
if (item.layer > LAYER_AMOUNT)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("Error rendering data: Can't render item to Layer {0} -> out of range\n", item.layer);
|
UE_LOG_ERROR("Error rendering data: Can't render item to Layer {0} -> out of range\n", item.layer);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
renderLayers.at(item.layer).push_back(item);
|
renderLayers.at(item.layer).push_back(item);
|
||||||
|
|
||||||
}
|
}
|
||||||
renderQueue.clear();
|
renderQueue.clear();
|
||||||
|
|
||||||
//Iterate layers.
|
//Iterate layers.
|
||||||
for (int j = 0; j < renderLayers.size(); j++)
|
for (int j = 0; j < renderLayers.size(); j++)
|
||||||
{
|
{
|
||||||
std::vector<DrawCall>& layer = renderLayers.at(j);
|
std::vector<DrawCall>& layer = renderLayers.at(j);
|
||||||
//Render items from layer j.
|
//Render items from layer j.
|
||||||
for (int k = 0; k < layer.size(); k++)
|
for (int k = 0; k < layer.size(); k++)
|
||||||
{
|
{
|
||||||
DrawCall item = layer.at(k);
|
DrawCall item = layer.at(k);
|
||||||
if (item.fullTexture)
|
if (item.fullTexture)
|
||||||
{
|
{
|
||||||
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
|
SDL_RenderCopy(main_Renderer, item.tx, NULL, &item.pos_rect);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
|
SDL_RenderCopy(main_Renderer, item.tx, &item.tx_rect, &item.pos_rect);
|
||||||
}
|
}
|
||||||
layer.clear();
|
layer.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Renderer::EndFrame()
|
void Renderer::EndFrame()
|
||||||
{
|
{
|
||||||
//SDL_UpdateWindowSurface(window);
|
//SDL_UpdateWindowSurface(window);
|
||||||
//SDL_RenderPresent(main_Renderer);
|
//SDL_RenderPresent(main_Renderer);
|
||||||
//SDL_RenderClear(main_Renderer);
|
//SDL_RenderClear(main_Renderer);
|
||||||
ImGui::Render();
|
ImGui::Render();
|
||||||
|
|
||||||
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
|
ImGui_ImplSDLRenderer_RenderDrawData(ImGui::GetDrawData());
|
||||||
|
|
||||||
SDL_RenderPresent(main_Renderer);
|
SDL_RenderPresent(main_Renderer);
|
||||||
|
|
||||||
//UE_LOG_INFO("CallCounter: {0} ; Renderer: {1}", callCounter, rendererCounter);
|
//UE_LOG_INFO("CallCounter: {0} ; Renderer: {1}", callCounter, rendererCounter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void Renderer::SetScreenSize(int newWidth, int newHeight)
|
void Renderer::SetScreenSize(int newWidth, int newHeight)
|
||||||
{
|
{
|
||||||
screenSize.x = newWidth;
|
screenSize.x = newWidth;
|
||||||
screenSize.y = newHeight;
|
screenSize.y = newHeight;
|
||||||
SDL_SetWindowSize(_window, newWidth, newHeight);
|
SDL_SetWindowSize(_window, newWidth, newHeight);
|
||||||
glViewport(0, 0, newWidth, newHeight);
|
glViewport(0, 0, newWidth, newHeight);
|
||||||
|
|
||||||
UE_LOG_TRACE("Screen size chaged to: {0}x{1}", newWidth, newHeight);
|
UE_LOG_TRACE("Screen size chaged to: {0}x{1}", newWidth, newHeight);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::SetCamPosition(int posX, int posY)
|
void Renderer::SetCamPosition(int posX, int posY)
|
||||||
{
|
{
|
||||||
camPosition.x = posX;
|
camPosition.x = posX;
|
||||||
camPosition.y = posY;
|
camPosition.y = posY;
|
||||||
//UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
|
//UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
|
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
|
||||||
{
|
{
|
||||||
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
||||||
glm::ivec2 fPos = worldCoord - camPosition;
|
glm::ivec2 fPos = worldCoord - camPosition;
|
||||||
|
|
||||||
return fPos;
|
return fPos;
|
||||||
}
|
}
|
||||||
|
|
||||||
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
|
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
|
||||||
{
|
{
|
||||||
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
||||||
glm::ivec2 fPos = screenCoord + camPosition;
|
glm::ivec2 fPos = screenCoord + camPosition;
|
||||||
|
|
||||||
return fPos;
|
return fPos;
|
||||||
}
|
}
|
||||||
|
|
||||||
//CREO QUE ESTE M�TODO NO FUNCIONA.
|
//CREO QUE ESTE M�TODO NO FUNCIONA.
|
||||||
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
|
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
|
||||||
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
|
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
|
||||||
{
|
{
|
||||||
|
|
||||||
//Generamos un rect que representa la pantalla.
|
//Generamos un rect que representa la pantalla.
|
||||||
SDL_Rect screen{ camPosition.x, camPosition.y, screenSize.x, screenSize.y };
|
SDL_Rect screen{ camPosition.x, camPosition.y, screenSize.x, screenSize.y };
|
||||||
//Comprobamos si hay intersecci�n entre ambos.
|
//Comprobamos si hay intersecci�n entre ambos.
|
||||||
if (!SDL_HasIntersection(&screen, objectRect))
|
if (!SDL_HasIntersection(&screen, objectRect))
|
||||||
{
|
{
|
||||||
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
|
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//�Deber�amos operar la posici�n para que tenga en cuenta la c�mara?
|
//�Deber�amos operar la posici�n para que tenga en cuenta la c�mara?
|
||||||
void Renderer::DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture)
|
void Renderer::DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture)
|
||||||
{
|
{
|
||||||
SDL_RenderCopy(main_Renderer, texture, texture_pos, position);
|
SDL_RenderCopy(main_Renderer, texture, texture_pos, position);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
void Renderer::QueueDrawCall(DrawCall drawCall)
|
void Renderer::QueueDrawCall(DrawCall drawCall)
|
||||||
{
|
{
|
||||||
//callCounter++;
|
//callCounter++;
|
||||||
//Add item i to layer number i.layer.
|
//Add item i to layer number i.layer.
|
||||||
if (drawCall.layer > LAYER_AMOUNT)
|
if (drawCall.layer > LAYER_AMOUNT)
|
||||||
{
|
{
|
||||||
UE_LOG_ERROR("Can't add DrawCall to Layer {0} -> out of range\n", drawCall.layer);
|
UE_LOG_ERROR("Can't add DrawCall to Layer {0} -> out of range\n", drawCall.layer);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
//Comprobamos si el objeto es visible.
|
//Comprobamos si el objeto es visible.
|
||||||
//
|
//
|
||||||
//Generamos un rect que representa la pantalla.
|
//Generamos un rect que representa la pantalla.
|
||||||
SDL_Rect screen{ 0, 0, screenSize.x, screenSize.y };
|
SDL_Rect screen{ 0, 0, screenSize.x, screenSize.y };
|
||||||
//Comprobamos si hay intersecci�n entre ambos.
|
//Comprobamos si hay intersecci�n entre ambos.
|
||||||
if (!SDL_HasIntersection(&screen, &drawCall.pos_rect))
|
if (!SDL_HasIntersection(&screen, &drawCall.pos_rect))
|
||||||
{
|
{
|
||||||
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
|
//UE_LOG_TRACE("Se omite el renderizado de un objeto al estar fuera de la c�mara.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
renderLayers.at(drawCall.layer).push_back(drawCall);
|
renderLayers.at(drawCall.layer).push_back(drawCall);
|
||||||
//rendererCounter++;
|
//rendererCounter++;
|
||||||
//renderQueue.push_back(drawCall);
|
//renderQueue.push_back(drawCall);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position)
|
void Renderer::QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position)
|
||||||
{
|
{
|
||||||
DrawCall dc = DrawCall(layer, position, texture, texture_position);
|
DrawCall dc = DrawCall(layer, position, texture, texture_position);
|
||||||
QueueDrawCall(dc);
|
QueueDrawCall(dc);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture)
|
void Renderer::QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture)
|
||||||
{
|
{
|
||||||
//std::cout << "Drawable added to queue";
|
//std::cout << "Drawable added to queue";
|
||||||
DrawCall dc = DrawCall(layer, position, texture);
|
DrawCall dc = DrawCall(layer, position, texture);
|
||||||
QueueDrawCall(dc);
|
QueueDrawCall(dc);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Renderer::Render(Drawable& drawable)
|
void Renderer::Render(Drawable& drawable)
|
||||||
{
|
{
|
||||||
drawable.Draw(this);
|
drawable.Draw(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
+107
-107
@@ -19,155 +19,155 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
struct DrawCall;
|
struct DrawCall;
|
||||||
|
|
||||||
|
|
||||||
class Renderer
|
class Renderer
|
||||||
{
|
{
|
||||||
|
|
||||||
public:
|
public:
|
||||||
/* Constructor */
|
/* Constructor */
|
||||||
Renderer(int windowWidth,
|
Renderer(int windowWidth,
|
||||||
int windowHeight,
|
int windowHeight,
|
||||||
int renderingLayers = 10)
|
int renderingLayers = 10)
|
||||||
|
|
||||||
: LAYER_AMOUNT(renderingLayers)
|
: LAYER_AMOUNT(renderingLayers)
|
||||||
{
|
{
|
||||||
screenSize.x = windowWidth;
|
screenSize.x = windowWidth;
|
||||||
screenSize.y = windowHeight;
|
screenSize.y = windowHeight;
|
||||||
//UE_LOG_INFO("Game Renderer Created.");
|
//UE_LOG_INFO("Game Renderer Created.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Inicializa los componentes necesarios:
|
/* Inicializa los componentes necesarios:
|
||||||
- Inicializa SDL
|
- Inicializa SDL
|
||||||
- Crea la ventana.
|
- Crea la ventana.
|
||||||
- Crea el renderer.
|
- Crea el renderer.
|
||||||
- ...
|
- ...
|
||||||
*/
|
*/
|
||||||
int InitRenderer();
|
int InitRenderer();
|
||||||
|
|
||||||
/* Limpia todo antes de salir. */
|
/* Limpia todo antes de salir. */
|
||||||
void CleanRenderer();
|
void CleanRenderer();
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
|
//Hace el SDL_RenderClear() para limpiar el buffer al principio de un nuevo frame.
|
||||||
void NewFrame();
|
void NewFrame();
|
||||||
|
|
||||||
//Ordena por layer todos los objetos de la renderQueue y los dibuja en orden.
|
//Ordena por layer todos los objetos de la renderQueue y los dibuja en orden.
|
||||||
//Se puede mover el proceso de ordenado a otra funci�n, con el objeto de ir vaciando la Queue.
|
//Se puede mover el proceso de ordenado a otra funci�n, con el objeto de ir vaciando la Queue.
|
||||||
void RenderData();
|
void RenderData();
|
||||||
|
|
||||||
|
|
||||||
//Hace el swap del render buffer (tras dibujar todos los objetos). Termina el renderizado.
|
//Hace el swap del render buffer (tras dibujar todos los objetos). Termina el renderizado.
|
||||||
void EndFrame();
|
void EndFrame();
|
||||||
|
|
||||||
|
|
||||||
//A�ade un DrawCall al renderQueue.
|
//A�ade un DrawCall al renderQueue.
|
||||||
void QueueDrawCall(DrawCall drawCall);
|
void QueueDrawCall(DrawCall drawCall);
|
||||||
void QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position);
|
void QueueDrawCall(int layer, SDL_Rect& position, SDL_Texture* texture, SDL_Rect& texture_position);
|
||||||
void QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture);
|
void QueueDrawCall(int layer, SDL_Rect & position, SDL_Texture* texture);
|
||||||
|
|
||||||
//Le pasamos este renderer al Drawable para que haga lo que quiera.
|
//Le pasamos este renderer al Drawable para que haga lo que quiera.
|
||||||
//Como si quiere usar el SDL_Renderer, es libre.
|
//Como si quiere usar el SDL_Renderer, es libre.
|
||||||
void Render(Drawable& drawable);
|
void Render(Drawable& drawable);
|
||||||
|
|
||||||
/* Get SDL Renderer. */
|
/* Get SDL Renderer. */
|
||||||
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
|
SDL_Renderer* GetSDLRenderer() { return main_Renderer; }
|
||||||
|
|
||||||
inline glm::ivec2 GetScreenSize() { return screenSize; }
|
inline glm::ivec2 GetScreenSize() { return screenSize; }
|
||||||
void SetScreenSize(int newWidth, int newHeight);
|
void SetScreenSize(int newWidth, int newHeight);
|
||||||
|
|
||||||
inline glm::ivec2 GetCamPosition() { return camPosition; }
|
inline glm::ivec2 GetCamPosition() { return camPosition; }
|
||||||
void SetCamPosition(int posX, int posY);
|
void SetCamPosition(int posX, int posY);
|
||||||
|
|
||||||
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
|
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
|
||||||
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
||||||
//Convierte coordenadas de mundo a la pantalla (en funci�n de la c�mara).
|
//Convierte coordenadas de mundo a la pantalla (en funci�n de la c�mara).
|
||||||
glm::ivec2 WorldToSreenCoords(glm::ivec2 worldCoord);
|
glm::ivec2 WorldToSreenCoords(glm::ivec2 worldCoord);
|
||||||
//Convierte coordenadas de la pantalla al mundo.
|
//Convierte coordenadas de la pantalla al mundo.
|
||||||
glm::ivec2 ScreenToWorldCoords(glm::ivec2 screenCoord);
|
glm::ivec2 ScreenToWorldCoords(glm::ivec2 screenCoord);
|
||||||
|
|
||||||
//Comprueba si un objeto est� dentro del rect�ngulo de la c�mara.
|
//Comprueba si un objeto est� dentro del rect�ngulo de la c�mara.
|
||||||
//Usada para saber si un objeto se deber�a de renderizar o no.
|
//Usada para saber si un objeto se deber�a de renderizar o no.
|
||||||
bool IsObjectVisible(SDL_Rect* objectRect);
|
bool IsObjectVisible(SDL_Rect* objectRect);
|
||||||
|
|
||||||
|
|
||||||
//DEBUG
|
//DEBUG
|
||||||
//Funci�n para renderizar un objeto un objeto en concreto directamente en el SDL_Renderer.
|
//Funci�n para renderizar un objeto un objeto en concreto directamente en el SDL_Renderer.
|
||||||
void DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture);
|
void DrawObject(SDL_Rect* position, SDL_Rect* texture_pos, SDL_Texture* texture);
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
|
//Realizar RenderClear(), RenderDraw() y RenderUpdate();
|
||||||
//Es decir, todo lo necesario para renderizar un frame.
|
//Es decir, todo lo necesario para renderizar un frame.
|
||||||
void RenderFrame();
|
void RenderFrame();
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
/* Objetos de SDL para el rendering. */
|
/* Objetos de SDL para el rendering. */
|
||||||
SDL_Window* _window = nullptr;
|
SDL_Window* _window = nullptr;
|
||||||
SDL_Surface* screenSurface = nullptr;
|
SDL_Surface* screenSurface = nullptr;
|
||||||
SDL_Renderer* main_Renderer = nullptr;
|
SDL_Renderer* main_Renderer = nullptr;
|
||||||
|
|
||||||
//SDL_GLContext _glContext = nullptr;
|
//SDL_GLContext _glContext = nullptr;
|
||||||
|
|
||||||
//Almacena todas las "draw calls" para luego ordenar los objetos por layers y dibujarlos.
|
//Almacena todas las "draw calls" para luego ordenar los objetos por layers y dibujarlos.
|
||||||
//Se podr�a sustituir por un std::queue o std::deque si fuera necesario.
|
//Se podr�a sustituir por un std::queue o std::deque si fuera necesario.
|
||||||
std::vector<DrawCall> renderQueue;
|
std::vector<DrawCall> renderQueue;
|
||||||
|
|
||||||
//Las capas en las que se organizan los diferentes objetos.
|
//Las capas en las que se organizan los diferentes objetos.
|
||||||
//Permite dibujar unos sprites sobre otros.
|
//Permite dibujar unos sprites sobre otros.
|
||||||
const int LAYER_AMOUNT = 10;
|
const int LAYER_AMOUNT = 10;
|
||||||
std::vector<std::vector<DrawCall>> renderLayers;
|
std::vector<std::vector<DrawCall>> renderLayers;
|
||||||
|
|
||||||
|
|
||||||
//int screenWidth = 640;
|
//int screenWidth = 640;
|
||||||
//int screenHeight = 480;
|
//int screenHeight = 480;
|
||||||
|
|
||||||
glm::ivec2 screenSize{ 640,480 };
|
glm::ivec2 screenSize{ 640,480 };
|
||||||
glm::ivec2 camPosition{ 0,0 };
|
glm::ivec2 camPosition{ 0,0 };
|
||||||
|
|
||||||
|
|
||||||
//DEBUG
|
//DEBUG
|
||||||
int callCounter = 0;
|
int callCounter = 0;
|
||||||
int rendererCounter = 0;
|
int rendererCounter = 0;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Contiene los valores necesarios para realizar el renderizado con SDL_RenderCopy();
|
Contiene los valores necesarios para realizar el renderizado con SDL_RenderCopy();
|
||||||
Se almacena en la renderQueue y luego son ordenados por las renderLayers.
|
Se almacena en la renderQueue y luego son ordenados por las renderLayers.
|
||||||
*/
|
*/
|
||||||
struct DrawCall
|
struct DrawCall
|
||||||
{
|
{
|
||||||
DrawCall(int layer,
|
DrawCall(int layer,
|
||||||
SDL_Rect position,
|
SDL_Rect position,
|
||||||
SDL_Texture* texture,
|
SDL_Texture* texture,
|
||||||
SDL_Rect texture_position)
|
SDL_Rect texture_position)
|
||||||
|
|
||||||
: layer(layer), tx(texture), tx_rect(texture_position), pos_rect(position)
|
: layer(layer), tx(texture), tx_rect(texture_position), pos_rect(position)
|
||||||
{}
|
{}
|
||||||
|
|
||||||
DrawCall(int layer,
|
DrawCall(int layer,
|
||||||
SDL_Rect position,
|
SDL_Rect position,
|
||||||
SDL_Texture* texture)
|
SDL_Texture* texture)
|
||||||
: layer(layer), tx(texture), pos_rect(position)
|
: layer(layer), tx(texture), pos_rect(position)
|
||||||
{
|
{
|
||||||
tx_rect = SDL_Rect();
|
tx_rect = SDL_Rect();
|
||||||
fullTexture = true;
|
fullTexture = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int layer;
|
int layer;
|
||||||
|
|
||||||
bool fullTexture = false;
|
bool fullTexture = false;
|
||||||
|
|
||||||
SDL_Texture* tx;
|
SDL_Texture* tx;
|
||||||
SDL_Rect tx_rect;
|
SDL_Rect tx_rect;
|
||||||
|
|
||||||
SDL_Rect pos_rect;
|
SDL_Rect pos_rect;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -7,41 +7,41 @@
|
|||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
/*
|
/*
|
||||||
Clase que contiene lo necesario para crear un objeto con posici�n en el espacio y modificarlo.
|
Clase que contiene lo necesario para crear un objeto con posici�n en el espacio y modificarlo.
|
||||||
*/
|
*/
|
||||||
class Transformable
|
class Transformable
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
|
||||||
|
|
||||||
//-----------
|
//-----------
|
||||||
//- Setters -
|
//- Setters -
|
||||||
//-----------
|
//-----------
|
||||||
|
|
||||||
|
|
||||||
//Modifica la posici�n del Objeto.
|
//Modifica la posici�n del Objeto.
|
||||||
inline void SetPosition(float x, float y) { _pos = glm::vec<2, float>(x, y); }
|
inline void SetPosition(float x, float y) { _pos = glm::vec<2, float>(x, y); }
|
||||||
inline void SetPosition(glm::vec<2, float> newPosition) { _pos = newPosition; }
|
inline void SetPosition(glm::vec<2, float> newPosition) { _pos = newPosition; }
|
||||||
|
|
||||||
//Modifica la escala de Objeto.
|
//Modifica la escala de Objeto.
|
||||||
inline void SetSize(float x, float y) { _size = glm::vec<2, float>(x, y); }
|
inline void SetSize(float x, float y) { _size = glm::vec<2, float>(x, y); }
|
||||||
inline void SetSize(glm::vec<2, float> newSize) { _size = newSize; }
|
inline void SetSize(glm::vec<2, float> newSize) { _size = newSize; }
|
||||||
|
|
||||||
//-----------
|
//-----------
|
||||||
//- Getters -
|
//- Getters -
|
||||||
//-----------
|
//-----------
|
||||||
|
|
||||||
inline glm::vec2 GetPosition() { return _pos; }
|
inline glm::vec2 GetPosition() { return _pos; }
|
||||||
inline glm::vec2 GetSize() { return _size; }
|
inline glm::vec2 GetSize() { return _size; }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//Se almacena la posici�n y el tama�o del objeto. Con esto se puede crear un SDL_Rect.
|
//Se almacena la posici�n y el tama�o del objeto. Con esto se puede crear un SDL_Rect.
|
||||||
glm::vec<2, float> _pos;
|
glm::vec<2, float> _pos;
|
||||||
glm::vec<2, float> _size;
|
glm::vec<2, float> _size;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -8,36 +8,36 @@ uint32_t UE::Time::_startTime;
|
|||||||
|
|
||||||
void UE::Time::StartFrame()
|
void UE::Time::StartFrame()
|
||||||
{
|
{
|
||||||
_startTime = SDL_GetTicks();
|
_startTime = SDL_GetTicks();
|
||||||
}
|
}
|
||||||
|
|
||||||
void UE::Time::EndFrame()
|
void UE::Time::EndFrame()
|
||||||
{
|
{
|
||||||
// Calculamos el tiempo que llevamos de Frame, para que si nos quedamos cortos, esperemos.
|
// Calculamos el tiempo que llevamos de Frame, para que si nos quedamos cortos, esperemos.
|
||||||
|
|
||||||
//FrameTime es el tiempo que ha tardado el frame (el deltaTime) en MS.
|
//FrameTime es el tiempo que ha tardado el frame (el deltaTime) en MS.
|
||||||
uint32_t frameTime = SDL_GetTicks() - _startTime;
|
uint32_t frameTime = SDL_GetTicks() - _startTime;
|
||||||
|
|
||||||
|
|
||||||
//Frames totales / segundos totales.
|
//Frames totales / segundos totales.
|
||||||
//_avgFPS = countedFrames / (SDL_GetTicks() / 1000.f);
|
//_avgFPS = countedFrames / (SDL_GetTicks() / 1000.f);
|
||||||
//std::cout << "FPS: " << avgFPS << " / " << "dT: " << deltaTime << std::endl;
|
//std::cout << "FPS: " << avgFPS << " / " << "dT: " << deltaTime << std::endl;
|
||||||
|
|
||||||
//Limitamos los FPS haciendo esperar al programa el tiempo extra que quede.
|
//Limitamos los FPS haciendo esperar al programa el tiempo extra que quede.
|
||||||
//En vez de sólo esperar, se podrían hacer tareas como cargar Assets o realizar cálculos pesados.
|
//En vez de s�lo esperar, se podr�an hacer tareas como cargar Assets o realizar c�lculos pesados.
|
||||||
if (frameTime < MS_PER_FRAME)
|
if (frameTime < MS_PER_FRAME)
|
||||||
{
|
{
|
||||||
SDL_Delay(MS_PER_FRAME - frameTime);
|
SDL_Delay(MS_PER_FRAME - frameTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Calculamos el deltaTime, que sí será el tiempo real que ha pasado, pues hemos esperado.
|
//Calculamos el deltaTime, que s� ser� el tiempo real que ha pasado, pues hemos esperado.
|
||||||
|
|
||||||
frameTime = SDL_GetTicks() - _startTime;
|
frameTime = SDL_GetTicks() - _startTime;
|
||||||
|
|
||||||
//Convertimos deltaTime a segundos pues es lo usado en los cálculos.
|
//Convertimos deltaTime a segundos pues es lo usado en los c�lculos.
|
||||||
deltaTime = frameTime / 1000.0f;
|
deltaTime = frameTime / 1000.0f;
|
||||||
|
|
||||||
|
|
||||||
//++countedFrames;
|
//++countedFrames;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+22
-22
@@ -2,42 +2,42 @@
|
|||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
|
||||||
/*
|
/*
|
||||||
TODO:
|
TODO:
|
||||||
- Buscar una mejor forma de calcular la media de FPS.
|
- Buscar una mejor forma de calcular la media de FPS.
|
||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace UE
|
namespace UE
|
||||||
{
|
{
|
||||||
|
|
||||||
class Time
|
class Time
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
|
|
||||||
//-------------------
|
//-------------------
|
||||||
//---- Métodos ------
|
//---- Métodos ------
|
||||||
//-------------------
|
//-------------------
|
||||||
static void StartFrame();
|
static void StartFrame();
|
||||||
|
|
||||||
|
|
||||||
static void EndFrame();
|
static void EndFrame();
|
||||||
|
|
||||||
//-------------------
|
//-------------------
|
||||||
//---- Variables ----
|
//---- Variables ----
|
||||||
//-------------------
|
//-------------------
|
||||||
static double deltaTime;
|
static double deltaTime;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static uint32_t _startTime;
|
static uint32_t _startTime;
|
||||||
//uint16_t countedFrames = 0;
|
//uint16_t countedFrames = 0;
|
||||||
float _avgFPS;
|
float _avgFPS;
|
||||||
|
|
||||||
|
|
||||||
static const int FPS = 60;
|
static const int FPS = 60;
|
||||||
//Milisegundos que tiene que tener un frame para poder hacer el número de FPS por segundo.
|
//Milisegundos que tiene que tener un frame para poder hacer el número de FPS por segundo.
|
||||||
static const int MS_PER_FRAME = 1000 / FPS;
|
static const int MS_PER_FRAME = 1000 / FPS;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user