// Includes de SDL3 directos para compatibilidad con archivos externos #include #include // for array #include // for rand, srand #include // for time #include // for basic_ostream, char_traits, operator<< #include // for unique_ptr, shared_ptr, make_shared #include // for operator+, string, to_string #include // for vector #include "ball.h" // for Ball import vibe2.core; // Módulo con constantes y tipos básicos import vibe2.themes; // Sistema de temas modular // import vibe2.physics; // Sistema de física modular (temporal) // import vibe2.rendering; // Sistema de renderizado modular (temporal - conflicto SDL) // import vibe2.input; // Sistema de entrada modular (temporal) #include "external/dbgtxt.h" // for dbg_init, dbg_print #include "external/texture.h" // for Texture // Variables globales usando tipos SDL directos para compatibilidad SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; std::shared_ptr texture = nullptr; std::vector> balls; std::array test = {1, 10, 100, 500, 1000, 10000, 50000, 100000}; // Usar namespace del módulo using namespace vibe2; bool should_exit = false; // Controla si la aplicación debe cerrarse // ticks eliminado - reemplazado por delta time system int scenario = 0; // Escenario actual basado en el número de bolas std::string text; // Texto a mostrar en pantalla int text_pos = 0; // Posición del texto en la pantalla bool show_text = true; // Determina si el texto se debe mostrar Uint64 text_init_time = 0; // Temporizador para mostrar el texto // Variables para contador de FPS Uint64 fps_last_time = 0; // Último tiempo para cálculo de FPS int fps_frame_count = 0; // Contador de frames int fps_current = 0; // FPS actuales calculados std::string fps_text = "FPS: 0"; // Texto del contador de FPS // Variables para V-Sync bool vsync_enabled = true; // Estado inicial del V-Sync (activado por defecto) std::string vsync_text = "VSYNC ON"; // Texto del estado V-Sync // Variables para Delta Time Uint64 last_frame_time = 0; // Tiempo del último frame en milisegundos float delta_time = 0.0f; // Tiempo transcurrido desde el último frame en segundos // Variables para Debug Display bool show_debug = false; // Debug display desactivado por defecto // Sistemas modulares themes::ThemeManager theme_manager; // std::unique_ptr gradient_renderer; // Temporal // std::unique_ptr batch_renderer; // Temporal // Función para renderizar fondo degradado usando el módulo void renderGradientBackground() { // TODO: Implementar con rendering module cuando se resuelvan conflictos SDL // const auto& theme_data = theme_manager.getCurrentThemeData(); // gradient_renderer->renderBackground(theme_data); // Fondo temporal básico SDL_SetRenderDrawColor(renderer, 32, 64, 128, 255); // Azul oscuro SDL_RenderClear(renderer); } // Función para añadir un sprite al batch usando el módulo void addSpriteToBatch(float x, float y, float w, float h, Uint8 r, Uint8 g, Uint8 b) { // TODO: Implementar con rendering module cuando se resuelvan conflictos SDL // Color color(r, g, b); // batch_renderer->addSprite(x, y, w, h, color); } // Establece el texto en pantalla mostrando el número de bolas actuales void setText() { const std::string TEXT_NUMBER = test[scenario] == 1 ? " PELOTA" : " PELOTAS"; text = std::to_string(test[scenario]) + TEXT_NUMBER; const int TEXT_SIZE = static_cast(text.size() * 8); text_pos = SCREEN_WIDTH / 2 - TEXT_SIZE / 2; text_init_time = SDL_GetTicks(); show_text = true; } // Inicializa las bolas según el escenario seleccionado void initBalls(int value) { balls.clear(); 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 const float VX = (((rand() % 20) + 10) * 0.1f) * SIGN; // Velocidad en X const float VY = ((rand() % 60) - 30) * 0.1f; // Velocidad en Y // Usar el theme manager para obtener un color aleatorio const Color COLOR = theme_manager.getRandomColor(); balls.emplace_back(std::make_unique(X, VX, VY, COLOR, texture)); } setText(); // Actualiza el texto } // Aumenta la velocidad vertical de las bolas "hacia arriba" void pushUpBalls() { for (auto &ball : balls) { const int SIGNO = ((rand() % 2) * 2) - 1; const float VX = (((rand() % 20) + 10) * 0.1f) * SIGNO; const float VY = ((rand() % 40) * 0.1f) + 5; ball->modVel(VX, -VY); // Modifica la velocidad de la bola } } // Cambia la gravedad de todas las bolas void switchBallsGravity() { for (auto &ball : balls) { ball->switchGravity(); } } // Alterna el estado del V-Sync void toggleVSync() { vsync_enabled = !vsync_enabled; vsync_text = vsync_enabled ? "VSYNC ON" : "VSYNC OFF"; // Aplicar el cambio de V-Sync al renderizador SDL_SetRenderVSync(renderer, vsync_enabled ? 1 : 0); } // Calcula el delta time entre frames void calculateDeltaTime() { Uint64 current_time = SDL_GetTicks(); // En el primer frame, inicializar el tiempo anterior if (last_frame_time == 0) { last_frame_time = current_time; delta_time = 1.0f / 60.0f; // Asumir 60 FPS para el primer frame return; } // Calcular delta time en segundos delta_time = (current_time - last_frame_time) / 1000.0f; last_frame_time = current_time; // Limitar delta time para evitar saltos grandes (pausa larga, depuración, etc.) if (delta_time > 0.05f) // Máximo 50ms (20 FPS mínimo) { delta_time = 1.0f / 60.0f; // Usar 60 FPS como fallback } } // Inicializa SDL y configura los componentes principales bool init() { bool success = true; // Inicializa SDL 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 texture = std::make_shared(renderer, "data/ball.png"); // Inicializar sistemas modulares (temporal comentado por conflictos SDL) // gradient_renderer = std::make_unique(renderer); // batch_renderer = std::make_unique(renderer); // ticks eliminado - delta time system se inicializa automáticamente srand(static_cast(time(nullptr))); dbg_init(renderer); initBalls(scenario); return success; } // Limpia todos los recursos y cierra SDL void close() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } // Verifica los eventos en la cola void checkEvents() { SDL_Event event; while (SDL_PollEvent(&event)) { // Evento de salida if (event.type == SDL_EVENT_QUIT) { should_exit = true; break; } // Procesar eventos de teclado if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) { switch (event.key.key) { case SDLK_ESCAPE: should_exit = true; break; case SDLK_SPACE: pushUpBalls(); break; case SDLK_G: switchBallsGravity(); break; case SDLK_V: toggleVSync(); break; case SDLK_H: show_debug = !show_debug; break; case SDLK_T: // Ciclar al siguiente tema usando el theme manager theme_manager.cycleTheme(); initBalls(scenario); // Regenerar bolas con nueva paleta break; case SDLK_F1: theme_manager.setTheme(ColorTheme::SUNSET); initBalls(scenario); break; case SDLK_F2: theme_manager.setTheme(ColorTheme::OCEAN); initBalls(scenario); break; case SDLK_F3: theme_manager.setTheme(ColorTheme::NEON); initBalls(scenario); break; case SDLK_F4: theme_manager.setTheme(ColorTheme::FOREST); initBalls(scenario); break; case SDLK_1: scenario = 0; initBalls(scenario); break; case SDLK_2: scenario = 1; initBalls(scenario); break; case SDLK_3: scenario = 2; initBalls(scenario); break; case SDLK_4: scenario = 3; initBalls(scenario); break; case SDLK_5: scenario = 4; initBalls(scenario); break; case SDLK_6: scenario = 5; initBalls(scenario); break; case SDLK_7: scenario = 6; initBalls(scenario); break; case SDLK_8: scenario = 7; initBalls(scenario); break; } } } } // Actualiza la lógica del juego void update() { // Calcular FPS fps_frame_count++; Uint64 current_time = SDL_GetTicks(); if (current_time - fps_last_time >= 1000) // Actualizar cada segundo { fps_current = fps_frame_count; fps_frame_count = 0; fps_last_time = current_time; fps_text = "FPS: " + std::to_string(fps_current); } // ¡DELTA TIME! Actualizar física siempre, usando tiempo transcurrido for (auto &ball : balls) { ball->update(delta_time); // Pasar delta time a cada pelota } // Actualizar texto (sin cambios en la lógica) if (show_text) { show_text = !(SDL_GetTicks() - text_init_time > TEXT_DURATION); } } // Renderiza el contenido en la pantalla void render() { // Renderizar fondo degradado usando el módulo renderGradientBackground(); // TODO: Reimplementar con batch rendering cuando se resuelvan conflictos SDL // Renderizado temporal directo de bolas for (auto &ball : balls) { SDL_FRect pos = ball->getPosition(); texture->render(nullptr, &pos); } if (show_text) { dbg_print(text_pos, 8, text.c_str(), 255, 255, 255); // Mostrar nombre del tema usando el theme manager std::string theme_name = theme_manager.getThemeNameES(); // TODO: Usar rendering::utils cuando se resuelvan conflictos SDL int theme_x = (SCREEN_WIDTH - static_cast(theme_name.length() * 8)) / 2; // Centrado temporal // Obtener color de debug del tema actual Color theme_color = theme_manager.getDebugColor(); dbg_print(theme_x, 24, theme_name.c_str(), theme_color.r, theme_color.g, theme_color.b); } // Debug display (solo si está activado con tecla H) if (show_debug) { // Mostrar contador de FPS en esquina superior derecha // TODO: Usar rendering::utils cuando se resuelvan conflictos SDL int fps_x = SCREEN_WIDTH - static_cast(fps_text.length() * 8) - 8; // Alineado derecha temporal dbg_print(fps_x, 8, fps_text.c_str(), 255, 255, 0); // Amarillo para distinguir // Mostrar estado V-Sync en esquina superior izquierda dbg_print(8, 8, vsync_text.c_str(), 0, 255, 255); // Cian para distinguir // Debug: Mostrar valores de la primera pelota (si existe) if (!balls.empty()) { // Línea 1: Gravedad (solo números enteros) int grav_int = static_cast(balls[0]->getGravityForce()); std::string grav_text = "GRAV " + std::to_string(grav_int); dbg_print(8, 24, grav_text.c_str(), 255, 0, 255); // Magenta para debug // Línea 2: Velocidad Y (solo números enteros) int vy_int = static_cast(balls[0]->getVelocityY()); std::string vy_text = "VY " + std::to_string(vy_int); dbg_print(8, 32, vy_text.c_str(), 255, 0, 255); // Magenta para debug // Línea 3: Estado suelo std::string floor_text = balls[0]->isOnFloor() ? "FLOOR YES" : "FLOOR NO"; dbg_print(8, 40, floor_text.c_str(), 255, 0, 255); // Magenta para debug } // Debug: Mostrar tema actual usando el theme manager std::string theme_text = std::string("THEME ") + theme_manager.getThemeName(); dbg_print(8, 48, theme_text.c_str(), 255, 255, 128); // Amarillo claro para tema } SDL_RenderPresent(renderer); } // Función principal int main(int argc, char *args[]) { if (!init()) { std::cout << "Ocurrió un error durante la inicialización." << std::endl; return 1; } while (!should_exit) { // 1. Calcular delta time antes de actualizar la lógica calculateDeltaTime(); // 2. Actualizar lógica del juego con delta time update(); // 3. Procesar eventos de entrada checkEvents(); // 4. Renderizar la escena render(); } close(); return 0; }