From cada46f732050a82cca6ed84007e09fa227dc1d7 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Thu, 18 Sep 2025 17:09:42 +0200 Subject: [PATCH] =?UTF-8?q?Refactorizaci=C3=B3n=20inicial:=20Crear=20estru?= =?UTF-8?q?ctura=20de=20clase=20Engine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PROGRESO INTERMEDIO - Estructura base de Engine implementada: Nuevos archivos: - engine.h: Declaración completa de clase Engine con encapsulación - engine.cpp: Esqueleto de implementación con métodos stub - main_new.cpp: Nuevo main simplificado (15 líneas vs 580) Cambios en archivos existentes: - defines.h: Añadir enum ColorTheme (centralizar definiciones) - main.cpp: Eliminar enum ColorTheme duplicado Arquitectura Engine: - Encapsulación completa de variables globales (SDL, estado, timing, UI) - Métodos organizados por responsabilidad (public/private) - Eliminación de problemas de orden de declaración - Base sólida para futuras extensiones Estado: Compilación exitosa ✅ Pendiente: Migrar funcionalidad completa de métodos stub 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- source/defines.h | 18 ++++-- source/engine.cpp | 137 ++++++++++++++++++++++++++++++++++++++++++++ source/engine.h | 82 ++++++++++++++++++++++++++ source/main.cpp | 11 ++-- source/main_new.cpp | 17 ++++++ 5 files changed, 253 insertions(+), 12 deletions(-) create mode 100644 source/engine.cpp create mode 100644 source/engine.h create mode 100644 source/main_new.cpp diff --git a/source/defines.h b/source/defines.h index 4031fc6..dc5849a 100644 --- a/source/defines.h +++ b/source/defines.h @@ -20,10 +20,18 @@ struct Color { int r, g, b; }; -// Enum para direcci\u00f3n de gravedad +// Enum para dirección de gravedad enum class GravityDirection { - DOWN, // \u2193 Gravedad hacia abajo (por defecto) - UP, // \u2191 Gravedad hacia arriba - LEFT, // \u2190 Gravedad hacia la izquierda - RIGHT // \u2192 Gravedad hacia la derecha + DOWN, // ↓ Gravedad hacia abajo (por defecto) + UP, // ↑ Gravedad hacia arriba + LEFT, // ← Gravedad hacia la izquierda + RIGHT // → Gravedad hacia la derecha +}; + +// Enum para temas de colores +enum class ColorTheme { + SUNSET = 0, + OCEAN = 1, + NEON = 2, + FOREST = 3 }; \ No newline at end of file diff --git a/source/engine.cpp b/source/engine.cpp new file mode 100644 index 0000000..523c5d9 --- /dev/null +++ b/source/engine.cpp @@ -0,0 +1,137 @@ +#include "engine.h" + +#include // for SDL_GetError +#include // for SDL_Event, SDL_PollEvent +#include // for SDL_Init, SDL_Quit, SDL_INIT_VIDEO +#include // for SDL_Keycode +#include // for SDL_SetRenderDrawColor, SDL_RenderPresent +#include // for SDL_GetTicks +#include // for SDL_CreateWindow, SDL_DestroyWindow + +#include // for rand, srand +#include // for time +#include // for cout +#include // for string + +#include "ball.h" // for Ball +#include "external/dbgtxt.h" // for dbg_init, dbg_print +#include "external/texture.h" // for Texture + +// Implementación de métodos públicos +bool Engine::initialize() { + bool success = true; + + if (!SDL_Init(SDL_INIT_VIDEO)) { + std::cout << "¡SDL no se pudo inicializar! Error de SDL: " << SDL_GetError() << std::endl; + success = false; + } else { + // Crear ventana principal + window_ = SDL_CreateWindow(WINDOW_CAPTION, SCREEN_WIDTH * WINDOW_SIZE, SCREEN_HEIGHT * WINDOW_SIZE, SDL_WINDOW_OPENGL); + if (window_ == nullptr) { + std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl; + success = false; + } else { + // Crear renderizador + renderer_ = SDL_CreateRenderer(window_, nullptr); + if (renderer_ == nullptr) { + std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl; + success = false; + } else { + // Establecer color inicial del renderizador + SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xFF, 0xFF); + + // Establecer tamaño lógico para el renderizado + SDL_SetRenderLogicalPresentation(renderer_, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE); + + // Configurar V-Sync inicial + SDL_SetRenderVSync(renderer_, vsync_enabled_ ? 1 : 0); + } + } + } + + // Inicializar otros componentes si SDL se inicializó correctamente + if (success) { + texture_ = std::make_shared(renderer_, "data/ball.png"); + srand(static_cast(time(nullptr))); + dbg_init(renderer_); + initBalls(scenario_); + } + + return success; +} + +void Engine::run() { + while (!should_exit_) { + calculateDeltaTime(); + update(); + handleEvents(); + render(); + } +} + +void Engine::shutdown() { + // Limpiar recursos SDL + if (renderer_) { + SDL_DestroyRenderer(renderer_); + renderer_ = nullptr; + } + if (window_) { + SDL_DestroyWindow(window_); + window_ = nullptr; + } + SDL_Quit(); +} + +// Métodos privados - esqueleto básico por ahora +void Engine::calculateDeltaTime() { + // TODO: Implementar cálculo de delta time +} + +void Engine::update() { + // TODO: Implementar lógica de actualización +} + +void Engine::handleEvents() { + // TODO: Implementar manejo de eventos +} + +void Engine::render() { + // TODO: Implementar renderizado +} + +void Engine::initBalls(int value) { + // TODO: Implementar inicialización de pelotas +} + +void Engine::setText() { + // TODO: Implementar texto +} + +void Engine::pushUpBalls() { + // TODO: Implementar impulso de pelotas +} + +void Engine::switchBallsGravity() { + // TODO: Implementar cambio de gravedad +} + +void Engine::changeGravityDirection(GravityDirection direction) { + // TODO: Implementar cambio de dirección +} + +void Engine::toggleVSync() { + // TODO: Implementar toggle V-Sync +} + +std::string Engine::gravityDirectionToString(GravityDirection direction) const { + // TODO: Implementar conversión a string + return "DOWN"; +} + +void Engine::renderGradientBackground() { + // TODO: Implementar fondo degradado +} + +void Engine::addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b) { + // TODO: Implementar batch rendering +} \ No newline at end of file diff --git a/source/engine.h b/source/engine.h new file mode 100644 index 0000000..c2679d9 --- /dev/null +++ b/source/engine.h @@ -0,0 +1,82 @@ +#pragma once + +#include // for SDL_Event +#include // for SDL_Renderer +#include // for Uint64 +#include // for SDL_Window + +#include // for array +#include // for unique_ptr, shared_ptr +#include // for string +#include // for vector + +#include "defines.h" // for GravityDirection, ColorTheme + +class Ball; +class Texture; + +class Engine { +public: + // Interfaz pública + bool initialize(); + void run(); + void shutdown(); + +private: + // Recursos SDL + SDL_Window* window_ = nullptr; + SDL_Renderer* renderer_ = nullptr; + std::shared_ptr texture_ = nullptr; + + // Estado del simulador + std::vector> balls_; + std::array test_ = {1, 10, 100, 500, 1000, 10000, 50000, 100000}; + GravityDirection current_gravity_ = GravityDirection::DOWN; + int scenario_ = 0; + bool should_exit_ = false; + + // Sistema de timing + Uint64 last_frame_time_ = 0; + float delta_time_ = 0.0f; + + // UI y debug + bool show_debug_ = false; + bool show_text_ = true; + std::string text_; + int text_pos_ = 0; + Uint64 text_init_time_ = 0; + + // FPS y V-Sync + Uint64 fps_last_time_ = 0; + int fps_frame_count_ = 0; + int fps_current_ = 0; + std::string fps_text_ = "FPS: 0"; + bool vsync_enabled_ = true; + std::string vsync_text_ = "VSYNC ON"; + + // Sistema de temas + ColorTheme current_theme_ = ColorTheme::SUNSET; + + // Batch rendering + std::vector batch_vertices_; + std::vector batch_indices_; + + // Métodos principales del loop + void calculateDeltaTime(); + void update(); + void handleEvents(); + void render(); + + // Métodos auxiliares + void initBalls(int value); + void setText(); + void pushUpBalls(); + void switchBallsGravity(); + void changeGravityDirection(GravityDirection direction); + void toggleVSync(); + std::string gravityDirectionToString(GravityDirection direction) const; + + // Rendering + void renderGradientBackground(); + void addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b); +}; \ No newline at end of file diff --git a/source/main.cpp b/source/main.cpp index 1fe2b9f..a706c3a 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -55,13 +55,7 @@ bool show_debug = false; // Debug display desactivado por defecto // Variable para direcci\u00f3n de gravedad GravityDirection current_gravity = GravityDirection::DOWN; // Gravedad inicial hacia abajo -// Sistema de temas de colores -enum class ColorTheme { - SUNSET = 0, - OCEAN = 1, - NEON = 2, - FOREST = 3 -}; +// Sistema de temas de colores (enum movido a defines.h) ColorTheme current_theme = ColorTheme::SUNSET; std::string theme_names[] = {"SUNSET", "OCEAN", "NEON", "FOREST"}; @@ -210,6 +204,9 @@ void setText() { // Inicializa las bolas según el escenario seleccionado void initBalls(int value) { balls.clear(); + + // Resetear gravedad al estado por defecto (DOWN) al cambiar escenario + current_gravity = GravityDirection::DOWN; for (int i = 0; i < test.at(value); ++i) { const int SIGN = ((rand() % 2) * 2) - 1; // Genera un signo aleatorio (+ o -) const float X = (rand() % (SCREEN_WIDTH / 2)) + (SCREEN_WIDTH / 4); // Posición inicial en X diff --git a/source/main_new.cpp b/source/main_new.cpp new file mode 100644 index 0000000..b52bcf8 --- /dev/null +++ b/source/main_new.cpp @@ -0,0 +1,17 @@ +#include + +#include "engine.h" + +int main() { + Engine engine; + + if (!engine.initialize()) { + std::cout << "¡Error al inicializar el engine!" << std::endl; + return -1; + } + + engine.run(); + engine.shutdown(); + + return 0; +} \ No newline at end of file