Compare commits
3 Commits
673587230e
...
f5da35bfb2
| Author | SHA1 | Date | |
|---|---|---|---|
| f5da35bfb2 | |||
| c0accd25e2 | |||
| ad8ad7e756 |
37
.clang-tidy
37
.clang-tidy
@@ -1,28 +1,25 @@
|
|||||||
Checks: >
|
Checks:
|
||||||
readability-*,
|
- readability-*
|
||||||
modernize-*,
|
- modernize-*
|
||||||
performance-*,
|
- performance-*
|
||||||
bugprone-unchecked-optional-access,
|
- bugprone-*
|
||||||
bugprone-sizeof-expression,
|
- -readability-identifier-length
|
||||||
bugprone-suspicious-missing-comma,
|
- -readability-magic-numbers
|
||||||
bugprone-suspicious-index,
|
- -bugprone-integer-division
|
||||||
bugprone-undefined-memory-manipulation,
|
- -bugprone-easily-swappable-parameters
|
||||||
bugprone-use-after-move,
|
- -bugprone-narrowing-conversions
|
||||||
bugprone-out-of-bound-access,
|
- -modernize-avoid-c-arrays,-warnings-as-errors
|
||||||
-readability-identifier-length,
|
|
||||||
-readability-magic-numbers,
|
|
||||||
-bugprone-narrowing-conversions,
|
|
||||||
-performance-enum-size,
|
|
||||||
-performance-inefficient-string-concatenation,
|
|
||||||
-bugprone-integer-division,
|
|
||||||
-bugprone-easily-swappable-parameters,
|
|
||||||
|
|
||||||
WarningsAsErrors: '*'
|
WarningsAsErrors: '*'
|
||||||
# Solo incluir archivos de tu código fuente
|
# Solo incluir archivos de tu código fuente (external tiene su propio .clang-tidy)
|
||||||
HeaderFilterRegex: '^source/(sections|ui)/.*'
|
# Excluye los headers SPIR-V generados en rendering/sdl3gpu/
|
||||||
|
HeaderFilterRegex: 'source/(?!external/|rendering/sdl3gpu/.*_spv\.h).*'
|
||||||
FormatStyle: file
|
FormatStyle: file
|
||||||
|
|
||||||
CheckOptions:
|
CheckOptions:
|
||||||
|
# bugprone-empty-catch: aceptar catches vacíos marcados con @INTENTIONAL en un comentario
|
||||||
|
- { key: bugprone-empty-catch.IgnoreCatchWithKeywords, value: '@INTENTIONAL' }
|
||||||
|
|
||||||
# Variables locales en snake_case
|
# Variables locales en snake_case
|
||||||
- { key: readability-identifier-naming.VariableCase, value: lower_case }
|
- { key: readability-identifier-naming.VariableCase, value: lower_case }
|
||||||
|
|
||||||
|
|||||||
@@ -106,7 +106,6 @@ set(APP_SOURCES
|
|||||||
|
|
||||||
# Fuentes de librerías de terceros
|
# Fuentes de librerías de terceros
|
||||||
set(EXTERNAL_SOURCES
|
set(EXTERNAL_SOURCES
|
||||||
source/external/jail_audio.cpp
|
|
||||||
source/external/json.hpp
|
source/external/json.hpp
|
||||||
source/external/gif.cpp
|
source/external/gif.cpp
|
||||||
)
|
)
|
||||||
@@ -243,6 +242,7 @@ set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAK
|
|||||||
|
|
||||||
find_program(CLANG_TIDY_EXE NAMES clang-tidy)
|
find_program(CLANG_TIDY_EXE NAMES clang-tidy)
|
||||||
find_program(CLANG_FORMAT_EXE NAMES clang-format)
|
find_program(CLANG_FORMAT_EXE NAMES clang-format)
|
||||||
|
find_program(CPPCHECK_EXE NAMES cppcheck)
|
||||||
|
|
||||||
# Recopilar todos los archivos fuente, excluyendo external/
|
# Recopilar todos los archivos fuente, excluyendo external/
|
||||||
file(GLOB_RECURSE ALL_SOURCE_FILES
|
file(GLOB_RECURSE ALL_SOURCE_FILES
|
||||||
@@ -252,6 +252,14 @@ file(GLOB_RECURSE ALL_SOURCE_FILES
|
|||||||
)
|
)
|
||||||
list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*")
|
list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*")
|
||||||
|
|
||||||
|
# Para cppcheck, pasar solo .cpp (los headers se procesan transitivamente).
|
||||||
|
# Si pasamos .hpp como TUs independientes, cppcheck reporta falsos positivos de
|
||||||
|
# 'unusedStructMember' porque no hace análisis cross-TU y ve miembros de clase
|
||||||
|
# cuyo uso vive en un .cpp distinto.
|
||||||
|
set(CPPCHECK_SOURCES ${ALL_SOURCE_FILES})
|
||||||
|
list(FILTER CPPCHECK_SOURCES INCLUDE REGEX ".*\\.cpp$")
|
||||||
|
list(FILTER CPPCHECK_SOURCES EXCLUDE REGEX ".*_spv\\.h$")
|
||||||
|
|
||||||
# Targets de clang-tidy
|
# Targets de clang-tidy
|
||||||
if(CLANG_TIDY_EXE)
|
if(CLANG_TIDY_EXE)
|
||||||
# En macOS con clang-tidy de Homebrew LLVM, es necesario pasar el sysroot
|
# En macOS con clang-tidy de Homebrew LLVM, es necesario pasar el sysroot
|
||||||
@@ -308,3 +316,28 @@ if(CLANG_FORMAT_EXE)
|
|||||||
else()
|
else()
|
||||||
message(STATUS "clang-format no encontrado - targets 'format' y 'format-check' no disponibles")
|
message(STATUS "clang-format no encontrado - targets 'format' y 'format-check' no disponibles")
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
# Targets de cppcheck
|
||||||
|
if(CPPCHECK_EXE)
|
||||||
|
add_custom_target(cppcheck
|
||||||
|
COMMAND ${CPPCHECK_EXE}
|
||||||
|
--enable=warning,style,performance,portability
|
||||||
|
--std=c++20
|
||||||
|
--language=c++
|
||||||
|
--inline-suppr
|
||||||
|
--suppress=missingIncludeSystem
|
||||||
|
--suppress=toomanyconfigs
|
||||||
|
-D_DEBUG
|
||||||
|
-DLINUX_BUILD
|
||||||
|
--quiet
|
||||||
|
-I ${CMAKE_SOURCE_DIR}/source
|
||||||
|
-I ${CMAKE_SOURCE_DIR}/source/external
|
||||||
|
-I ${CMAKE_SOURCE_DIR}/source/rendering
|
||||||
|
-I ${CMAKE_SOURCE_DIR}/source/rendering/sdl3gpu
|
||||||
|
${CPPCHECK_SOURCES}
|
||||||
|
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
|
||||||
|
COMMENT "Running cppcheck..."
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
message(STATUS "cppcheck no encontrado - target 'cppcheck' no disponible")
|
||||||
|
endif()
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.1 KiB |
@@ -4,7 +4,21 @@
|
|||||||
|
|
||||||
#include <algorithm> // Para clamp
|
#include <algorithm> // Para clamp
|
||||||
|
|
||||||
#include "external/jail_audio.h" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
|
// Implementación de stb_vorbis (debe estar ANTES de incluir jail_audio.hpp).
|
||||||
|
// clang-format off
|
||||||
|
#undef STB_VORBIS_HEADER_ONLY
|
||||||
|
#include "external/stb_vorbis.h"
|
||||||
|
// stb_vorbis.h filtra les macros L, C i R (i PLAYBACK_*) al TU. Les netegem
|
||||||
|
// perquè xocarien amb noms de paràmetres de plantilla en json.hpp i altres.
|
||||||
|
#undef L
|
||||||
|
#undef C
|
||||||
|
#undef R
|
||||||
|
#undef PLAYBACK_MONO
|
||||||
|
#undef PLAYBACK_LEFT
|
||||||
|
#undef PLAYBACK_RIGHT
|
||||||
|
// clang-format on
|
||||||
|
|
||||||
|
#include "external/jail_audio.hpp" // Para JA_FadeOutMusic, JA_Init, JA_PauseM...
|
||||||
#include "options.hpp" // Para AudioOptions, audio, MusicOptions
|
#include "options.hpp" // Para AudioOptions, audio, MusicOptions
|
||||||
#include "resource.hpp" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "ui/logger.hpp" // Para logger
|
#include "ui/logger.hpp" // Para logger
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
#include "asset.hpp" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "audio.hpp" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
#include "external/fkyaml_node.hpp" // Para fkyaml::node
|
||||||
|
#include "global_events.hpp" // Para GlobalEvents::handle
|
||||||
#include "input.hpp" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "lang.hpp" // Para setLanguage
|
#include "lang.hpp" // Para setLanguage
|
||||||
#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable
|
#include "manage_hiscore_table.hpp" // Para ManageHiScoreTable
|
||||||
@@ -75,6 +76,9 @@ Director::Director(int argc, std::span<char*> argv) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Director::~Director() {
|
Director::~Director() {
|
||||||
|
// Libera las secciones primero: sus destructores pueden tocar Audio/Resource/Screen,
|
||||||
|
// que close() destruye a continuación.
|
||||||
|
resetActiveSection();
|
||||||
close();
|
close();
|
||||||
Logger::put("\nBye!");
|
Logger::put("\nBye!");
|
||||||
}
|
}
|
||||||
@@ -335,28 +339,48 @@ void Director::createSystemFolder(const std::string& folder) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ejecuta la sección con el logo
|
// Libera todos los unique_ptr de sección (solo uno tiene propiedad a la vez)
|
||||||
void Director::runLogo() {
|
void Director::resetActiveSection() {
|
||||||
auto logo = std::make_unique<Logo>();
|
logo_.reset();
|
||||||
logo->run();
|
intro_.reset();
|
||||||
|
title_.reset();
|
||||||
|
game_.reset();
|
||||||
|
instructions_.reset();
|
||||||
|
hi_score_table_.reset();
|
||||||
|
credits_.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ejecuta la sección con la secuencia de introducción
|
// Destruye la sección anterior y construye la nueva cuando Section::name cambia
|
||||||
void Director::runIntro() {
|
void Director::handleSectionTransition() {
|
||||||
auto intro = std::make_unique<Intro>();
|
// RESET: recarga recursos y vuelve a LOGO (el propio reset() cambia Section::name)
|
||||||
intro->run();
|
if (Section::name == Section::Name::RESET) {
|
||||||
|
resetActiveSection(); // libera recursos actuales antes del reload
|
||||||
|
reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ejecuta la sección con el título del juego
|
if (Section::name == last_built_section_name_) {
|
||||||
void Director::runTitle() {
|
return; // ya tenemos la sección correcta viva
|
||||||
auto title = std::make_unique<Title>();
|
|
||||||
title->run();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ejecuta la sección donde se juega al juego
|
// Destruye la sección anterior
|
||||||
void Director::runGame() {
|
resetActiveSection();
|
||||||
|
|
||||||
|
// Construye la nueva
|
||||||
|
switch (Section::name) {
|
||||||
|
case Section::Name::LOGO:
|
||||||
|
logo_ = std::make_unique<Logo>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::INTRO:
|
||||||
|
intro_ = std::make_unique<Intro>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::TITLE:
|
||||||
|
title_ = std::make_unique<Title>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::GAME: {
|
||||||
Player::Id player_id = Player::Id::PLAYER1;
|
Player::Id player_id = Player::Id::PLAYER1;
|
||||||
|
|
||||||
switch (Section::options) {
|
switch (Section::options) {
|
||||||
case Section::Options::GAME_PLAY_1P:
|
case Section::Options::GAME_PLAY_1P:
|
||||||
player_id = Player::Id::PLAYER1;
|
player_id = Player::Id::PLAYER1;
|
||||||
@@ -370,40 +394,41 @@ void Director::runGame() {
|
|||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef _DEBUG
|
#ifdef _DEBUG
|
||||||
const int CURRENT_STAGE = debug_config.initial_stage;
|
const int CURRENT_STAGE = debug_config.initial_stage;
|
||||||
#else
|
#else
|
||||||
constexpr int CURRENT_STAGE = 0;
|
constexpr int CURRENT_STAGE = 0;
|
||||||
#endif
|
#endif
|
||||||
auto game = std::make_unique<Game>(player_id, CURRENT_STAGE, Game::DEMO_OFF);
|
game_ = std::make_unique<Game>(player_id, CURRENT_STAGE, Game::DEMO_OFF);
|
||||||
game->run();
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ejecuta la sección donde se muestran las instrucciones
|
case Section::Name::GAME_DEMO: {
|
||||||
void Director::runInstructions() {
|
|
||||||
auto instructions = std::make_unique<Instructions>();
|
|
||||||
instructions->run();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ejecuta la sección donde se muestran los creditos del programa
|
|
||||||
void Director::runCredits() {
|
|
||||||
auto credits = std::make_unique<Credits>();
|
|
||||||
credits->run();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ejecuta la sección donde se muestra la tabla de puntuaciones
|
|
||||||
void Director::runHiScoreTable() {
|
|
||||||
auto hi_score_table = std::make_unique<HiScoreTable>();
|
|
||||||
hi_score_table->run();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ejecuta el juego en modo demo
|
|
||||||
void Director::runDemoGame() {
|
|
||||||
const auto PLAYER_ID = static_cast<Player::Id>((rand() % 2) + 1);
|
const auto PLAYER_ID = static_cast<Player::Id>((rand() % 2) + 1);
|
||||||
constexpr auto CURRENT_STAGE = 0;
|
constexpr auto CURRENT_STAGE = 0;
|
||||||
auto game = std::make_unique<Game>(PLAYER_ID, CURRENT_STAGE, Game::DEMO_ON);
|
game_ = std::make_unique<Game>(PLAYER_ID, CURRENT_STAGE, Game::DEMO_ON);
|
||||||
game->run();
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case Section::Name::INSTRUCTIONS:
|
||||||
|
instructions_ = std::make_unique<Instructions>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::CREDITS:
|
||||||
|
credits_ = std::make_unique<Credits>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::HI_SCORE_TABLE:
|
||||||
|
hi_score_table_ = std::make_unique<HiScoreTable>();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Section::Name::RESET:
|
||||||
|
case Section::Name::QUIT:
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
last_built_section_name_ = Section::name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reinicia objetos y vuelve a la sección inicial
|
// Reinicia objetos y vuelve a la sección inicial
|
||||||
@@ -418,43 +443,58 @@ void Director::reset() {
|
|||||||
Section::name = Section::Name::LOGO;
|
Section::name = Section::Name::LOGO;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto Director::run() -> int {
|
// Avanza un frame de la sección activa (llamado desde SDL_AppIterate)
|
||||||
// Bucle principal
|
auto Director::iterate() -> SDL_AppResult {
|
||||||
while (Section::name != Section::Name::QUIT) {
|
if (Section::name == Section::Name::QUIT) {
|
||||||
switch (Section::name) {
|
return SDL_APP_SUCCESS;
|
||||||
case Section::Name::RESET:
|
|
||||||
reset();
|
|
||||||
break;
|
|
||||||
case Section::Name::LOGO:
|
|
||||||
runLogo();
|
|
||||||
break;
|
|
||||||
case Section::Name::INTRO:
|
|
||||||
runIntro();
|
|
||||||
break;
|
|
||||||
case Section::Name::TITLE:
|
|
||||||
runTitle();
|
|
||||||
break;
|
|
||||||
case Section::Name::GAME:
|
|
||||||
runGame();
|
|
||||||
break;
|
|
||||||
case Section::Name::HI_SCORE_TABLE:
|
|
||||||
runHiScoreTable();
|
|
||||||
break;
|
|
||||||
case Section::Name::GAME_DEMO:
|
|
||||||
runDemoGame();
|
|
||||||
break;
|
|
||||||
case Section::Name::INSTRUCTIONS:
|
|
||||||
runInstructions();
|
|
||||||
break;
|
|
||||||
case Section::Name::CREDITS:
|
|
||||||
runCredits();
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
// Gestiona las transiciones entre secciones (destruye la anterior y construye la nueva)
|
||||||
|
handleSectionTransition();
|
||||||
|
|
||||||
|
// Ejecuta un frame de la sección activa
|
||||||
|
if (logo_) {
|
||||||
|
logo_->iterate();
|
||||||
|
} else if (intro_) {
|
||||||
|
intro_->iterate();
|
||||||
|
} else if (title_) {
|
||||||
|
title_->iterate();
|
||||||
|
} else if (game_) {
|
||||||
|
game_->iterate();
|
||||||
|
} else if (instructions_) {
|
||||||
|
instructions_->iterate();
|
||||||
|
} else if (hi_score_table_) {
|
||||||
|
hi_score_table_->iterate();
|
||||||
|
} else if (credits_) {
|
||||||
|
credits_->iterate();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (Section::name == Section::Name::QUIT) ? SDL_APP_SUCCESS : SDL_APP_CONTINUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento SDL (llamado desde SDL_AppEvent)
|
||||||
|
auto Director::handleEvent(SDL_Event& event) -> SDL_AppResult {
|
||||||
|
// Eventos globales (SDL_EVENT_QUIT, resize, render target reset, hotplug, service menu, ratón)
|
||||||
|
GlobalEvents::handle(event);
|
||||||
|
|
||||||
|
// Reenvía a la sección activa
|
||||||
|
if (logo_) {
|
||||||
|
logo_->handleEvent(event);
|
||||||
|
} else if (intro_) {
|
||||||
|
intro_->handleEvent(event);
|
||||||
|
} else if (title_) {
|
||||||
|
title_->handleEvent(event);
|
||||||
|
} else if (game_) {
|
||||||
|
game_->handleEvent(event);
|
||||||
|
} else if (instructions_) {
|
||||||
|
instructions_->handleEvent(event);
|
||||||
|
} else if (hi_score_table_) {
|
||||||
|
hi_score_table_->handleEvent(event);
|
||||||
|
} else if (credits_) {
|
||||||
|
credits_->handleEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (Section::name == Section::Name::QUIT) ? SDL_APP_SUCCESS : SDL_APP_CONTINUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Apaga el sistema de forma segura
|
// Apaga el sistema de forma segura
|
||||||
|
|||||||
@@ -1,12 +1,26 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <SDL3/SDL.h> // Para SDL_AppResult, SDL_Event
|
||||||
|
|
||||||
|
#include <memory> // Para unique_ptr
|
||||||
#include <span> // Para Span
|
#include <span> // Para Span
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
|
||||||
|
#include "section.hpp" // Para Section::Name
|
||||||
|
|
||||||
namespace Lang {
|
namespace Lang {
|
||||||
enum class Code : int;
|
enum class Code : int;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Declaraciones adelantadas de las secciones
|
||||||
|
class Logo;
|
||||||
|
class Intro;
|
||||||
|
class Title;
|
||||||
|
class Game;
|
||||||
|
class Instructions;
|
||||||
|
class HiScoreTable;
|
||||||
|
class Credits;
|
||||||
|
|
||||||
// --- Clase Director: gestor principal de la aplicación ---
|
// --- Clase Director: gestor principal de la aplicación ---
|
||||||
class Director {
|
class Director {
|
||||||
public:
|
public:
|
||||||
@@ -14,8 +28,9 @@ class Director {
|
|||||||
Director(int argc, std::span<char*> argv);
|
Director(int argc, std::span<char*> argv);
|
||||||
~Director();
|
~Director();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para SDL_MAIN_USE_CALLBACKS ---
|
||||||
static auto run() -> int;
|
auto iterate() -> SDL_AppResult; // Avanza un frame de la sección activa
|
||||||
|
auto handleEvent(SDL_Event& event) -> SDL_AppResult; // Procesa un evento SDL
|
||||||
|
|
||||||
// --- Debug config (accesible desde otras clases) ---
|
// --- Debug config (accesible desde otras clases) ---
|
||||||
struct DebugConfig {
|
struct DebugConfig {
|
||||||
@@ -37,6 +52,16 @@ class Director {
|
|||||||
std::string executable_path_; // Ruta del ejecutable
|
std::string executable_path_; // Ruta del ejecutable
|
||||||
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
std::string system_folder_; // Carpeta del sistema para almacenar datos
|
||||||
|
|
||||||
|
// --- Sección activa (una y sólo una viva en cada momento) ---
|
||||||
|
std::unique_ptr<Logo> logo_;
|
||||||
|
std::unique_ptr<Intro> intro_;
|
||||||
|
std::unique_ptr<Title> title_;
|
||||||
|
std::unique_ptr<Game> game_;
|
||||||
|
std::unique_ptr<Instructions> instructions_;
|
||||||
|
std::unique_ptr<HiScoreTable> hi_score_table_;
|
||||||
|
std::unique_ptr<Credits> credits_;
|
||||||
|
Section::Name last_built_section_name_ = Section::Name::RESET;
|
||||||
|
|
||||||
// --- Inicialización y cierre del sistema ---
|
// --- Inicialización y cierre del sistema ---
|
||||||
void init(); // Inicializa la aplicación
|
void init(); // Inicializa la aplicación
|
||||||
static void close(); // Cierra y libera recursos
|
static void close(); // Cierra y libera recursos
|
||||||
@@ -51,15 +76,9 @@ class Director {
|
|||||||
void loadAssets(); // Crea el índice de archivos disponibles
|
void loadAssets(); // Crea el índice de archivos disponibles
|
||||||
void checkProgramArguments(int argc, std::span<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
void checkProgramArguments(int argc, std::span<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
|
||||||
|
|
||||||
// --- Secciones del programa ---
|
// --- Gestión de secciones ---
|
||||||
static void runLogo(); // Ejecuta la pantalla con el logo
|
void handleSectionTransition(); // Destruye la sección anterior y construye la nueva si Section::name ha cambiado
|
||||||
static void runIntro(); // Ejecuta la introducción del juego
|
void resetActiveSection(); // Libera todos los unique_ptr de sección
|
||||||
static void runTitle(); // Ejecuta la pantalla de título
|
|
||||||
static void runGame(); // Inicia el juego
|
|
||||||
static void runInstructions(); // Muestra las instrucciones
|
|
||||||
static void runCredits(); // Muestra los créditos del juego
|
|
||||||
static void runHiScoreTable(); // Muestra la tabla de puntuaciones
|
|
||||||
static void runDemoGame(); // Ejecuta el modo demo
|
|
||||||
static void reset(); // Reinicia objetos y vuelve a la sección inicial
|
static void reset(); // Reinicia objetos y vuelve a la sección inicial
|
||||||
|
|
||||||
// --- Gestión de archivos de idioma ---
|
// --- Gestión de archivos de idioma ---
|
||||||
|
|||||||
477
source/external/jail_audio.cpp
vendored
477
source/external/jail_audio.cpp
vendored
@@ -1,477 +0,0 @@
|
|||||||
#ifndef JA_USESDLMIXER
|
|
||||||
#include "jail_audio.h"
|
|
||||||
|
|
||||||
#include <SDL3/SDL.h> // Para SDL_AudioFormat, SDL_BindAudioStream, SDL_SetAudioStreamGain, SDL_PutAudioStreamData, SDL_DestroyAudioStream, SDL_GetAudioStreamAvailable, Uint8, SDL_CreateAudioStream, SDL_UnbindAudioStream, Uint32, SDL_CloseAudioDevice, SDL_GetTicks, SDL_Log, SDL_free, SDL_AudioSpec, SDL_AudioStream, SDL_IOFromMem, SDL_LoadWAV, SDL_LoadWAV_IO, SDL_OpenAudioDevice, SDL_clamp, SDL_malloc, SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, SDL_AudioDeviceID, SDL_memcpy
|
|
||||||
#include <stdint.h> // Para uint32_t, uint8_t
|
|
||||||
#include <stdio.h> // Para NULL, fseek, printf, fclose, fopen, fread, ftell, FILE, SEEK_END, SEEK_SET
|
|
||||||
#include <stdlib.h> // Para free, malloc
|
|
||||||
#include <string.h> // Para strcpy, strlen
|
|
||||||
|
|
||||||
#include "stb_vorbis.h" // Para stb_vorbis_decode_memory
|
|
||||||
|
|
||||||
#define JA_MAX_SIMULTANEOUS_CHANNELS 20
|
|
||||||
#define JA_MAX_GROUPS 2
|
|
||||||
|
|
||||||
struct JA_Sound_t
|
|
||||||
{
|
|
||||||
SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 };
|
|
||||||
Uint32 length { 0 };
|
|
||||||
Uint8 *buffer { NULL };
|
|
||||||
};
|
|
||||||
|
|
||||||
struct JA_Channel_t
|
|
||||||
{
|
|
||||||
JA_Sound_t *sound { nullptr };
|
|
||||||
int pos { 0 };
|
|
||||||
int times { 0 };
|
|
||||||
int group { 0 };
|
|
||||||
SDL_AudioStream *stream { nullptr };
|
|
||||||
JA_Channel_state state { JA_CHANNEL_FREE };
|
|
||||||
};
|
|
||||||
|
|
||||||
struct JA_Music_t
|
|
||||||
{
|
|
||||||
SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 };
|
|
||||||
Uint32 length { 0 };
|
|
||||||
Uint8 *buffer { nullptr };
|
|
||||||
char *filename { nullptr };
|
|
||||||
|
|
||||||
int pos { 0 };
|
|
||||||
int times { 0 };
|
|
||||||
SDL_AudioStream *stream { nullptr };
|
|
||||||
JA_Music_state state { JA_MUSIC_INVALID };
|
|
||||||
};
|
|
||||||
|
|
||||||
JA_Music_t *current_music { nullptr };
|
|
||||||
JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
|
|
||||||
|
|
||||||
SDL_AudioSpec JA_audioSpec { SDL_AUDIO_S16, 2, 48000 };
|
|
||||||
float JA_musicVolume { 1.0f };
|
|
||||||
float JA_soundVolume[JA_MAX_GROUPS];
|
|
||||||
bool JA_musicEnabled { true };
|
|
||||||
bool JA_soundEnabled { true };
|
|
||||||
SDL_AudioDeviceID sdlAudioDevice { 0 };
|
|
||||||
//SDL_TimerID JA_timerID { 0 };
|
|
||||||
|
|
||||||
bool fading = false;
|
|
||||||
int fade_start_time;
|
|
||||||
int fade_duration;
|
|
||||||
int fade_initial_volume;
|
|
||||||
|
|
||||||
|
|
||||||
void JA_Update()
|
|
||||||
{
|
|
||||||
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING)
|
|
||||||
{
|
|
||||||
if (fading) {
|
|
||||||
int time = SDL_GetTicks();
|
|
||||||
if (time > (fade_start_time+fade_duration)) {
|
|
||||||
fading = false;
|
|
||||||
JA_StopMusic();
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
const int time_passed = time - fade_start_time;
|
|
||||||
const float percent = (float)time_passed / (float)fade_duration;
|
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume*(1.0 - percent));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (current_music->times != 0)
|
|
||||||
{
|
|
||||||
if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length/2)) {
|
|
||||||
SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length);
|
|
||||||
}
|
|
||||||
if (current_music->times>0) current_music->times--;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (JA_soundEnabled)
|
|
||||||
{
|
|
||||||
for (int i=0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
|
|
||||||
if (channels[i].state == JA_CHANNEL_PLAYING)
|
|
||||||
{
|
|
||||||
if (channels[i].times != 0)
|
|
||||||
{
|
|
||||||
if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length/2)) {
|
|
||||||
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
|
|
||||||
if (channels[i].times>0) channels[i].times--;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels)
|
|
||||||
{
|
|
||||||
#ifdef DEBUG
|
|
||||||
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
JA_audioSpec = {format, num_channels, freq };
|
|
||||||
if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
|
|
||||||
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
|
|
||||||
if (sdlAudioDevice==0) SDL_Log("Failed to initialize SDL audio!");
|
|
||||||
for (int i=0; i<JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
|
|
||||||
for (int i=0; i<JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_Quit()
|
|
||||||
{
|
|
||||||
if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
|
|
||||||
sdlAudioDevice = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length)
|
|
||||||
{
|
|
||||||
JA_Music_t *music = new JA_Music_t();
|
|
||||||
|
|
||||||
int chan, samplerate;
|
|
||||||
short *output;
|
|
||||||
music->length = stb_vorbis_decode_memory(buffer, length, &chan, &samplerate, &output) * chan * 2;
|
|
||||||
|
|
||||||
music->spec.channels = chan;
|
|
||||||
music->spec.freq = samplerate;
|
|
||||||
music->spec.format = SDL_AUDIO_S16;
|
|
||||||
music->buffer = (Uint8*)SDL_malloc(music->length);
|
|
||||||
SDL_memcpy(music->buffer, output, music->length);
|
|
||||||
free(output);
|
|
||||||
music->pos = 0;
|
|
||||||
music->state = JA_MUSIC_STOPPED;
|
|
||||||
|
|
||||||
return music;
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Music_t *JA_LoadMusic(const char* filename)
|
|
||||||
{
|
|
||||||
// [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid.
|
|
||||||
FILE *f = fopen(filename, "rb");
|
|
||||||
fseek(f, 0, SEEK_END);
|
|
||||||
long fsize = ftell(f);
|
|
||||||
fseek(f, 0, SEEK_SET);
|
|
||||||
Uint8 *buffer = (Uint8*)malloc(fsize + 1);
|
|
||||||
if (fread(buffer, fsize, 1, f)!=1) return NULL;
|
|
||||||
fclose(f);
|
|
||||||
|
|
||||||
JA_Music_t *music = JA_LoadMusic(buffer, fsize);
|
|
||||||
music->filename = (char*)malloc(strlen(filename)+1);
|
|
||||||
strcpy(music->filename, filename);
|
|
||||||
|
|
||||||
free(buffer);
|
|
||||||
|
|
||||||
return music;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_PlayMusic(JA_Music_t *music, const int loop)
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return;
|
|
||||||
|
|
||||||
JA_StopMusic();
|
|
||||||
|
|
||||||
current_music = music;
|
|
||||||
current_music->pos = 0;
|
|
||||||
current_music->state = JA_MUSIC_PLAYING;
|
|
||||||
current_music->times = loop;
|
|
||||||
|
|
||||||
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec);
|
|
||||||
if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n");
|
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
|
||||||
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n");
|
|
||||||
//SDL_ResumeAudioStreamDevice(current_music->stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
char *JA_GetMusicFilename(JA_Music_t *music)
|
|
||||||
{
|
|
||||||
if (!music) music = current_music;
|
|
||||||
return music->filename;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_PauseMusic()
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return;
|
|
||||||
if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
|
|
||||||
|
|
||||||
current_music->state = JA_MUSIC_PAUSED;
|
|
||||||
//SDL_PauseAudioStreamDevice(current_music->stream);
|
|
||||||
SDL_UnbindAudioStream(current_music->stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_ResumeMusic()
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return;
|
|
||||||
if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
|
|
||||||
|
|
||||||
current_music->state = JA_MUSIC_PLAYING;
|
|
||||||
//SDL_ResumeAudioStreamDevice(current_music->stream);
|
|
||||||
SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_StopMusic()
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return;
|
|
||||||
if (!current_music || current_music->state == JA_MUSIC_INVALID) return;
|
|
||||||
|
|
||||||
current_music->pos = 0;
|
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
|
||||||
//SDL_PauseAudioStreamDevice(current_music->stream);
|
|
||||||
SDL_DestroyAudioStream(current_music->stream);
|
|
||||||
current_music->stream = nullptr;
|
|
||||||
free(current_music->filename);
|
|
||||||
current_music->filename = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_FadeOutMusic(const int milliseconds)
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return;
|
|
||||||
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return;
|
|
||||||
|
|
||||||
fading = true;
|
|
||||||
fade_start_time = SDL_GetTicks();
|
|
||||||
fade_duration = milliseconds;
|
|
||||||
fade_initial_volume = JA_musicVolume;
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Music_state JA_GetMusicState()
|
|
||||||
{
|
|
||||||
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
|
|
||||||
if (!current_music) return JA_MUSIC_INVALID;
|
|
||||||
|
|
||||||
return current_music->state;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_DeleteMusic(JA_Music_t *music)
|
|
||||||
{
|
|
||||||
if (current_music == music) current_music = nullptr;
|
|
||||||
SDL_free(music->buffer);
|
|
||||||
if (music->stream) SDL_DestroyAudioStream(music->stream);
|
|
||||||
delete music;
|
|
||||||
}
|
|
||||||
|
|
||||||
float JA_SetMusicVolume(float volume)
|
|
||||||
{
|
|
||||||
JA_musicVolume = SDL_clamp( volume, 0.0f, 1.0f );
|
|
||||||
if (current_music) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
|
||||||
return JA_musicVolume;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_SetMusicPosition(float value)
|
|
||||||
{
|
|
||||||
if (!current_music) return;
|
|
||||||
current_music->pos = value * current_music->spec.freq;
|
|
||||||
}
|
|
||||||
|
|
||||||
float JA_GetMusicPosition()
|
|
||||||
{
|
|
||||||
if (!current_music) return 0;
|
|
||||||
return float(current_music->pos)/float(current_music->spec.freq);
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_EnableMusic(const bool value)
|
|
||||||
{
|
|
||||||
if ( !value && current_music && (current_music->state==JA_MUSIC_PLAYING) ) JA_StopMusic();
|
|
||||||
|
|
||||||
JA_musicEnabled = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
|
|
||||||
{
|
|
||||||
JA_Sound_t *sound = new JA_Sound_t();
|
|
||||||
sound->buffer = buffer;
|
|
||||||
sound->length = length;
|
|
||||||
return sound;
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Sound_t *JA_LoadSound(uint8_t* buffer, uint32_t size)
|
|
||||||
{
|
|
||||||
JA_Sound_t *sound = new JA_Sound_t();
|
|
||||||
SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size),1, &sound->spec, &sound->buffer, &sound->length);
|
|
||||||
|
|
||||||
return sound;
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Sound_t *JA_LoadSound(const char* filename)
|
|
||||||
{
|
|
||||||
JA_Sound_t *sound = new JA_Sound_t();
|
|
||||||
SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length);
|
|
||||||
|
|
||||||
return sound;
|
|
||||||
}
|
|
||||||
|
|
||||||
int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return -1;
|
|
||||||
|
|
||||||
int channel = 0;
|
|
||||||
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; }
|
|
||||||
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) channel = 0;
|
|
||||||
JA_StopChannel(channel);
|
|
||||||
|
|
||||||
channels[channel].sound = sound;
|
|
||||||
channels[channel].times = loop;
|
|
||||||
channels[channel].pos = 0;
|
|
||||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
|
||||||
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
|
|
||||||
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer, channels[channel].sound->length);
|
|
||||||
SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume[group]);
|
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
|
||||||
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, const int group)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return -1;
|
|
||||||
|
|
||||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1;
|
|
||||||
JA_StopChannel(channel);
|
|
||||||
|
|
||||||
channels[channel].sound = sound;
|
|
||||||
channels[channel].times = loop;
|
|
||||||
channels[channel].pos = 0;
|
|
||||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
|
||||||
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
|
|
||||||
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer, channels[channel].sound->length);
|
|
||||||
SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume[group]);
|
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
|
||||||
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_DeleteSound(JA_Sound_t *sound)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
|
||||||
if (channels[i].sound == sound) JA_StopChannel(i);
|
|
||||||
}
|
|
||||||
SDL_free(sound->buffer);
|
|
||||||
delete sound;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_PauseChannel(const int channel)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return;
|
|
||||||
|
|
||||||
if (channel == -1)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
|
||||||
if (channels[i].state == JA_CHANNEL_PLAYING)
|
|
||||||
{
|
|
||||||
channels[i].state = JA_CHANNEL_PAUSED;
|
|
||||||
//SDL_PauseAudioStreamDevice(channels[i].stream);
|
|
||||||
SDL_UnbindAudioStream(channels[i].stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
|
|
||||||
{
|
|
||||||
if (channels[channel].state == JA_CHANNEL_PLAYING)
|
|
||||||
{
|
|
||||||
channels[channel].state = JA_CHANNEL_PAUSED;
|
|
||||||
//SDL_PauseAudioStreamDevice(channels[channel].stream);
|
|
||||||
SDL_UnbindAudioStream(channels[channel].stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_ResumeChannel(const int channel)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return;
|
|
||||||
|
|
||||||
if (channel == -1)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
|
||||||
if (channels[i].state == JA_CHANNEL_PAUSED)
|
|
||||||
{
|
|
||||||
channels[i].state = JA_CHANNEL_PLAYING;
|
|
||||||
//SDL_ResumeAudioStreamDevice(channels[i].stream);
|
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
|
|
||||||
{
|
|
||||||
if (channels[channel].state == JA_CHANNEL_PAUSED)
|
|
||||||
{
|
|
||||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
|
||||||
//SDL_ResumeAudioStreamDevice(channels[channel].stream);
|
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_StopChannel(const int channel)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return;
|
|
||||||
|
|
||||||
if (channel == -1)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
|
||||||
if (channels[i].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[i].stream);
|
|
||||||
channels[i].stream = nullptr;
|
|
||||||
channels[i].state = JA_CHANNEL_FREE;
|
|
||||||
channels[i].pos = 0;
|
|
||||||
channels[i].sound = NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS)
|
|
||||||
{
|
|
||||||
if (channels[channel].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[channel].stream);
|
|
||||||
channels[channel].stream = nullptr;
|
|
||||||
channels[channel].state = JA_CHANNEL_FREE;
|
|
||||||
channels[channel].pos = 0;
|
|
||||||
channels[channel].sound = NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
JA_Channel_state JA_GetChannelState(const int channel)
|
|
||||||
{
|
|
||||||
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
|
|
||||||
|
|
||||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID;
|
|
||||||
|
|
||||||
return channels[channel].state;
|
|
||||||
}
|
|
||||||
|
|
||||||
float JA_SetSoundVolume(float volume, const int group)
|
|
||||||
{
|
|
||||||
const float v = SDL_clamp( volume, 0.0f, 1.0f );
|
|
||||||
for (int i = 0; i < JA_MAX_GROUPS; ++i) {
|
|
||||||
if (group==-1 || group==i) JA_soundVolume[i]=v;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
|
||||||
if ( ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) &&
|
|
||||||
((group==-1) || (channels[i].group==group)) )
|
|
||||||
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[i]);
|
|
||||||
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
void JA_EnableSound(const bool value)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
|
||||||
{
|
|
||||||
if (channels[i].state == JA_CHANNEL_PLAYING) JA_StopChannel(i);
|
|
||||||
}
|
|
||||||
JA_soundEnabled = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
float JA_SetVolume(float volume)
|
|
||||||
{
|
|
||||||
JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f);
|
|
||||||
|
|
||||||
return JA_musicVolume;
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
43
source/external/jail_audio.h
vendored
43
source/external/jail_audio.h
vendored
@@ -1,43 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <SDL3/SDL.h>
|
|
||||||
|
|
||||||
enum JA_Channel_state { JA_CHANNEL_INVALID, JA_CHANNEL_FREE, JA_CHANNEL_PLAYING, JA_CHANNEL_PAUSED, JA_SOUND_DISABLED };
|
|
||||||
enum JA_Music_state { JA_MUSIC_INVALID, JA_MUSIC_PLAYING, JA_MUSIC_PAUSED, JA_MUSIC_STOPPED, JA_MUSIC_DISABLED };
|
|
||||||
|
|
||||||
struct JA_Sound_t;
|
|
||||||
struct JA_Music_t;
|
|
||||||
|
|
||||||
void JA_Update();
|
|
||||||
|
|
||||||
void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels);
|
|
||||||
void JA_Quit();
|
|
||||||
|
|
||||||
JA_Music_t *JA_LoadMusic(const char* filename);
|
|
||||||
JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length);
|
|
||||||
void JA_PlayMusic(JA_Music_t *music, const int loop = -1);
|
|
||||||
char *JA_GetMusicFilename(JA_Music_t *music = nullptr);
|
|
||||||
void JA_PauseMusic();
|
|
||||||
void JA_ResumeMusic();
|
|
||||||
void JA_StopMusic();
|
|
||||||
void JA_FadeOutMusic(const int milliseconds);
|
|
||||||
JA_Music_state JA_GetMusicState();
|
|
||||||
void JA_DeleteMusic(JA_Music_t *music);
|
|
||||||
float JA_SetMusicVolume(float volume);
|
|
||||||
void JA_SetMusicPosition(float value);
|
|
||||||
float JA_GetMusicPosition();
|
|
||||||
void JA_EnableMusic(const bool value);
|
|
||||||
|
|
||||||
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length);
|
|
||||||
JA_Sound_t *JA_LoadSound(Uint8* buffer, Uint32 length);
|
|
||||||
JA_Sound_t *JA_LoadSound(const char* filename);
|
|
||||||
int JA_PlaySound(JA_Sound_t *sound, const int loop = 0, const int group=0);
|
|
||||||
int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0, const int group=0);
|
|
||||||
void JA_PauseChannel(const int channel);
|
|
||||||
void JA_ResumeChannel(const int channel);
|
|
||||||
void JA_StopChannel(const int channel);
|
|
||||||
JA_Channel_state JA_GetChannelState(const int channel);
|
|
||||||
void JA_DeleteSound(JA_Sound_t *sound);
|
|
||||||
float JA_SetSoundVolume(float volume, const int group=0);
|
|
||||||
void JA_EnableSound(const bool value);
|
|
||||||
|
|
||||||
float JA_SetVolume(float volume);
|
|
||||||
555
source/external/jail_audio.hpp
vendored
Normal file
555
source/external/jail_audio.hpp
vendored
Normal file
@@ -0,0 +1,555 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
// --- Includes ---
|
||||||
|
#include <SDL3/SDL.h>
|
||||||
|
#include <stdint.h> // Para uint32_t, uint8_t
|
||||||
|
#include <stdio.h> // Para NULL, fseek, printf, fclose, fopen, fread, ftell, FILE, SEEK_END, SEEK_SET
|
||||||
|
#include <stdlib.h> // Para free, malloc
|
||||||
|
#include <string.h> // Para strcpy, strlen
|
||||||
|
|
||||||
|
#define STB_VORBIS_HEADER_ONLY
|
||||||
|
#include "external/stb_vorbis.h" // Para stb_vorbis_decode_memory
|
||||||
|
|
||||||
|
// --- Public Enums ---
|
||||||
|
enum JA_Channel_state { JA_CHANNEL_INVALID,
|
||||||
|
JA_CHANNEL_FREE,
|
||||||
|
JA_CHANNEL_PLAYING,
|
||||||
|
JA_CHANNEL_PAUSED,
|
||||||
|
JA_SOUND_DISABLED };
|
||||||
|
enum JA_Music_state { JA_MUSIC_INVALID,
|
||||||
|
JA_MUSIC_PLAYING,
|
||||||
|
JA_MUSIC_PAUSED,
|
||||||
|
JA_MUSIC_STOPPED,
|
||||||
|
JA_MUSIC_DISABLED };
|
||||||
|
|
||||||
|
// --- Struct Definitions ---
|
||||||
|
#define JA_MAX_SIMULTANEOUS_CHANNELS 20
|
||||||
|
#define JA_MAX_GROUPS 2
|
||||||
|
|
||||||
|
struct JA_Sound_t {
|
||||||
|
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
||||||
|
Uint32 length{0};
|
||||||
|
Uint8* buffer{NULL};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct JA_Channel_t {
|
||||||
|
JA_Sound_t* sound{nullptr};
|
||||||
|
int pos{0};
|
||||||
|
int times{0};
|
||||||
|
int group{0};
|
||||||
|
SDL_AudioStream* stream{nullptr};
|
||||||
|
JA_Channel_state state{JA_CHANNEL_FREE};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct JA_Music_t {
|
||||||
|
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
||||||
|
|
||||||
|
// OGG comprimit en memòria. Propietat nostra; es copia des del fitxer una
|
||||||
|
// sola vegada en JA_LoadMusic i es descomprimix en chunks per streaming.
|
||||||
|
Uint8* ogg_data{nullptr};
|
||||||
|
Uint32 ogg_length{0};
|
||||||
|
stb_vorbis* vorbis{nullptr}; // Handle del decoder, viu tot el cicle del JA_Music_t
|
||||||
|
|
||||||
|
char* filename{nullptr};
|
||||||
|
|
||||||
|
int times{0}; // Loops restants (-1 = infinit, 0 = un sol play)
|
||||||
|
SDL_AudioStream* stream{nullptr};
|
||||||
|
JA_Music_state state{JA_MUSIC_INVALID};
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Internal Global State ---
|
||||||
|
// Marcado 'inline' (C++17) para asegurar una única instancia.
|
||||||
|
|
||||||
|
inline JA_Music_t* current_music{nullptr};
|
||||||
|
inline JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
|
||||||
|
|
||||||
|
inline SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000};
|
||||||
|
inline float JA_musicVolume{1.0f};
|
||||||
|
inline float JA_soundVolume[JA_MAX_GROUPS];
|
||||||
|
inline bool JA_musicEnabled{true};
|
||||||
|
inline bool JA_soundEnabled{true};
|
||||||
|
inline SDL_AudioDeviceID sdlAudioDevice{0};
|
||||||
|
|
||||||
|
inline bool fading{false};
|
||||||
|
inline int fade_start_time{0};
|
||||||
|
inline int fade_duration{0};
|
||||||
|
inline float fade_initial_volume{0.0f}; // Corregido de 'int' a 'float'
|
||||||
|
|
||||||
|
// --- Forward Declarations ---
|
||||||
|
inline void JA_StopMusic();
|
||||||
|
inline void JA_StopChannel(const int channel);
|
||||||
|
inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop = 0, const int group = 0);
|
||||||
|
|
||||||
|
// --- Music streaming internals ---
|
||||||
|
// Bytes-per-sample per canal (sempre s16)
|
||||||
|
static constexpr int JA_MUSIC_BYTES_PER_SAMPLE = 2;
|
||||||
|
// Quants shorts decodifiquem per crida a get_samples_short_interleaved.
|
||||||
|
// 8192 shorts = 4096 samples/channel en estèreo ≈ 85ms de so a 48kHz.
|
||||||
|
static constexpr int JA_MUSIC_CHUNK_SHORTS = 8192;
|
||||||
|
// Umbral d'audio per davant del cursor de reproducció. Mantenim ≥ 0.5 s a
|
||||||
|
// l'SDL_AudioStream per absorbir jitter de frame i evitar underruns.
|
||||||
|
static constexpr float JA_MUSIC_LOW_WATER_SECONDS = 0.5f;
|
||||||
|
|
||||||
|
// Decodifica un chunk del vorbis i el volca a l'stream. Retorna samples
|
||||||
|
// decodificats per canal (0 = EOF de l'stream vorbis).
|
||||||
|
inline int JA_FeedMusicChunk(JA_Music_t* music) {
|
||||||
|
if (!music || !music->vorbis || !music->stream) return 0;
|
||||||
|
|
||||||
|
short chunk[JA_MUSIC_CHUNK_SHORTS];
|
||||||
|
const int channels = music->spec.channels;
|
||||||
|
const int samples_per_channel = stb_vorbis_get_samples_short_interleaved(
|
||||||
|
music->vorbis,
|
||||||
|
channels,
|
||||||
|
chunk,
|
||||||
|
JA_MUSIC_CHUNK_SHORTS);
|
||||||
|
if (samples_per_channel <= 0) return 0;
|
||||||
|
|
||||||
|
const int bytes = samples_per_channel * channels * JA_MUSIC_BYTES_PER_SAMPLE;
|
||||||
|
SDL_PutAudioStreamData(music->stream, chunk, bytes);
|
||||||
|
return samples_per_channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reompli l'stream fins que tinga ≥ JA_MUSIC_LOW_WATER_SECONDS bufferats.
|
||||||
|
// En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
|
||||||
|
inline void JA_PumpMusic(JA_Music_t* music) {
|
||||||
|
if (!music || !music->vorbis || !music->stream) return;
|
||||||
|
|
||||||
|
const int bytes_per_second = music->spec.freq * music->spec.channels * JA_MUSIC_BYTES_PER_SAMPLE;
|
||||||
|
const int low_water_bytes = static_cast<int>(JA_MUSIC_LOW_WATER_SECONDS * static_cast<float>(bytes_per_second));
|
||||||
|
|
||||||
|
while (SDL_GetAudioStreamAvailable(music->stream) < low_water_bytes) {
|
||||||
|
const int decoded = JA_FeedMusicChunk(music);
|
||||||
|
if (decoded > 0) continue;
|
||||||
|
|
||||||
|
// EOF: si queden loops, rebobinar; si no, tallar i deixar drenar.
|
||||||
|
if (music->times != 0) {
|
||||||
|
stb_vorbis_seek_start(music->vorbis);
|
||||||
|
if (music->times > 0) music->times--;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Core Functions ---
|
||||||
|
|
||||||
|
inline void JA_Update() {
|
||||||
|
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) {
|
||||||
|
if (fading) {
|
||||||
|
int time = SDL_GetTicks();
|
||||||
|
if (time > (fade_start_time + fade_duration)) {
|
||||||
|
fading = false;
|
||||||
|
JA_StopMusic();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
const int time_passed = time - fade_start_time;
|
||||||
|
const float percent = (float)time_passed / (float)fade_duration;
|
||||||
|
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume * (1.0 - percent));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Streaming: rellenem l'stream fins al low-water-mark i parem si el
|
||||||
|
// vorbis s'ha esgotat i no queden loops.
|
||||||
|
JA_PumpMusic(current_music);
|
||||||
|
if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
|
||||||
|
JA_StopMusic();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (JA_soundEnabled) {
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
|
||||||
|
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
||||||
|
if (channels[i].times != 0) {
|
||||||
|
if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) {
|
||||||
|
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length);
|
||||||
|
if (channels[i].times > 0) channels[i].times--;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) {
|
||||||
|
#ifdef _DEBUG
|
||||||
|
SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
JA_audioSpec = {format, num_channels, freq};
|
||||||
|
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice
|
||||||
|
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
|
||||||
|
if (sdlAudioDevice == 0) SDL_Log("Failed to initialize SDL audio!");
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
|
||||||
|
for (int i = 0; i < JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_Quit() {
|
||||||
|
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); // Corregido: !sdlAudioDevice -> sdlAudioDevice
|
||||||
|
sdlAudioDevice = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Music Functions ---
|
||||||
|
|
||||||
|
inline JA_Music_t* JA_LoadMusic(const Uint8* buffer, Uint32 length) {
|
||||||
|
if (!buffer || length == 0) return nullptr;
|
||||||
|
|
||||||
|
// Còpia del OGG comprimit: stb_vorbis llig de forma persistent aquesta
|
||||||
|
// memòria mentre el handle estiga viu, així que hem de posseir-la nosaltres.
|
||||||
|
Uint8* ogg_copy = static_cast<Uint8*>(SDL_malloc(length));
|
||||||
|
if (!ogg_copy) return nullptr;
|
||||||
|
SDL_memcpy(ogg_copy, buffer, length);
|
||||||
|
|
||||||
|
int error = 0;
|
||||||
|
stb_vorbis* vorbis = stb_vorbis_open_memory(ogg_copy, static_cast<int>(length), &error, nullptr);
|
||||||
|
if (!vorbis) {
|
||||||
|
SDL_free(ogg_copy);
|
||||||
|
SDL_Log("JA_LoadMusic: stb_vorbis_open_memory failed (error %d)", error);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto* music = new JA_Music_t();
|
||||||
|
music->ogg_data = ogg_copy;
|
||||||
|
music->ogg_length = length;
|
||||||
|
music->vorbis = vorbis;
|
||||||
|
|
||||||
|
const stb_vorbis_info info = stb_vorbis_get_info(vorbis);
|
||||||
|
music->spec.channels = info.channels;
|
||||||
|
music->spec.freq = static_cast<int>(info.sample_rate);
|
||||||
|
music->spec.format = SDL_AUDIO_S16;
|
||||||
|
music->state = JA_MUSIC_STOPPED;
|
||||||
|
|
||||||
|
return music;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline JA_Music_t* JA_LoadMusic(const char* filename) {
|
||||||
|
// [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid.
|
||||||
|
FILE* f = fopen(filename, "rb");
|
||||||
|
if (!f) return NULL; // Añadida comprobación de apertura
|
||||||
|
fseek(f, 0, SEEK_END);
|
||||||
|
long fsize = ftell(f);
|
||||||
|
fseek(f, 0, SEEK_SET);
|
||||||
|
auto* buffer = static_cast<Uint8*>(malloc(fsize + 1));
|
||||||
|
if (!buffer) { // Añadida comprobación de malloc
|
||||||
|
fclose(f);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
if (fread(buffer, fsize, 1, f) != 1) {
|
||||||
|
fclose(f);
|
||||||
|
free(buffer);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
fclose(f);
|
||||||
|
|
||||||
|
JA_Music_t* music = JA_LoadMusic(buffer, fsize);
|
||||||
|
if (music) { // Comprobar que JA_LoadMusic tuvo éxito
|
||||||
|
music->filename = static_cast<char*>(malloc(strlen(filename) + 1));
|
||||||
|
if (music->filename) {
|
||||||
|
strcpy(music->filename, filename);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(buffer);
|
||||||
|
|
||||||
|
return music;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_PlayMusic(JA_Music_t* music, const int loop = -1) {
|
||||||
|
if (!JA_musicEnabled || !music || !music->vorbis) return;
|
||||||
|
|
||||||
|
JA_StopMusic();
|
||||||
|
|
||||||
|
current_music = music;
|
||||||
|
current_music->state = JA_MUSIC_PLAYING;
|
||||||
|
current_music->times = loop;
|
||||||
|
|
||||||
|
// Rebobinem l'stream de vorbis al principi. Cobreix tant play-per-primera-
|
||||||
|
// vegada com replays/canvis de track que tornen a la mateixa pista.
|
||||||
|
stb_vorbis_seek_start(current_music->vorbis);
|
||||||
|
|
||||||
|
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec);
|
||||||
|
if (!current_music->stream) {
|
||||||
|
SDL_Log("Failed to create audio stream!");
|
||||||
|
current_music->state = JA_MUSIC_STOPPED;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
||||||
|
|
||||||
|
// Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
|
||||||
|
JA_PumpMusic(current_music);
|
||||||
|
|
||||||
|
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
inline char* JA_GetMusicFilename(const JA_Music_t* music = nullptr) {
|
||||||
|
if (!music) music = current_music;
|
||||||
|
if (!music) return nullptr; // Añadida comprobación
|
||||||
|
return music->filename;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_PauseMusic() {
|
||||||
|
if (!JA_musicEnabled) return;
|
||||||
|
if (!current_music || current_music->state != JA_MUSIC_PLAYING) return; // Comprobación mejorada
|
||||||
|
|
||||||
|
current_music->state = JA_MUSIC_PAUSED;
|
||||||
|
SDL_UnbindAudioStream(current_music->stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_ResumeMusic() {
|
||||||
|
if (!JA_musicEnabled) return;
|
||||||
|
if (!current_music || current_music->state != JA_MUSIC_PAUSED) return; // Comprobación mejorada
|
||||||
|
|
||||||
|
current_music->state = JA_MUSIC_PLAYING;
|
||||||
|
SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_StopMusic() {
|
||||||
|
if (!current_music || current_music->state == JA_MUSIC_INVALID || current_music->state == JA_MUSIC_STOPPED) return;
|
||||||
|
|
||||||
|
current_music->state = JA_MUSIC_STOPPED;
|
||||||
|
if (current_music->stream) {
|
||||||
|
SDL_DestroyAudioStream(current_music->stream);
|
||||||
|
current_music->stream = nullptr;
|
||||||
|
}
|
||||||
|
// Deixem el handle de vorbis viu — es tanca en JA_DeleteMusic.
|
||||||
|
// Rebobinem perquè un futur JA_PlayMusic comence des del principi.
|
||||||
|
if (current_music->vorbis) {
|
||||||
|
stb_vorbis_seek_start(current_music->vorbis);
|
||||||
|
}
|
||||||
|
// No liberem filename aquí; es fa en JA_DeleteMusic.
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_FadeOutMusic(const int milliseconds) {
|
||||||
|
if (!JA_musicEnabled) return;
|
||||||
|
if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return;
|
||||||
|
|
||||||
|
fading = true;
|
||||||
|
fade_start_time = SDL_GetTicks();
|
||||||
|
fade_duration = milliseconds;
|
||||||
|
fade_initial_volume = JA_musicVolume;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline JA_Music_state JA_GetMusicState() {
|
||||||
|
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
|
||||||
|
if (!current_music) return JA_MUSIC_INVALID;
|
||||||
|
|
||||||
|
return current_music->state;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_DeleteMusic(JA_Music_t* music) {
|
||||||
|
if (!music) return;
|
||||||
|
if (current_music == music) {
|
||||||
|
JA_StopMusic();
|
||||||
|
current_music = nullptr;
|
||||||
|
}
|
||||||
|
if (music->stream) SDL_DestroyAudioStream(music->stream);
|
||||||
|
if (music->vorbis) stb_vorbis_close(music->vorbis);
|
||||||
|
SDL_free(music->ogg_data);
|
||||||
|
free(music->filename); // filename es libera aquí
|
||||||
|
delete music;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float JA_SetMusicVolume(float volume) {
|
||||||
|
JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f);
|
||||||
|
if (current_music && current_music->stream) {
|
||||||
|
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
||||||
|
}
|
||||||
|
return JA_musicVolume;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_SetMusicPosition(float /*value*/) {
|
||||||
|
// No implementat amb el backend de streaming. Mai va arribar a usar-se
|
||||||
|
// en el codi existent, així que es manté com a stub.
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float JA_GetMusicPosition() {
|
||||||
|
// Veure nota a JA_SetMusicPosition.
|
||||||
|
return 0.0f;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_EnableMusic(const bool value) {
|
||||||
|
if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) JA_StopMusic();
|
||||||
|
|
||||||
|
JA_musicEnabled = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Sound Functions ---
|
||||||
|
|
||||||
|
inline JA_Sound_t* JA_NewSound(Uint8* buffer, Uint32 length) {
|
||||||
|
JA_Sound_t* sound = new JA_Sound_t();
|
||||||
|
sound->buffer = buffer;
|
||||||
|
sound->length = length;
|
||||||
|
// Nota: spec se queda con los valores por defecto.
|
||||||
|
return sound;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline JA_Sound_t* JA_LoadSound(uint8_t* buffer, uint32_t size) {
|
||||||
|
JA_Sound_t* sound = new JA_Sound_t();
|
||||||
|
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length)) {
|
||||||
|
SDL_Log("Failed to load WAV from memory: %s", SDL_GetError());
|
||||||
|
delete sound;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
return sound;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline JA_Sound_t* JA_LoadSound(const char* filename) {
|
||||||
|
JA_Sound_t* sound = new JA_Sound_t();
|
||||||
|
if (!SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length)) {
|
||||||
|
SDL_Log("Failed to load WAV file: %s", SDL_GetError());
|
||||||
|
delete sound;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
return sound;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int JA_PlaySound(JA_Sound_t* sound, const int loop = 0, const int group = 0) {
|
||||||
|
if (!JA_soundEnabled || !sound) return -1;
|
||||||
|
|
||||||
|
int channel = 0;
|
||||||
|
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; }
|
||||||
|
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
|
// No hay canal libre, reemplazamos el primero
|
||||||
|
channel = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return JA_PlaySoundOnChannel(sound, channel, loop, group);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop, const int group) {
|
||||||
|
if (!JA_soundEnabled || !sound) return -1;
|
||||||
|
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1;
|
||||||
|
|
||||||
|
JA_StopChannel(channel); // Detiene y limpia el canal si estaba en uso
|
||||||
|
|
||||||
|
channels[channel].sound = sound;
|
||||||
|
channels[channel].times = loop;
|
||||||
|
channels[channel].pos = 0;
|
||||||
|
channels[channel].group = group; // Asignar grupo
|
||||||
|
channels[channel].state = JA_CHANNEL_PLAYING;
|
||||||
|
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
|
||||||
|
|
||||||
|
if (!channels[channel].stream) {
|
||||||
|
SDL_Log("Failed to create audio stream for sound!");
|
||||||
|
channels[channel].state = JA_CHANNEL_FREE;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer, channels[channel].sound->length);
|
||||||
|
SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume[group]);
|
||||||
|
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
||||||
|
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_DeleteSound(JA_Sound_t* sound) {
|
||||||
|
if (!sound) return;
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||||
|
if (channels[i].sound == sound) JA_StopChannel(i);
|
||||||
|
}
|
||||||
|
SDL_free(sound->buffer);
|
||||||
|
delete sound;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_PauseChannel(const int channel) {
|
||||||
|
if (!JA_soundEnabled) return;
|
||||||
|
|
||||||
|
if (channel == -1) {
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
||||||
|
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
||||||
|
channels[i].state = JA_CHANNEL_PAUSED;
|
||||||
|
SDL_UnbindAudioStream(channels[i].stream);
|
||||||
|
}
|
||||||
|
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
|
if (channels[channel].state == JA_CHANNEL_PLAYING) {
|
||||||
|
channels[channel].state = JA_CHANNEL_PAUSED;
|
||||||
|
SDL_UnbindAudioStream(channels[channel].stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_ResumeChannel(const int channel) {
|
||||||
|
if (!JA_soundEnabled) return;
|
||||||
|
|
||||||
|
if (channel == -1) {
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
||||||
|
if (channels[i].state == JA_CHANNEL_PAUSED) {
|
||||||
|
channels[i].state = JA_CHANNEL_PLAYING;
|
||||||
|
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
|
||||||
|
}
|
||||||
|
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
|
if (channels[channel].state == JA_CHANNEL_PAUSED) {
|
||||||
|
channels[channel].state = JA_CHANNEL_PLAYING;
|
||||||
|
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_StopChannel(const int channel) {
|
||||||
|
if (channel == -1) {
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||||
|
if (channels[i].state != JA_CHANNEL_FREE) {
|
||||||
|
if (channels[i].stream) SDL_DestroyAudioStream(channels[i].stream);
|
||||||
|
channels[i].stream = nullptr;
|
||||||
|
channels[i].state = JA_CHANNEL_FREE;
|
||||||
|
channels[i].pos = 0;
|
||||||
|
channels[i].sound = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
|
if (channels[channel].state != JA_CHANNEL_FREE) {
|
||||||
|
if (channels[channel].stream) SDL_DestroyAudioStream(channels[channel].stream);
|
||||||
|
channels[channel].stream = nullptr;
|
||||||
|
channels[channel].state = JA_CHANNEL_FREE;
|
||||||
|
channels[channel].pos = 0;
|
||||||
|
channels[channel].sound = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline JA_Channel_state JA_GetChannelState(const int channel) {
|
||||||
|
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
|
||||||
|
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID;
|
||||||
|
|
||||||
|
return channels[channel].state;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float JA_SetSoundVolume(float volume, const int group = -1) // -1 para todos los grupos
|
||||||
|
{
|
||||||
|
const float v = SDL_clamp(volume, 0.0f, 1.0f);
|
||||||
|
|
||||||
|
if (group == -1) {
|
||||||
|
for (int i = 0; i < JA_MAX_GROUPS; ++i) {
|
||||||
|
JA_soundVolume[i] = v;
|
||||||
|
}
|
||||||
|
} else if (group >= 0 && group < JA_MAX_GROUPS) {
|
||||||
|
JA_soundVolume[group] = v;
|
||||||
|
} else {
|
||||||
|
return v; // Grupo inválido
|
||||||
|
}
|
||||||
|
|
||||||
|
// Aplicar volumen a canales activos
|
||||||
|
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||||
|
if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) {
|
||||||
|
if (group == -1 || channels[i].group == group) {
|
||||||
|
if (channels[i].stream) {
|
||||||
|
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[channels[i].group]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void JA_EnableSound(const bool value) {
|
||||||
|
if (!value) {
|
||||||
|
JA_StopChannel(-1); // Detener todos los canales
|
||||||
|
}
|
||||||
|
JA_soundEnabled = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline float JA_SetVolume(float volume) {
|
||||||
|
float v = JA_SetMusicVolume(volume);
|
||||||
|
JA_SetSoundVolume(v, -1); // Aplicar a todos los grupos de sonido
|
||||||
|
return v;
|
||||||
|
}
|
||||||
@@ -306,10 +306,17 @@ void Input::addGamepadMappingsFromFile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Input::discoverGamepads() {
|
void Input::discoverGamepads() {
|
||||||
SDL_Event event;
|
// Enumera los gamepads ya conectados sin drenar la cola de eventos de SDL
|
||||||
while (SDL_PollEvent(&event)) {
|
// (necesario con SDL_MAIN_USE_CALLBACKS, que entrega los eventos por SDL_AppEvent).
|
||||||
handleEvent(event); // Comprueba mandos conectados
|
int count = 0;
|
||||||
|
SDL_JoystickID* joysticks = SDL_GetGamepads(&count);
|
||||||
|
if (joysticks == nullptr) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
for (int i = 0; i < count; ++i) {
|
||||||
|
addGamepad(joysticks[i]);
|
||||||
|
}
|
||||||
|
SDL_free(joysticks);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Input::initSDLGamePad() {
|
void Input::initSDLGamePad() {
|
||||||
|
|||||||
@@ -7,15 +7,26 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
|
|||||||
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <memory> // Para make_unique, unique_ptr
|
#define SDL_MAIN_USE_CALLBACKS 1
|
||||||
|
#include <SDL3/SDL_main.h>
|
||||||
|
|
||||||
#include <span> // Para span
|
#include <span> // Para span
|
||||||
|
|
||||||
#include "director.hpp" // Para Director
|
#include "director.hpp" // Para Director
|
||||||
|
|
||||||
auto main(int argc, char* argv[]) -> int {
|
SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) {
|
||||||
// Crea el objeto Director
|
*appstate = new Director(argc, std::span<char*>(argv, argc));
|
||||||
auto director = std::make_unique<Director>(argc, std::span<char*>(argv, argc));
|
return SDL_APP_CONTINUE;
|
||||||
|
}
|
||||||
// Bucle principal
|
|
||||||
return Director::run();
|
SDL_AppResult SDL_AppIterate(void* appstate) {
|
||||||
|
return static_cast<Director*>(appstate)->iterate();
|
||||||
|
}
|
||||||
|
|
||||||
|
SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
|
||||||
|
return static_cast<Director*>(appstate)->handleEvent(*event);
|
||||||
|
}
|
||||||
|
|
||||||
|
void SDL_AppQuit(void* appstate, SDL_AppResult /*result*/) {
|
||||||
|
delete static_cast<Director*>(appstate);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
#include "asset.hpp" // Para Asset
|
#include "asset.hpp" // Para Asset
|
||||||
#include "color.hpp" // Para Color, NO_COLOR_MOD
|
#include "color.hpp" // Para Color, NO_COLOR_MOD
|
||||||
#include "external/jail_audio.h" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
#include "external/jail_audio.hpp" // Para JA_LoadMusic, JA_LoadSound, JA_DeleteMusic, JA_DeleteSound
|
||||||
#include "lang.hpp" // Para getText
|
#include "lang.hpp" // Para getText
|
||||||
#include "param.hpp" // Para Param, param, ParamPlayer, ParamResource, ParamGame
|
#include "param.hpp" // Para Param, param, ParamPlayer, ParamResource, ParamGame
|
||||||
#include "resource_helper.hpp" // Para loadFile
|
#include "resource_helper.hpp" // Para loadFile
|
||||||
@@ -467,10 +467,10 @@ void Resource::reload() {
|
|||||||
|
|
||||||
// Carga los sonidos del juego
|
// Carga los sonidos del juego
|
||||||
void Resource::loadSounds() {
|
void Resource::loadSounds() {
|
||||||
Logger::info("SOUND FILES");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::SOUND);
|
auto list = Asset::get()->getListByType(Asset::Type::SOUND);
|
||||||
sounds_.clear();
|
sounds_.clear();
|
||||||
|
|
||||||
|
int failed = 0;
|
||||||
for (const auto& l : list) {
|
for (const auto& l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
@@ -479,21 +479,23 @@ void Resource::loadSounds() {
|
|||||||
if (!audio_data.data.empty()) {
|
if (!audio_data.data.empty()) {
|
||||||
sound = JA_LoadSound(audio_data.data.data(), audio_data.data.size());
|
sound = JA_LoadSound(audio_data.data.data(), audio_data.data.size());
|
||||||
} else {
|
} else {
|
||||||
// Fallback a cargar desde disco si no está en pack
|
|
||||||
sound = JA_LoadSound(l.c_str());
|
sound = JA_LoadSound(l.c_str());
|
||||||
}
|
}
|
||||||
sounds_.emplace_back(name, sound);
|
if (sound == nullptr) {
|
||||||
Logger::dots("Sound : ", name, "[ LOADED ]");
|
Logger::error(" Sound load failed: " + name);
|
||||||
|
++failed;
|
||||||
}
|
}
|
||||||
|
sounds_.emplace_back(name, sound);
|
||||||
|
}
|
||||||
|
Logger::info("Sounds loaded: " + std::to_string(list.size() - failed) + "/" + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga las músicas del juego
|
// Carga las músicas del juego
|
||||||
void Resource::loadMusics() {
|
void Resource::loadMusics() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("MUSIC FILES");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::MUSIC);
|
auto list = Asset::get()->getListByType(Asset::Type::MUSIC);
|
||||||
musics_.clear();
|
musics_.clear();
|
||||||
|
|
||||||
|
int failed = 0;
|
||||||
for (const auto& l : list) {
|
for (const auto& l : list) {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
@@ -502,18 +504,19 @@ void Resource::loadMusics() {
|
|||||||
if (!audio_data.data.empty()) {
|
if (!audio_data.data.empty()) {
|
||||||
music = JA_LoadMusic(audio_data.data.data(), audio_data.data.size());
|
music = JA_LoadMusic(audio_data.data.data(), audio_data.data.size());
|
||||||
} else {
|
} else {
|
||||||
// Fallback a cargar desde disco si no está en pack
|
|
||||||
music = JA_LoadMusic(l.c_str());
|
music = JA_LoadMusic(l.c_str());
|
||||||
}
|
}
|
||||||
musics_.emplace_back(name, music);
|
if (music == nullptr) {
|
||||||
Logger::dots("Music : ", name, "[ LOADED ]");
|
Logger::error(" Music load failed: " + name);
|
||||||
|
++failed;
|
||||||
}
|
}
|
||||||
|
musics_.emplace_back(name, music);
|
||||||
|
}
|
||||||
|
Logger::info("Musics loaded: " + std::to_string(list.size() - failed) + "/" + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga las texturas del juego
|
// Carga las texturas del juego
|
||||||
void Resource::loadTextures() {
|
void Resource::loadTextures() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("TEXTURES");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::BITMAP);
|
auto list = Asset::get()->getListByType(Asset::Type::BITMAP);
|
||||||
textures_.clear();
|
textures_.clear();
|
||||||
|
|
||||||
@@ -522,12 +525,11 @@ void Resource::loadTextures() {
|
|||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
|
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
|
||||||
}
|
}
|
||||||
|
Logger::info("Textures loaded: " + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga los ficheros de texto del juego
|
// Carga los ficheros de texto del juego
|
||||||
void Resource::loadTextFiles() {
|
void Resource::loadTextFiles() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("TEXT FILES");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::FONT);
|
auto list = Asset::get()->getListByType(Asset::Type::FONT);
|
||||||
text_files_.clear();
|
text_files_.clear();
|
||||||
|
|
||||||
@@ -536,12 +538,11 @@ void Resource::loadTextFiles() {
|
|||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
text_files_.emplace_back(name, Text::loadFile(l));
|
text_files_.emplace_back(name, Text::loadFile(l));
|
||||||
}
|
}
|
||||||
|
Logger::info("Text files loaded: " + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga las animaciones del juego
|
// Carga las animaciones del juego
|
||||||
void Resource::loadAnimations() {
|
void Resource::loadAnimations() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("ANIMATIONS");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::ANIMATION);
|
auto list = Asset::get()->getListByType(Asset::Type::ANIMATION);
|
||||||
animations_.clear();
|
animations_.clear();
|
||||||
|
|
||||||
@@ -550,12 +551,11 @@ void Resource::loadAnimations() {
|
|||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
animations_.emplace_back(name, loadAnimationsFromFile(l));
|
animations_.emplace_back(name, loadAnimationsFromFile(l));
|
||||||
}
|
}
|
||||||
|
Logger::info("Animations loaded: " + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga los datos para el modo demostración
|
// Carga los datos para el modo demostración
|
||||||
void Resource::loadDemoData() {
|
void Resource::loadDemoData() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("DEMO FILES");
|
|
||||||
auto list = Asset::get()->getListByType(Asset::Type::DEMODATA);
|
auto list = Asset::get()->getListByType(Asset::Type::DEMODATA);
|
||||||
demos_.clear();
|
demos_.clear();
|
||||||
|
|
||||||
@@ -564,13 +564,11 @@ void Resource::loadDemoData() {
|
|||||||
updateLoadingProgress(name);
|
updateLoadingProgress(name);
|
||||||
demos_.emplace_back(loadDemoDataFromFile(l));
|
demos_.emplace_back(loadDemoDataFromFile(l));
|
||||||
}
|
}
|
||||||
|
Logger::info("Demo files loaded: " + std::to_string(list.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea las texturas de jugadores con todas sus variantes de paleta
|
// Crea las texturas de jugadores con todas sus variantes de paleta
|
||||||
void Resource::createPlayerTextures() {
|
void Resource::createPlayerTextures() {
|
||||||
Logger::cr();
|
|
||||||
Logger::info("CREATING PLAYER TEXTURES");
|
|
||||||
|
|
||||||
// Configuración de jugadores y sus paletas
|
// Configuración de jugadores y sus paletas
|
||||||
struct PlayerConfig {
|
struct PlayerConfig {
|
||||||
std::string base_texture;
|
std::string base_texture;
|
||||||
@@ -641,9 +639,9 @@ void Resource::createPlayerTextures() {
|
|||||||
// Guardar con nombre específico
|
// Guardar con nombre específico
|
||||||
std::string texture_name = player.name_prefix + "_pal" + std::to_string(palette_idx);
|
std::string texture_name = player.name_prefix + "_pal" + std::to_string(palette_idx);
|
||||||
textures_.emplace_back(texture_name, texture);
|
textures_.emplace_back(texture_name, texture);
|
||||||
Logger::dots("Player Texture : ", texture_name, "[ DONE ]");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Logger::info("Player textures created: " + std::to_string(players.size() * 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes
|
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes
|
||||||
@@ -657,9 +655,6 @@ void Resource::createTextTextures() {
|
|||||||
text(std::move(text_init)) {}
|
text(std::move(text_init)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
Logger::cr();
|
|
||||||
Logger::info("CREATING TEXTURES");
|
|
||||||
|
|
||||||
// Texturas de tamaño normal con outline
|
// Texturas de tamaño normal con outline
|
||||||
std::vector<NameAndText> strings1 = {
|
std::vector<NameAndText> strings1 = {
|
||||||
{"game_text_1000_points", "1.000"},
|
{"game_text_1000_points", "1.000"},
|
||||||
@@ -673,7 +668,6 @@ void Resource::createTextTextures() {
|
|||||||
auto text1 = getText("04b_25_enhanced");
|
auto text1 = getText("04b_25_enhanced");
|
||||||
for (const auto& s : strings1) {
|
for (const auto& s : strings1) {
|
||||||
textures_.emplace_back(s.name, text1->writeDXToTexture(Text::STROKE, s.text, -2, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
textures_.emplace_back(s.name, text1->writeDXToTexture(Text::STROKE, s.text, -2, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
||||||
Logger::dots("Texture : ", s.name, "[ DONE ]");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Texturas de tamaño doble
|
// Texturas de tamaño doble
|
||||||
@@ -688,8 +682,9 @@ void Resource::createTextTextures() {
|
|||||||
auto text2 = getText("04b_25_2x_enhanced");
|
auto text2 = getText("04b_25_2x_enhanced");
|
||||||
for (const auto& s : strings2) {
|
for (const auto& s : strings2) {
|
||||||
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
textures_.emplace_back(s.name, text2->writeDXToTexture(Text::STROKE, s.text, -4, Colors::NO_COLOR_MOD, 1, param.game.item_text_outline_color));
|
||||||
Logger::dots("Texture : ", s.name, "[ DONE ]");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Logger::info("Text textures created: " + std::to_string(strings1.size() + strings2.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Crea los objetos de texto a partir de los archivos de textura y texto
|
// Crea los objetos de texto a partir de los archivos de textura y texto
|
||||||
@@ -707,9 +702,6 @@ void Resource::createText() {
|
|||||||
white_texture_file(std::move(w_file)) {}
|
white_texture_file(std::move(w_file)) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
Logger::cr();
|
|
||||||
Logger::info("CREATING TEXT OBJECTS");
|
|
||||||
|
|
||||||
std::vector<ResourceInfo> resources = {
|
std::vector<ResourceInfo> resources = {
|
||||||
{"04b_25", "04b_25.png", "04b_25.txt"},
|
{"04b_25", "04b_25.png", "04b_25.txt"},
|
||||||
{"04b_25_enhanced", "04b_25.png", "04b_25.txt", "04b_25_white.png"}, // Nueva fuente con textura blanca
|
{"04b_25_enhanced", "04b_25.png", "04b_25.txt", "04b_25_white.png"}, // Nueva fuente con textura blanca
|
||||||
@@ -735,8 +727,8 @@ void Resource::createText() {
|
|||||||
// Crear texto normal
|
// Crear texto normal
|
||||||
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
|
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
|
||||||
}
|
}
|
||||||
Logger::dots("Text : ", resource.key, "[ DONE ]");
|
|
||||||
}
|
}
|
||||||
|
Logger::info("Text objects created: " + std::to_string(resources.size()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vacía el vector de sonidos y libera la memoria asociada
|
// Vacía el vector de sonidos y libera la memoria asociada
|
||||||
@@ -853,23 +845,6 @@ void Resource::renderProgress() {
|
|||||||
screen->coreRender();
|
screen->coreRender();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos durante la carga (permite salir con ESC o cerrar ventana)
|
|
||||||
void Resource::checkEvents() {
|
|
||||||
SDL_Event event;
|
|
||||||
while (SDL_PollEvent(&event)) {
|
|
||||||
switch (event.type) {
|
|
||||||
case SDL_EVENT_QUIT:
|
|
||||||
exit(0);
|
|
||||||
break;
|
|
||||||
case SDL_EVENT_KEY_DOWN:
|
|
||||||
if (event.key.key == SDLK_ESCAPE) {
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Carga los datos para el modo demostración (sin mostrar progreso)
|
// Carga los datos para el modo demostración (sin mostrar progreso)
|
||||||
void Resource::loadDemoDataQuiet() {
|
void Resource::loadDemoDataQuiet() {
|
||||||
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES (quiet load)");
|
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> DEMO FILES (quiet load)");
|
||||||
@@ -892,13 +867,12 @@ void Resource::initProgressBar() {
|
|||||||
loading_full_rect_ = {.x = X_PADDING, .y = BAR_Y_POSITION, .w = FULL_BAR_WIDTH, .h = BAR_HEIGHT};
|
loading_full_rect_ = {.x = X_PADDING, .y = BAR_Y_POSITION, .w = FULL_BAR_WIDTH, .h = BAR_HEIGHT};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza el progreso de carga, muestra la barra y procesa eventos
|
// Actualiza el progreso de carga y muestra la barra
|
||||||
void Resource::updateLoadingProgress(std::string name) {
|
void Resource::updateLoadingProgress(std::string name) {
|
||||||
loading_resource_name_ = std::move(name);
|
loading_resource_name_ = std::move(name);
|
||||||
loading_count_.increase();
|
loading_count_.increase();
|
||||||
updateProgressBar();
|
updateProgressBar();
|
||||||
renderProgress();
|
renderProgress();
|
||||||
checkEvents();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Actualiza la barra de estado
|
// Actualiza la barra de estado
|
||||||
|
|||||||
@@ -174,7 +174,6 @@ class Resource {
|
|||||||
// --- Métodos internos para gestionar el progreso ---
|
// --- Métodos internos para gestionar el progreso ---
|
||||||
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
void calculateTotalResources(); // Calcula el número de recursos para cargar
|
||||||
void renderProgress(); // Muestra el progreso de carga
|
void renderProgress(); // Muestra el progreso de carga
|
||||||
static void checkEvents(); // Comprueba los eventos durante la carga
|
|
||||||
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
|
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
|
||||||
void initProgressBar(); // Inicializa los rectangulos que definen la barra de progreso
|
void initProgressBar(); // Inicializa los rectangulos que definen la barra de progreso
|
||||||
void updateProgressBar(); // Actualiza la barra de estado
|
void updateProgressBar(); // Actualiza la barra de estado
|
||||||
|
|||||||
@@ -28,6 +28,7 @@
|
|||||||
#include "text.hpp" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "texture.hpp" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "ui/service_menu.hpp" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.hpp" // Para Zone
|
#include "utils.hpp" // Para Zone
|
||||||
|
|
||||||
@@ -47,6 +48,11 @@ Credits::Credits()
|
|||||||
}
|
}
|
||||||
initVars();
|
initVars();
|
||||||
startCredits();
|
startCredits();
|
||||||
|
|
||||||
|
Logger::section("CREDITS");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time para el primer frame del callback
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -69,7 +75,20 @@ auto Credits::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME;
|
return DELTA_TIME;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Avanza un frame (llamado desde Director::iterate)
|
||||||
|
void Credits::iterate() {
|
||||||
|
checkInput();
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void Credits::handleEvent(const SDL_Event& /*event*/) {
|
||||||
|
// Eventos globales ya gestionados por Director::handleEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle principal legacy (fallback)
|
||||||
void Credits::run() {
|
void Credits::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,11 @@ class Credits {
|
|||||||
Credits();
|
Credits();
|
||||||
~Credits();
|
~Credits();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -41,6 +41,7 @@
|
|||||||
#include "smart_sprite.hpp" // Para SmartSprite
|
#include "smart_sprite.hpp" // Para SmartSprite
|
||||||
#include "stage.hpp" // Para StageManager, StageData
|
#include "stage.hpp" // Para StageManager, StageData
|
||||||
#include "tabe.hpp" // Para Tabe
|
#include "tabe.hpp" // Para Tabe
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "text.hpp" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "texture.hpp" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "ui/service_menu.hpp" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
@@ -131,6 +132,11 @@ Game::Game(Player::Id player_id, int current_stage, bool demo_enabled)
|
|||||||
#ifdef RECORDING
|
#ifdef RECORDING
|
||||||
setState(State::PLAYING);
|
setState(State::PLAYING);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
Logger::section(demo_.enabled ? "GAME (DEMO)" : "GAME");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time para el primer frame del callback
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
}
|
}
|
||||||
|
|
||||||
Game::~Game() {
|
Game::~Game() {
|
||||||
@@ -978,7 +984,33 @@ auto Game::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME_MS / 1000.0F; // Convertir de milisegundos a segundos
|
return DELTA_TIME_MS / 1000.0F; // Convertir de milisegundos a segundos
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para el juego
|
// Avanza un frame del juego (llamado desde Director::iterate)
|
||||||
|
void Game::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento del juego (llamado desde Director::handleEvent)
|
||||||
|
void Game::handleEvent(const SDL_Event& event) {
|
||||||
|
switch (event.type) {
|
||||||
|
case SDL_EVENT_WINDOW_FOCUS_LOST:
|
||||||
|
pause_manager_->setFocusLossPause(!demo_.enabled);
|
||||||
|
break;
|
||||||
|
case SDL_EVENT_WINDOW_FOCUS_GAINED:
|
||||||
|
pause_manager_->setFocusLossPause(false);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _DEBUG
|
||||||
|
handleDebugEvents(event);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle para el juego (fallback legacy)
|
||||||
void Game::run() {
|
void Game::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,11 @@ class Game {
|
|||||||
Game(Player::Id player_id, int current_stage, bool demo_enabled); // Constructor principal
|
Game(Player::Id player_id, int current_stage, bool demo_enabled); // Constructor principal
|
||||||
~Game(); // Destructor
|
~Game(); // Destructor
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run(); // Ejecuta el bucle principal del juego
|
void run(); // Ejecuta el bucle principal del juego
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
#include "resource.hpp" // Para Resource
|
#include "resource.hpp" // Para Resource
|
||||||
#include "screen.hpp" // Para Screen
|
#include "screen.hpp" // Para Screen
|
||||||
#include "section.hpp" // Para Name, name, Options, options
|
#include "section.hpp" // Para Name, name, Options, options
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "sprite.hpp" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR
|
#include "text.hpp" // Para Text, Text::SHADOW, Text::COLOR
|
||||||
#include "texture.hpp" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
@@ -45,6 +46,12 @@ HiScoreTable::HiScoreTable()
|
|||||||
initBackground();
|
initBackground();
|
||||||
iniEntryColors();
|
iniEntryColors();
|
||||||
createSprites();
|
createSprites();
|
||||||
|
|
||||||
|
Logger::section("HI-SCORE TABLE");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time y arranca la música
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
Audio::get()->playMusic("title.ogg");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -126,7 +133,20 @@ auto HiScoreTable::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME;
|
return DELTA_TIME;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para la pantalla de instrucciones
|
// Avanza un frame (llamado desde Director::iterate)
|
||||||
|
void HiScoreTable::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void HiScoreTable::handleEvent(const SDL_Event& /*event*/) {
|
||||||
|
// Eventos globales ya gestionados por Director::handleEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle para la pantalla de puntuaciones (fallback legacy)
|
||||||
void HiScoreTable::run() {
|
void HiScoreTable::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
Audio::get()->playMusic("title.ogg");
|
Audio::get()->playMusic("title.ogg");
|
||||||
|
|||||||
@@ -27,7 +27,11 @@ class HiScoreTable {
|
|||||||
HiScoreTable();
|
HiScoreTable();
|
||||||
~HiScoreTable();
|
~HiScoreTable();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
#include "sprite.hpp" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW
|
#include "text.hpp" // Para Text, Text::CENTER, Text::COLOR, Text::SHADOW
|
||||||
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "utils.hpp"
|
#include "utils.hpp"
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
@@ -57,6 +58,12 @@ Instructions::Instructions()
|
|||||||
|
|
||||||
// Inicializa los sprites de los items
|
// Inicializa los sprites de los items
|
||||||
iniSprites();
|
iniSprites();
|
||||||
|
|
||||||
|
Logger::section("INSTRUCTIONS");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time y arranca la música
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
Audio::get()->playMusic("title.ogg");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -262,7 +269,20 @@ auto Instructions::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME;
|
return DELTA_TIME;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para la pantalla de instrucciones
|
// Avanza un frame (llamado desde Director::iterate)
|
||||||
|
void Instructions::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void Instructions::handleEvent(const SDL_Event& /*event*/) {
|
||||||
|
// Eventos globales ya gestionados por Director::handleEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle para la pantalla de instrucciones (fallback legacy)
|
||||||
void Instructions::run() {
|
void Instructions::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
Audio::get()->playMusic("title.ogg");
|
Audio::get()->playMusic("title.ogg");
|
||||||
|
|||||||
@@ -48,7 +48,11 @@ class Instructions {
|
|||||||
Instructions();
|
Instructions();
|
||||||
~Instructions();
|
~Instructions();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
#include "text.hpp" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "texture.hpp" // Para Texture
|
#include "texture.hpp" // Para Texture
|
||||||
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "utils.hpp" // Para easeOutBounce
|
#include "utils.hpp" // Para easeOutBounce
|
||||||
#include "writer.hpp" // Para Writer
|
#include "writer.hpp" // Para Writer
|
||||||
|
|
||||||
@@ -39,6 +40,12 @@ Intro::Intro()
|
|||||||
// Configura el fondo
|
// Configura el fondo
|
||||||
tiled_bg_->setSpeed(TILED_BG_SPEED);
|
tiled_bg_->setSpeed(TILED_BG_SPEED);
|
||||||
tiled_bg_->setColor(bg_color_);
|
tiled_bg_->setColor(bg_color_);
|
||||||
|
|
||||||
|
Logger::section("INTRO");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time y arranca la música
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
Audio::get()->playMusic("intro.ogg", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprueba los eventos
|
// Comprueba los eventos
|
||||||
@@ -265,7 +272,20 @@ auto Intro::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME;
|
return DELTA_TIME;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle principal
|
// Avanza un frame (llamado desde Director::iterate)
|
||||||
|
void Intro::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void Intro::handleEvent(const SDL_Event& /*event*/) {
|
||||||
|
// Eventos globales ya gestionados por Director::handleEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle principal legacy (fallback)
|
||||||
void Intro::run() {
|
void Intro::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
Audio::get()->playMusic("intro.ogg", 0);
|
Audio::get()->playMusic("intro.ogg", 0);
|
||||||
|
|||||||
@@ -30,7 +30,11 @@ class Intro {
|
|||||||
Intro();
|
Intro();
|
||||||
~Intro() = default;
|
~Intro() = default;
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
#include "audio.hpp" // Para Audio
|
#include "audio.hpp" // Para Audio
|
||||||
#include "color.hpp" // Para Color
|
#include "color.hpp" // Para Color
|
||||||
#include "global_events.hpp" // Para handle
|
#include "global_events.hpp" // Para handle
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "global_inputs.hpp" // Para check
|
#include "global_inputs.hpp" // Para check
|
||||||
#include "input.hpp" // Para Input
|
#include "input.hpp" // Para Input
|
||||||
#include "param.hpp" // Para Param, ParamGame, param
|
#include "param.hpp" // Para Param, ParamGame, param
|
||||||
@@ -47,6 +48,11 @@ Logo::Logo()
|
|||||||
jail_sprite_.push_back(std::move(temp));
|
jail_sprite_.push_back(std::move(temp));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Logger::section("LOGO");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time para el primer frame del callback
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
// Inicializa el vector de colores con la paleta ZX Spectrum
|
// Inicializa el vector de colores con la paleta ZX Spectrum
|
||||||
color_.emplace_back(SPECTRUM_BLACK);
|
color_.emplace_back(SPECTRUM_BLACK);
|
||||||
color_.emplace_back(SPECTRUM_BLUE);
|
color_.emplace_back(SPECTRUM_BLUE);
|
||||||
@@ -169,7 +175,20 @@ auto Logo::calculateDeltaTime() -> float {
|
|||||||
return DELTA_TIME;
|
return DELTA_TIME;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para el logo del juego
|
// Avanza un frame del logo (llamado desde Director::iterate)
|
||||||
|
void Logo::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void Logo::handleEvent(const SDL_Event& /*event*/) {
|
||||||
|
// Eventos globales (QUIT, resize, hotplug) ya gestionados por Director::handleEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle para el logo del juego (fallback legacy)
|
||||||
void Logo::run() {
|
void Logo::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,11 @@ class Logo {
|
|||||||
Logo();
|
Logo();
|
||||||
~Logo();
|
~Logo();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
#include "sprite.hpp" // Para Sprite
|
#include "sprite.hpp" // Para Sprite
|
||||||
#include "text.hpp" // Para Text
|
#include "text.hpp" // Para Text
|
||||||
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
|
||||||
|
#include "ui/logger.hpp" // Para section
|
||||||
#include "ui/notifier.hpp" // Para Notifier
|
#include "ui/notifier.hpp" // Para Notifier
|
||||||
#include "ui/service_menu.hpp" // Para ServiceMenu
|
#include "ui/service_menu.hpp" // Para ServiceMenu
|
||||||
#include "utils.hpp" // Para Zone, BLOCK
|
#include "utils.hpp" // Para Zone, BLOCK
|
||||||
@@ -59,6 +60,11 @@ Title::Title()
|
|||||||
anchor_.mini_logo = (param.game.height / MINI_LOGO_Y_DIVISOR * MINI_LOGO_Y_FACTOR) + BLOCK;
|
anchor_.mini_logo = (param.game.height / MINI_LOGO_Y_DIVISOR * MINI_LOGO_Y_FACTOR) + BLOCK;
|
||||||
mini_logo_sprite_->setY(anchor_.mini_logo);
|
mini_logo_sprite_->setY(anchor_.mini_logo);
|
||||||
anchor_.copyright_text = anchor_.mini_logo + mini_logo_sprite_->getHeight() + COPYRIGHT_TEXT_SPACING;
|
anchor_.copyright_text = anchor_.mini_logo + mini_logo_sprite_->getHeight() + COPYRIGHT_TEXT_SPACING;
|
||||||
|
|
||||||
|
Logger::section("TITLE");
|
||||||
|
|
||||||
|
// Inicializa el timer de delta time para el primer frame del callback
|
||||||
|
last_time_ = SDL_GetTicks();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
@@ -213,7 +219,22 @@ void Title::activatePlayerAndSetState(Player::Id player_id) {
|
|||||||
counter_time_ = 0.0F;
|
counter_time_ = 0.0F;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bucle para el titulo del juego
|
// Avanza un frame (llamado desde Director::iterate)
|
||||||
|
void Title::iterate() {
|
||||||
|
const float DELTA_TIME = calculateDeltaTime();
|
||||||
|
checkInput();
|
||||||
|
update(DELTA_TIME);
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Procesa un evento (llamado desde Director::handleEvent)
|
||||||
|
void Title::handleEvent(const SDL_Event& event) {
|
||||||
|
if (event.type == SDL_EVENT_KEY_DOWN) {
|
||||||
|
handleKeyDownEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucle para el titulo del juego (fallback legacy)
|
||||||
void Title::run() {
|
void Title::run() {
|
||||||
last_time_ = SDL_GetTicks();
|
last_time_ = SDL_GetTicks();
|
||||||
|
|
||||||
|
|||||||
@@ -40,7 +40,11 @@ class Title {
|
|||||||
Title();
|
Title();
|
||||||
~Title();
|
~Title();
|
||||||
|
|
||||||
// --- Bucle principal ---
|
// --- Callbacks para el bucle SDL_MAIN_USE_CALLBACKS ---
|
||||||
|
void iterate(); // Ejecuta un frame
|
||||||
|
void handleEvent(const SDL_Event& event); // Procesa un evento
|
||||||
|
|
||||||
|
// --- Bucle principal legacy (fallback) ---
|
||||||
void run();
|
void run();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -365,14 +365,15 @@ void ServiceMenu::initializeOptions() {
|
|||||||
|
|
||||||
// Shader: Desactivat / PostFX / CrtPi
|
// Shader: Desactivat / PostFX / CrtPi
|
||||||
{
|
{
|
||||||
const std::string DISABLED_TEXT = Lang::getText("[SERVICE_MENU] SHADER_DISABLED");
|
std::string disabled_text = Lang::getText("[SERVICE_MENU] SHADER_DISABLED");
|
||||||
std::vector<std::string> shader_values = {DISABLED_TEXT, "PostFX", "CrtPi"};
|
std::vector<std::string> shader_values = {disabled_text, "PostFX", "CrtPi"};
|
||||||
auto shader_getter = [DISABLED_TEXT]() -> std::string {
|
auto shader_getter = [disabled_text]() -> std::string {
|
||||||
if (!Options::video.shader.enabled) { return DISABLED_TEXT; }
|
// NOLINTNEXTLINE(performance-no-automatic-move) -- captura por valor en lambda const, no se puede mover
|
||||||
|
if (!Options::video.shader.enabled) { return disabled_text; }
|
||||||
return (Options::video.shader.current_shader == Rendering::ShaderType::CRTPI) ? "CrtPi" : "PostFX";
|
return (Options::video.shader.current_shader == Rendering::ShaderType::CRTPI) ? "CrtPi" : "PostFX";
|
||||||
};
|
};
|
||||||
auto shader_setter = [DISABLED_TEXT](const std::string& val) {
|
auto shader_setter = [disabled_text](const std::string& val) {
|
||||||
if (val == DISABLED_TEXT) {
|
if (val == disabled_text) {
|
||||||
Options::video.shader.enabled = false;
|
Options::video.shader.enabled = false;
|
||||||
} else {
|
} else {
|
||||||
Options::video.shader.enabled = true;
|
Options::video.shader.enabled = true;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h> // Para SDL_Event
|
#include <SDL3/SDL.h> // Para SDL_Event
|
||||||
|
|
||||||
#include <cstddef> // Para size_t
|
#include <cstddef> // Para size_t
|
||||||
|
#include <cstdint> // Para std::uint8_t
|
||||||
#include <functional> // Para function
|
#include <functional> // Para function
|
||||||
#include <iterator> // Para pair
|
#include <iterator> // Para pair
|
||||||
#include <memory> // Para unique_ptr
|
#include <memory> // Para unique_ptr
|
||||||
@@ -19,7 +20,7 @@ class MenuRenderer;
|
|||||||
class ServiceMenu {
|
class ServiceMenu {
|
||||||
public:
|
public:
|
||||||
// --- Enums y constantes ---
|
// --- Enums y constantes ---
|
||||||
enum class SettingsGroup {
|
enum class SettingsGroup : std::uint8_t {
|
||||||
CONTROLS,
|
CONTROLS,
|
||||||
VIDEO,
|
VIDEO,
|
||||||
AUDIO,
|
AUDIO,
|
||||||
@@ -27,7 +28,7 @@ class ServiceMenu {
|
|||||||
SYSTEM,
|
SYSTEM,
|
||||||
MAIN
|
MAIN
|
||||||
};
|
};
|
||||||
enum class GroupAlignment {
|
enum class GroupAlignment : std::uint8_t {
|
||||||
CENTERED,
|
CENTERED,
|
||||||
LEFT
|
LEFT
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_FRect
|
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_FRect
|
||||||
|
|
||||||
#include <algorithm> // Para min
|
#include <algorithm> // Para min
|
||||||
|
#include <cstdint> // Para std::uint8_t
|
||||||
#include <memory> // Para allocator, shared_ptr
|
#include <memory> // Para allocator, shared_ptr
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <vector> // Para vector
|
#include <vector> // Para vector
|
||||||
@@ -13,7 +14,7 @@
|
|||||||
|
|
||||||
class WindowMessage {
|
class WindowMessage {
|
||||||
public:
|
public:
|
||||||
enum class PositionMode {
|
enum class PositionMode : std::uint8_t {
|
||||||
CENTERED, // La ventana se centra en el punto especificado
|
CENTERED, // La ventana se centra en el punto especificado
|
||||||
FIXED // La esquina superior izquierda coincide con el punto
|
FIXED // La esquina superior izquierda coincide con el punto
|
||||||
};
|
};
|
||||||
@@ -176,7 +177,7 @@ class WindowMessage {
|
|||||||
|
|
||||||
// Animación de mostrar/ocultar
|
// Animación de mostrar/ocultar
|
||||||
struct ShowHideAnimation {
|
struct ShowHideAnimation {
|
||||||
enum class Type { NONE,
|
enum class Type : std::uint8_t { NONE,
|
||||||
SHOWING,
|
SHOWING,
|
||||||
HIDING };
|
HIDING };
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
// NOLINTNEXTLINE(bugprone-reserved-identifier) -- requerido por <cmath> para exponer M_PI en MSVC
|
||||||
#define _USE_MATH_DEFINES
|
#define _USE_MATH_DEFINES
|
||||||
#include "utils.hpp"
|
#include "utils.hpp"
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
SECONDS=0
|
|
||||||
make linux_debug
|
|
||||||
duration=$SECONDS
|
|
||||||
echo "$((duration / 60)) minutes and $((duration % 60)) seconds elapsed."
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
SOURCEPATH=../source/
|
|
||||||
|
|
||||||
for i in "$SOURCEPATH"/*.cpp
|
|
||||||
do
|
|
||||||
include-what-you-use -D _DEBUG -std=c++20 -Wall "$i"
|
|
||||||
done
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
SOURCEPATH=../source/
|
|
||||||
|
|
||||||
for i in "$SOURCEPATH"/*.cpp
|
|
||||||
do
|
|
||||||
include-what-you-use -D DEBUG -std=c++20 -Wall "$i"
|
|
||||||
read -r -p "Presiona cualquier tecla para continuar..."
|
|
||||||
clear
|
|
||||||
done
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# Verifica que se haya proporcionado un archivo como argumento
|
|
||||||
if [ $# -eq 0 ]; then
|
|
||||||
echo "Uso: $0 <archivo.cpp>"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
FILE="$1"
|
|
||||||
|
|
||||||
include-what-you-use -D _DEBUG -std=c++20 -Wall "$FILE" \
|
|
||||||
-I../source \
|
|
||||||
-Xiwyu --mapping_file=sdl3_mapping.imp \
|
|
||||||
-Xiwyu --update_comments \
|
|
||||||
-Xiwyu --verbose=3
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
# Per a un fitxer, desde l'arrel del projecte executar:
|
|
||||||
clang-tidy source/fitxer.cpp -p build/ --fix
|
|
||||||
|
|
||||||
# Per a varios fitxers, desde l'arrel:
|
|
||||||
find source/ \( -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) | \
|
|
||||||
xargs -P4 -I{} bash -c 'echo "Procesando: {}"; clang-tidy {} -p build/ --fix'
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/stb*
|
|
||||||
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/gif.c
|
|
||||||
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/jail*
|
|
||||||
*:/usr/include/*
|
|
||||||
*:../source/stb*
|
|
||||||
*:../source/gif.c
|
|
||||||
*:../source/jail*
|
|
||||||
*:/usr/include/*
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# 🏁 Ruta base del proyecto
|
|
||||||
BASE_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition"
|
|
||||||
|
|
||||||
# 📁 Ruta al build
|
|
||||||
BUILD_DIR="$BASE_DIR/build"
|
|
||||||
|
|
||||||
# 📄 Archivo de mapping personalizado
|
|
||||||
MAPPING_FILE="$BASE_DIR/linux_utils/sdl3_mapping.imp"
|
|
||||||
|
|
||||||
# 📦 Generar compile_commands.json
|
|
||||||
echo "🔧 Generando compile_commands.json..."
|
|
||||||
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR"
|
|
||||||
|
|
||||||
@@ -1,553 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
|
|
||||||
##===--- iwyu_tool.py -----------------------------------------------------===##
|
|
||||||
#
|
|
||||||
# The LLVM Compiler Infrastructure
|
|
||||||
#
|
|
||||||
# This file is distributed under the University of Illinois Open Source
|
|
||||||
# License. See LICENSE.TXT for details.
|
|
||||||
#
|
|
||||||
##===----------------------------------------------------------------------===##
|
|
||||||
|
|
||||||
""" Driver to consume a Clang compilation database and invoke IWYU.
|
|
||||||
|
|
||||||
Example usage with CMake:
|
|
||||||
|
|
||||||
# Unix systems
|
|
||||||
$ mkdir build && cd build
|
|
||||||
$ CC="clang" CXX="clang++" cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ...
|
|
||||||
$ iwyu_tool.py -p .
|
|
||||||
|
|
||||||
# Windows systems
|
|
||||||
$ mkdir build && cd build
|
|
||||||
$ cmake -DCMAKE_CXX_COMPILER="%VCINSTALLDIR%/bin/cl.exe" \
|
|
||||||
-DCMAKE_C_COMPILER="%VCINSTALLDIR%/VC/bin/cl.exe" \
|
|
||||||
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
|
|
||||||
-G Ninja ...
|
|
||||||
$ python3 iwyu_tool.py -p .
|
|
||||||
|
|
||||||
See iwyu_tool.py -h for more details on command-line arguments.
|
|
||||||
"""
|
|
||||||
from __future__ import print_function
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
import shlex
|
|
||||||
import shutil
|
|
||||||
import argparse
|
|
||||||
import tempfile
|
|
||||||
import subprocess
|
|
||||||
|
|
||||||
|
|
||||||
CORRECT_RE = re.compile(r'^\((.*?) has correct #includes/fwd-decls\)$')
|
|
||||||
SHOULD_ADD_RE = re.compile(r'^(.*?) should add these lines:$')
|
|
||||||
ADD_RE = re.compile('^(.*?) +// (.*)$')
|
|
||||||
SHOULD_REMOVE_RE = re.compile(r'^(.*?) should remove these lines:$')
|
|
||||||
FULL_LIST_RE = re.compile(r'The full include-list for (.*?):$')
|
|
||||||
END_RE = re.compile(r'^---$')
|
|
||||||
LINES_RE = re.compile(r'^- (.*?) // lines ([0-9]+)-[0-9]+$')
|
|
||||||
|
|
||||||
|
|
||||||
GENERAL, ADD, REMOVE, LIST = range(4)
|
|
||||||
|
|
||||||
|
|
||||||
def clang_formatter(output, style):
|
|
||||||
""" Process iwyu's output into something clang-like. """
|
|
||||||
formatted = []
|
|
||||||
|
|
||||||
state = (GENERAL, None)
|
|
||||||
for line in output.splitlines():
|
|
||||||
match = CORRECT_RE.match(line)
|
|
||||||
if match:
|
|
||||||
# See PR#1806 for more info
|
|
||||||
continue
|
|
||||||
match = SHOULD_ADD_RE.match(line)
|
|
||||||
if match:
|
|
||||||
state = (ADD, match.group(1))
|
|
||||||
continue
|
|
||||||
match = SHOULD_REMOVE_RE.match(line)
|
|
||||||
if match:
|
|
||||||
state = (REMOVE, match.group(1))
|
|
||||||
continue
|
|
||||||
match = FULL_LIST_RE.match(line)
|
|
||||||
if match:
|
|
||||||
state = (LIST, match.group(1))
|
|
||||||
elif END_RE.match(line):
|
|
||||||
state = (GENERAL, None)
|
|
||||||
elif not line.strip():
|
|
||||||
continue
|
|
||||||
elif state[0] == GENERAL:
|
|
||||||
formatted.append(line)
|
|
||||||
elif state[0] == ADD:
|
|
||||||
match = ADD_RE.match(line)
|
|
||||||
if match:
|
|
||||||
formatted.append("%s:1:1: %s: add '%s' (%s)" %
|
|
||||||
(state[1],
|
|
||||||
style,
|
|
||||||
match.group(1),
|
|
||||||
match.group(2)))
|
|
||||||
else:
|
|
||||||
formatted.append("%s:1:1: %s: add '%s'" %
|
|
||||||
(state[1], style, line))
|
|
||||||
elif state[0] == REMOVE:
|
|
||||||
match = LINES_RE.match(line)
|
|
||||||
line_no = match.group(2) if match else '1'
|
|
||||||
formatted.append("%s:%s:1: %s: superfluous '%s'" %
|
|
||||||
(state[1], line_no, style, match.group(1)))
|
|
||||||
|
|
||||||
return os.linesep.join(formatted)
|
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_FORMAT = 'iwyu'
|
|
||||||
FORMATTERS = {
|
|
||||||
'iwyu': lambda output: output,
|
|
||||||
'clang': lambda output: clang_formatter(output, style="error"),
|
|
||||||
'clang-warning': lambda output: clang_formatter(output, style="warning"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
if sys.platform.startswith('win'):
|
|
||||||
# Case-insensitive match on Windows
|
|
||||||
def normcase(s):
|
|
||||||
return s.lower()
|
|
||||||
else:
|
|
||||||
def normcase(s):
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
def is_subpath_of(path, parent):
|
|
||||||
""" Return True if path is equal to or fully contained within parent.
|
|
||||||
|
|
||||||
Assumes both paths are canonicalized with os.path.realpath.
|
|
||||||
"""
|
|
||||||
parent = normcase(parent)
|
|
||||||
path = normcase(path)
|
|
||||||
|
|
||||||
if path == parent:
|
|
||||||
return True
|
|
||||||
|
|
||||||
if not path.startswith(parent):
|
|
||||||
return False
|
|
||||||
|
|
||||||
# Now we know parent is a prefix of path, but they only share lineage if the
|
|
||||||
# difference between them starts with a path separator, e.g. /a/b/c/file
|
|
||||||
# is not a parent of /a/b/c/file.cpp, but /a/b/c and /a/b/c/ are.
|
|
||||||
parent = parent.rstrip(os.path.sep)
|
|
||||||
suffix = path[len(parent):]
|
|
||||||
return suffix.startswith(os.path.sep)
|
|
||||||
|
|
||||||
|
|
||||||
def is_msvc_driver(compile_command):
|
|
||||||
""" Return True if compile_command matches an MSVC CL-style driver. """
|
|
||||||
compile_command = normcase(compile_command)
|
|
||||||
|
|
||||||
if compile_command.endswith('cl.exe'):
|
|
||||||
# Native MSVC compiler or clang-cl.exe
|
|
||||||
return True
|
|
||||||
|
|
||||||
if compile_command.endswith('clang-cl'):
|
|
||||||
# Cross clang-cl on non-Windows
|
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def win_split(cmdline):
|
|
||||||
""" Minimal implementation of shlex.split for Windows following
|
|
||||||
https://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft.aspx.
|
|
||||||
"""
|
|
||||||
def split_iter(cmdline):
|
|
||||||
in_quotes = False
|
|
||||||
backslashes = 0
|
|
||||||
arg = ''
|
|
||||||
for c in cmdline:
|
|
||||||
if c == '\\':
|
|
||||||
# MSDN: Backslashes are interpreted literally, unless they
|
|
||||||
# immediately precede a double quotation mark.
|
|
||||||
# Buffer them until we know what comes next.
|
|
||||||
backslashes += 1
|
|
||||||
elif c == '"':
|
|
||||||
# Quotes can either be an escaped quote or the start of a quoted
|
|
||||||
# string. Paraphrasing MSDN:
|
|
||||||
# Before quotes, place one backslash in the arg for every pair
|
|
||||||
# of leading backslashes. If the number of backslashes is odd,
|
|
||||||
# retain the double quotation mark, otherwise interpret it as a
|
|
||||||
# string delimiter and switch state.
|
|
||||||
arg += '\\' * (backslashes // 2)
|
|
||||||
if backslashes % 2 == 1:
|
|
||||||
arg += c
|
|
||||||
else:
|
|
||||||
in_quotes = not in_quotes
|
|
||||||
backslashes = 0
|
|
||||||
elif c in (' ', '\t') and not in_quotes:
|
|
||||||
# MSDN: Arguments are delimited by white space, which is either
|
|
||||||
# a space or a tab [but only outside of a string].
|
|
||||||
# Flush any buffered backslashes and yield arg, unless empty.
|
|
||||||
arg += '\\' * backslashes
|
|
||||||
if arg:
|
|
||||||
yield arg
|
|
||||||
arg = ''
|
|
||||||
backslashes = 0
|
|
||||||
else:
|
|
||||||
# Flush buffered backslashes and append.
|
|
||||||
arg += '\\' * backslashes
|
|
||||||
arg += c
|
|
||||||
backslashes = 0
|
|
||||||
|
|
||||||
if arg:
|
|
||||||
arg += '\\' * backslashes
|
|
||||||
yield arg
|
|
||||||
|
|
||||||
return list(split_iter(cmdline))
|
|
||||||
|
|
||||||
|
|
||||||
def split_command(cmdstr):
|
|
||||||
""" Split a command string into a list, respecting shell quoting. """
|
|
||||||
if sys.platform.startswith('win'):
|
|
||||||
# shlex.split does not work for Windows command-lines, so special-case
|
|
||||||
# to our own implementation.
|
|
||||||
cmd = win_split(cmdstr)
|
|
||||||
else:
|
|
||||||
cmd = shlex.split(cmdstr)
|
|
||||||
|
|
||||||
return cmd
|
|
||||||
|
|
||||||
|
|
||||||
def find_include_what_you_use():
|
|
||||||
""" Find IWYU executable and return its full pathname. """
|
|
||||||
env_iwyu_path = os.environ.get('IWYU_BINARY')
|
|
||||||
if env_iwyu_path:
|
|
||||||
return os.path.realpath(env_iwyu_path)
|
|
||||||
|
|
||||||
# Search in same dir as this script.
|
|
||||||
iwyu_path = shutil.which('include-what-you-use',
|
|
||||||
path=os.path.dirname(__file__))
|
|
||||||
if iwyu_path:
|
|
||||||
return os.path.realpath(iwyu_path)
|
|
||||||
|
|
||||||
# Search the system PATH.
|
|
||||||
iwyu_path = shutil.which('include-what-you-use')
|
|
||||||
if iwyu_path:
|
|
||||||
return os.path.realpath(iwyu_path)
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
IWYU_EXECUTABLE = find_include_what_you_use()
|
|
||||||
|
|
||||||
|
|
||||||
class Process(object):
|
|
||||||
""" Manages an IWYU process in flight """
|
|
||||||
def __init__(self, proc, outfile):
|
|
||||||
self.proc = proc
|
|
||||||
self.outfile = outfile
|
|
||||||
self.output = None
|
|
||||||
|
|
||||||
def poll(self):
|
|
||||||
""" Return the exit code if the process has completed, None otherwise.
|
|
||||||
"""
|
|
||||||
return self.proc.poll()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def returncode(self):
|
|
||||||
return self.proc.returncode
|
|
||||||
|
|
||||||
def get_output(self):
|
|
||||||
""" Return stdout+stderr output of the process.
|
|
||||||
|
|
||||||
This call blocks until the process is complete, then returns the output.
|
|
||||||
"""
|
|
||||||
if not self.output:
|
|
||||||
self.proc.wait()
|
|
||||||
self.outfile.seek(0)
|
|
||||||
self.output = self.outfile.read().decode("utf-8")
|
|
||||||
self.outfile.close()
|
|
||||||
|
|
||||||
return self.output
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def start(cls, invocation):
|
|
||||||
""" Start a Process for the invocation and capture stdout+stderr. """
|
|
||||||
outfile = tempfile.TemporaryFile(prefix='iwyu')
|
|
||||||
process = subprocess.Popen(
|
|
||||||
invocation.command,
|
|
||||||
cwd=invocation.cwd,
|
|
||||||
stdout=outfile,
|
|
||||||
stderr=subprocess.STDOUT)
|
|
||||||
return cls(process, outfile)
|
|
||||||
|
|
||||||
|
|
||||||
KNOWN_COMPILER_WRAPPERS=frozenset([
|
|
||||||
"ccache"
|
|
||||||
])
|
|
||||||
|
|
||||||
|
|
||||||
class Invocation(object):
|
|
||||||
""" Holds arguments of an IWYU invocation. """
|
|
||||||
def __init__(self, command, cwd):
|
|
||||||
self.command = command
|
|
||||||
self.cwd = cwd
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return ' '.join(self.command)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_compile_command(cls, entry, extra_args):
|
|
||||||
""" Parse a JSON compilation database entry into new Invocation. """
|
|
||||||
if 'arguments' in entry:
|
|
||||||
# arguments is a command-line in list form.
|
|
||||||
command = entry['arguments']
|
|
||||||
elif 'command' in entry:
|
|
||||||
# command is a command-line in string form, split to list.
|
|
||||||
command = split_command(entry['command'])
|
|
||||||
else:
|
|
||||||
raise ValueError('Invalid compilation database entry: %s' % entry)
|
|
||||||
|
|
||||||
if command[0] in KNOWN_COMPILER_WRAPPERS:
|
|
||||||
# Remove the compiler wrapper from the command.
|
|
||||||
command = command[1:]
|
|
||||||
|
|
||||||
# Rewrite the compile command for IWYU
|
|
||||||
compile_command, compile_args = command[0], command[1:]
|
|
||||||
if is_msvc_driver(compile_command):
|
|
||||||
# If the compiler is cl-compatible, let IWYU be cl-compatible.
|
|
||||||
extra_args = ['--driver-mode=cl'] + extra_args
|
|
||||||
|
|
||||||
command = [IWYU_EXECUTABLE] + extra_args + compile_args
|
|
||||||
return cls(command, entry['directory'])
|
|
||||||
|
|
||||||
def start(self, verbose):
|
|
||||||
""" Run invocation and collect output. """
|
|
||||||
if verbose:
|
|
||||||
print('# %s' % self, file=sys.stderr)
|
|
||||||
|
|
||||||
return Process.start(self)
|
|
||||||
|
|
||||||
|
|
||||||
def fixup_compilation_db(compilation_db):
|
|
||||||
""" Canonicalize paths in JSON compilation database. """
|
|
||||||
for entry in compilation_db:
|
|
||||||
# Convert relative paths to absolute ones if possible, based on the entry's directory.
|
|
||||||
if 'directory' in entry and not os.path.isabs(entry['file']):
|
|
||||||
entry['file'] = os.path.join(entry['directory'], entry['file'])
|
|
||||||
|
|
||||||
# Expand relative paths and symlinks
|
|
||||||
entry['file'] = os.path.realpath(entry['file'])
|
|
||||||
|
|
||||||
return compilation_db
|
|
||||||
|
|
||||||
|
|
||||||
def select_compilation_db(compilation_db, selection):
|
|
||||||
""" Return a new compilation database reduced to the paths in selection. """
|
|
||||||
if not selection:
|
|
||||||
return compilation_db
|
|
||||||
|
|
||||||
# Canonicalize selection paths to match compilation database.
|
|
||||||
selection = [os.path.realpath(p) for p in selection]
|
|
||||||
|
|
||||||
new_db = []
|
|
||||||
for path in selection:
|
|
||||||
if not os.path.exists(path):
|
|
||||||
print('warning: \'%s\' not found on disk.' % path, file=sys.stderr)
|
|
||||||
continue
|
|
||||||
|
|
||||||
found = [e for e in compilation_db if is_subpath_of(e['file'], path)]
|
|
||||||
if not found:
|
|
||||||
print('warning: \'%s\' not found in compilation database.' % path,
|
|
||||||
file=sys.stderr)
|
|
||||||
continue
|
|
||||||
|
|
||||||
new_db.extend(found)
|
|
||||||
|
|
||||||
return new_db
|
|
||||||
|
|
||||||
def slice_compilation_db(compilation_db, selection, exclude):
|
|
||||||
""" Return a new compilation database with filtered entries. """
|
|
||||||
|
|
||||||
new_db = select_compilation_db(compilation_db, selection)
|
|
||||||
|
|
||||||
# Canonicalize selection paths to match compilation database.
|
|
||||||
exclude = [os.path.realpath(p) for p in exclude]
|
|
||||||
|
|
||||||
for path in exclude:
|
|
||||||
if not os.path.exists(path):
|
|
||||||
print('warning: excluded path \'%s\' not found on disk.' % path,
|
|
||||||
file=sys.stderr)
|
|
||||||
continue
|
|
||||||
|
|
||||||
new_db = [e for e in new_db if not is_subpath_of(e['file'], path)]
|
|
||||||
|
|
||||||
return new_db
|
|
||||||
|
|
||||||
|
|
||||||
def worst_exit_code(worst, cur):
|
|
||||||
"""Return the most extreme exit code of two.
|
|
||||||
|
|
||||||
Negative exit codes occur if the program exits due to a signal (Unix) or
|
|
||||||
structured exception (Windows). If we've seen a negative one before, keep
|
|
||||||
it, as it usually indicates a critical error.
|
|
||||||
|
|
||||||
Otherwise return the biggest positive exit code.
|
|
||||||
"""
|
|
||||||
if cur < 0:
|
|
||||||
# Negative results take precedence, return the minimum
|
|
||||||
return min(worst, cur)
|
|
||||||
elif worst < 0:
|
|
||||||
# We know cur is non-negative, negative worst must be minimum
|
|
||||||
return worst
|
|
||||||
else:
|
|
||||||
# We know neither are negative, return the maximum
|
|
||||||
return max(worst, cur)
|
|
||||||
|
|
||||||
|
|
||||||
def execute(invocations, verbose, formatter, jobs, max_load_average=0):
|
|
||||||
""" Launch processes described by invocations. """
|
|
||||||
exit_code = 0
|
|
||||||
if jobs == 1:
|
|
||||||
for invocation in invocations:
|
|
||||||
proc = invocation.start(verbose)
|
|
||||||
print(formatter(proc.get_output()))
|
|
||||||
exit_code = worst_exit_code(exit_code, proc.returncode)
|
|
||||||
return exit_code
|
|
||||||
|
|
||||||
pending = []
|
|
||||||
while invocations or pending:
|
|
||||||
# Collect completed IWYU processes and print results.
|
|
||||||
complete = [proc for proc in pending if proc.poll() is not None]
|
|
||||||
for proc in complete:
|
|
||||||
pending.remove(proc)
|
|
||||||
print(formatter(proc.get_output()))
|
|
||||||
exit_code = worst_exit_code(exit_code, proc.returncode)
|
|
||||||
|
|
||||||
# Schedule new processes if there's room.
|
|
||||||
capacity = jobs - len(pending)
|
|
||||||
|
|
||||||
if max_load_average > 0:
|
|
||||||
one_min_load_average, _, _ = os.getloadavg()
|
|
||||||
load_capacity = max_load_average - one_min_load_average
|
|
||||||
if load_capacity < 0:
|
|
||||||
load_capacity = 0
|
|
||||||
if load_capacity < capacity:
|
|
||||||
capacity = int(load_capacity)
|
|
||||||
if not capacity and not pending:
|
|
||||||
# Ensure there is at least one job running.
|
|
||||||
capacity = 1
|
|
||||||
|
|
||||||
pending.extend(i.start(verbose) for i in invocations[:capacity])
|
|
||||||
invocations = invocations[capacity:]
|
|
||||||
|
|
||||||
# Yield CPU.
|
|
||||||
time.sleep(0.0001)
|
|
||||||
return exit_code
|
|
||||||
|
|
||||||
|
|
||||||
def main(compilation_db_path, source_files, exclude, verbose, formatter, jobs,
|
|
||||||
max_load_average, extra_args):
|
|
||||||
""" Entry point. """
|
|
||||||
|
|
||||||
if not IWYU_EXECUTABLE:
|
|
||||||
print('error: include-what-you-use executable not found',
|
|
||||||
file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
try:
|
|
||||||
if os.path.isdir(compilation_db_path):
|
|
||||||
compilation_db_path = os.path.join(compilation_db_path,
|
|
||||||
'compile_commands.json')
|
|
||||||
|
|
||||||
# Read compilation db from disk.
|
|
||||||
compilation_db_path = os.path.realpath(compilation_db_path)
|
|
||||||
with open(compilation_db_path, 'r') as fileobj:
|
|
||||||
compilation_db = json.load(fileobj)
|
|
||||||
except IOError as why:
|
|
||||||
print('error: failed to parse compilation database: %s' % why,
|
|
||||||
file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
compilation_db = fixup_compilation_db(compilation_db)
|
|
||||||
compilation_db = slice_compilation_db(compilation_db, source_files, exclude)
|
|
||||||
|
|
||||||
# Transform compilation db entries into a list of IWYU invocations.
|
|
||||||
invocations = [
|
|
||||||
Invocation.from_compile_command(e, extra_args) for e in compilation_db
|
|
||||||
]
|
|
||||||
|
|
||||||
return execute(invocations, verbose, formatter, jobs, max_load_average)
|
|
||||||
|
|
||||||
|
|
||||||
def _bootstrap(sys_argv):
|
|
||||||
""" Parse arguments and dispatch to main(). """
|
|
||||||
|
|
||||||
# This hackery is necessary to add the forwarded IWYU args to the
|
|
||||||
# usage and help strings.
|
|
||||||
def customize_usage(parser):
|
|
||||||
""" Rewrite the parser's format_usage. """
|
|
||||||
original_format_usage = parser.format_usage
|
|
||||||
parser.format_usage = lambda: original_format_usage().rstrip() + \
|
|
||||||
' -- [<IWYU args>]' + os.linesep
|
|
||||||
|
|
||||||
def customize_help(parser):
|
|
||||||
""" Rewrite the parser's format_help. """
|
|
||||||
original_format_help = parser.format_help
|
|
||||||
|
|
||||||
def custom_help():
|
|
||||||
""" Customized help string, calls the adjusted format_usage. """
|
|
||||||
helpmsg = original_format_help()
|
|
||||||
helplines = helpmsg.splitlines()
|
|
||||||
helplines[0] = parser.format_usage().rstrip()
|
|
||||||
return os.linesep.join(helplines) + os.linesep
|
|
||||||
|
|
||||||
parser.format_help = custom_help
|
|
||||||
|
|
||||||
# Parse arguments.
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
description='Include-what-you-use compilation database driver.',
|
|
||||||
epilog='Assumes include-what-you-use is available on the PATH.')
|
|
||||||
customize_usage(parser)
|
|
||||||
customize_help(parser)
|
|
||||||
|
|
||||||
parser.add_argument('-v', '--verbose', action='store_true',
|
|
||||||
help='Print IWYU commands')
|
|
||||||
parser.add_argument('-o', '--output-format', type=str,
|
|
||||||
choices=FORMATTERS.keys(), default=DEFAULT_FORMAT,
|
|
||||||
help='Output format (default: %s)' % DEFAULT_FORMAT)
|
|
||||||
parser.add_argument('-j', '--jobs', type=int, default=1,
|
|
||||||
nargs='?', const=0,
|
|
||||||
help=('Number of concurrent subprocesses. If zero, '
|
|
||||||
'will try to match the logical cores of the '
|
|
||||||
'system.'))
|
|
||||||
parser.add_argument('-l', '--load', type=float, default=0,
|
|
||||||
help=('Do not start new jobs if the 1min load average '
|
|
||||||
'is greater than the provided value'))
|
|
||||||
parser.add_argument('-p', metavar='<build-path>', required=True,
|
|
||||||
help='Compilation database path', dest='dbpath')
|
|
||||||
parser.add_argument('-e', '--exclude', action='append', default=[],
|
|
||||||
help=('Do not run IWYU on source files (or directories) '
|
|
||||||
'below this path.'))
|
|
||||||
parser.add_argument('source', nargs='*',
|
|
||||||
help=('Zero or more source files (or directories) to '
|
|
||||||
'run IWYU on. Defaults to all in compilation '
|
|
||||||
'database.'))
|
|
||||||
|
|
||||||
def partition_args(argv):
|
|
||||||
""" Split around '--' into driver args and IWYU args. """
|
|
||||||
try:
|
|
||||||
double_dash = argv.index('--')
|
|
||||||
return argv[:double_dash], argv[double_dash+1:]
|
|
||||||
except ValueError:
|
|
||||||
return argv, []
|
|
||||||
argv, extra_args = partition_args(sys_argv[1:])
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
|
|
||||||
jobs = args.jobs
|
|
||||||
if jobs == 0:
|
|
||||||
jobs = os.cpu_count() or 1
|
|
||||||
|
|
||||||
return main(args.dbpath, args.source, args.exclude, args.verbose,
|
|
||||||
FORMATTERS[args.output_format], jobs, args.load, extra_args)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
sys.exit(_bootstrap(sys.argv))
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# Script para ejecutar clang-tidy en múltiples directorios
|
|
||||||
# Uso: ./run_clang-tidy.sh [--fix]
|
|
||||||
# --fix: Aplica las correcciones automáticamente (opcional)
|
|
||||||
|
|
||||||
# Detectar si se pasó el parámetro --fix
|
|
||||||
FIX_FLAG=""
|
|
||||||
if [[ "$1" == "--fix" ]]; then
|
|
||||||
FIX_FLAG="--fix"
|
|
||||||
echo "Modo: Aplicando correcciones automáticamente (--fix)"
|
|
||||||
else
|
|
||||||
echo "Modo: Solo análisis (sin --fix)"
|
|
||||||
fi
|
|
||||||
echo
|
|
||||||
|
|
||||||
# Lista de rutas donde ejecutar clang-tidy
|
|
||||||
PATHS=(
|
|
||||||
"/home/sergio/gitea/coffee_crisis_arcade_edition/source"
|
|
||||||
"/home/sergio/gitea/coffee_crisis_arcade_edition/source/rendering"
|
|
||||||
"/home/sergio/gitea/coffee_crisis_arcade_edition/source/rendering/opengl"
|
|
||||||
"/home/sergio/gitea/coffee_crisis_arcade_edition/source/sections"
|
|
||||||
"/home/sergio/gitea/coffee_crisis_arcade_edition/source/ui"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Ruta del directorio build (relativa desde donde se ejecuta el script)
|
|
||||||
BUILD_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition/build/"
|
|
||||||
|
|
||||||
# Función para procesar un directorio
|
|
||||||
process_directory() {
|
|
||||||
local dir="$1"
|
|
||||||
|
|
||||||
echo "=== Procesando directorio: $dir ==="
|
|
||||||
|
|
||||||
# Verificar que el directorio existe
|
|
||||||
if [[ ! -d "$dir" ]]; then
|
|
||||||
echo "Error: El directorio $dir no existe"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Cambiar al directorio y ejecutar find con -maxdepth 1 para un solo nivel
|
|
||||||
cd "$dir" || return 1
|
|
||||||
|
|
||||||
# Buscar archivos .cpp, .h, .hpp solo en el nivel actual (no subdirectorios)
|
|
||||||
find . -maxdepth 1 \( -name '*.cpp' -o -name '*.h' -o -name '*.hpp' \) -print0 | \
|
|
||||||
xargs -0 -P4 -I{} bash -c 'echo "Procesando: {}"; clang-tidy {} -p '"$BUILD_DIR"' '"$FIX_FLAG"
|
|
||||||
|
|
||||||
echo "=== Completado: $dir ==="
|
|
||||||
echo
|
|
||||||
}
|
|
||||||
|
|
||||||
# Procesar cada directorio en la lista
|
|
||||||
for path in "${PATHS[@]}"; do
|
|
||||||
process_directory "$path"
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "¡Proceso completado para todos los directorios!"
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# Función para mostrar el uso del script
|
|
||||||
mostrar_uso() {
|
|
||||||
echo "Uso: $0 [-o opción]"
|
|
||||||
echo "Opciones:"
|
|
||||||
echo " w Ejecutar cppcheck con warning, style, performance"
|
|
||||||
echo " a Ejecutar cppcheck con todas las opciones habilitadas"
|
|
||||||
echo " u Ejecutar cppcheck para unusedFunction"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Inicializar las variables
|
|
||||||
opcion=""
|
|
||||||
|
|
||||||
# Procesar las opciones
|
|
||||||
while getopts "o:" opt; do
|
|
||||||
case $opt in
|
|
||||||
o)
|
|
||||||
opcion=$OPTARG
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
mostrar_uso
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
# Ejecutar según la opción seleccionada
|
|
||||||
case $opcion in
|
|
||||||
w)
|
|
||||||
cppcheck --force --enable=warning,style,performance --std=c++20 \
|
|
||||||
--check-level=exhaustive \
|
|
||||||
--suppressions-list=./cppcheck_suppressions \
|
|
||||||
../source/ \
|
|
||||||
2>./cppcheck-result-warning-style-performance.txt
|
|
||||||
;;
|
|
||||||
a)
|
|
||||||
cppcheck --force --enable=all -I /usr/include --std=c++20 \
|
|
||||||
--suppress=missingIncludeSystem \
|
|
||||||
--suppressions-list=./cppcheck_suppressions \
|
|
||||||
../source/ \
|
|
||||||
2>./cppcheck-result-all.txt
|
|
||||||
;;
|
|
||||||
u)
|
|
||||||
cppcheck --enable=style --std=c++20 \
|
|
||||||
--suppressions-list=./cppcheck_suppressions \
|
|
||||||
../source/ \
|
|
||||||
2>./cppcheck-result-unusedFunction.txt
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
mostrar_uso
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# 🏁 Ruta base del proyecto
|
|
||||||
BASE_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition"
|
|
||||||
|
|
||||||
# 📁 Ruta al build
|
|
||||||
BUILD_DIR="$BASE_DIR/build"
|
|
||||||
|
|
||||||
# 📄 Archivo de mapping personalizado
|
|
||||||
MAPPING_FILE="$BASE_DIR/linux_utils/sdl3_mapping.imp"
|
|
||||||
|
|
||||||
# 📦 Generar compile_commands.json
|
|
||||||
echo "🔧 Generando compile_commands.json..."
|
|
||||||
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR"
|
|
||||||
|
|
||||||
# 🛠️ Ejecutar IWYU con fix_includes.py
|
|
||||||
echo "🚀 Ejecutando IWYU..."
|
|
||||||
./iwyu_tool.py -p "$BUILD_DIR" -- -Xiwyu --mapping_file="$MAPPING_FILE" -Xiwyu --verbose=3 \
|
|
||||||
| fix_include --update_comments --reorder --nosafe_headers
|
|
||||||
|
|
||||||
# 🧹 Reemplazar // for por // Para en líneas de #include
|
|
||||||
echo "✍️ Corrigiendo comentarios en includes..."
|
|
||||||
find "$BASE_DIR" -type f \( -name "*.cpp" -o -name "*.h" \) -exec \
|
|
||||||
sed -i '/^#include .*\/\/ for/s/\/\/ for/\/\/ Para/' {} +
|
|
||||||
|
|
||||||
echo "✅ Script completado."
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
# 🏁 Ruta base del proyecto
|
|
||||||
BASE_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition"
|
|
||||||
|
|
||||||
# 📁 Ruta al build
|
|
||||||
BUILD_DIR="$BASE_DIR/build"
|
|
||||||
|
|
||||||
# 📄 Archivo de mapping personalizado
|
|
||||||
MAPPING_FILE="$BASE_DIR/linux_utils/sdl3_mapping.imp"
|
|
||||||
|
|
||||||
# 📦 Generar compile_commands.json
|
|
||||||
echo "🔧 Generando compile_commands.json..."
|
|
||||||
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR"
|
|
||||||
|
|
||||||
# 🛠️ Ejecutar IWYU con fix_includes.py
|
|
||||||
echo "🚀 Ejecutando IWYU..."
|
|
||||||
iwyu_tool.py -p "$BUILD_DIR" -- -Xiwyu --mapping_file="$MAPPING_FILE" -Xiwyu --verbose=3 \
|
|
||||||
| python3 /usr/bin/fix_includes.py --update_comments --reorder --nosafe_headers --dry_run
|
|
||||||
|
|
||||||
# 🧹 Reemplazar // for por // Para en líneas de #include
|
|
||||||
echo "✍️ Corrigiendo comentarios en includes..."
|
|
||||||
find "$BASE_DIR" -type f \( -name "*.cpp" -o -name "*.h" \) -exec \
|
|
||||||
sed -i '/^#include .*\/\/ for/s/\/\/ for/\/\/ Para/' {} +
|
|
||||||
|
|
||||||
echo "✅ Script completado."
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
valgrind --suppressions=valgrind_exceptions \
|
|
||||||
--leak-check=full \
|
|
||||||
~/gitea/coffee_crisis_arcade_edition/coffee_crisis_arcade_edition \
|
|
||||||
> ~/gitea/coffee_crisis_arcade_edition/linux_utils/valgrind_out.txt 2>&1
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
[
|
|
||||||
{ "include": ["<SDL3/SDL_stdinc.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_assert.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_asyncio.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_atomic.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_audio.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_bits.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_blendmode.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_camera.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_clipboard.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_cpuinfo.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_dialog.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_endian.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_error.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_events.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_filesystem.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_gamepad.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_gpu.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_guid.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_haptic.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_hidapi.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_hints.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_init.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_iostream.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_joystick.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_keyboard.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_keycode.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_loadso.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_locale.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_log.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_messagebox.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_metal.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_misc.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_mouse.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_mutex.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_pen.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_pixels.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_platform.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_power.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_process.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_properties.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_rect.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_render.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_scancode.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_sensor.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_storage.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_surface.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_system.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_thread.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_time.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_timer.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_tray.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_touch.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_version.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_video.h>", "private", "<SDL3/SDL.h>", "public"] },
|
|
||||||
{ "include": ["<SDL3/SDL_oldnames.h>", "private", "<SDL3/SDL.h>", "public"] }
|
|
||||||
]
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
ignore_unversioned_libs
|
|
||||||
Memcheck:Leak
|
|
||||||
...
|
|
||||||
obj:*/lib*/lib*.so
|
|
||||||
}
|
|
||||||
{
|
|
||||||
ignore_versioned_libs
|
|
||||||
Memcheck:Leak
|
|
||||||
...
|
|
||||||
obj:*/lib*/lib*.so.*
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user