Corrige bug donde pulsar F en modo LOGO (llegando desde DEMO) causaba salida automática a DEMO debido a uso incorrecto de previous_app_mode_ como flag de "¿puede salir automáticamente?". ## Problema **Flujo con bug:** 1. SANDBOX → D → DEMO 2. DEMO → K → LOGO (guarda previous_app_mode_ = DEMO) 3. LOGO (SHAPE) → F → LOGO (PHYSICS) ← Acción MANUAL 4. updateDemoMode() ejecuta lógica de LOGO 5. Línea 1628: `if (previous_app_mode_ != SANDBOX && rand() < 60%)` 6. Como previous_app_mode_ == DEMO → Sale a DEMO ❌ **Causa raíz:** La variable previous_app_mode_ se usaba para dos propósitos: - Guardar a dónde volver (correcto) - Decidir si puede salir automáticamente (incorrecto) Esto causaba que acciones manuales del usuario (como F) activaran la probabilidad de salida automática. ## Solución Implementada **Nueva variable explícita:** ```cpp bool logo_entered_manually_; // true si tecla K, false si desde DEMO ``` **Asignación en enterLogoMode():** ```cpp logo_entered_manually_ = !from_demo; ``` **Condición corregida en updateDemoMode():** ```cpp // ANTES (incorrecto): if (previous_app_mode_ != AppMode::SANDBOX && rand() % 100 < 60) // AHORA (correcto): if (!logo_entered_manually_ && rand() % 100 < 60) ``` ## Ventajas ✅ **Separación de responsabilidades:** - previous_app_mode_: Solo para saber a dónde volver - logo_entered_manually_: Solo para control de salida automática ✅ **Semántica clara:** - Código más legible y expresivo ✅ **Más robusto:** - No depende de comparaciones indirectas ## Flujos Verificados **Flujo 1 (Manual desde SANDBOX):** - SANDBOX → K → LOGO (logo_entered_manually_ = true) - LOGO → F → PHYSICS - No sale automáticamente ✅ **Flujo 2 (Manual desde DEMO):** - SANDBOX → D → DEMO → K → LOGO (logo_entered_manually_ = true) - LOGO → F → PHYSICS - No sale automáticamente ✅ **Flujo 3 (Automático desde DEMO):** - SANDBOX → D → DEMO → auto → LOGO (logo_entered_manually_ = false) - LOGO ejecuta acciones automáticas - Sale a DEMO con 60% probabilidad ✅ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
197 lines
9.4 KiB
C++
197 lines
9.4 KiB
C++
#pragma once
|
|
|
|
#include <SDL3/SDL_events.h> // for SDL_Event
|
|
#include <SDL3/SDL_render.h> // for SDL_Renderer
|
|
#include <SDL3/SDL_stdinc.h> // for Uint64
|
|
#include <SDL3/SDL_video.h> // for SDL_Window
|
|
|
|
#include <array> // for array
|
|
#include <memory> // for unique_ptr, shared_ptr
|
|
#include <string> // for string
|
|
#include <vector> // for vector
|
|
|
|
#include "ball.h" // for Ball
|
|
#include "defines.h" // for GravityDirection, ColorTheme, ShapeType
|
|
#include "external/texture.h" // for Texture
|
|
#include "shapes/shape.h" // for Shape (interfaz polimórfica)
|
|
#include "text/textrenderer.h" // for TextRenderer
|
|
#include "theme_manager.h" // for ThemeManager
|
|
#include "ui/notifier.h" // for Notifier
|
|
|
|
// Modos de aplicación mutuamente excluyentes
|
|
enum class AppMode {
|
|
SANDBOX, // Control manual del usuario (modo sandbox)
|
|
DEMO, // Modo demo completo (auto-play)
|
|
DEMO_LITE, // Modo demo lite (solo física/figuras)
|
|
LOGO // Modo logo (easter egg)
|
|
};
|
|
|
|
class Engine {
|
|
public:
|
|
// Interfaz pública
|
|
bool initialize(int width = 0, int height = 0, int zoom = 0, bool fullscreen = false);
|
|
void run();
|
|
void shutdown();
|
|
|
|
private:
|
|
// Recursos SDL
|
|
SDL_Window* window_ = nullptr;
|
|
SDL_Renderer* renderer_ = nullptr;
|
|
std::shared_ptr<Texture> texture_ = nullptr; // Textura activa actual
|
|
std::vector<std::shared_ptr<Texture>> textures_; // Todas las texturas disponibles
|
|
std::vector<std::string> texture_names_; // Nombres de texturas (sin extensión)
|
|
size_t current_texture_index_ = 0; // Índice de textura activa
|
|
int current_ball_size_ = 10; // Tamaño actual de pelotas (dinámico, se actualiza desde texture)
|
|
|
|
// Estado del simulador
|
|
std::vector<std::unique_ptr<Ball>> balls_;
|
|
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; // OBSOLETO: usar notifier_ en su lugar
|
|
TextRenderer text_renderer_; // Sistema de renderizado de texto para display (centrado)
|
|
TextRenderer text_renderer_debug_; // Sistema de renderizado de texto para debug (HUD)
|
|
TextRenderer text_renderer_notifier_; // Sistema de renderizado de texto para notificaciones (tamaño fijo)
|
|
Notifier notifier_; // Sistema de notificaciones estilo iOS/Android
|
|
|
|
// Sistema de zoom dinámico
|
|
int current_window_zoom_ = DEFAULT_WINDOW_ZOOM;
|
|
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";
|
|
bool fullscreen_enabled_ = false;
|
|
bool real_fullscreen_enabled_ = false;
|
|
ScalingMode current_scaling_mode_ = ScalingMode::INTEGER; // Modo de escalado actual (F5)
|
|
|
|
// Resolución base (configurada por CLI o default)
|
|
int base_screen_width_ = DEFAULT_SCREEN_WIDTH;
|
|
int base_screen_height_ = DEFAULT_SCREEN_HEIGHT;
|
|
|
|
// Resolución dinámica actual (cambia en fullscreen real)
|
|
int current_screen_width_ = DEFAULT_SCREEN_WIDTH;
|
|
int current_screen_height_ = DEFAULT_SCREEN_HEIGHT;
|
|
|
|
// Resolución física real de ventana/pantalla (para texto absoluto)
|
|
int physical_window_width_ = DEFAULT_SCREEN_WIDTH;
|
|
int physical_window_height_ = DEFAULT_SCREEN_HEIGHT;
|
|
|
|
// Sistema de temas (delegado a ThemeManager)
|
|
std::unique_ptr<ThemeManager> theme_manager_;
|
|
int theme_page_ = 0; // Página actual de temas (0 o 1) para acceso por Numpad
|
|
|
|
// Sistema de Figuras 3D (polimórfico)
|
|
SimulationMode current_mode_ = SimulationMode::PHYSICS;
|
|
ShapeType current_shape_type_ = ShapeType::SPHERE; // Tipo de figura actual
|
|
ShapeType last_shape_type_ = ShapeType::SPHERE; // Última figura para toggle F
|
|
std::unique_ptr<Shape> active_shape_; // Puntero polimórfico a figura activa
|
|
float shape_scale_factor_ = 1.0f; // Factor de escala manual (Numpad +/-)
|
|
bool depth_zoom_enabled_ = true; // Zoom por profundidad Z activado
|
|
|
|
// Sistema de Modo DEMO (auto-play)
|
|
AppMode current_app_mode_ = AppMode::SANDBOX; // Modo actual (mutuamente excluyente)
|
|
AppMode previous_app_mode_ = AppMode::SANDBOX; // Modo previo antes de entrar a LOGO
|
|
float demo_timer_ = 0.0f; // Contador de tiempo para próxima acción
|
|
float demo_next_action_time_ = 0.0f; // Tiempo aleatorio hasta próxima acción (segundos)
|
|
|
|
// Sistema de convergencia para LOGO MODE (escala con resolución)
|
|
float shape_convergence_ = 0.0f; // % de pelotas cerca del objetivo (0.0-1.0)
|
|
float logo_convergence_threshold_ = 0.90f; // Threshold aleatorio (75-100%)
|
|
float logo_min_time_ = 3.0f; // Tiempo mínimo escalado con resolución
|
|
float logo_max_time_ = 5.0f; // Tiempo máximo escalado (backup)
|
|
|
|
// Sistema de espera de flips en LOGO MODE (camino alternativo)
|
|
bool logo_waiting_for_flip_ = false; // true si eligió el camino "esperar flip"
|
|
int logo_target_flip_number_ = 0; // En qué flip actuar (1, 2 o 3)
|
|
float logo_target_flip_percentage_ = 0.0f; // % de flip a esperar (0.2-0.8)
|
|
int logo_current_flip_count_ = 0; // Flips observados hasta ahora
|
|
|
|
// Control de entrada manual vs automática a LOGO MODE
|
|
bool logo_entered_manually_ = false; // true si se activó con tecla K, false si automático desde DEMO
|
|
|
|
// Estado previo antes de entrar a Logo Mode (para restaurar al salir)
|
|
int logo_previous_theme_ = 0; // Índice de tema (0-9)
|
|
size_t logo_previous_texture_index_ = 0;
|
|
float logo_previous_shape_scale_ = 1.0f;
|
|
|
|
// Batch rendering
|
|
std::vector<SDL_Vertex> batch_vertices_;
|
|
std::vector<int> batch_indices_;
|
|
|
|
// Configuración del sistema de texto (constantes configurables)
|
|
static constexpr const char* TEXT_FONT_PATH = "data/fonts/determination.ttf";
|
|
static constexpr int TEXT_BASE_SIZE = 24; // Tamaño base para 240p
|
|
static constexpr bool TEXT_ANTIALIASING = true; // true = suavizado, false = píxeles nítidos
|
|
|
|
// Métodos principales del loop
|
|
void calculateDeltaTime();
|
|
void update();
|
|
void handleEvents();
|
|
void render();
|
|
|
|
// Métodos auxiliares
|
|
void initBalls(int value);
|
|
void setText(); // DEPRECATED - usar showNotificationForAction() en su lugar
|
|
void showNotificationForAction(const std::string& text); // Mostrar notificación solo en modo MANUAL
|
|
void pushBallsAwayFromGravity();
|
|
void switchBallsGravity();
|
|
void enableBallsGravityIfDisabled();
|
|
void forceBallsGravityOn();
|
|
void forceBallsGravityOff();
|
|
void changeGravityDirection(GravityDirection direction);
|
|
void toggleVSync();
|
|
void toggleFullscreen();
|
|
void toggleRealFullscreen();
|
|
void toggleIntegerScaling();
|
|
std::string gravityDirectionToString(GravityDirection direction) const;
|
|
|
|
// Sistema de gestión de estados (MANUAL/DEMO/DEMO_LITE/LOGO)
|
|
void setState(AppMode new_mode); // Cambiar modo de aplicación (mutuamente excluyente)
|
|
|
|
// Sistema de Modo DEMO
|
|
void updateDemoMode();
|
|
void performDemoAction(bool is_lite);
|
|
void randomizeOnDemoStart(bool is_lite);
|
|
void toggleGravityOnOff();
|
|
|
|
// Sistema de Modo Logo (easter egg)
|
|
void toggleLogoMode(); // Activar/desactivar modo logo manual (tecla K)
|
|
void enterLogoMode(bool from_demo = false); // Entrar al modo logo (manual o automático)
|
|
void exitLogoMode(bool return_to_demo = false); // Salir del modo logo
|
|
|
|
// Sistema de cambio de sprites dinámico
|
|
void switchTexture(bool show_notification = true); // Cambia a siguiente textura disponible
|
|
void updateBallSizes(int old_size, int new_size); // Ajusta posiciones al cambiar tamaño
|
|
|
|
// Sistema de zoom dinámico
|
|
int calculateMaxWindowZoom() const;
|
|
void setWindowZoom(int new_zoom);
|
|
void zoomIn();
|
|
void zoomOut();
|
|
void updatePhysicalWindowSize(); // Actualizar tamaño físico real de ventana
|
|
|
|
// Rendering
|
|
void addSpriteToBatch(float x, float y, float w, float h, int r, int g, int b, float scale = 1.0f);
|
|
|
|
// Sistema de Figuras 3D
|
|
void toggleShapeMode(bool force_gravity_on_exit = true); // Toggle PHYSICS ↔ última figura (tecla F)
|
|
void activateShape(ShapeType type); // Activar figura específica (teclas Q/W/E/R/Y/U/I)
|
|
void updateShape(); // Actualizar figura activa
|
|
void generateShape(); // Generar puntos de figura activa
|
|
void clampShapeScale(); // Limitar escala para evitar clipping
|
|
};
|