Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
08f566fda6 | ||
|
|
724807e9f2 |
@@ -15,6 +15,7 @@ namespace UE
|
||||
UE_LOG_INFO("AssetManager Iniciado con éxito.");
|
||||
}
|
||||
|
||||
|
||||
void AssetManager::CleanAssetManager()
|
||||
{
|
||||
//Destruye todas las texturas de SDL.
|
||||
@@ -38,6 +39,7 @@ namespace UE
|
||||
}
|
||||
|
||||
|
||||
|
||||
void AssetManager::LoadAssetsFromFile(std::string filePath)
|
||||
{
|
||||
std::fstream file(filePath.c_str());
|
||||
@@ -119,40 +121,10 @@ namespace UE
|
||||
|
||||
|
||||
|
||||
|
||||
void AssetManager::LoadTexture(std::string name, std::string txPath)
|
||||
{
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -164,11 +136,37 @@ namespace UE
|
||||
}
|
||||
|
||||
|
||||
Texture* AssetManager::getTexture(std::string textureName)
|
||||
{
|
||||
Texture* txPtr;
|
||||
try
|
||||
{
|
||||
//Obtenemos la tx indicada.
|
||||
txPtr = _textures.at(textureName);
|
||||
}
|
||||
catch (const std::out_of_range&)
|
||||
{
|
||||
//Si no existe, usamos la por defecto.
|
||||
txPtr = _textures.at(defaultAsset);
|
||||
}
|
||||
|
||||
return txPtr;
|
||||
|
||||
}
|
||||
|
||||
|
||||
Texture* AssetManager::getDefaultTexture()
|
||||
{
|
||||
return _textures.at(defaultAsset);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void AssetManager::LoadFont(std::string name, std::string fontPath)
|
||||
{
|
||||
Font* fo = new Font(fontPath);
|
||||
_fonts.insert(std::make_pair(name, fo));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -180,6 +178,29 @@ namespace UE
|
||||
}
|
||||
|
||||
|
||||
Font* AssetManager::GetFont(std::string fontName)
|
||||
{
|
||||
Font* fontPtr;
|
||||
try
|
||||
{
|
||||
//Obtenemos la tx indicada.
|
||||
fontPtr = _fonts.at(fontName);
|
||||
}
|
||||
catch (const std::out_of_range&)
|
||||
{
|
||||
//Si no existe, usamos la por defecto.
|
||||
fontPtr = _fonts.at(defaultAsset);
|
||||
}
|
||||
|
||||
return fontPtr;
|
||||
}
|
||||
|
||||
|
||||
Font* AssetManager::getDefaultFont()
|
||||
{
|
||||
return _fonts.at(defaultAsset);
|
||||
}
|
||||
|
||||
//////////DEBUG//////////
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ namespace UE
|
||||
: _SDL_Renderer(SDLrenderer) {}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
* Init AssetManager y todo lo necesario para funcionar correctamente.
|
||||
* - Inicia SDL_IMG.
|
||||
@@ -57,6 +60,9 @@ namespace UE
|
||||
void CleanAssetManager();
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/* Carga de Assets */
|
||||
|
||||
/**
|
||||
@@ -78,6 +84,9 @@ namespace UE
|
||||
void LoadAsset(Asset& as);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
* Procesa la cola de carga de Assets.
|
||||
*
|
||||
@@ -93,33 +102,66 @@ namespace UE
|
||||
*/
|
||||
inline int GetAssetQueueSize() { return _assetQueue.size(); }
|
||||
|
||||
/// <summary>
|
||||
/// Comprueba si la cola de carga de Assets est� vac�a.
|
||||
/// </summary>
|
||||
/// <returns>El resultado de la cola.</returns>
|
||||
/**
|
||||
* Permite saber si la cola de carga de Assets está vacía.
|
||||
*
|
||||
* @return True si está vacía; false si hay algún Asset.
|
||||
*/
|
||||
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.
|
||||
/**
|
||||
* Carga una textura dado su nombre y su Path.
|
||||
*
|
||||
* @param name: Nombre identificador de la tx.
|
||||
* @param txPath: Ubicación de la tx que se quiere cargar.
|
||||
*/
|
||||
void LoadTexture(std::string name, std::string txPath);
|
||||
|
||||
//Elimina una textura del mapa a partir de su nombre.
|
||||
|
||||
/**
|
||||
* Descarga la textura con el nombre identificador indicado.
|
||||
* NOTA AssetManager: Quizás queramos cambiar el nombre de los métodos de descarga: RemoveAsset -> UnloadAsset.
|
||||
*
|
||||
* @param name: Nombre identificador.
|
||||
*/
|
||||
void RemoveTexture(std::string name);
|
||||
|
||||
/*
|
||||
Obtiene una textura del mapa a partir de su nombre.
|
||||
NOTA REWORK getTexture() -> La tx que se retorna habrá de ser const para evitar que modifiquen datos comunes.
|
||||
Así el TextureLoader o quien la cree podrá modificar lo que desee, pero no una vez metida aquí (hecha común).
|
||||
|
||||
|
||||
/**
|
||||
* Obtiene una textura del mapa a partir de su nombre.
|
||||
*
|
||||
* NOTA REWORK getTexture() -> La tx que se retorna habrá de ser const para evitar que modifiquen datos comunes.
|
||||
* Así el TextureLoader o quien la cree podrá modificar lo que desee, pero no una vez metida aquí (hecha común).
|
||||
*
|
||||
* @param textureName: Nombre de la textura que se quiere.
|
||||
*
|
||||
* @return Ptr a la tx solicitada.
|
||||
*/
|
||||
inline Texture* getTexture(std::string textureName) { return _textures.at(textureName); }
|
||||
Texture* getTexture(std::string textureName);
|
||||
|
||||
/**
|
||||
* Devuelve un Ptr a la textura por defecto.
|
||||
* Utilizado cuando no exista una textura específica.
|
||||
*
|
||||
* @return Ptr a la textura por defecto.
|
||||
*/
|
||||
Texture* getDefaultTexture();
|
||||
|
||||
//inline std::vector<SDL_Rect>* getTexureRects(std::string textureName) { return &_textureRects.at(textureName); }
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/*------------------------------------/
|
||||
* M�todos para manejar las fuentes. *
|
||||
*------------------------------------*/
|
||||
@@ -129,15 +171,13 @@ namespace UE
|
||||
*
|
||||
* @param name : Nombre del asset (key para el mapa de fuentes).
|
||||
* @param fontPath : Ubicaci�n del archivo de datos sobre la fuente.
|
||||
*
|
||||
*/
|
||||
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 dado su nombre identificador.
|
||||
*
|
||||
* @param name : Nombre del Asset (key del mapa de fuentes).
|
||||
*
|
||||
*/
|
||||
void RemoveFont(std::string name);
|
||||
|
||||
@@ -145,11 +185,21 @@ namespace UE
|
||||
* Obtiene y devuelve el ptr a una fuente dado su nombre de 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); }
|
||||
Font* GetFont(std::string fontName);
|
||||
|
||||
/**
|
||||
* Devuelve un Ptr a la fuente por defecto.
|
||||
* Utilizado cuando no exista o no se indique una fuente específica.
|
||||
*
|
||||
* @return Ptr a la fuente por defecto.
|
||||
*/
|
||||
Font* getDefaultFont();
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
///////DEBUG////////
|
||||
@@ -163,11 +213,24 @@ namespace UE
|
||||
//---------------------
|
||||
|
||||
|
||||
//std::string _assetPath;
|
||||
/**
|
||||
* Nombre de los Assets por defecto.
|
||||
* Sustituirá a un Asset no disponible.
|
||||
* NOTA: UberEngine debería traer Assets por defecto para esta funcionalidad.
|
||||
*/
|
||||
const std::string defaultAsset = "default";
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//std::vector<UE::Asset> _assets = {};
|
||||
std::deque<UE::Asset> _assetQueue = {};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/* Almacenes de asssets */
|
||||
|
||||
//Almac�n de SDL_Texture* (ptrs, pues lo gestiona SDL).
|
||||
@@ -179,6 +242,9 @@ namespace UE
|
||||
std::unordered_map<std::string, Font*> _fonts = {};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//Necesario para crear las SDL_Texture a partir de SDL_Surface.
|
||||
SDL_Renderer* _SDL_Renderer = NULL;
|
||||
};
|
||||
|
||||
@@ -15,8 +15,8 @@ TTF_Font* UE::Font::GetFont(int size)
|
||||
auto it = _fonts.find(size);
|
||||
if (it == _fonts.end())
|
||||
{
|
||||
//El tama�o pedido no est� disponible.
|
||||
//La creamos nueva.
|
||||
//El font size pedido no está disponible.
|
||||
//Creamos el nuevo size.
|
||||
font = CreateFontSize(size);
|
||||
return font;
|
||||
}
|
||||
@@ -62,18 +62,18 @@ void UE::Font::CleanFont()
|
||||
|
||||
TTF_Font* UE::Font::CreateFontSize(int size)
|
||||
{
|
||||
//Creamos la fuente del tama�o requerido.
|
||||
//Creamos la font size requerida.
|
||||
TTF_Font* font = TTF_OpenFont(_fontPath.c_str(), size);
|
||||
if (font == nullptr)
|
||||
{
|
||||
UE_LOG_ERROR("No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
||||
UE_LOG_ERROR("Font - No se ha podido crear la fuente: {0} - Size: {1}", _fontPath, size);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
//La a�adimos al mapa.
|
||||
//Add to the map
|
||||
_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 el Size: {1}", _fontPath, size);
|
||||
|
||||
return font;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,10 @@ namespace UE
|
||||
{
|
||||
/**
|
||||
* Clase Wrapper para las SDL_Fonts.
|
||||
* 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.
|
||||
*
|
||||
* Dada una fuente ttf, carga los glyphos con los tamaños indicados y almacena el TTF_Font del tamaño correspondiente.
|
||||
* Esta clase contiene todos los tamaños cargados.
|
||||
* En caso de pedir un tamaño no cargado, lo cargará desde el archivo.
|
||||
* REWORK Font -> Quizás se pueda sacar el loader a otro lado (Como en UE::Texture). Aunque en este caso, como es una especie de FontManager, no sé.
|
||||
*/
|
||||
class Font
|
||||
{
|
||||
@@ -31,53 +32,67 @@ namespace UE
|
||||
CleanFont();
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//-----------------------
|
||||
//------- Methods -------
|
||||
//-----------------------
|
||||
|
||||
|
||||
/**
|
||||
* Devuelve la fuente del tama�o pedido.
|
||||
* En caso de no estar disponible, la genera y la a�ade al cache antes de devolverla.
|
||||
* Devuelve la fuente del size pedido.
|
||||
* En caso de no estar disponible, la genera y la añade al cache antes de devolverla.
|
||||
*
|
||||
* @param size : tama�o de la fuente.
|
||||
* @return TTF_Font* : Fuente del tama�o solicitado.
|
||||
* @return TTF_Font* : Fuente del size solicitado. En caso de error, devuelve un nullptr.
|
||||
*/
|
||||
TTF_Font* GetFont(int size);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
private:
|
||||
/**
|
||||
* Crea la fuente a partir del archivo de datos.
|
||||
* Crea la clase a partir del archivo de datos.
|
||||
*/
|
||||
void InitFont();
|
||||
|
||||
/**
|
||||
* Limpia la fuente, eliminando todos sus tama�os y vaciando toda la memoria.
|
||||
* Limpia la clase, eliminando todos los font sizes y vaciando toda la memoria.
|
||||
*/
|
||||
void CleanFont();
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
* Se encarga de generar el tama�o de fuente deseado.
|
||||
* Se encarga de generar el Font Size de fuente deseado.
|
||||
*
|
||||
* @param size : tama�o a generar.
|
||||
* @return TTF_Font* : Ptr al nuevo tama�o generado. Hay que guardarlo en alg�n sitio.
|
||||
* @param size : Font Size a generar.
|
||||
* @return TTF_Font* : Ptr al nuevo Font Size generado.
|
||||
*/
|
||||
TTF_Font* CreateFontSize(int size);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
private:
|
||||
//-----------------------
|
||||
//------ Variables ------
|
||||
//-----------------------
|
||||
|
||||
private:
|
||||
//Ubicaci�n del archivo de datos (.json).
|
||||
std::string _dataPath = "";
|
||||
|
||||
//Ubicaci�n de la tipograf�a (.ttf).
|
||||
//Path del archivo de datos (.json).
|
||||
std::string _dataPath = "";
|
||||
//Path de la tipografía (.ttf).
|
||||
std::string _fontPath = "";
|
||||
|
||||
//Cach� de los diferentes tama�os de la fuente.
|
||||
//Cache de los diferentes Font Sizes (glyphos).
|
||||
std::unordered_map<int, TTF_Font*> _fonts = {};
|
||||
|
||||
};
|
||||
|
||||
@@ -8,17 +8,17 @@
|
||||
#include <json/json.hpp>
|
||||
using json = nlohmann::ordered_json;
|
||||
|
||||
SDL_Rect* UE::Texture::GetTextureRect(int i)
|
||||
SDL_Rect UE::Texture::GetTextureRect(int i)
|
||||
{
|
||||
try
|
||||
{
|
||||
SDL_Rect* rect = &_txRects.at(i);
|
||||
SDL_Rect rect = _txRects.at(i);
|
||||
return rect;
|
||||
}
|
||||
catch (const std::out_of_range&)
|
||||
{
|
||||
UE_LOG_ERROR("La textura {0} no tiene rect {1}", _txPath, i);
|
||||
return &_txRects.at(0);
|
||||
UE_LOG_WARN("La textura {0} no tiene rect {1}", _txPath, i);
|
||||
return _txRects.at(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -45,7 +45,7 @@ void UE::Texture::InitTexture()
|
||||
//Comprobamos si el archivo se ha abierto.
|
||||
if (!file.is_open())
|
||||
{
|
||||
UE_LOG_ERROR("No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
||||
UE_LOG_ERROR("Texture - No se ha podido abrir el archivo de datos de textura: {0}", _dataPath);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,11 +53,22 @@ void UE::Texture::InitTexture()
|
||||
_txPath = jread["TexturePath"].get<std::string>();
|
||||
|
||||
//Creamos la textura.
|
||||
CreateTexture();
|
||||
if (int error = CreateTexture() < 0)
|
||||
{
|
||||
UE_LOG_ERROR("Texture {0}: La textura no se ha cargado. Se esperan excepciones. Error {1}",
|
||||
_txPath,
|
||||
error);
|
||||
|
||||
//En principio, los Rects se pueden cargar. Por tanto, continuamos.
|
||||
}
|
||||
|
||||
//Cargamos los Rects.
|
||||
json textureRects = jread["TextureRects"];
|
||||
|
||||
//Por defecto, el Rect 0 es la textura completa.
|
||||
AddRect(SDL_Rect{ 0, 0, txSizeX, txSizeY });
|
||||
|
||||
//Este bucle debe empezar en 0, pues iteramos por los valores del JSON, no los de la textura.
|
||||
for (int i = 0; i < textureRects.size(); i++)
|
||||
{
|
||||
AddRect(textureRects.at(i).get<SDL_Rect>());
|
||||
@@ -73,14 +84,40 @@ void UE::Texture::CleanTexture()
|
||||
_txRects.clear();
|
||||
}
|
||||
|
||||
void UE::Texture::CreateTexture()
|
||||
int UE::Texture::CreateTexture()
|
||||
{
|
||||
SDL_Surface* loadSurface = IMG_Load(_txPath.c_str());
|
||||
if (loadSurface == NULL)
|
||||
{
|
||||
UE_LOG_ERROR("Texture - No se ha podido cargar la tx en {0}: {1}",
|
||||
_txPath,
|
||||
IMG_GetError()
|
||||
);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
//Extraemos el Size de la tx.
|
||||
txSizeX = loadSurface->w;
|
||||
txSizeY = loadSurface->h;
|
||||
|
||||
_texture = SDL_CreateTextureFromSurface(_SDL_Renderer, loadSurface);
|
||||
if (_texture == NULL)
|
||||
{
|
||||
UE_LOG_ERROR("Texture - No se ha podido crear la tx {0}: {1}",
|
||||
_txPath,
|
||||
SDL_GetError()
|
||||
);
|
||||
|
||||
return -2;
|
||||
}
|
||||
|
||||
SDL_FreeSurface(loadSurface);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void UE::Texture::AddRect(SDL_Rect newRect)
|
||||
void UE::Texture::AddRect(SDL_Rect& newRect)
|
||||
{
|
||||
_txRects.push_back(newRect);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,13 @@
|
||||
|
||||
namespace UE
|
||||
{
|
||||
//REWORK Texture -> Separar los datos (sdl_tx, rects, ...) del loader. No me gusta que una textura se tenga que cargar a si misma.
|
||||
/**
|
||||
* Wrapper para SDL_Texture permitiendo Texturas "animadas" o "SpriteSheets".
|
||||
* Contiene una SDL_Texture y un conjunto de SDL_Rects, indicando las distintas partes de la textura.
|
||||
* El SDL_Rect index 0 indica la textura completa.
|
||||
*
|
||||
* REWORK Texture -> Separar los datos (sdl_tx, rects, ...) del loader. No me gusta que una textura se tenga que cargar a si misma.
|
||||
*/
|
||||
class Texture
|
||||
{
|
||||
public:
|
||||
@@ -24,41 +30,51 @@ namespace UE
|
||||
InitTexture();
|
||||
}
|
||||
|
||||
|
||||
//HACK Texture() -> Lo utilizaremos únicamente para poder crear Texture vacias, hasta que separemos el loader.
|
||||
Texture()
|
||||
{
|
||||
//Creo que no es necesario nada...
|
||||
_dataPath = "";
|
||||
_txPath = "";
|
||||
}
|
||||
Texture() {}
|
||||
|
||||
~Texture()
|
||||
{
|
||||
CleanTexture();
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//-----------------------
|
||||
//------- Methods -------
|
||||
//-----------------------
|
||||
|
||||
|
||||
/**
|
||||
* Retorna la textura.
|
||||
* Retorna la textura interna.
|
||||
*
|
||||
* @return Ptr a la SDL_Texture que contiene.
|
||||
*/
|
||||
inline SDL_Texture* GetTexture() { return _texture; }
|
||||
|
||||
|
||||
/**
|
||||
* Retorna los Rects de la textura.
|
||||
*
|
||||
* @return Vector con todos los Rects de la textura.
|
||||
*/
|
||||
inline std::vector<SDL_Rect>* GetRectsVector() { return &_txRects; }
|
||||
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* Retorna el Rect indicado, comprobando que esté disponible.
|
||||
* Si no está disponible, devuelve el rect de index 0.
|
||||
*
|
||||
* @param i : �ndice del rect.
|
||||
* @return El SDL_Rect* solicitado (o el por defecto en caso de error).
|
||||
* @param i : index del rect. (El index 0 es la textura completa).
|
||||
* @return El SDL_Rect solicitado (o el por defecto si no está disponible).
|
||||
*/
|
||||
SDL_Rect* GetTextureRect(int i); // -> Devolver un SDL_Rect, el Ptr ocupa incluso más.
|
||||
SDL_Rect GetTextureRect(int i);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//HACK Tiene que ser posible hacer un SetTexture. Será necesario cuando no cree su propia textura.
|
||||
@@ -66,12 +82,20 @@ namespace UE
|
||||
void SetTexture(SDL_Texture* newTexture);
|
||||
|
||||
|
||||
/*
|
||||
M�todo que a�ade un SDL_Rect al vector correspondiente.
|
||||
@param newRect : Nuevo Rect que a�adir al vector de Rects.
|
||||
NOTA para REWORK -> Estaba en privado. Lo he movido aquí porque será público, pero no modificable si es const.
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
* Add a SDL_Rect to the Rect Array.
|
||||
*
|
||||
* NOTA para REWORK -> Estaba en privado. Lo he movido aquí porque será público, pero no modificable si es const.
|
||||
*
|
||||
* @param newRect: New Rect to add. Lo enviamos como referencia para ahorrar copias. IDK if is better...
|
||||
*/
|
||||
void AddRect(SDL_Rect newRect);
|
||||
void AddRect(SDL_Rect& newRect);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
private:
|
||||
@@ -85,32 +109,51 @@ namespace UE
|
||||
*/
|
||||
void CleanTexture();
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
* M�todo encargado de generar la textura a partir de los valores de la clase.
|
||||
* Genera la textura a partir de los valores de la clase.
|
||||
*/
|
||||
void CreateTexture();
|
||||
int CreateTexture();
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
private:
|
||||
//-----------------------
|
||||
//------ Variables ------
|
||||
//-----------------------
|
||||
|
||||
private:
|
||||
//Ubicaci�n del archivo de datos (.json).
|
||||
//Path del archivo de datos (.json).
|
||||
std::string _dataPath = "";
|
||||
|
||||
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
|
||||
SDL_Renderer* _SDL_Renderer = nullptr;
|
||||
|
||||
//Ubicaci�n de la textura (.png).
|
||||
//Path de la textura (.png o formato de la imagen).
|
||||
std::string _txPath = "";
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//La propia textura.
|
||||
SDL_Texture* _texture = nullptr;
|
||||
//Conjunto de rects que hay en la textura.
|
||||
std::vector<SDL_Rect> _txRects = {};
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
//Size de la SDL_Texture. Por si se necesita para algo...
|
||||
//NOTA Texture Size vars: Quizás haya que implementar algún método para estas vars.
|
||||
int txSizeX = 0;
|
||||
int txSizeY = 0;
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//El propio renderer de SDL. Es necesario para crear y operar con las SDL_Textures.
|
||||
//NOTA Texture: Para quitarlo de aquí, tenemos que mover el proceso de carga.
|
||||
SDL_Renderer* _SDL_Renderer = nullptr;
|
||||
|
||||
|
||||
};
|
||||
|
||||
@@ -61,7 +61,7 @@ namespace UE
|
||||
UE::Texture* _tx = nullptr;
|
||||
|
||||
//Sección de la textura que se utilizará.
|
||||
SDL_Rect _txRect;
|
||||
SDL_Rect _txRect{0, 0, 0, 0};
|
||||
|
||||
//UE::Texture contiene una lista de rects, con esto, podemos seleccionar el rect que queramos.
|
||||
//Pero es redundante con _txRect y para que sea seguro habría que encapsular todo.
|
||||
|
||||
@@ -10,12 +10,9 @@
|
||||
void UE::Sprite::SetTextureRect(int textureID)
|
||||
{
|
||||
_txRectID = textureID;
|
||||
SDL_Rect* newRect = _tx->GetTextureRect(textureID);
|
||||
|
||||
if (newRect != nullptr)
|
||||
{
|
||||
_txRect = *newRect;
|
||||
}
|
||||
|
||||
//Sabemos que en caso de no estar disponible, no devolverá el Rect 0 (Textura completa).
|
||||
_txRect = _tx->GetTextureRect(textureID);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,34 @@
|
||||
#include "Camera.h"
|
||||
#include "Logging/Logger.h"
|
||||
|
||||
#include <SDL_rect.h>
|
||||
|
||||
namespace UE
|
||||
{
|
||||
|
||||
void Camera::SetCamPosition(int posX, int posY)
|
||||
glm::vec2 Camera::WorldToSreenCoords(glm::vec<2, float> worldCoord)
|
||||
{
|
||||
camPosition.x = posX;
|
||||
camPosition.y = posY;
|
||||
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
||||
glm::ivec2 fPos = worldCoord - _pos;
|
||||
|
||||
UE_LOG_TRACE("Cam position chaged to: {0}x{1}", posX, posY);
|
||||
return fPos;
|
||||
}
|
||||
|
||||
glm::vec2 Camera::ScreenToWorldCoords(glm::vec<2, float> screenCoord)
|
||||
{
|
||||
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
||||
glm::ivec2 fPos = screenCoord + _pos;
|
||||
|
||||
return fPos;
|
||||
}
|
||||
|
||||
SDL_Rect Camera::WorldToScreenRect(SDL_Rect worldRect)
|
||||
{
|
||||
return SDL_Rect();
|
||||
}
|
||||
|
||||
SDL_Rect Camera::ScreenToWorldRect(SDL_Rect screenRect)
|
||||
{
|
||||
return SDL_Rect();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include <glm/vec2.hpp>
|
||||
|
||||
#include "Interfaces/Transformable.h"
|
||||
|
||||
//
|
||||
// ToDO:
|
||||
// - La cámara debería tener un tamaño definido.
|
||||
@@ -12,23 +14,43 @@
|
||||
|
||||
namespace UE
|
||||
{
|
||||
class Camera
|
||||
class Camera : public Transformable
|
||||
{
|
||||
public:
|
||||
|
||||
Camera() {}
|
||||
|
||||
Camera(int posX, int posY)
|
||||
: camPosition{posX, posY}
|
||||
{}
|
||||
{
|
||||
_pos = { posX, posY };
|
||||
}
|
||||
|
||||
inline glm::ivec2 GetCamPosition() { return camPosition; }
|
||||
void SetCamPosition(int posX, int posY);
|
||||
Camera(int posX, int posY, int sizeX, int sizeY)
|
||||
{
|
||||
_pos = { posX, posY };
|
||||
_size = { sizeX, sizeY };
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/* Métodos para transformar y proyectar coordenadas en función de la Camera. */
|
||||
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
||||
|
||||
//Proyecta las coordenadas de mundo a coordenadas de pantalla.
|
||||
glm::vec2 WorldToSreenCoords(glm::vec<2, float> worldCoord);
|
||||
|
||||
//Proyecta coordenadas de pantalla al mundo.
|
||||
glm::vec2 ScreenToWorldCoords(glm::vec<2, float> screenCoord);
|
||||
|
||||
|
||||
SDL_Rect WorldToScreenRect(SDL_Rect worldRect);
|
||||
SDL_Rect ScreenToWorldRect(SDL_Rect screenRect);
|
||||
|
||||
|
||||
|
||||
private:
|
||||
glm::ivec2 camPosition { 0, 0 };
|
||||
|
||||
//glm::ivec2 camSize { 0, 0 };
|
||||
|
||||
|
||||
@@ -98,8 +98,10 @@ namespace UE
|
||||
}
|
||||
|
||||
//Actualizamos el rect que representa la pantalla.
|
||||
glm::ivec2 camPos = activeCam->GetCamPosition();
|
||||
_screenRect = {camPos.x, camPos.y, screenSize.x, screenSize.y};
|
||||
glm::vec2 camPos = activeCam->GetPosition();
|
||||
int x = camPos.x;
|
||||
int y = camPos.y;
|
||||
_screenRect = {x, y, screenSize.x, screenSize.y};
|
||||
}
|
||||
|
||||
void Renderer::RenderData()
|
||||
@@ -118,11 +120,13 @@ namespace UE
|
||||
//Extract Drawable k
|
||||
Drawable* item = layer.at(k);
|
||||
|
||||
// FIX: Cuando la tx sea nullptr o salte except. -> Log y usar default tx.
|
||||
// En definitiva, añadir seguridad aquí, se puede usar la tx default.
|
||||
SDL_Texture* tx = item->_tx->GetTexture();
|
||||
|
||||
//Los están en WorldCoords. Convertimos la posición a ScreenCoords.
|
||||
// NOTA: Se deberá transformar todo el Rect en función de la cam, no sólo la pos.
|
||||
glm::ivec2 screenCoords = WorldToSreenCoords(item->_pos);
|
||||
glm::ivec2 screenCoords = activeCam->WorldToSreenCoords(item->_pos);
|
||||
SDL_Rect screenRect = { screenCoords.x, screenCoords.y, item->_size.x, item->_size.y };
|
||||
|
||||
//Le pasamos todo al SDL_Renderer.
|
||||
@@ -194,23 +198,6 @@ namespace UE
|
||||
}
|
||||
|
||||
|
||||
|
||||
glm::ivec2 Renderer::WorldToSreenCoords(glm::ivec2 worldCoord)
|
||||
{
|
||||
//Convertimos las coordenas de WorldCoords a ScreenCoords relativas a la camPosition.
|
||||
glm::ivec2 fPos = worldCoord - activeCam->GetCamPosition();
|
||||
|
||||
return fPos;
|
||||
}
|
||||
|
||||
glm::ivec2 Renderer::ScreenToWorldCoords(glm::ivec2 screenCoord)
|
||||
{
|
||||
//Convertimos las coordenas de ScreenCoords a WorldCoords relativas a la camPosition.
|
||||
glm::ivec2 fPos = screenCoord + activeCam->GetCamPosition();
|
||||
|
||||
return fPos;
|
||||
}
|
||||
|
||||
//CREO QUE ESTE MÉTODO NO FUNCIONA.
|
||||
//LAS COORDS QUE USAMOS EN LA COMPROBACI�N NO SON LAS ADECUADAS.
|
||||
bool Renderer::IsObjectVisible(SDL_Rect* objectRect)
|
||||
|
||||
@@ -145,18 +145,6 @@ namespace UE
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/* M�todos para transformar las coordenadas entre Screen y Wolrd. */
|
||||
//WorldCoords = ScreenPos + CamPos -> ScreenPos = WorldCoords - CamPos;
|
||||
|
||||
//Convierte coordenadas de mundo a la pantalla (en función de la cámara).
|
||||
glm::ivec2 WorldToSreenCoords(glm::ivec2 worldCoord);
|
||||
//Convierte coordenadas de la pantalla al mundo.
|
||||
glm::ivec2 ScreenToWorldCoords(glm::ivec2 screenCoord);
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
//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.
|
||||
bool IsObjectVisible(SDL_Rect* objectRect);
|
||||
|
||||
+8
-8
@@ -150,27 +150,27 @@ void Loop()
|
||||
UE::Camera* cam = UE_Renderer->GetCamera();
|
||||
if (keyStates[SDL_SCANCODE_W])
|
||||
{
|
||||
glm::ivec2 camPos = cam->GetCamPosition();
|
||||
glm::ivec2 camPos = cam->GetPosition();
|
||||
camPos.y -= 5;
|
||||
cam->SetCamPosition(camPos.x, camPos.y);
|
||||
cam->SetPosition(camPos.x, camPos.y);
|
||||
}
|
||||
if (keyStates[SDL_SCANCODE_S])
|
||||
{
|
||||
glm::ivec2 camPos = cam->GetCamPosition();
|
||||
glm::ivec2 camPos = cam->GetPosition();
|
||||
camPos.y += 5;
|
||||
cam->SetCamPosition(camPos.x, camPos.y);
|
||||
cam->SetPosition(camPos.x, camPos.y);
|
||||
}
|
||||
if (keyStates[SDL_SCANCODE_D])
|
||||
{
|
||||
glm::ivec2 camPos = cam->GetCamPosition();
|
||||
glm::ivec2 camPos = cam->GetPosition();
|
||||
camPos.x += 5;
|
||||
cam->SetCamPosition(camPos.x, camPos.y);
|
||||
cam->SetPosition(camPos.x, camPos.y);
|
||||
}
|
||||
if (keyStates[SDL_SCANCODE_A])
|
||||
{
|
||||
glm::ivec2 camPos = cam->GetCamPosition();
|
||||
glm::ivec2 camPos = cam->GetPosition();
|
||||
camPos.x -= 5;
|
||||
cam->SetCamPosition(camPos.x, camPos.y);
|
||||
cam->SetPosition(camPos.x, camPos.y);
|
||||
}
|
||||
|
||||
currentScene->SceneUpdate();
|
||||
|
||||
@@ -50,7 +50,7 @@ public:
|
||||
|
||||
UE::Sprite bg(as->getTexture("bg1"), 1, 0, glm::vec2(0, 0), UE::Engine::GetRenderer()->GetScreenSize());
|
||||
|
||||
UE::Sprite mapSP(as->getTexture("PruebaMap"), 0, 2, glm::vec2(50, 45), glm::vec2(145, 145));
|
||||
UE::Sprite mapSP(as->getTexture("PruebaMap"), 1, 2, glm::vec2(50, 45), glm::vec2(145, 145));
|
||||
|
||||
|
||||
sprites.push_back(sp1);
|
||||
|
||||
@@ -42,7 +42,7 @@ public:
|
||||
glm::vec2 size(100, 100);
|
||||
glm::vec2 pos = size * i;
|
||||
|
||||
UE::Sprite sp(tx, rand()%5, 1, pos, size);
|
||||
UE::Sprite sp(tx, (rand()%4)+1, 1, pos, size);
|
||||
sprites.push_back(sp);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ public:
|
||||
{
|
||||
UE::Renderer* rend = UE::Engine::GetRenderer();
|
||||
glm::ivec2 mPos(event->button.x, event->button.y);
|
||||
glm::ivec2 wPos = rend->ScreenToWorldCoords(mPos);
|
||||
glm::ivec2 wPos = rend->GetCamera()->ScreenToWorldCoords(mPos);
|
||||
GAME_LOG_TRACE("Posicion del raton: \n\tPantalla: {0}x{1}, Mundo: {2}x{3}: ", mPos.x, mPos.y, wPos.x, wPos.y);
|
||||
ModificarSprite(wPos);
|
||||
}
|
||||
@@ -115,7 +115,7 @@ private:
|
||||
SDL_Rect sp_Pos = sp.GetTransformRect();
|
||||
if (SDL_HasIntersection(&mouseRect, &sp_Pos))
|
||||
{
|
||||
int i = rand() % 5;
|
||||
int i = rand() % 4 +1;
|
||||
sp.SetTextureRect(i);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
{
|
||||
"TexturePath": "resources/Sprites/Textures/Player.png",
|
||||
"TextureRects": [
|
||||
{
|
||||
"posX": 0,
|
||||
"posY": 0,
|
||||
"sizeX": 16,
|
||||
"sizeY": 16
|
||||
},
|
||||
{
|
||||
"posX": 16,
|
||||
"posY": 0,
|
||||
"sizeX": 16,
|
||||
"sizeY": 16
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,12 +1,6 @@
|
||||
{
|
||||
"TexturePath": "resources/Sprites/Textures/bc.png",
|
||||
"TextureRects": [
|
||||
{
|
||||
"posX": 0,
|
||||
"posY": 0,
|
||||
"sizeX": 320,
|
||||
"sizeY": 240
|
||||
},
|
||||
{
|
||||
"posX": 80,
|
||||
"posY": 60,
|
||||
|
||||
Reference in New Issue
Block a user