Compare commits
7 Commits
2025-10-25
...
ea27a771ab
| Author | SHA1 | Date | |
|---|---|---|---|
| ea27a771ab | |||
| 09303537a4 | |||
| df17e85a8a | |||
| ce5c4681b8 | |||
| b79f1c3424 | |||
| a65544e8b3 | |||
| b9264c96a1 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -12,7 +12,6 @@ vibe3_physics.exe
|
||||
*.lib
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Archivos de compilación y enlazado
|
||||
*.d
|
||||
@@ -26,6 +25,7 @@ Build/
|
||||
BUILD/
|
||||
cmake-build-*/
|
||||
.cmake/
|
||||
.cache/
|
||||
|
||||
# Archivos generados por CMake
|
||||
CMakeFiles/
|
||||
|
||||
@@ -59,3 +59,8 @@ set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAK
|
||||
|
||||
# Enlazar las bibliotecas necesarias
|
||||
target_link_libraries(${PROJECT_NAME} ${LINK_LIBS})
|
||||
|
||||
# Tool: pack_resources
|
||||
add_executable(pack_resources tools/pack_resources.cpp source/resource_pack.cpp)
|
||||
target_include_directories(pack_resources PRIVATE ${CMAKE_SOURCE_DIR}/source)
|
||||
set_target_properties(pack_resources PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tools")
|
||||
|
||||
2
Makefile
2
Makefile
@@ -159,7 +159,7 @@ windows_release: force_resource_pack
|
||||
# Copia los ficheros que estan en la raíz del proyecto
|
||||
@copy /Y "LICENSE" "$(RELEASE_FOLDER)\" >nul 2>&1 || echo LICENSE not found (optional)
|
||||
@copy /Y "README.md" "$(RELEASE_FOLDER)\" >nul
|
||||
@copy /Y release\*.dll "$(RELEASE_FOLDER)\" >nul 2>&1 || echo DLLs copied successfully
|
||||
@copy /Y release\dll\*.dll "$(RELEASE_FOLDER)\" >nul 2>&1 || echo DLLs copied successfully
|
||||
|
||||
# Compila
|
||||
@windres release/vibe3.rc -O coff -o $(RESOURCE_FILE)
|
||||
|
||||
BIN
release/dll/libwinpthread-1.dll
Normal file
BIN
release/dll/libwinpthread-1.dll
Normal file
Binary file not shown.
@@ -32,6 +32,7 @@ constexpr Uint64 NOTIFICATION_FADE_TIME = 200; // Duración animación salida
|
||||
constexpr float NOTIFICATION_BG_ALPHA = 0.7f; // Opacidad fondo semitransparente (0.0-1.0)
|
||||
constexpr int NOTIFICATION_PADDING = 10; // Padding interno del fondo (píxeles físicos)
|
||||
constexpr int NOTIFICATION_TOP_MARGIN = 20; // Margen superior desde borde pantalla (píxeles físicos)
|
||||
constexpr char KIOSK_NOTIFICATION_TEXT[] = "MODO KIOSKO";
|
||||
|
||||
// Configuración de pérdida aleatoria en rebotes
|
||||
constexpr float BASE_BOUNCE_COEFFICIENT = 0.75f; // Coeficiente base IGUAL para todas las pelotas
|
||||
@@ -52,6 +53,13 @@ constexpr float BALL_SPAWN_MARGIN = 0.15f; // Margen lateral para spawn (0.25 =
|
||||
// Escenarios de número de pelotas (teclas 1-8)
|
||||
constexpr int BALL_COUNT_SCENARIOS[8] = {10, 50, 100, 500, 1000, 5000, 10000, 50000};
|
||||
|
||||
// Límites de escenario para modos automáticos (índices en BALL_COUNT_SCENARIOS)
|
||||
// BALL_COUNT_SCENARIOS = {10, 50, 100, 500, 1000, 5000, 10000, 50000}
|
||||
// 0 1 2 3 4 5 6 7
|
||||
constexpr int DEMO_AUTO_MIN_SCENARIO = 2; // mínimo 100 bolas
|
||||
constexpr int DEMO_AUTO_MAX_SCENARIO = 7; // máximo sin restricción hardware (ajustado por benchmark)
|
||||
constexpr int LOGO_MIN_SCENARIO_IDX = 4; // mínimo 1000 bolas (sustituye LOGO_MODE_MIN_BALLS)
|
||||
|
||||
// Estructura para representar colores RGB
|
||||
struct Color {
|
||||
int r, g, b; // Componentes rojo, verde, azul (0-255)
|
||||
|
||||
@@ -282,6 +282,16 @@ bool Engine::initialize(int width, int height, int zoom, bool fullscreen, AppMod
|
||||
// No es crítico, continuar sin logo
|
||||
app_logo_.reset();
|
||||
}
|
||||
|
||||
// Benchmark de rendimiento (determina max_auto_scenario_ para modos automáticos)
|
||||
runPerformanceBenchmark();
|
||||
|
||||
// Precalentar caché: shapes PNG (evitar I/O en primera activación de PNG_SHAPE)
|
||||
{
|
||||
unsigned char* tmp = nullptr; size_t tmp_size = 0;
|
||||
ResourceManager::loadResource("shapes/jailgames.png", tmp, tmp_size);
|
||||
delete[] tmp;
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
@@ -1282,7 +1292,7 @@ void Engine::executeDemoAction(bool is_lite) {
|
||||
|
||||
if (is_lite) {
|
||||
// DEMO LITE: Verificar condiciones para salto a Logo Mode
|
||||
if (static_cast<int>(scene_manager_->getBallCount()) >= LOGO_MODE_MIN_BALLS &&
|
||||
if (static_cast<int>(scene_manager_->getBallCount()) >= BALL_COUNT_SCENARIOS[LOGO_MIN_SCENARIO_IDX] &&
|
||||
theme_manager_->getCurrentThemeIndex() == 5) { // MONOCHROME
|
||||
// 10% probabilidad de saltar a Logo Mode
|
||||
if (rand() % 100 < LOGO_JUMP_PROBABILITY_FROM_DEMO_LITE) {
|
||||
@@ -1292,7 +1302,7 @@ void Engine::executeDemoAction(bool is_lite) {
|
||||
}
|
||||
} else {
|
||||
// DEMO COMPLETO: Verificar condiciones para salto a Logo Mode
|
||||
if (static_cast<int>(scene_manager_->getBallCount()) >= LOGO_MODE_MIN_BALLS) {
|
||||
if (static_cast<int>(scene_manager_->getBallCount()) >= BALL_COUNT_SCENARIOS[LOGO_MIN_SCENARIO_IDX]) {
|
||||
// 15% probabilidad de saltar a Logo Mode
|
||||
if (rand() % 100 < LOGO_JUMP_PROBABILITY_FROM_DEMO) {
|
||||
state_manager_->enterLogoMode(true, current_screen_width_, current_screen_height_, scene_manager_->getBallCount());
|
||||
@@ -1406,12 +1416,12 @@ void Engine::executeDemoAction(bool is_lite) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Cambiar escenario (10%) - EXCLUIR índices 0, 6, 7 (1, 50K, 100K pelotas)
|
||||
// Cambiar escenario (10%) - rango dinámico según benchmark de rendimiento
|
||||
accumulated_weight += DEMO_WEIGHT_SCENARIO;
|
||||
if (random_value < accumulated_weight) {
|
||||
// Escenarios válidos: índices 1, 2, 3, 4, 5 (10, 100, 500, 1000, 10000 pelotas)
|
||||
int valid_scenarios[] = {1, 2, 3, 4, 5};
|
||||
int new_scenario = valid_scenarios[rand() % 5];
|
||||
int auto_max = std::min(max_auto_scenario_, DEMO_AUTO_MAX_SCENARIO);
|
||||
int range = auto_max - DEMO_AUTO_MIN_SCENARIO + 1;
|
||||
int new_scenario = DEMO_AUTO_MIN_SCENARIO + (rand() % range);
|
||||
scene_manager_->changeScenario(new_scenario, current_mode_);
|
||||
|
||||
// Si estamos en modo SHAPE, regenerar la figura con nuevo número de pelotas
|
||||
@@ -1566,9 +1576,10 @@ void Engine::executeRandomizeOnDemoStart(bool is_lite) {
|
||||
// changeScenario() creará las pelotas y luego llamará a generateShape()
|
||||
}
|
||||
|
||||
// 2. Escenario (excluir índices 0, 6, 7) - AHORA con current_mode_ ya establecido correctamente
|
||||
int valid_scenarios[] = {1, 2, 3, 4, 5};
|
||||
int new_scenario = valid_scenarios[rand() % 5];
|
||||
// 2. Escenario - rango dinámico según benchmark de rendimiento
|
||||
int auto_max = std::min(max_auto_scenario_, DEMO_AUTO_MAX_SCENARIO);
|
||||
int range = auto_max - DEMO_AUTO_MIN_SCENARIO + 1;
|
||||
int new_scenario = DEMO_AUTO_MIN_SCENARIO + (rand() % range);
|
||||
scene_manager_->changeScenario(new_scenario, current_mode_);
|
||||
|
||||
// Si estamos en modo SHAPE, generar la figura y activar atracción
|
||||
@@ -1614,16 +1625,80 @@ void Engine::executeToggleGravityOnOff() {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// BENCHMARK DE RENDIMIENTO
|
||||
// ============================================================================
|
||||
|
||||
void Engine::runPerformanceBenchmark() {
|
||||
int num_displays = 0;
|
||||
SDL_DisplayID* displays = SDL_GetDisplays(&num_displays);
|
||||
float monitor_hz = 60.0f;
|
||||
if (displays && num_displays > 0) {
|
||||
const auto* dm = SDL_GetCurrentDisplayMode(displays[0]);
|
||||
if (dm && dm->refresh_rate > 0) monitor_hz = dm->refresh_rate;
|
||||
SDL_free(displays);
|
||||
}
|
||||
|
||||
// Ocultar ventana y desactivar V-sync para medición limpia
|
||||
SDL_HideWindow(window_);
|
||||
SDL_SetRenderVSync(renderer_, 0);
|
||||
|
||||
const int BENCH_DURATION_MS = 600;
|
||||
const int WARMUP_FRAMES = 5;
|
||||
|
||||
auto restore = [&]() {
|
||||
SDL_SetRenderVSync(renderer_, vsync_enabled_ ? 1 : 0);
|
||||
SDL_ShowWindow(window_);
|
||||
scene_manager_->changeScenario(0, current_mode_);
|
||||
last_frame_time_ = 0;
|
||||
};
|
||||
|
||||
// Probar de más pesado a más ligero
|
||||
for (int idx = DEMO_AUTO_MAX_SCENARIO; idx >= DEMO_AUTO_MIN_SCENARIO; --idx) {
|
||||
scene_manager_->changeScenario(idx, current_mode_);
|
||||
|
||||
// Warmup: estabilizar física y pipeline GPU
|
||||
last_frame_time_ = 0;
|
||||
for (int w = 0; w < WARMUP_FRAMES; ++w) {
|
||||
calculateDeltaTime();
|
||||
SDL_Event e; while (SDL_PollEvent(&e)) {}
|
||||
update();
|
||||
render();
|
||||
}
|
||||
|
||||
// Medición
|
||||
int frame_count = 0;
|
||||
Uint64 start = SDL_GetTicks();
|
||||
while (SDL_GetTicks() - start < static_cast<Uint64>(BENCH_DURATION_MS)) {
|
||||
calculateDeltaTime();
|
||||
SDL_Event e;
|
||||
while (SDL_PollEvent(&e)) { /* descartar */ }
|
||||
update();
|
||||
render();
|
||||
++frame_count;
|
||||
}
|
||||
|
||||
float measured_fps = static_cast<float>(frame_count) / (BENCH_DURATION_MS / 1000.0f);
|
||||
if (measured_fps >= monitor_hz) {
|
||||
max_auto_scenario_ = idx;
|
||||
restore();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Fallback: escenario mínimo
|
||||
max_auto_scenario_ = DEMO_AUTO_MIN_SCENARIO;
|
||||
restore();
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CALLBACKS PARA STATEMANAGER - LOGO MODE
|
||||
// ============================================================================
|
||||
|
||||
// Callback para StateManager - Configuración visual al entrar a LOGO MODE
|
||||
void Engine::executeEnterLogoMode(size_t ball_count) {
|
||||
// Verificar mínimo de pelotas
|
||||
if (static_cast<int>(ball_count) < LOGO_MODE_MIN_BALLS) {
|
||||
// Ajustar a 5000 pelotas automáticamente
|
||||
scene_manager_->changeScenario(5, current_mode_); // Escenario 5000 pelotas (índice 5 en BALL_COUNT_SCENARIOS)
|
||||
// Verificar mínimo de pelotas (LOGO_MIN_SCENARIO_IDX = índice 4 → 1000 bolas)
|
||||
if (scene_manager_->getCurrentScenario() < LOGO_MIN_SCENARIO_IDX) {
|
||||
scene_manager_->changeScenario(LOGO_MIN_SCENARIO_IDX, current_mode_);
|
||||
}
|
||||
|
||||
// Guardar estado previo (para restaurar al salir)
|
||||
@@ -1829,7 +1904,7 @@ void Engine::activateShapeInternal(ShapeType type) {
|
||||
active_shape_ = std::make_unique<AtomShape>();
|
||||
break;
|
||||
case ShapeType::PNG_SHAPE:
|
||||
active_shape_ = std::make_unique<PNGShape>("data/shapes/jailgames.png");
|
||||
active_shape_ = std::make_unique<PNGShape>("shapes/jailgames.png");
|
||||
break;
|
||||
default:
|
||||
active_shape_ = std::make_unique<SphereShape>(); // Fallback
|
||||
|
||||
@@ -71,6 +71,13 @@ class Engine {
|
||||
void toggleRealFullscreen();
|
||||
void toggleIntegerScaling();
|
||||
|
||||
// Modo kiosko
|
||||
void setKioskMode(bool enabled) { kiosk_mode_ = enabled; }
|
||||
bool isKioskMode() const { return kiosk_mode_; }
|
||||
|
||||
// Notificaciones (público para InputHandler)
|
||||
void showNotificationForAction(const std::string& text);
|
||||
|
||||
// Modos de aplicación (DEMO/LOGO)
|
||||
void toggleDemoMode();
|
||||
void toggleDemoLiteMode();
|
||||
@@ -97,6 +104,7 @@ class Engine {
|
||||
int getCurrentScreenHeight() const { return current_screen_height_; }
|
||||
int getBaseScreenWidth() const { return base_screen_width_; }
|
||||
int getBaseScreenHeight() const { return base_screen_height_; }
|
||||
int getMaxAutoScenario() const { return max_auto_scenario_; }
|
||||
|
||||
private:
|
||||
// === Componentes del sistema (Composición) ===
|
||||
@@ -131,6 +139,7 @@ class Engine {
|
||||
bool vsync_enabled_ = true;
|
||||
bool fullscreen_enabled_ = false;
|
||||
bool real_fullscreen_enabled_ = false;
|
||||
bool kiosk_mode_ = false;
|
||||
ScalingMode current_scaling_mode_ = ScalingMode::INTEGER; // Modo de escalado actual (F5)
|
||||
|
||||
// Resolución base (configurada por CLI o default)
|
||||
@@ -164,6 +173,7 @@ class Engine {
|
||||
// StateManager coordina los triggers y timers, Engine ejecuta las acciones
|
||||
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)
|
||||
int max_auto_scenario_ = 5; // Índice máximo en modos auto (default conservador: 5000 bolas)
|
||||
|
||||
// Sistema de convergencia para LOGO MODE (escala con resolución)
|
||||
// Usado por performLogoAction() para detectar cuando las bolas forman el logo
|
||||
@@ -203,8 +213,10 @@ class Engine {
|
||||
void update();
|
||||
void render();
|
||||
|
||||
// Benchmark de rendimiento (determina max_auto_scenario_ al inicio)
|
||||
void runPerformanceBenchmark();
|
||||
|
||||
// Métodos auxiliares privados (llamados por la interfaz pública)
|
||||
void showNotificationForAction(const std::string& text); // Mostrar notificación solo en modo MANUAL
|
||||
|
||||
// Sistema de cambio de sprites dinámico - Métodos privados
|
||||
void switchTextureInternal(bool show_notification); // Implementación interna del cambio de textura
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
#include <SDL3/SDL_keycode.h> // for SDL_Keycode
|
||||
#include <string> // for std::string, std::to_string
|
||||
|
||||
#include "engine.hpp" // for Engine
|
||||
#include "defines.hpp" // for KIOSK_NOTIFICATION_TEXT
|
||||
#include "engine.hpp" // for Engine
|
||||
#include "external/mouse.hpp" // for Mouse namespace
|
||||
|
||||
bool InputHandler::processEvents(Engine& engine) {
|
||||
@@ -21,6 +22,10 @@ bool InputHandler::processEvents(Engine& engine) {
|
||||
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0) {
|
||||
switch (event.key.key) {
|
||||
case SDLK_ESCAPE:
|
||||
if (engine.isKioskMode()) {
|
||||
engine.showNotificationForAction(KIOSK_NOTIFICATION_TEXT);
|
||||
break;
|
||||
}
|
||||
return true; // Solicitar salida
|
||||
|
||||
case SDLK_SPACE:
|
||||
@@ -221,21 +226,25 @@ bool InputHandler::processEvents(Engine& engine) {
|
||||
|
||||
// Controles de zoom dinámico (solo si no estamos en fullscreen)
|
||||
case SDLK_F1:
|
||||
engine.handleZoomOut();
|
||||
if (engine.isKioskMode()) engine.showNotificationForAction(KIOSK_NOTIFICATION_TEXT);
|
||||
else engine.handleZoomOut();
|
||||
break;
|
||||
|
||||
case SDLK_F2:
|
||||
engine.handleZoomIn();
|
||||
if (engine.isKioskMode()) engine.showNotificationForAction(KIOSK_NOTIFICATION_TEXT);
|
||||
else engine.handleZoomIn();
|
||||
break;
|
||||
|
||||
// Control de pantalla completa
|
||||
case SDLK_F3:
|
||||
engine.toggleFullscreen();
|
||||
if (engine.isKioskMode()) engine.showNotificationForAction(KIOSK_NOTIFICATION_TEXT);
|
||||
else engine.toggleFullscreen();
|
||||
break;
|
||||
|
||||
// Modo real fullscreen (cambia resolución interna)
|
||||
case SDLK_F4:
|
||||
engine.toggleRealFullscreen();
|
||||
if (engine.isKioskMode()) engine.showNotificationForAction(KIOSK_NOTIFICATION_TEXT);
|
||||
else engine.toggleRealFullscreen();
|
||||
break;
|
||||
|
||||
// Toggle escalado entero/estirado (solo en fullscreen F3)
|
||||
|
||||
@@ -16,6 +16,7 @@ void printHelp() {
|
||||
std::cout << " -z, --zoom <n> Zoom de ventana (default: 3)\n";
|
||||
std::cout << " -f, --fullscreen Modo pantalla completa (F3 - letterbox)\n";
|
||||
std::cout << " -F, --real-fullscreen Modo pantalla completa real (F4 - nativo)\n";
|
||||
std::cout << " -k, --kiosk Modo kiosko (F4 fijo, sin ESC, sin zoom)\n";
|
||||
std::cout << " -m, --mode <mode> Modo inicial: sandbox, demo, demo-lite, logo (default: sandbox)\n";
|
||||
std::cout << " --help Mostrar esta ayuda\n\n";
|
||||
std::cout << "Ejemplos:\n";
|
||||
@@ -24,6 +25,7 @@ void printHelp() {
|
||||
std::cout << " vibe3_physics -w 640 -h 480 -z 2 # 640x480 zoom 2 (ventana 1280x960)\n";
|
||||
std::cout << " vibe3_physics -f # Fullscreen letterbox (F3)\n";
|
||||
std::cout << " vibe3_physics -F # Fullscreen real (F4 - resolución nativa)\n";
|
||||
std::cout << " vibe3_physics -k # Modo kiosko (pantalla completa real, bloqueado)\n";
|
||||
std::cout << " vibe3_physics --mode demo # Arrancar en modo DEMO (auto-play)\n";
|
||||
std::cout << " vibe3_physics -m demo-lite # Arrancar en modo DEMO_LITE (solo física)\n";
|
||||
std::cout << " vibe3_physics -F --mode logo # Fullscreen + modo LOGO (easter egg)\n\n";
|
||||
@@ -36,6 +38,7 @@ int main(int argc, char* argv[]) {
|
||||
int zoom = 0;
|
||||
bool fullscreen = false;
|
||||
bool real_fullscreen = false;
|
||||
bool kiosk_mode = false;
|
||||
AppMode initial_mode = AppMode::SANDBOX; // Modo inicial (default: SANDBOX)
|
||||
|
||||
// Parsear argumentos
|
||||
@@ -80,6 +83,8 @@ int main(int argc, char* argv[]) {
|
||||
fullscreen = true;
|
||||
} else if (strcmp(argv[i], "-F") == 0 || strcmp(argv[i], "--real-fullscreen") == 0) {
|
||||
real_fullscreen = true;
|
||||
} else if (strcmp(argv[i], "-k") == 0 || strcmp(argv[i], "--kiosk") == 0) {
|
||||
kiosk_mode = true;
|
||||
} else if (strcmp(argv[i], "-m") == 0 || strcmp(argv[i], "--mode") == 0) {
|
||||
if (i + 1 < argc) {
|
||||
std::string mode_str = argv[++i];
|
||||
@@ -118,10 +123,13 @@ int main(int argc, char* argv[]) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Si se especificó real fullscreen (F4), activar después de inicializar
|
||||
if (real_fullscreen) {
|
||||
// Si se especificó real fullscreen (F4) o modo kiosko, activar después de inicializar
|
||||
if (real_fullscreen || kiosk_mode) {
|
||||
engine.toggleRealFullscreen();
|
||||
}
|
||||
if (kiosk_mode) {
|
||||
engine.setKioskMode(true);
|
||||
}
|
||||
|
||||
engine.run();
|
||||
engine.shutdown();
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
|
||||
// Inicializar el puntero estático
|
||||
// Inicializar estáticos
|
||||
ResourcePack* ResourceManager::resourcePack_ = nullptr;
|
||||
std::map<std::string, std::vector<unsigned char>> ResourceManager::cache_;
|
||||
|
||||
bool ResourceManager::init(const std::string& packFilePath) {
|
||||
// Si ya estaba inicializado, liberar primero
|
||||
@@ -29,6 +31,7 @@ bool ResourceManager::init(const std::string& packFilePath) {
|
||||
}
|
||||
|
||||
void ResourceManager::shutdown() {
|
||||
cache_.clear();
|
||||
if (resourcePack_ != nullptr) {
|
||||
delete resourcePack_;
|
||||
resourcePack_ = nullptr;
|
||||
@@ -39,36 +42,41 @@ bool ResourceManager::loadResource(const std::string& resourcePath, unsigned cha
|
||||
data = nullptr;
|
||||
size = 0;
|
||||
|
||||
// 1. Intentar cargar desde pack (si está disponible)
|
||||
// 1. Consultar caché en RAM (sin I/O)
|
||||
auto it = cache_.find(resourcePath);
|
||||
if (it != cache_.end()) {
|
||||
size = it->second.size();
|
||||
data = new unsigned char[size];
|
||||
std::memcpy(data, it->second.data(), size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Intentar cargar desde pack (si está disponible)
|
||||
if (resourcePack_ != nullptr) {
|
||||
ResourcePack::ResourceData packData = resourcePack_->loadResource(resourcePath);
|
||||
if (packData.data != nullptr) {
|
||||
cache_[resourcePath] = std::vector<unsigned char>(packData.data, packData.data + packData.size);
|
||||
data = packData.data;
|
||||
size = packData.size;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fallback: cargar desde disco
|
||||
// 3. Fallback: cargar desde disco
|
||||
std::ifstream file(resourcePath, std::ios::binary | std::ios::ate);
|
||||
if (!file) {
|
||||
// Intentar con "data/" como prefijo si no se encontró
|
||||
std::string dataPath = "data/" + resourcePath;
|
||||
file.open(dataPath, std::ios::binary | std::ios::ate);
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
if (!file) { return false; }
|
||||
}
|
||||
|
||||
// Obtener tamaño del archivo
|
||||
size = static_cast<size_t>(file.tellg());
|
||||
file.seekg(0, std::ios::beg);
|
||||
|
||||
// Alocar buffer y leer
|
||||
data = new unsigned char[size];
|
||||
file.read(reinterpret_cast<char*>(data), size);
|
||||
file.close();
|
||||
|
||||
// Guardar en caché
|
||||
cache_[resourcePath] = std::vector<unsigned char>(data, data + size);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -79,4 +80,7 @@ private:
|
||||
|
||||
// Instancia del pack (nullptr si no está cargado)
|
||||
static ResourcePack* resourcePack_;
|
||||
|
||||
// Caché en RAM para evitar I/O repetido en el bucle principal
|
||||
static std::map<std::string, std::vector<unsigned char>> cache_;
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "png_shape.hpp"
|
||||
#include "defines.hpp"
|
||||
#include "external/stb_image.h"
|
||||
#include "resource_manager.hpp"
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
@@ -9,6 +10,7 @@
|
||||
PNGShape::PNGShape(const char* png_path) {
|
||||
// Cargar PNG desde path
|
||||
if (!loadPNG(png_path)) {
|
||||
std::cerr << "[PNGShape] Usando fallback 10x10" << std::endl;
|
||||
// Fallback: generar un cuadrado simple si falla la carga
|
||||
image_width_ = 10;
|
||||
image_height_ = 10;
|
||||
@@ -19,24 +21,29 @@ PNGShape::PNGShape(const char* png_path) {
|
||||
next_idle_time_ = PNG_IDLE_TIME_MIN + (rand() % 1000) / 1000.0f * (PNG_IDLE_TIME_MAX - PNG_IDLE_TIME_MIN);
|
||||
}
|
||||
|
||||
bool PNGShape::loadPNG(const char* path) {
|
||||
int width, height, channels;
|
||||
unsigned char* data = stbi_load(path, &width, &height, &channels, 1); // Forzar 1 canal (grayscale)
|
||||
|
||||
if (!data) {
|
||||
bool PNGShape::loadPNG(const char* resource_key) {
|
||||
std::cout << "[PNGShape] Cargando recurso: " << resource_key << std::endl;
|
||||
unsigned char* file_data = nullptr;
|
||||
size_t file_size = 0;
|
||||
if (!ResourceManager::loadResource(resource_key, file_data, file_size)) {
|
||||
std::cerr << "[PNGShape] ERROR: recurso no encontrado: " << resource_key << std::endl;
|
||||
return false;
|
||||
}
|
||||
int width, height, channels;
|
||||
unsigned char* pixels = stbi_load_from_memory(file_data, static_cast<int>(file_size),
|
||||
&width, &height, &channels, 1);
|
||||
delete[] file_data;
|
||||
if (!pixels) {
|
||||
std::cerr << "[PNGShape] ERROR al decodificar PNG: " << stbi_failure_reason() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
image_width_ = width;
|
||||
image_height_ = height;
|
||||
pixel_data_.resize(width * height);
|
||||
|
||||
// Convertir a mapa booleano (true = píxel blanco/visible, false = negro/transparente)
|
||||
for (int i = 0; i < width * height; i++) {
|
||||
pixel_data_[i] = (data[i] > 128); // Umbral: >128 = blanco
|
||||
pixel_data_[i] = (pixels[i] > 128);
|
||||
}
|
||||
|
||||
stbi_image_free(data);
|
||||
stbi_image_free(pixels);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -269,7 +269,7 @@ void ShapeManager::activateShapeInternal(ShapeType type) {
|
||||
active_shape_ = std::make_unique<AtomShape>();
|
||||
break;
|
||||
case ShapeType::PNG_SHAPE:
|
||||
active_shape_ = std::make_unique<PNGShape>("data/shapes/jailgames.png");
|
||||
active_shape_ = std::make_unique<PNGShape>("shapes/jailgames.png");
|
||||
break;
|
||||
default:
|
||||
active_shape_ = std::make_unique<SphereShape>(); // Fallback
|
||||
|
||||
@@ -276,6 +276,25 @@ void UIManager::renderDebugHUD(const Engine* engine,
|
||||
text_renderer_debug_->printAbsolute(margin, left_y, balls_text.c_str(), {128, 255, 128, 255}); // Verde claro
|
||||
left_y += line_height;
|
||||
|
||||
// Máximo de pelotas en modos automáticos (resultado del benchmark)
|
||||
int max_auto_idx = engine->getMaxAutoScenario();
|
||||
int max_auto_balls = BALL_COUNT_SCENARIOS[max_auto_idx];
|
||||
std::string max_auto_text;
|
||||
if (max_auto_balls >= 1000) {
|
||||
std::string count_str = std::to_string(max_auto_balls);
|
||||
std::string formatted;
|
||||
int digits = count_str.length();
|
||||
for (int i = 0; i < digits; i++) {
|
||||
if (i > 0 && (digits - i) % 3 == 0) formatted += ',';
|
||||
formatted += count_str[i];
|
||||
}
|
||||
max_auto_text = "Auto max: " + formatted;
|
||||
} else {
|
||||
max_auto_text = "Auto max: " + std::to_string(max_auto_balls);
|
||||
}
|
||||
text_renderer_debug_->printAbsolute(margin, left_y, max_auto_text.c_str(), {128, 255, 128, 255}); // Verde claro
|
||||
left_y += line_height;
|
||||
|
||||
// V-Sync
|
||||
text_renderer_debug_->printAbsolute(margin, left_y, vsync_text_.c_str(), {0, 255, 255, 255}); // Cian
|
||||
left_y += line_height;
|
||||
|
||||
Reference in New Issue
Block a user