Treballant en la caché de les paletes

This commit is contained in:
2025-03-05 22:58:26 +01:00
parent 5cc163dd14
commit 10debde847
11 changed files with 150 additions and 323 deletions

View File

@@ -102,7 +102,7 @@ namespace globalInputs
else if (Input::get()->checkInput(InputAction::TOGGLE_PALETTE, REPEAT_FALSE)) else if (Input::get()->checkInput(InputAction::TOGGLE_PALETTE, REPEAT_FALSE))
{ {
switchPalette(); switchPalette();
Notifier::get()->show({"PALETTE " + std::string(options.video.palette == Palette::ZXSPECTRUM ? "ZX SPECTRUM" : "ZX ARNE")}, NotificationText::CENTER); //Notifier::get()->show({"PALETTE " + std::string(options.video.palette == Palette::ZXSPECTRUM ? "ZX SPECTRUM" : "ZX ARNE")}, NotificationText::CENTER);
} }
} }
} }

View File

@@ -21,7 +21,7 @@ void initOptions()
options = Options(); options = Options();
#ifdef DEBUG #ifdef DEBUG
options.section = SectionState(Section::ENDING2, Subsection::NONE); options.section = SectionState(Section::LOGO, Subsection::LOGO_TO_INTRO);
options.console = true; options.console = true;
#else #else
options.section = SectionState(Section::LOGO, Subsection::LOGO_TO_INTRO); options.section = SectionState(Section::LOGO, Subsection::LOGO_TO_INTRO);
@@ -148,25 +148,25 @@ bool saveOptionsToFile(const std::string &file_path)
file << "\n## VIDEO\n"; file << "\n## VIDEO\n";
file << "# Modo de video: 0 = Ventana, 1 = Pantalla completa, 2 = Pantalla completa (escritorio)\n"; file << "# Modo de video: 0 = Ventana, 1 = Pantalla completa, 2 = Pantalla completa (escritorio)\n";
file << "video.mode " << options.video.mode << "\n"; file << "video.mode " << options.video.mode << "\n\n";
file << "# Filtro de pantalla: 0 = Nearest, 1 = Linear\n"; file << "# Filtro de pantalla: 0 = Nearest, 1 = Linear\n";
file << "video.filter " << static_cast<int>(options.video.filter) << "\n"; file << "video.filter " << static_cast<int>(options.video.filter) << "\n\n";
file << "# Shaders: 1 = Activado, 0 = Desactivado\n"; file << "# Shaders: 1 = Activado, 0 = Desactivado\n";
file << "video.shaders " << boolToString(options.video.shaders) << "\n"; file << "video.shaders " << boolToString(options.video.shaders) << "\n\n";
file << "# Sincronización vertical: 1 = Activado, 0 = Desactivado\n"; file << "# Sincronización vertical: 1 = Activado, 0 = Desactivado\n";
file << "video.vertical_sync " << boolToString(options.video.vertical_sync) << "\n"; file << "video.vertical_sync " << boolToString(options.video.vertical_sync) << "\n\n";
file << "# Escalado entero: 1 = Activado, 0 = Desactivado\n"; file << "# Escalado entero: 1 = Activado, 0 = Desactivado\n";
file << "video.integer_scale " << boolToString(options.video.integer_scale) << "\n"; file << "video.integer_scale " << boolToString(options.video.integer_scale) << "\n\n";
file << "# Mantener aspecto: 1 = Activado, 0 = Desactivado\n"; file << "# Mantener aspecto: 1 = Activado, 0 = Desactivado\n";
file << "video.keep_aspect " << boolToString(options.video.keep_aspect) << "\n"; file << "video.keep_aspect " << boolToString(options.video.keep_aspect) << "\n\n";
file << "# Borde: 1 = Activado, 0 = Desactivado\n"; file << "# Borde: 1 = Activado, 0 = Desactivado\n";
file << "video.border.enabled " << boolToString(options.video.border.enabled) << "\n"; file << "video.border.enabled " << boolToString(options.video.border.enabled) << "\n\n";
file << "# Ancho del borde\n"; file << "# Ancho del borde\n";
file << "video.border.width " << options.video.border.width << "\n"; file << "video.border.width " << options.video.border.width << "\n\n";
file << "# Alto del borde\n"; file << "# Alto del borde\n";
file << "video.border.height " << options.video.border.height << "\n"; file << "video.border.height " << options.video.border.height << "\n\n";
file << "# Paleta: 0 = ZX Spectrum, 1 = ZX Arne\n"; file << "# Paleta:\n";
file << "video.palette " << static_cast<int>(options.video.palette) << "\n"; file << "video.palette " << options.video.palette << "\n";
// Cierra el fichero // Cierra el fichero
file.close(); file.close();
@@ -263,10 +263,10 @@ bool setOptions(const std::string &var, const std::string &value)
}}, }},
{"video.palette", [](const std::string &v) {"video.palette", [](const std::string &v)
{ {
int val = safeStoi(v, static_cast<int>(DEFAULT_PALETTE)); std::string val = v;
if (val == static_cast<int>(Palette::ZXSPECTRUM) || val == static_cast<int>(Palette::ZXARNE)) if (val == "arreglar" || val == "esto")
{ {
options.video.palette = static_cast<Palette>(val); options.video.palette = val;
} }
else else
{ {

View File

@@ -75,7 +75,7 @@ constexpr int DEFAULT_MUSIC_VOLUME = 80;
constexpr bool DEFAULT_MUSIC_ENABLED = true; // Musica habilitada por defecto constexpr bool DEFAULT_MUSIC_ENABLED = true; // Musica habilitada por defecto
constexpr int DEFAULT_AUDIO_VOLUME = 100; // Volumen por defecto constexpr int DEFAULT_AUDIO_VOLUME = 100; // Volumen por defecto
constexpr bool DEFAULT_AUDIO_ENABLED = true; // Audio por defecto constexpr bool DEFAULT_AUDIO_ENABLED = true; // Audio por defecto
constexpr Palette DEFAULT_PALETTE = Palette::ZXSPECTRUM; // Paleta por defecto constexpr const char *DEFAULT_PALETTE = "zx-spectrum"; // Paleta por defecto
constexpr Section DEFAULT_SECTION = Section::LOGO; // Sección por defecto constexpr Section DEFAULT_SECTION = Section::LOGO; // Sección por defecto
constexpr Subsection DEFAULT_SUBSECTION = Subsection::LOGO_TO_INTRO; // Subsección por defecto constexpr Subsection DEFAULT_SUBSECTION = Subsection::LOGO_TO_INTRO; // Subsección por defecto
constexpr ControlScheme DEFAULT_CONTROL_SCHEME = ControlScheme::CURSOR; // Control por defecto constexpr ControlScheme DEFAULT_CONTROL_SCHEME = ControlScheme::CURSOR; // Control por defecto
@@ -265,7 +265,7 @@ struct OptionsVideo
bool integer_scale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa bool integer_scale; // Indica si el escalado de la imagen ha de ser entero en el modo a pantalla completa
bool keep_aspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa bool keep_aspect; // Indica si se ha de mantener la relación de aspecto al poner el modo a pantalla completa
Border border; // Borde de la pantalla Border border; // Borde de la pantalla
Palette palette; // Paleta de colores a usar en el juego std::string palette; // Paleta de colores a usar en el juego
// Constructor por defecto // Constructor por defecto
OptionsVideo() OptionsVideo()
@@ -279,7 +279,7 @@ struct OptionsVideo
palette(DEFAULT_PALETTE) {} palette(DEFAULT_PALETTE) {}
// Constructor // Constructor
OptionsVideo(Uint32 m, ScreenFilter f, bool vs, bool s, bool is, bool ka, Border b, Palette p) OptionsVideo(Uint32 m, ScreenFilter f, bool vs, bool s, bool is, bool ka, Border b, std::string p)
: mode(m), : mode(m),
filter(f), filter(f),
vertical_sync(vs), vertical_sync(vs),

View File

@@ -20,28 +20,16 @@ struct JA_Sound_t; // lines 13-13
Resource *Resource::resource_ = nullptr; Resource *Resource::resource_ = nullptr;
// [SINGLETON] Crearemos el objeto screen con esta función estática // [SINGLETON] Crearemos el objeto screen con esta función estática
void Resource::init() void Resource::init() { Resource::resource_ = new Resource(); }
{
Resource::resource_ = new Resource();
}
// [SINGLETON] Destruiremos el objeto screen con esta función estática // [SINGLETON] Destruiremos el objeto screen con esta función estática
void Resource::destroy() void Resource::destroy() { delete Resource::resource_; }
{
delete Resource::resource_;
}
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él // [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
Resource *Resource::get() Resource *Resource::get() { return Resource::resource_; }
{
return Resource::resource_;
}
// Constructor // Constructor
Resource::Resource() Resource::Resource() { load(); }
{
load();
}
// Vacia todos los vectores de recursos // Vacia todos los vectores de recursos
void Resource::clear() void Resource::clear()
@@ -49,6 +37,7 @@ void Resource::clear()
clearSounds(); clearSounds();
clearMusics(); clearMusics();
surfaces_.clear(); surfaces_.clear();
palettes_.clear();
text_files_.clear(); text_files_.clear();
texts_.clear(); texts_.clear();
animations_.clear(); animations_.clear();
@@ -64,6 +53,7 @@ void Resource::load()
loadSounds(); loadSounds();
loadMusics(); loadMusics();
loadSurfaces(); loadSurfaces();
loadPalettes();
loadTextFiles(); loadTextFiles();
loadAnimations(); loadAnimations();
loadTileMaps(); loadTileMaps();
@@ -109,7 +99,7 @@ JA_Music_t *Resource::getMusic(const std::string &name)
throw std::runtime_error("Música no encontrada: " + name); throw std::runtime_error("Música no encontrada: " + name);
} }
// Obtiene la textura a partir de un nombre // Obtiene la surface a partir de un nombre
std::shared_ptr<Surface> Resource::getSurface(const std::string &name) std::shared_ptr<Surface> Resource::getSurface(const std::string &name)
{ {
auto it = std::find_if(surfaces_.begin(), surfaces_.end(), [&name](const auto &t) auto it = std::find_if(surfaces_.begin(), surfaces_.end(), [&name](const auto &t)
@@ -124,6 +114,21 @@ std::shared_ptr<Surface> Resource::getSurface(const std::string &name)
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
// Obtiene la paleta a partir de un nombre
Palette Resource::getPalette(const std::string &name)
{
auto it = std::find_if(palettes_.begin(), palettes_.end(), [&name](const auto &t)
{ return t.name == name; });
if (it != palettes_.end())
{
return it->palette;
}
std::cerr << "Error: Paleta no encontrada " << name << std::endl;
throw std::runtime_error("Paleta no encontrada: " + name);
}
// Obtiene el fichero de texto a partir de un nombre // Obtiene el fichero de texto a partir de un nombre
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
{ {
@@ -252,6 +257,21 @@ void Resource::loadSurfaces()
} }
} }
// Carga las paletas
void Resource::loadPalettes()
{
std::cout << "\n>> PALETTES" << std::endl;
auto list = Asset::get()->getListByType(AssetType::PALETTE);
palettes_.clear();
for (const auto &l : list)
{
auto name = getFileName(l);
palettes_.emplace_back(ResourcePalette(name, loadPalette(l)));
updateLoadingProgress();
}
}
// Carga los ficheros de texto // Carga los ficheros de texto
void Resource::loadTextFiles() void Resource::loadTextFiles()
{ {

View File

@@ -43,6 +43,17 @@ struct ResourceSurface
: name(name), surface(surface) {} : name(name), surface(surface) {}
}; };
// Estructura para almacenar objetos Palette y su nombre
struct ResourcePalette
{
std::string name; // Nombre de la surface
Palette palette; // Paleta
// Constructor
ResourcePalette(const std::string &name, Palette palette)
: name(name), palette(palette) {}
};
// Estructura para almacenar ficheros TextFile y su nombre // Estructura para almacenar ficheros TextFile y su nombre
struct ResourceTextFile struct ResourceTextFile
{ {
@@ -134,6 +145,7 @@ private:
std::vector<ResourceSound> sounds_; // Vector con los sonidos std::vector<ResourceSound> sounds_; // Vector con los sonidos
std::vector<ResourceMusic> musics_; // Vector con las musicas std::vector<ResourceMusic> musics_; // Vector con las musicas
std::vector<ResourceSurface> surfaces_; // Vector con las surfaces std::vector<ResourceSurface> surfaces_; // Vector con las surfaces
std::vector<ResourcePalette> palettes_; // Vector con las paletas
std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto std::vector<ResourceTextFile> text_files_; // Vector con los ficheros de texto
std::vector<ResourceText> texts_; // Vector con los objetos de texto std::vector<ResourceText> texts_; // Vector con los objetos de texto
std::vector<ResourceAnimation> animations_; // Vector con las animaciones std::vector<ResourceAnimation> animations_; // Vector con las animaciones
@@ -151,6 +163,9 @@ private:
// Carga las surfaces // Carga las surfaces
void loadSurfaces(); void loadSurfaces();
// Carga las paletas
void loadPalettes();
// Carga los ficheros de texto // Carga los ficheros de texto
void loadTextFiles(); void loadTextFiles();
@@ -217,6 +232,9 @@ public:
// Obtiene la surface a partir de un nombre // Obtiene la surface a partir de un nombre
std::shared_ptr<Surface> getSurface(const std::string &name); std::shared_ptr<Surface> getSurface(const std::string &name);
// Obtiene la paleta a partir de un nombre
Palette getPalette(const std::string &name);
// Obtiene el fichero de texto a partir de un nombre // Obtiene el fichero de texto a partir de un nombre
std::shared_ptr<TextFile> getTextFile(const std::string &name); std::shared_ptr<TextFile> getTextFile(const std::string &name);

View File

@@ -14,6 +14,7 @@
#include "options.h" #include "options.h"
#include "mouse.h" #include "mouse.h"
#include "surface.h" #include "surface.h"
#include "resource.h"
// [SINGLETON] // [SINGLETON]
Screen *Screen::screen_ = nullptr; Screen *Screen::screen_ = nullptr;
@@ -395,6 +396,6 @@ void Screen::nextPalette()
current_palette_ = 0; current_palette_ = 0;
} }
game_surface_->loadPalette(palettes_.at(current_palette_)); game_surface_->loadPalette(Resource::get()->getPalette(palettes_.at(current_palette_)));
border_surface_->loadPalette(palettes_.at(current_palette_)); border_surface_->loadPalette(Resource::get()->getPalette(palettes_.at(current_palette_)));
} }

View File

@@ -11,6 +11,43 @@
#include "screen.h" #include "screen.h"
#include "gif.h" // for LoadGif, LoadPalette #include "gif.h" // for LoadGif, LoadPalette
// Carga una paleta desde un archivo
Palette loadPalette(const std::string &file_path)
{
// Abrir el archivo en modo binario
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file.is_open())
{
throw std::runtime_error("Error opening file: " + file_path);
}
// Leer el contenido del archivo en un buffer
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{
throw std::runtime_error("Error reading file: " + file_path);
}
// Cargar la paleta usando los datos del buffer
std::unique_ptr<Uint32[]> pal(LoadPalette(buffer.data()));
if (pal == nullptr)
{
throw std::runtime_error("Error loading palette from file: " + file_path);
}
// Crear la paleta y copiar los datos
Palette palette;
std::copy(pal.get(), pal.get() + palette.size(), palette.begin());
// Mensaje de depuración
printWithDots("Palette : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
return palette;
}
// Constructor // Constructor
Surface::Surface(int w, int h) Surface::Surface(int w, int h)
: surface_data_(std::make_shared<SurfaceData>(w, h)), : surface_data_(std::make_shared<SurfaceData>(w, h)),
@@ -60,33 +97,13 @@ SurfaceData Surface::loadSurface(const std::string &file_path)
// Carga una paleta desde un archivo // Carga una paleta desde un archivo
void Surface::loadPalette(const std::string &file_path) void Surface::loadPalette(const std::string &file_path)
{ {
// Abrir el archivo en modo binario palette_ = ::loadPalette(file_path);
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file.is_open())
{
throw std::runtime_error("Error opening file: " + file_path);
} }
// Leer el contenido del archivo en un buffer // Carga una paleta desde otra paleta
std::streamsize size = file.tellg(); void Surface::loadPalette(Palette palette)
file.seekg(0, std::ios::beg);
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{ {
throw std::runtime_error("Error reading file: " + file_path); palette_ = palette;
}
// Cargar la paleta usando los datos del buffer
std::unique_ptr<Uint32[]> pal(LoadPalette(buffer.data()));
if (pal == nullptr)
{
throw std::runtime_error("Error loading palette from file: " + file_path);
}
// Copiar los datos de la paleta al std::array
printWithDots("Palette : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
std::copy(pal.get(), pal.get() + palette_.size(), palette_.begin());
} }
// Establece un color en la paleta // Establece un color en la paleta

View File

@@ -6,6 +6,11 @@
#include <memory> #include <memory>
#include <string> #include <string>
// Alias
using Palette = std::array<Uint32, 256>;
Palette loadPalette(const std::string &file_path);
struct SurfaceData struct SurfaceData
{ {
Uint8 *data; // Listado de indices de la paleta que conforman la imagen almacenada Uint8 *data; // Listado de indices de la paleta que conforman la imagen almacenada
@@ -61,7 +66,7 @@ class Surface
{ {
private: private:
std::shared_ptr<SurfaceData> surface_data_; // Datos a dibujar std::shared_ptr<SurfaceData> surface_data_; // Datos a dibujar
std::array<Uint32, 256> palette_; // Paleta para volcar la SurfaceData a una Textura Palette palette_; // Paleta para volcar la SurfaceData a una Textura
int transparent_color_; // Indice de la paleta que se omite en la copia de datos int transparent_color_; // Indice de la paleta que se omite en la copia de datos
public: public:
@@ -77,6 +82,7 @@ public:
// Carga una paleta desde un archivo // Carga una paleta desde un archivo
void loadPalette(const std::string &file_path); void loadPalette(const std::string &file_path);
void loadPalette(Palette palette);
// Copia una región de la SurfaceData de origen a la SurfaceData de destino // Copia una región de la SurfaceData de origen a la SurfaceData de destino
void render(int dx, int dy, int sx, int sy, int w, int h); void render(int dx, int dy, int sx, int sy, int w, int h);

View File

@@ -27,22 +27,6 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
{ {
loadFromFile(path_); loadFromFile(path_);
} }
// .gif
/*else if (extension == "gif")
{
// Crea la surface desde un fichero
surface_ = loadSurface(path_);
// Añade la propia paleta del fichero a la lista
addPaletteFromFile(path_);
// setPaletteColor(0, 0, 0x00000000);
// Crea la textura, establece el BlendMode y copia la surface a la textura
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
flipSurface();
}*/
} }
} }
@@ -50,7 +34,6 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
Texture::~Texture() Texture::~Texture()
{ {
unloadTexture(); unloadTexture();
// unloadSurface();
palettes_.clear(); palettes_.clear();
} }
@@ -58,7 +41,9 @@ Texture::~Texture()
bool Texture::loadFromFile(const std::string &file_path) bool Texture::loadFromFile(const std::string &file_path)
{ {
if (file_path.empty()) if (file_path.empty())
{
return false; return false;
}
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width, height, orig_format;
@@ -75,18 +60,10 @@ bool Texture::loadFromFile(const std::string &file_path)
int depth, pitch; int depth, pitch;
Uint32 pixel_format; Uint32 pixel_format;
/*if (req_format == STBI_rgb) // STBI_rgb_alpha (RGBA)
{
depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels por linea
pixel_format = SDL_PIXELFORMAT_RGB24;
}
else*/
{ // STBI_rgb_alpha (RGBA)
depth = 32; depth = 32;
pitch = 4 * width; pitch = 4 * width;
pixel_format = SDL_PIXELFORMAT_RGBA32; pixel_format = SDL_PIXELFORMAT_RGBA32;
}
// Limpia // Limpia
unloadTexture(); unloadTexture();
@@ -157,26 +134,14 @@ void Texture::unloadTexture()
} }
// Establece el color para la modulacion // Establece el color para la modulacion
void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue) void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue) { SDL_SetTextureColorMod(texture_, red, green, blue); }
{ void Texture::setColor(Color color) { SDL_SetTextureColorMod(texture_, color.r, color.g, color.b); }
SDL_SetTextureColorMod(texture_, red, green, blue);
}
void Texture::setColor(Color color)
{
SDL_SetTextureColorMod(texture_, color.r, color.g, color.b);
}
// Establece el blending // Establece el blending
void Texture::setBlendMode(SDL_BlendMode blending) void Texture::setBlendMode(SDL_BlendMode blending) { SDL_SetTextureBlendMode(texture_, blending); }
{
SDL_SetTextureBlendMode(texture_, blending);
}
// Establece el alpha para la modulación // Establece el alpha para la modulación
void Texture::setAlpha(Uint8 alpha) void Texture::setAlpha(Uint8 alpha) { SDL_SetTextureAlphaMod(texture_, alpha); }
{
SDL_SetTextureAlphaMod(texture_, alpha);
}
// Renderiza la textura en un punto específico // Renderiza la textura en un punto específico
void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
@@ -207,177 +172,19 @@ void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, dou
} }
// Establece la textura como objetivo de renderizado // Establece la textura como objetivo de renderizado
void Texture::setAsRenderTarget(SDL_Renderer *renderer) void Texture::setAsRenderTarget(SDL_Renderer *renderer) { SDL_SetRenderTarget(renderer, texture_); }
{
SDL_SetRenderTarget(renderer, texture_);
}
// Obtiene el ancho de la imagen // Obtiene el ancho de la imagen
int Texture::getWidth() int Texture::getWidth() { return width_; }
{
return width_;
}
// Obtiene el alto de la imagen // Obtiene el alto de la imagen
int Texture::getHeight() int Texture::getHeight() { return height_; }
{
return height_;
}
// Recarga la textura // Recarga la textura
bool Texture::reLoad() bool Texture::reLoad() { return loadFromFile(path_); }
{
return loadFromFile(path_);
}
// Obtiene la textura // Obtiene la textura
SDL_Texture *Texture::getSDLTexture() SDL_Texture *Texture::getSDLTexture() { return texture_; }
{
return texture_;
}
// Desencadenar la superficie actual
/*void Texture::unloadSurface()
{
surface_.reset(); // Resetea el shared_ptr
width_ = 0;
height_ = 0;
}*/
// Crea una surface desde un fichero .gif
/*std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path)
{
// Desencadenar la superficie actual
unloadSurface();
// Abrir el archivo usando std::ifstream para manejo automático del recurso
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file)
{
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
// Obtener el tamaño del archivo
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
// Leer el contenido del archivo en un buffer
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{
std::cerr << "Error al leer el fichero " << file_path << std::endl;
throw std::runtime_error("Error al leer el fichero: " + file_path);
}
// Cerrar el archivo (automáticamente manejado por std::ifstream)
file.close();
// Llamar a la función LoadGif
Uint16 w, h;
Uint8 *rawPixels = LoadGif(buffer.data(), &w, &h);
if (!rawPixels)
{
return nullptr;
}
// Crear un std::shared_ptr con std::make_shared para pixels
auto pixels = std::shared_ptr<Uint8[]>(rawPixels, std::default_delete<Uint8[]>());
auto surface = std::make_shared<Surface>(w, h, pixels);
// Actualizar la anchura y altura
width_ = w;
height_ = h;
return surface;
}*/
// Vuelca la surface en la textura
/*void Texture::flipSurface()
{
// Limpia la textura
auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, texture_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, temp);
// Vuelca los datos
Uint32 *pixels;
int pitch;
SDL_LockTexture(texture_, nullptr, reinterpret_cast<void **>(&pixels), &pitch);
for (int i = 0; i < width_ * height_; ++i)
{
pixels[i] = palettes_[current_palette_][surface_->data[i]];
}
SDL_UnlockTexture(texture_);
}*/
// Establece un color de la paleta
/*void Texture::setPaletteColor(int palette, int index, Uint32 color)
{
palettes_.at(palette)[index] = color;
}*/
// Carga una paleta desde un fichero
/*std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
{
std::vector<Uint32> palette;
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file)
{
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
}
else
{
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
}
auto size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<Uint8> buffer(size);
if (!file.read(reinterpret_cast<char *>(buffer.data()), size))
{
std::cerr << "Error: No se pudo leer completamente el fichero " << getFileName(file_path) << std::endl;
throw std::runtime_error("Error al leer el fichero: " + getFileName(file_path));
}
const auto pal = LoadPalette(buffer.data());
if (!pal)
{
return palette;
}
for (int i = 0; i < 256; ++i)
{
palette.push_back((pal[i] << 8) + 255);
}
return palette;
}*/
// Añade una paleta a la lista
/*void Texture::addPaletteFromFile(const std::string &path)
{
palettes_.emplace_back(loadPaletteFromFile(path));
setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000);
}
// Cambia la paleta de la textura
void Texture::setPalette(int palette)
{
if (palette < (int)palettes_.size())
{
current_palette_ = palette;
flipSurface();
}
}*/
// Obtiene el renderizador // Obtiene el renderizador
SDL_Renderer *Texture::getRenderer() SDL_Renderer *Texture::getRenderer() { return renderer_; }
{
return renderer_;
}

View File

@@ -9,47 +9,22 @@
#include <vector> // for vector #include <vector> // for vector
struct Color; // lines 11-11 struct Color; // lines 11-11
// Definiciones de tipos
/*struct Surface
{
std::shared_ptr<Uint8[]> data;
Uint16 w, h;
// Constructor
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels)
: data(pixels), w(width), h(height) {}
};*/
class Texture class Texture
{ {
private: private:
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
SDL_Texture *texture_ = nullptr; // La textura SDL_Texture *texture_ = nullptr; // La textura
//std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imagenes en formato gif con paleta
// Variables // Variables
std::string path_; // Ruta de la imagen de la textura std::string path_; // Ruta de la imagen de la textura
int width_ = 0; // Ancho de la imagen int width_ = 0; // Ancho de la imagen
int height_ = 0; // Alto de la imagen int height_ = 0; // Alto de la imagen
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
int current_palette_ = 0; // Indice de la paleta en uso
// Crea una surface desde un fichero .gif
// std::shared_ptr<Surface> loadSurface(const std::string &file_name);
// Vuelca la surface en la textura
// void flipSurface();
// Carga una paleta desde un fichero
// std::vector<Uint32> loadPaletteFromFile(const std::string &file_name);
// Libera la memoria de la textura // Libera la memoria de la textura
void unloadTexture(); void unloadTexture();
// Desencadenar la superficie actual
// void unloadSurface();
public: public:
// Constructor // Constructor
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string()); explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
@@ -91,15 +66,6 @@ public:
// Obtiene la textura // Obtiene la textura
SDL_Texture *getSDLTexture(); SDL_Texture *getSDLTexture();
// Añade una paleta a la lista
// void addPaletteFromFile(const std::string &path);
// Establece un color de la paleta
// void setPaletteColor(int palette, int index, Uint32 color);
// Cambia la paleta de la textura
// void setPalette(int palette);
// Obtiene el renderizador // Obtiene el renderizador
SDL_Renderer *getRenderer(); SDL_Renderer *getRenderer();
}; };

View File

@@ -6,13 +6,6 @@
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
// Tipos de paleta
enum class Palette : int
{
ZXSPECTRUM,
ZXARNE
};
// Estructura para definir un circulo // Estructura para definir un circulo
struct Circle struct Circle
{ {
@@ -97,7 +90,6 @@ bool checkCollision(const SDL_Point &p, const LineDiagonal &l);
void normalizeLine(LineDiagonal &l); void normalizeLine(LineDiagonal &l);
// Devuelve un Color a partir de un string // Devuelve un Color a partir de un string
Color stringToColor(Palette pal, const std::string &str);
Uint8 stringToColor(const std::string &str); Uint8 stringToColor(const std::string &str);
// Convierte una cadena a un entero de forma segura // Convierte una cadena a un entero de forma segura