7 Commits

Author SHA1 Message Date
d6b2e97777 afegit nivell de brillo per shape 2025-12-02 22:11:17 +01:00
98c90e6075 treballant en el starfield 2025-12-02 21:19:43 +01:00
f795c86a38 afegida escena TITOL 2025-12-02 21:03:21 +01:00
c1c5774406 retocs disseny en LOGO 2025-12-02 17:27:18 +01:00
0139da4764 corregit el escalat de finestra i mode fullscreen 2025-12-02 17:10:53 +01:00
ec911979fb afegit so al LOGO 2025-12-02 14:01:53 +01:00
e51749dbc6 afegit sistema de audio 2025-12-02 13:51:54 +01:00
27 changed files with 6189 additions and 110 deletions

View File

@@ -1,7 +1,7 @@
# CMakeLists.txt # CMakeLists.txt
cmake_minimum_required(VERSION 3.10) cmake_minimum_required(VERSION 3.10)
project(orni VERSION 0.2.0) project(orni VERSION 0.3.0)
# Info del proyecto # Info del proyecto
set(PROJECT_LONG_NAME "Orni Attack") set(PROJECT_LONG_NAME "Orni Attack")
@@ -45,8 +45,12 @@ set(APP_SOURCES
source/core/graphics/shape.cpp source/core/graphics/shape.cpp
source/core/graphics/shape_loader.cpp source/core/graphics/shape_loader.cpp
source/core/graphics/vector_text.cpp source/core/graphics/vector_text.cpp
source/core/graphics/starfield.cpp
source/core/audio/audio.cpp
source/core/audio/audio_cache.cpp
source/game/options.cpp source/game/options.cpp
source/game/escenes/escena_logo.cpp source/game/escenes/escena_logo.cpp
source/game/escenes/escena_titol.cpp
source/game/escenes/escena_joc.cpp source/game/escenes/escena_joc.cpp
source/game/entities/nau.cpp source/game/entities/nau.cpp
source/game/entities/bala.cpp source/game/entities/bala.cpp

View File

@@ -36,6 +36,8 @@ APP_SOURCES := \
source/main.cpp \ source/main.cpp \
source/core/system/director.cpp \ source/core/system/director.cpp \
source/core/system/global_events.cpp \ source/core/system/global_events.cpp \
source/core/audio/audio.cpp \
source/core/audio/audio_cache.cpp \
source/core/rendering/sdl_manager.cpp \ source/core/rendering/sdl_manager.cpp \
source/core/rendering/line_renderer.cpp \ source/core/rendering/line_renderer.cpp \
source/core/rendering/color_oscillator.cpp \ source/core/rendering/color_oscillator.cpp \
@@ -45,8 +47,10 @@ APP_SOURCES := \
source/core/graphics/shape.cpp \ source/core/graphics/shape.cpp \
source/core/graphics/shape_loader.cpp \ source/core/graphics/shape_loader.cpp \
source/core/graphics/vector_text.cpp \ source/core/graphics/vector_text.cpp \
source/core/graphics/starfield.cpp \
source/game/options.cpp \ source/game/options.cpp \
source/game/escenes/escena_logo.cpp \ source/game/escenes/escena_logo.cpp \
source/game/escenes/escena_titol.cpp \
source/game/escenes/escena_joc.cpp \ source/game/escenes/escena_joc.cpp \
source/game/entities/nau.cpp \ source/game/entities/nau.cpp \
source/game/entities/bala.cpp \ source/game/entities/bala.cpp \

View File

@@ -0,0 +1,12 @@
# char_copyright.shp - Símbolo © (copyright)
# Dimensiones: 20×40 (blocky display)
name: char_copyright
scale: 1.0
center: 10, 20
# Círculo exterior (aproximado con 12 puntos)
polyline: 10,8 13,9 15,11 17,14 18,17 18,23 17,26 15,29 13,31 10,32 7,31 5,29 3,26 2,23 2,17 3,14 5,11 7,9 10,8
# Letra C interior
polyline: 13,16 9,14 7,16 6,20 7,24 9,26 13,24

19
data/shapes/star.shp Normal file
View File

@@ -0,0 +1,19 @@
# star.shp - Estrella per a starfield
# © 2025 Orni Attack
name: star
scale: 1.0
center: 0, 0
# Estrella de 4 puntes (diamant/creu)
# Petita i simple per a l'efecte starfield
#
# Punts:
# angle=0°: (0, -3) Dalt
# angle=90°: (3, 0) Dreta
# angle=180°: (0, 3) Baix
# angle=270°: (-3, 0) Esquerra
#
# Forma de diamant amb línies de centre a puntes
polyline: 0,-3 3,0 0,3 -3,0 0,-3

BIN
data/sounds/explosion.wav Normal file

Binary file not shown.

BIN
data/sounds/laser_shoot.wav Normal file

Binary file not shown.

BIN
data/sounds/logo.wav Normal file

Binary file not shown.

View File

@@ -22,7 +22,11 @@ SDLManager::SDLManager()
current_height_(Defaults::Window::HEIGHT), current_height_(Defaults::Window::HEIGHT),
is_fullscreen_(false), is_fullscreen_(false),
max_width_(1920), max_width_(1920),
max_height_(1080) { max_height_(1080),
zoom_factor_(Defaults::Window::BASE_ZOOM),
windowed_width_(Defaults::Window::WIDTH),
windowed_height_(Defaults::Window::HEIGHT),
max_zoom_(1.0f) {
// Inicialitzar SDL3 // Inicialitzar SDL3
if (!SDL_Init(SDL_INIT_VIDEO)) { if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl; std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
@@ -82,7 +86,11 @@ SDLManager::SDLManager(int width, int height, bool fullscreen)
current_height_(height), current_height_(height),
is_fullscreen_(fullscreen), is_fullscreen_(fullscreen),
max_width_(1920), max_width_(1920),
max_height_(1080) { max_height_(1080),
zoom_factor_(static_cast<float>(width) / Defaults::Window::WIDTH),
windowed_width_(width),
windowed_height_(height),
max_zoom_(1.0f) {
// Inicialitzar SDL3 // Inicialitzar SDL3
if (!SDL_Init(SDL_INIT_VIDEO)) { if (!SDL_Init(SDL_INIT_VIDEO)) {
std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl; std::cerr << "Error inicialitzant SDL3: " << SDL_GetError() << std::endl;
@@ -173,6 +181,64 @@ void SDLManager::calculateMaxWindowSize() {
std::cerr << "No s'ha pogut detectar el display, usant fallback: " std::cerr << "No s'ha pogut detectar el display, usant fallback: "
<< max_width_ << "x" << max_height_ << std::endl; << max_width_ << "x" << max_height_ << std::endl;
} }
// Calculate max zoom immediately after determining max size
calculateMaxZoom();
}
void SDLManager::calculateMaxZoom() {
// Maximum zoom limited by BOTH width and height (preserves 4:3)
float max_zoom_width = static_cast<float>(max_width_) / Defaults::Window::WIDTH;
float max_zoom_height = static_cast<float>(max_height_) / Defaults::Window::HEIGHT;
// Take smaller constraint
float max_zoom_unrounded = std::min(max_zoom_width, max_zoom_height);
// Round DOWN to nearest 0.1 increment (user preference)
max_zoom_ = std::floor(max_zoom_unrounded / Defaults::Window::ZOOM_INCREMENT) * Defaults::Window::ZOOM_INCREMENT;
// Safety clamp
max_zoom_ = std::max(max_zoom_, Defaults::Window::MIN_ZOOM);
std::cout << "Max zoom: " << max_zoom_ << "x (display: "
<< max_width_ << "x" << max_height_ << ")" << std::endl;
}
void SDLManager::applyZoom(float new_zoom) {
// Clamp to valid range
new_zoom = std::max(Defaults::Window::MIN_ZOOM,
std::min(new_zoom, max_zoom_));
// Round to nearest 0.1 increment
new_zoom = std::round(new_zoom / Defaults::Window::ZOOM_INCREMENT) * Defaults::Window::ZOOM_INCREMENT;
// No change?
if (std::abs(new_zoom - zoom_factor_) < 0.01f) {
return;
}
zoom_factor_ = new_zoom;
// Calculate physical dimensions (4:3 maintained automatically)
int new_width = static_cast<int>(std::round(
Defaults::Window::WIDTH * zoom_factor_));
int new_height = static_cast<int>(std::round(
Defaults::Window::HEIGHT * zoom_factor_));
// Apply to window (centers via applyWindowSize)
applyWindowSize(new_width, new_height);
// Update windowed size cache
windowed_width_ = new_width;
windowed_height_ = new_height;
// Persist
Options::window.width = new_width;
Options::window.height = new_height;
Options::window.zoom_factor = zoom_factor_;
std::cout << "Zoom: " << zoom_factor_ << "x ("
<< new_width << "x" << new_height << ")" << std::endl;
} }
void SDLManager::updateLogicalPresentation() { void SDLManager::updateLogicalPresentation() {
@@ -188,48 +254,22 @@ void SDLManager::updateLogicalPresentation() {
void SDLManager::increaseWindowSize() { void SDLManager::increaseWindowSize() {
if (is_fullscreen_) if (is_fullscreen_)
return; // No operar en fullscreen return;
int new_width = current_width_ + Defaults::Window::SIZE_INCREMENT; float new_zoom = zoom_factor_ + Defaults::Window::ZOOM_INCREMENT;
int new_height = current_height_ + Defaults::Window::SIZE_INCREMENT; applyZoom(new_zoom);
// Clamp a màxim std::cout << "F2: Zoom aumentat a " << zoom_factor_ << "x" << std::endl;
new_width = std::min(new_width, max_width_);
new_height = std::min(new_height, max_height_);
if (new_width != current_width_ || new_height != current_height_) {
applyWindowSize(new_width, new_height);
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
Options::window.width = current_width_;
Options::window.height = current_height_;
std::cout << "F2: Finestra augmentada a " << new_width << "x" << new_height
<< std::endl;
}
} }
void SDLManager::decreaseWindowSize() { void SDLManager::decreaseWindowSize() {
if (is_fullscreen_) if (is_fullscreen_)
return; return;
int new_width = current_width_ - Defaults::Window::SIZE_INCREMENT; float new_zoom = zoom_factor_ - Defaults::Window::ZOOM_INCREMENT;
int new_height = current_height_ - Defaults::Window::SIZE_INCREMENT; applyZoom(new_zoom);
// Clamp a mínim std::cout << "F1: Zoom reduït a " << zoom_factor_ << "x" << std::endl;
new_width = std::max(new_width, Defaults::Window::MIN_WIDTH);
new_height = std::max(new_height, Defaults::Window::MIN_HEIGHT);
if (new_width != current_width_ || new_height != current_height_) {
applyWindowSize(new_width, new_height);
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
Options::window.width = current_width_;
Options::window.height = current_height_;
std::cout << "F1: Finestra reduïda a " << new_width << "x" << new_height
<< std::endl;
}
} }
void SDLManager::applyWindowSize(int new_width, int new_height) { void SDLManager::applyWindowSize(int new_width, int new_height) {
@@ -265,26 +305,49 @@ void SDLManager::applyWindowSize(int new_width, int new_height) {
} }
void SDLManager::toggleFullscreen() { void SDLManager::toggleFullscreen() {
is_fullscreen_ = !is_fullscreen_; if (!is_fullscreen_) {
SDL_SetWindowFullscreen(finestra_, is_fullscreen_); // ENTERING FULLSCREEN
windowed_width_ = current_width_;
windowed_height_ = current_height_;
is_fullscreen_ = true;
SDL_SetWindowFullscreen(finestra_, true);
std::cout << "F3: Fullscreen activat (guardada: "
<< windowed_width_ << "x" << windowed_height_ << ")" << std::endl;
} else {
// EXITING FULLSCREEN
is_fullscreen_ = false;
SDL_SetWindowFullscreen(finestra_, false);
// CRITICAL: Explicitly restore windowed size
applyWindowSize(windowed_width_, windowed_height_);
std::cout << "F3: Fullscreen desactivat (restaurada: "
<< windowed_width_ << "x" << windowed_height_ << ")" << std::endl;
}
// Persistir canvis a Options (es guardarà a config.yaml al tancar)
Options::window.fullscreen = is_fullscreen_; Options::window.fullscreen = is_fullscreen_;
std::cout << "F3: Fullscreen " << (is_fullscreen_ ? "activat" : "desactivat")
<< std::endl;
// En fullscreen, SDL gestiona tot automàticament
// En sortir, restaura la mida anterior
} }
bool SDLManager::handleWindowEvent(const SDL_Event& event) { bool SDLManager::handleWindowEvent(const SDL_Event& event) {
if (event.type == SDL_EVENT_WINDOW_RESIZED) { if (event.type == SDL_EVENT_WINDOW_RESIZED) {
// Usuari ha redimensionat manualment (arrossegar vora)
// Actualitzar el nostre tracking
SDL_GetWindowSize(finestra_, &current_width_, &current_height_); SDL_GetWindowSize(finestra_, &current_width_, &current_height_);
std::cout << "Finestra redimensionada manualment a " << current_width_
<< "x" << current_height_ << std::endl; // Calculate zoom from actual size (may not align to 0.1 increments)
float new_zoom = static_cast<float>(current_width_) / Defaults::Window::WIDTH;
zoom_factor_ = std::max(Defaults::Window::MIN_ZOOM,
std::min(new_zoom, max_zoom_));
// Update windowed cache (if not in fullscreen)
if (!is_fullscreen_) {
windowed_width_ = current_width_;
windowed_height_ = current_height_;
}
std::cout << "Finestra redimensionada: " << current_width_
<< "x" << current_height_ << " (zoom ≈" << zoom_factor_ << "x)"
<< std::endl;
return true; return true;
} }
return false; return false;

View File

@@ -62,8 +62,16 @@ class SDLManager {
int max_width_; // Calculat des del display int max_width_; // Calculat des del display
int max_height_; int max_height_;
// [ZOOM SYSTEM]
float zoom_factor_; // Current zoom (0.5x to max_zoom_)
int windowed_width_; // Saved size before fullscreen
int windowed_height_; // Saved size before fullscreen
float max_zoom_; // Maximum zoom (calculated from display)
// [NUEVO] Funcions internes // [NUEVO] Funcions internes
void calculateMaxWindowSize(); // Llegir resolució del display void calculateMaxWindowSize(); // Llegir resolució del display
void calculateMaxZoom(); // Calculate max zoom from display
void applyZoom(float new_zoom); // Apply zoom and resize window
void applyWindowSize(int width, int height); // Canviar mida + centrar void applyWindowSize(int width, int height); // Canviar mida + centrar
void updateLogicalPresentation(); // Actualitzar viewport void updateLogicalPresentation(); // Actualitzar viewport

5565
source/external/stb_vorbis.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -41,8 +41,7 @@ inline void obtenir_limits_zona(float& min_x, float& max_x, float& min_y, float&
} }
// Obtenir límits segurs (compensant radi de l'entitat) // Obtenir límits segurs (compensant radi de l'entitat)
inline void obtenir_limits_zona_segurs(float radi, float& min_x, float& max_x, inline void obtenir_limits_zona_segurs(float radi, float& min_x, float& max_x, float& min_y, float& max_y) {
float& min_y, float& max_y) {
const auto& zona = Defaults::Zones::PLAYAREA; const auto& zona = Defaults::Zones::PLAYAREA;
constexpr float MARGE_SEGURETAT = 10.0f; // Safety margin constexpr float MARGE_SEGURETAT = 10.0f; // Safety margin

View File

@@ -7,6 +7,7 @@
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
#include "core/audio/audio.hpp"
#include "core/defaults.hpp" #include "core/defaults.hpp"
#include "core/rendering/line_renderer.hpp" #include "core/rendering/line_renderer.hpp"
@@ -51,6 +52,9 @@ void DebrisManager::explotar(const std::shared_ptr<Graphics::Shape>& shape,
return; return;
} }
// Reproducir sonido de explosión
Audio::get()->playSound(Defaults::Sound::EXPLOSION, Audio::Group::GAME);
// Obtenir centre de la forma per a transformacions // Obtenir centre de la forma per a transformacions
const Punt& shape_centre = shape->get_centre(); const Punt& shape_centre = shape->get_centre();

View File

@@ -7,6 +7,8 @@
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
#include "core/audio/audio.hpp"
#include "core/defaults.hpp"
#include "core/graphics/shape_loader.hpp" #include "core/graphics/shape_loader.hpp"
#include "core/rendering/shape_renderer.hpp" #include "core/rendering/shape_renderer.hpp"
#include "game/constants.hpp" #include "game/constants.hpp"
@@ -16,7 +18,8 @@ Bala::Bala(SDL_Renderer* renderer)
centre_({0.0f, 0.0f}), centre_({0.0f, 0.0f}),
angle_(0.0f), angle_(0.0f),
velocitat_(0.0f), velocitat_(0.0f),
esta_(false) { esta_(false),
brightness_(Defaults::Brightness::BALA) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("bullet.shp"); forma_ = Graphics::ShapeLoader::load("bullet.shp");
@@ -50,6 +53,9 @@ void Bala::disparar(const Punt& posicio, float angle) {
// Velocitat alta (el joc Pascal original usava 7 px/frame) // Velocitat alta (el joc Pascal original usava 7 px/frame)
// 7 px/frame × 20 FPS = 140 px/s // 7 px/frame × 20 FPS = 140 px/s
velocitat_ = 140.0f; velocitat_ = 140.0f;
// Reproducir sonido de disparo láser
Audio::get()->playSound(Defaults::Sound::LASER, Audio::Group::GAME);
} }
void Bala::actualitzar(float delta_time) { void Bala::actualitzar(float delta_time) {
@@ -62,7 +68,7 @@ void Bala::dibuixar() const {
if (esta_ && forma_) { if (esta_ && forma_) {
// [NUEVO] Usar render_shape en lloc de rota_pol // [NUEVO] Usar render_shape en lloc de rota_pol
// Les bales no roten visualment (angle sempre 0.0f) // Les bales no roten visualment (angle sempre 0.0f)
Rendering::render_shape(renderer_, forma_, centre_, 0.0f, 1.0f, true); Rendering::render_shape(renderer_, forma_, centre_, 0.0f, 1.0f, true, 1.0f, brightness_);
} }
} }
@@ -87,7 +93,10 @@ void Bala::mou(float delta_time) {
// CORRECCIÓ: Usar límits segurs amb radi de la bala // CORRECCIÓ: Usar límits segurs amb radi de la bala
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::BULLET_RADIUS, Constants::obtenir_limits_zona_segurs(Defaults::Entities::BULLET_RADIUS,
min_x, max_x, min_y, max_y); min_x,
max_x,
min_y,
max_y);
if (centre_.x < min_x || centre_.x > max_x || if (centre_.x < min_x || centre_.x > max_x ||
centre_.y < min_y || centre_.y > max_y) { centre_.y < min_y || centre_.y > max_y) {

View File

@@ -37,6 +37,7 @@ class Bala {
float angle_; float angle_;
float velocitat_; float velocitat_;
bool esta_; bool esta_;
float brightness_; // Factor de brillantor (0.0-1.0)
void mou(float delta_time); void mou(float delta_time);
}; };

View File

@@ -8,6 +8,7 @@
#include <cstdlib> #include <cstdlib>
#include <iostream> #include <iostream>
#include "core/defaults.hpp"
#include "core/graphics/shape_loader.hpp" #include "core/graphics/shape_loader.hpp"
#include "core/rendering/shape_renderer.hpp" #include "core/rendering/shape_renderer.hpp"
#include "game/constants.hpp" #include "game/constants.hpp"
@@ -19,7 +20,8 @@ Enemic::Enemic(SDL_Renderer* renderer)
velocitat_(0.0f), velocitat_(0.0f),
drotacio_(0.0f), drotacio_(0.0f),
rotacio_(0.0f), rotacio_(0.0f),
esta_(false) { esta_(false),
brightness_(Defaults::Brightness::ENEMIC) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("enemy_pentagon.shp"); forma_ = Graphics::ShapeLoader::load("enemy_pentagon.shp");
@@ -40,7 +42,10 @@ void Enemic::inicialitzar() {
// Calcular rangs segurs amb radi de l'enemic // Calcular rangs segurs amb radi de l'enemic
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS, Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS,
min_x, max_x, min_y, max_y); min_x,
max_x,
min_y,
max_y);
// Spawn aleatori dins dels límits segurs // Spawn aleatori dins dels límits segurs
int range_x = static_cast<int>(max_x - min_x); int range_x = static_cast<int>(max_x - min_x);
@@ -76,7 +81,7 @@ void Enemic::actualitzar(float delta_time) {
void Enemic::dibuixar() const { void Enemic::dibuixar() const {
if (esta_ && forma_) { if (esta_ && forma_) {
// [NUEVO] Usar render_shape en lloc de rota_pol // [NUEVO] Usar render_shape en lloc de rota_pol
Rendering::render_shape(renderer_, forma_, centre_, rotacio_, 1.0f, true); Rendering::render_shape(renderer_, forma_, centre_, rotacio_, 1.0f, true, 1.0f, brightness_);
} }
} }
@@ -102,7 +107,10 @@ void Enemic::mou(float delta_time) {
// Obtenir límits segurs compensant el radi de l'enemic // Obtenir límits segurs compensant el radi de l'enemic
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS, Constants::obtenir_limits_zona_segurs(Defaults::Entities::ENEMY_RADIUS,
min_x, max_x, min_y, max_y); min_x,
max_x,
min_y,
max_y);
// Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament // Lògica Pascal: Actualitza Y si dins, sinó ajusta angle aleatòriament
// if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy) // if (dy>marge_dalt) and (dy<marge_baix) then orni.centre.y:=round(Dy)

View File

@@ -34,11 +34,12 @@ class Enemic {
// [NUEVO] Estat de la instància (separat de la geometria) // [NUEVO] Estat de la instància (separat de la geometria)
Punt centre_; Punt centre_;
float angle_; // Angle de moviment float angle_; // Angle de moviment
float velocitat_; float velocitat_;
float drotacio_; // Delta rotació visual (rad/s) float drotacio_; // Delta rotació visual (rad/s)
float rotacio_; // Rotació visual acumulada float rotacio_; // Rotació visual acumulada
bool esta_; bool esta_;
float brightness_; // Factor de brillantor (0.0-1.0)
void mou(float delta_time); void mou(float delta_time);
}; };

View File

@@ -19,7 +19,8 @@ Nau::Nau(SDL_Renderer* renderer)
centre_({0.0f, 0.0f}), centre_({0.0f, 0.0f}),
angle_(0.0f), angle_(0.0f),
velocitat_(0.0f), velocitat_(0.0f),
esta_tocada_(false) { esta_tocada_(false),
brightness_(Defaults::Brightness::NAU) {
// [NUEVO] Carregar forma compartida des de fitxer // [NUEVO] Carregar forma compartida des de fitxer
forma_ = Graphics::ShapeLoader::load("ship.shp"); forma_ = Graphics::ShapeLoader::load("ship.shp");
@@ -106,7 +107,7 @@ void Nau::dibuixar() const {
float velocitat_visual = velocitat_ / 33.33f; float velocitat_visual = velocitat_ / 33.33f;
float escala = 1.0f + (velocitat_visual / 12.0f); float escala = 1.0f + (velocitat_visual / 12.0f);
Rendering::render_shape(renderer_, forma_, centre_, angle_, escala, true); Rendering::render_shape(renderer_, forma_, centre_, angle_, escala, true, 1.0f, brightness_);
} }
void Nau::aplicar_fisica(float delta_time) { void Nau::aplicar_fisica(float delta_time) {
@@ -127,7 +128,10 @@ void Nau::aplicar_fisica(float delta_time) {
// CORRECCIÓ: Usar límits segurs i inequalitats inclusives // CORRECCIÓ: Usar límits segurs i inequalitats inclusives
float min_x, max_x, min_y, max_y; float min_x, max_x, min_y, max_y;
Constants::obtenir_limits_zona_segurs(Defaults::Entities::SHIP_RADIUS, Constants::obtenir_limits_zona_segurs(Defaults::Entities::SHIP_RADIUS,
min_x, max_x, min_y, max_y); min_x,
max_x,
min_y,
max_y);
// Inequalitats inclusives (>= i <=) // Inequalitats inclusives (>= i <=)
if (dy >= min_y && dy <= max_y) { if (dy >= min_y && dy <= max_y) {

View File

@@ -38,9 +38,10 @@ class Nau {
// [NUEVO] Estat de la instància (separat de la geometria) // [NUEVO] Estat de la instància (separat de la geometria)
Punt centre_; Punt centre_;
float angle_; // Angle d'orientació float angle_; // Angle d'orientació
float velocitat_; // Velocitat (px/s) float velocitat_; // Velocitat (px/s)
bool esta_tocada_; bool esta_tocada_;
float brightness_; // Factor de brillantor (0.0-1.0)
void aplicar_fisica(float delta_time); void aplicar_fisica(float delta_time);
}; };

View File

@@ -10,6 +10,7 @@
#include <iostream> #include <iostream>
#include <vector> #include <vector>
#include "../../core/audio/audio.hpp"
#include "../../core/rendering/line_renderer.hpp" #include "../../core/rendering/line_renderer.hpp"
#include "../../core/system/gestor_escenes.hpp" #include "../../core/system/gestor_escenes.hpp"
#include "../../core/system/global_events.hpp" #include "../../core/system/global_events.hpp"
@@ -73,6 +74,9 @@ void EscenaJoc::executar() {
// Actualitzar física del joc amb delta_time real // Actualitzar física del joc amb delta_time real
actualitzar(delta_time); actualitzar(delta_time);
// Actualitzar sistema d'audio
Audio::update();
// Actualitzar colors oscil·lats // Actualitzar colors oscil·lats
sdl_.updateColors(delta_time); sdl_.updateColors(delta_time);
@@ -289,11 +293,11 @@ void EscenaJoc::detectar_col·lisions_bales_enemics() {
// 2. Crear explosió de fragments // 2. Crear explosió de fragments
debris_manager_.explotar( debris_manager_.explotar(
enemic.get_forma(), // Forma vectorial del pentàgon enemic.get_forma(), // Forma vectorial del pentàgon
pos_enemic, // Posició central pos_enemic, // Posició central
0.0f, // Angle (enemic té rotació interna) 0.0f, // Angle (enemic té rotació interna)
1.0f, // Escala normal 1.0f, // Escala normal
VELOCITAT_EXPLOSIO // 50 px/s (explosió suau) VELOCITAT_EXPLOSIO // 50 px/s (explosió suau)
); );
// 3. Desactivar bala // 3. Desactivar bala

View File

@@ -50,8 +50,8 @@ class EscenaJoc {
// Funcions privades // Funcions privades
void tocado(); void tocado();
void detectar_col·lisions_bales_enemics(); // Col·lisions bala-enemic void detectar_col·lisions_bales_enemics(); // Col·lisions bala-enemic
void dibuixar_marges() const; // Dibuixar vores de la zona de joc void dibuixar_marges() const; // Dibuixar vores de la zona de joc
void dibuixar_marcador(); // Dibuixar marcador de puntuació void dibuixar_marcador(); // Dibuixar marcador de puntuació
}; };
#endif // ESCENA_JOC_HPP #endif // ESCENA_JOC_HPP

View File

@@ -6,11 +6,14 @@
#include <algorithm> #include <algorithm>
#include <cfloat> #include <cfloat>
#include <iostream> #include <iostream>
#include <random>
#include <set>
#include "../../core/graphics/shape_loader.hpp" #include "core/audio/audio.hpp"
#include "../../core/rendering/shape_renderer.hpp" #include "core/graphics/shape_loader.hpp"
#include "../../core/system/gestor_escenes.hpp" #include "core/rendering/shape_renderer.hpp"
#include "../../core/system/global_events.hpp" #include "core/system/gestor_escenes.hpp"
#include "core/system/global_events.hpp"
// Helper: calcular el progrés individual d'una lletra // Helper: calcular el progrés individual d'una lletra
// en funció del progrés global (efecte seqüencial) // en funció del progrés global (efecte seqüencial)
@@ -42,6 +45,7 @@ EscenaLogo::EscenaLogo(SDLManager& sdl)
lletra_explosio_index_(0), lletra_explosio_index_(0),
temps_des_ultima_explosio_(0.0f) { temps_des_ultima_explosio_(0.0f) {
std::cout << "Escena Logo: Inicialitzant...\n"; std::cout << "Escena Logo: Inicialitzant...\n";
so_reproduit_.fill(false); // Inicialitzar seguiment de sons
inicialitzar_lletres(); inicialitzar_lletres();
} }
@@ -179,6 +183,15 @@ void EscenaLogo::canviar_estat(EstatAnimacio nou_estat) {
if (nou_estat == EstatAnimacio::EXPLOSION) { if (nou_estat == EstatAnimacio::EXPLOSION) {
lletra_explosio_index_ = 0; lletra_explosio_index_ = 0;
temps_des_ultima_explosio_ = 0.0f; temps_des_ultima_explosio_ = 0.0f;
// Generar ordre aleatori d'explosions
ordre_explosio_.clear();
for (size_t i = 0; i < lletres_.size(); i++) {
ordre_explosio_.push_back(i);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(ordre_explosio_.begin(), ordre_explosio_.end(), g);
} }
std::cout << "[EscenaLogo] Canvi a estat: " << static_cast<int>(nou_estat) std::cout << "[EscenaLogo] Canvi a estat: " << static_cast<int>(nou_estat)
@@ -196,8 +209,9 @@ void EscenaLogo::actualitzar_explosions(float delta_time) {
// Comprovar si és el moment d'explotar la següent lletra // Comprovar si és el moment d'explotar la següent lletra
if (temps_des_ultima_explosio_ >= DELAY_ENTRE_EXPLOSIONS) { if (temps_des_ultima_explosio_ >= DELAY_ENTRE_EXPLOSIONS) {
if (lletra_explosio_index_ < lletres_.size()) { if (lletra_explosio_index_ < lletres_.size()) {
// Explotar lletra actual // Explotar lletra actual (en ordre aleatori)
const auto& lletra = lletres_[lletra_explosio_index_]; size_t index_actual = ordre_explosio_[lletra_explosio_index_];
const auto& lletra = lletres_[index_actual];
debris_manager_->explotar( debris_manager_->explotar(
lletra.forma, // Forma a explotar lletra.forma, // Forma a explotar
@@ -229,11 +243,31 @@ void EscenaLogo::actualitzar(float delta_time) {
} }
break; break;
case EstatAnimacio::ANIMATION: case EstatAnimacio::ANIMATION: {
// Reproduir so per cada lletra quan comença a aparèixer
float global_progress = std::min(temps_estat_actual_ / DURACIO_ZOOM, 1.0f);
for (size_t i = 0; i < lletres_.size() && i < so_reproduit_.size(); i++) {
if (!so_reproduit_[i]) {
float letra_progress = calcular_progress_letra(
i,
lletres_.size(),
global_progress,
THRESHOLD_LETRA);
// Reproduir so quan la lletra comença a aparèixer (progress > 0)
if (letra_progress > 0.0f) {
Audio::get()->playSound("logo.wav", Audio::Group::INTERFACE);
so_reproduit_[i] = true;
}
}
}
if (totes_lletres_completes()) { if (totes_lletres_completes()) {
canviar_estat(EstatAnimacio::POST_ANIMATION); canviar_estat(EstatAnimacio::POST_ANIMATION);
} }
break; break;
}
case EstatAnimacio::POST_ANIMATION: case EstatAnimacio::POST_ANIMATION:
if (temps_estat_actual_ >= DURACIO_POST_ANIMATION) { if (temps_estat_actual_ >= DURACIO_POST_ANIMATION) {
@@ -247,7 +281,7 @@ void EscenaLogo::actualitzar(float delta_time) {
case EstatAnimacio::POST_EXPLOSION: case EstatAnimacio::POST_EXPLOSION:
if (temps_estat_actual_ >= DURACIO_POST_EXPLOSION) { if (temps_estat_actual_ >= DURACIO_POST_EXPLOSION) {
GestorEscenes::actual = GestorEscenes::Escena::JOC; GestorEscenes::actual = GestorEscenes::Escena::TITOL;
} }
break; break;
} }
@@ -313,17 +347,26 @@ void EscenaLogo::dibuixar() {
// EXPLOSION: Dibuixar només lletres que encara no han explotat // EXPLOSION: Dibuixar només lletres que encara no han explotat
if (estat_actual_ == EstatAnimacio::EXPLOSION) { if (estat_actual_ == EstatAnimacio::EXPLOSION) {
for (size_t i = lletra_explosio_index_; i < lletres_.size(); i++) { // Crear conjunt de lletres ja explotades
const auto& lletra = lletres_[i]; std::set<size_t> explotades;
for (size_t i = 0; i < lletra_explosio_index_; i++) {
explotades.insert(ordre_explosio_[i]);
}
Rendering::render_shape( // Dibuixar només lletres que NO han explotat
sdl_.obte_renderer(), for (size_t i = 0; i < lletres_.size(); i++) {
lletra.forma, if (explotades.find(i) == explotades.end()) {
lletra.posicio, const auto& lletra = lletres_[i];
0.0f,
ESCALA_FINAL, Rendering::render_shape(
true, sdl_.obte_renderer(),
1.0f); lletra.forma,
lletra.posicio,
0.0f,
ESCALA_FINAL,
true,
1.0f);
}
} }
} }
@@ -336,9 +379,9 @@ void EscenaLogo::dibuixar() {
} }
void EscenaLogo::processar_events(const SDL_Event& event) { void EscenaLogo::processar_events(const SDL_Event& event) {
// Qualsevol tecla o clic de ratolí salta al joc // Qualsevol tecla o clic de ratolí salta a la pantalla de títol
if (event.type == SDL_EVENT_KEY_DOWN || if (event.type == SDL_EVENT_KEY_DOWN ||
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) { event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
GestorEscenes::actual = GestorEscenes::Escena::JOC; GestorEscenes::actual = GestorEscenes::Escena::TITOL;
} }
} }

View File

@@ -39,8 +39,9 @@ class EscenaLogo {
std::unique_ptr<Effects::DebrisManager> debris_manager_; std::unique_ptr<Effects::DebrisManager> debris_manager_;
// Seguiment d'explosions seqüencials // Seguiment d'explosions seqüencials
size_t lletra_explosio_index_; // Índex de la següent lletra a explotar size_t lletra_explosio_index_; // Índex de la següent lletra a explotar
float temps_des_ultima_explosio_; // Temps des de l'última explosió float temps_des_ultima_explosio_; // Temps des de l'última explosió
std::vector<size_t> ordre_explosio_; // Ordre aleatori d'índexs de lletres
// Estructura per a cada lletra del logo // Estructura per a cada lletra del logo
struct LetraLogo { struct LetraLogo {
@@ -52,20 +53,23 @@ class EscenaLogo {
std::vector<LetraLogo> lletres_; // 9 lletres: J-A-I-L-G-A-M-E-S std::vector<LetraLogo> lletres_; // 9 lletres: J-A-I-L-G-A-M-E-S
// Seguiment de sons de lletres (evitar reproduccions repetides)
std::array<bool, 9> so_reproduit_; // Track si cada lletra ja ha reproduit el so
// Constants d'animació // Constants d'animació
static constexpr float DURACIO_PRE = 1.5f; // Duració PRE_ANIMATION (pantalla negra) static constexpr float DURACIO_PRE = 1.5f; // Duració PRE_ANIMATION (pantalla negra)
static constexpr float DURACIO_ZOOM = 4.0f; // Duració del zoom (segons) static constexpr float DURACIO_ZOOM = 4.0f; // Duració del zoom (segons)
static constexpr float DURACIO_POST_ANIMATION = 3.0f; // Duració POST_ANIMATION (logo complet) static constexpr float DURACIO_POST_ANIMATION = 3.0f; // Duració POST_ANIMATION (logo complet)
static constexpr float DURACIO_POST_EXPLOSION = 3.0f; // Duració POST_EXPLOSION (espera final) static constexpr float DURACIO_POST_EXPLOSION = 3.0f; // Duració POST_EXPLOSION (espera final)
static constexpr float DELAY_ENTRE_EXPLOSIONS = 0.15f; // Temps entre explosions de lletres static constexpr float DELAY_ENTRE_EXPLOSIONS = 0.1f; // Temps entre explosions de lletres
static constexpr float VELOCITAT_EXPLOSIO = 80.0f; // Velocitat base fragments (px/s) static constexpr float VELOCITAT_EXPLOSIO = 240.0f; // Velocitat base fragments (px/s)
static constexpr float ESCALA_INICIAL = 0.1f; // Escala inicial (10%) static constexpr float ESCALA_INICIAL = 0.1f; // Escala inicial (10%)
static constexpr float ESCALA_FINAL = 0.8f; // Escala final (80%) static constexpr float ESCALA_FINAL = 0.8f; // Escala final (80%)
static constexpr float ESPAI_ENTRE_LLETRES = 10.0f; // Espaiat entre lletres static constexpr float ESPAI_ENTRE_LLETRES = 10.0f; // Espaiat entre lletres
// Constants d'animació seqüencial // Constants d'animació seqüencial
static constexpr float THRESHOLD_LETRA = 0.6f; // Umbral per activar següent lletra (0.0-1.0) static constexpr float THRESHOLD_LETRA = 0.6f; // Umbral per activar següent lletra (0.0-1.0)
static constexpr float ORIGEN_ZOOM_X = Defaults::Game::WIDTH * 0.5f; // Punt inicial X del zoom static constexpr float ORIGEN_ZOOM_X = Defaults::Game::WIDTH * 0.5f; // Punt inicial X del zoom
static constexpr float ORIGEN_ZOOM_Y = Defaults::Game::HEIGHT * 0.4f; // Punt inicial Y del zoom static constexpr float ORIGEN_ZOOM_Y = Defaults::Game::HEIGHT * 0.4f; // Punt inicial Y del zoom
// Mètodes privats // Mètodes privats

View File

@@ -0,0 +1,176 @@
// escena_titol.cpp - Implementació de l'escena de títol
// © 2025 Port a C++20
#include "escena_titol.hpp"
#include <iostream>
#include <string>
#include "../../core/audio/audio.hpp"
#include "../../core/system/gestor_escenes.hpp"
#include "../../core/system/global_events.hpp"
#include "build/project.h"
EscenaTitol::EscenaTitol(SDLManager& sdl)
: sdl_(sdl),
text_(sdl.obte_renderer()),
estat_actual_(EstatTitol::INIT),
temps_acumulat_(0.0f) {
std::cout << "Escena Titol: Inicialitzant...\n";
// Crear starfield de fons
Punt centre_pantalla{
Defaults::Game::WIDTH / 2.0f,
Defaults::Game::HEIGHT / 2.0f};
SDL_FRect area_completa{
0, 0,
static_cast<float>(Defaults::Game::WIDTH),
static_cast<float>(Defaults::Game::HEIGHT)};
starfield_ = std::make_unique<Graphics::Starfield>(
sdl_.obte_renderer(),
centre_pantalla,
area_completa,
150 // densitat: 150 estrelles (50 per capa)
);
}
void EscenaTitol::executar() {
SDL_Event event;
Uint64 last_time = SDL_GetTicks();
while (GestorEscenes::actual == GestorEscenes::Escena::TITOL) {
// Calcular delta_time real
Uint64 current_time = SDL_GetTicks();
float delta_time = (current_time - last_time) / 1000.0f;
last_time = current_time;
// Limitar delta_time per evitar grans salts
if (delta_time > 0.05f) {
delta_time = 0.05f;
}
// Actualitzar comptador de FPS
sdl_.updateFPS(delta_time);
// Processar events SDL
while (SDL_PollEvent(&event)) {
// Manejo de finestra
if (sdl_.handleWindowEvent(event)) {
continue;
}
// Events globals (F1/F2/F3/F4/ESC/QUIT)
if (GlobalEvents::handle(event, sdl_)) {
continue;
}
// Processar events de l'escena
processar_events(event);
}
// Actualitzar lògica
actualitzar(delta_time);
// Actualitzar sistema d'audio
Audio::update();
// Actualitzar colors oscil·lats
sdl_.updateColors(delta_time);
// Netejar pantalla
sdl_.neteja(0, 0, 0);
// Dibuixar
dibuixar();
// Presentar renderer (swap buffers)
sdl_.presenta();
}
std::cout << "Escena Titol: Finalitzant...\n";
}
void EscenaTitol::actualitzar(float delta_time) {
// Actualitzar starfield (sempre actiu)
if (starfield_) {
starfield_->actualitzar(delta_time);
}
switch (estat_actual_) {
case EstatTitol::INIT:
temps_acumulat_ += delta_time;
if (temps_acumulat_ >= DURACIO_INIT) {
estat_actual_ = EstatTitol::MAIN;
}
break;
case EstatTitol::MAIN:
// No hi ha lògica d'actualització en l'estat MAIN
break;
}
}
void EscenaTitol::dibuixar() {
// Dibuixar starfield de fons (sempre, en tots els estats)
if (starfield_) {
starfield_->dibuixar();
}
// En l'estat INIT, només mostrar starfield (sense text)
if (estat_actual_ == EstatTitol::INIT) {
return;
}
// Estat MAIN: Dibuixar text de títol i copyright (sobre el starfield)
if (estat_actual_ == EstatTitol::MAIN) {
// Text principal centrat (vertical i horitzontalment)
const std::string main_text = "PRESS BUTTON TO PLAY";
const float escala_main = 1.0f;
const float spacing = 2.0f;
float text_width = text_.get_text_width(main_text, escala_main, spacing);
float text_height = text_.get_text_height(escala_main);
float x_center = (Defaults::Game::WIDTH - text_width) / 2.0f;
float y_center = (Defaults::Game::HEIGHT - text_height) / 2.0f;
text_.render(main_text, Punt{x_center, y_center}, escala_main, spacing);
// Copyright a la part inferior (centrat horitzontalment)
// Convert to uppercase since VectorText only supports A-Z
std::string copyright = Project::COPYRIGHT;
for (char& c : copyright) {
if (c >= 'a' && c <= 'z') {
c = c - 32; // Convert to uppercase
}
}
const float escala_copy = 0.6f;
float copy_width = text_.get_text_width(copyright, escala_copy, spacing);
float copy_height = text_.get_text_height(escala_copy);
float x_copy = (Defaults::Game::WIDTH - copy_width) / 2.0f;
float y_copy = Defaults::Game::HEIGHT - copy_height - 20.0f; // 20px des del fons
text_.render(copyright, Punt{x_copy, y_copy}, escala_copy, spacing);
}
}
void EscenaTitol::processar_events(const SDL_Event& event) {
// Qualsevol tecla o clic de ratolí
if (event.type == SDL_EVENT_KEY_DOWN ||
event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
switch (estat_actual_) {
case EstatTitol::INIT:
// Saltar a MAIN
estat_actual_ = EstatTitol::MAIN;
break;
case EstatTitol::MAIN:
// Anar al joc
GestorEscenes::actual = GestorEscenes::Escena::JOC;
break;
}
}
}

View File

@@ -0,0 +1,41 @@
// escena_titol.hpp - Pantalla de títol del joc
// Mostra missatge "PRESS BUTTON TO PLAY" i copyright
// © 2025 Port a C++20
#pragma once
#include <SDL3/SDL.h>
#include <memory>
#include "../../core/graphics/starfield.hpp"
#include "../../core/graphics/vector_text.hpp"
#include "../../core/rendering/sdl_manager.hpp"
#include "core/defaults.hpp"
class EscenaTitol {
public:
explicit EscenaTitol(SDLManager& sdl);
void executar(); // Bucle principal de l'escena
private:
// Màquina d'estats per la pantalla de títol
enum class EstatTitol {
INIT, // Pantalla negra inicial (2 segons)
MAIN // Pantalla de títol amb text
};
SDLManager& sdl_;
Graphics::VectorText text_; // Sistema de text vectorial
std::unique_ptr<Graphics::Starfield> starfield_; // Camp d'estrelles de fons
EstatTitol estat_actual_; // Estat actual de la màquina
float temps_acumulat_; // Temps acumulat per l'estat INIT
// Constants
static constexpr float DURACIO_INIT = 2.0f; // Duració de l'estat INIT (2 segons)
// Mètodes privats
void actualitzar(float delta_time);
void dibuixar();
void processar_events(const SDL_Event& event);
};

View File

@@ -22,7 +22,7 @@ void init() {
window.width = Defaults::Window::WIDTH; window.width = Defaults::Window::WIDTH;
window.height = Defaults::Window::HEIGHT; window.height = Defaults::Window::HEIGHT;
window.fullscreen = false; window.fullscreen = false;
window.size_increment = Defaults::Window::SIZE_INCREMENT; window.zoom_factor = Defaults::Window::BASE_ZOOM;
// Physics // Physics
physics.rotation_speed = Defaults::Physics::ROTATION_SPEED; physics.rotation_speed = Defaults::Physics::ROTATION_SPEED;
@@ -39,6 +39,14 @@ void init() {
// Rendering // Rendering
rendering.vsync = Defaults::Rendering::VSYNC_DEFAULT; rendering.vsync = Defaults::Rendering::VSYNC_DEFAULT;
// Audio
audio.enabled = Defaults::Audio::ENABLED;
audio.volume = Defaults::Audio::VOLUME;
audio.music.enabled = Defaults::Music::ENABLED;
audio.music.volume = Defaults::Music::VOLUME;
audio.sound.enabled = Defaults::Sound::ENABLED;
audio.sound.volume = Defaults::Sound::VOLUME;
// Version // Version
version = std::string(Project::VERSION); version = std::string(Project::VERSION);
} }
@@ -82,14 +90,19 @@ static void loadWindowConfigFromYaml(const fkyaml::node& yaml) {
} }
} }
if (win.contains("size_increment")) { if (win.contains("zoom_factor")) {
try { try {
auto val = win["size_increment"].get_value<int>(); auto val = win["zoom_factor"].get_value<float>();
window.size_increment = window.zoom_factor = (val >= Defaults::Window::MIN_ZOOM && val <= 10.0f)
(val > 0) ? val : Defaults::Window::SIZE_INCREMENT; ? val
: Defaults::Window::BASE_ZOOM;
} catch (...) { } catch (...) {
window.size_increment = Defaults::Window::SIZE_INCREMENT; window.zoom_factor = Defaults::Window::BASE_ZOOM;
} }
} else {
// Legacy config: infer zoom from width
window.zoom_factor = static_cast<float>(window.width) / Defaults::Window::WIDTH;
window.zoom_factor = std::max(Defaults::Window::MIN_ZOOM, window.zoom_factor);
} }
} }
} }
@@ -200,6 +213,71 @@ static void loadRenderingConfigFromYaml(const fkyaml::node& yaml) {
} }
} }
static void loadAudioConfigFromYaml(const fkyaml::node& yaml) {
if (yaml.contains("audio")) {
const auto& aud = yaml["audio"];
if (aud.contains("enabled")) {
try {
audio.enabled = aud["enabled"].get_value<bool>();
} catch (...) {
audio.enabled = Defaults::Audio::ENABLED;
}
}
if (aud.contains("volume")) {
try {
float val = aud["volume"].get_value<float>();
audio.volume = (val >= 0.0f && val <= 1.0f) ? val : Defaults::Audio::VOLUME;
} catch (...) {
audio.volume = Defaults::Audio::VOLUME;
}
}
if (aud.contains("music")) {
const auto& mus = aud["music"];
if (mus.contains("enabled")) {
try {
audio.music.enabled = mus["enabled"].get_value<bool>();
} catch (...) {
audio.music.enabled = Defaults::Music::ENABLED;
}
}
if (mus.contains("volume")) {
try {
float val = mus["volume"].get_value<float>();
audio.music.volume = (val >= 0.0f && val <= 1.0f) ? val : Defaults::Music::VOLUME;
} catch (...) {
audio.music.volume = Defaults::Music::VOLUME;
}
}
}
if (aud.contains("sound")) {
const auto& snd = aud["sound"];
if (snd.contains("enabled")) {
try {
audio.sound.enabled = snd["enabled"].get_value<bool>();
} catch (...) {
audio.sound.enabled = Defaults::Sound::ENABLED;
}
}
if (snd.contains("volume")) {
try {
float val = snd["volume"].get_value<float>();
audio.sound.volume = (val >= 0.0f && val <= 1.0f) ? val : Defaults::Sound::VOLUME;
} catch (...) {
audio.sound.volume = Defaults::Sound::VOLUME;
}
}
}
}
}
// Carregar configuració des del fitxer YAML // Carregar configuració des del fitxer YAML
auto loadFromFile() -> bool { auto loadFromFile() -> bool {
const std::string CONFIG_VERSION = std::string(Project::VERSION); const std::string CONFIG_VERSION = std::string(Project::VERSION);
@@ -246,6 +324,7 @@ auto loadFromFile() -> bool {
loadPhysicsConfigFromYaml(yaml); loadPhysicsConfigFromYaml(yaml);
loadGameplayConfigFromYaml(yaml); loadGameplayConfigFromYaml(yaml);
loadRenderingConfigFromYaml(yaml); loadRenderingConfigFromYaml(yaml);
loadAudioConfigFromYaml(yaml);
if (console) { if (console) {
std::cout << "Config carregada correctament des de: " << config_file_path std::cout << "Config carregada correctament des de: " << config_file_path
@@ -286,10 +365,10 @@ auto saveToFile() -> bool {
file << "# FINESTRA\n"; file << "# FINESTRA\n";
file << "window:\n"; file << "window:\n";
file << " width: " << window.width << "\n"; file << " width: " << window.width << " # Calculated from zoom_factor\n";
file << " height: " << window.height << "\n"; file << " height: " << window.height << " # Calculated from zoom_factor\n";
file << " fullscreen: " << (window.fullscreen ? "true" : "false") << "\n"; file << " fullscreen: " << (window.fullscreen ? "true" : "false") << "\n";
file << " size_increment: " << window.size_increment << "\n\n"; file << " zoom_factor: " << window.zoom_factor << " # 0.5x-max (0.1 increments)\n\n";
file << "# FÍSICA (tots els valors en px/s, rad/s, etc.)\n"; file << "# FÍSICA (tots els valors en px/s, rad/s, etc.)\n";
file << "physics:\n"; file << "physics:\n";
@@ -309,7 +388,18 @@ auto saveToFile() -> bool {
file << "# RENDERITZACIÓ\n"; file << "# RENDERITZACIÓ\n";
file << "rendering:\n"; file << "rendering:\n";
file << " vsync: " << rendering.vsync << " # 0=disabled, 1=enabled\n"; file << " vsync: " << rendering.vsync << " # 0=disabled, 1=enabled\n\n";
file << "# AUDIO\n";
file << "audio:\n";
file << " enabled: " << (audio.enabled ? "true" : "false") << "\n";
file << " volume: " << audio.volume << " # 0.0 to 1.0\n";
file << " music:\n";
file << " enabled: " << (audio.music.enabled ? "true" : "false") << "\n";
file << " volume: " << audio.music.volume << " # 0.0 to 1.0\n";
file << " sound:\n";
file << " enabled: " << (audio.sound.enabled ? "true" : "false") << "\n";
file << " volume: " << audio.sound.volume << " # 0.0 to 1.0\n";
file.close(); file.close();

View File

@@ -10,7 +10,7 @@ struct Window {
int width{640}; int width{640};
int height{480}; int height{480};
bool fullscreen{false}; bool fullscreen{false};
int size_increment{100}; // Increment per F1/F2 float zoom_factor{1.0f}; // Zoom level (0.5x to max_zoom)
}; };
struct Physics { struct Physics {
@@ -31,6 +31,23 @@ struct Rendering {
int vsync{1}; // 0=disabled, 1=enabled int vsync{1}; // 0=disabled, 1=enabled
}; };
struct Music {
bool enabled{true};
float volume{0.8f};
};
struct Sound {
bool enabled{true};
float volume{1.0f};
};
struct Audio {
Music music{};
Sound sound{};
bool enabled{true};
float volume{1.0f};
};
// Variables globals (inline per evitar ODR violations) // Variables globals (inline per evitar ODR violations)
inline std::string version{}; // Versió del config per validació inline std::string version{}; // Versió del config per validació
@@ -39,6 +56,7 @@ inline Window window{};
inline Physics physics{}; inline Physics physics{};
inline Gameplay gameplay{}; inline Gameplay gameplay{};
inline Rendering rendering{}; inline Rendering rendering{};
inline Audio audio{};
inline std::string config_file_path{}; // Establert per setConfigFile() inline std::string config_file_path{}; // Establert per setConfigFile()

View File

@@ -12,3 +12,4 @@ ORNI TODO:
- Crear progresion: fichero con enemigos para ese nivel. cuando se acaba la lista de niveles -> loop con dificultad aumentada. Pensar si jefe final. Juego no tiene fin - Crear progresion: fichero con enemigos para ese nivel. cuando se acaba la lista de niveles -> loop con dificultad aumentada. Pensar si jefe final. Juego no tiene fin
- Menu de servicio? numero de vidas, numero de continues o free play, controles de audio, controles de video, colores, activar parpadeo o cambiar frecuencia - Menu de servicio? numero de vidas, numero de continues o free play, controles de audio, controles de video, colores, activar parpadeo o cambiar frecuencia
- Cuando se destruye un enemigo, salen dos mas pequeños - Cuando se destruye un enemigo, salen dos mas pequeños
- El escalado de pantalla hace cosas raras al salir de full screen: permite ventanas no-4:3