Subsistema d'àudio: port de ../aee/core/audio refactoritzat amb namespace Ja, desacoblat d'Options via Audio::Config i extensió de Resource::Cache per preloading de música i sons; pyramid_1.ogg sona a GameScene (v0.15.0)
This commit is contained in:
1 parent
6f3fafbfff
commit
e2b8d0e459
16 files changed
+6796
-5
No files matched your search
@@ -0,0 +1,213 @@
|
||||
#include "core/audio/audio.hpp"
|
||||
|
||||
#include <SDL3/SDL.h> // Para SDL_GetError, SDL_Init
|
||||
|
||||
#include <algorithm> // Para clamp
|
||||
#include <iostream> // Para std::cout
|
||||
|
||||
// Implementació de stb_vorbis (ha d'anar ABANS d'incloure jail_audio.hpp).
|
||||
// clang-format off
|
||||
#undef STB_VORBIS_HEADER_ONLY
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include)
|
||||
#include "external/stb_vorbis.c"
|
||||
// stb_vorbis.c filtra les macros L, C i R (i PLAYBACK_*) al TU. Les netegem
|
||||
// perquè xocarien amb noms de paràmetres de plantilla en altres headers.
|
||||
#undef L
|
||||
#undef C
|
||||
#undef R
|
||||
#undef PLAYBACK_MONO
|
||||
#undef PLAYBACK_LEFT
|
||||
#undef PLAYBACK_RIGHT
|
||||
// clang-format on
|
||||
|
||||
#include "core/audio/audio_adapter.hpp" // Para AudioResource::getMusic/getSound
|
||||
#include "core/audio/jail_audio.hpp" // Para Ja::* (engine jailgames)
|
||||
|
||||
// Singleton
|
||||
std::unique_ptr<Audio> Audio::instance;
|
||||
|
||||
// Inicialitza la instància única del singleton amb la configuració rebuda
|
||||
void Audio::init(const Config& config) { Audio::instance = std::unique_ptr<Audio>(new Audio(config)); }
|
||||
|
||||
// Libera la instancia
|
||||
void Audio::destroy() { Audio::instance.reset(); }
|
||||
|
||||
// Obtiene la instancia
|
||||
auto Audio::get() -> Audio* { return Audio::instance.get(); }
|
||||
|
||||
// Constructor
|
||||
Audio::Audio(const Config& config)
|
||||
: config_(config) { initSDLAudio(); }
|
||||
|
||||
// Destructor
|
||||
Audio::~Audio() {
|
||||
Ja::quit();
|
||||
}
|
||||
|
||||
// Método principal
|
||||
void Audio::update() {
|
||||
Ja::update();
|
||||
|
||||
// Sincronitzar estat: detectar quan la música s'ha parat (p. ex. fade-out completat)
|
||||
if (instance && instance->music_.state == MusicState::PLAYING && Ja::getMusicState() != Ja::MusicState::PLAYING) {
|
||||
instance->music_.state = MusicState::STOPPED;
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduce la música por nombre (con crossfade opcional)
|
||||
void Audio::playMusic(const std::string& name, const int loop, const int crossfade_ms) {
|
||||
const bool NEW_LOOP = (loop != 0);
|
||||
|
||||
// Si ja sona exactament la mateixa pista i mateix mode loop, no fem res
|
||||
if (music_.state == MusicState::PLAYING && music_.name == name && music_.loop == NEW_LOOP) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!music_enabled_) { return; }
|
||||
|
||||
auto* resource = AudioResource::getMusic(name);
|
||||
if (resource == nullptr) { return; }
|
||||
|
||||
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
||||
Ja::crossfadeMusic(resource, crossfade_ms, loop);
|
||||
} else {
|
||||
if (music_.state == MusicState::PLAYING) {
|
||||
Ja::stopMusic();
|
||||
}
|
||||
Ja::playMusic(resource, loop);
|
||||
}
|
||||
|
||||
music_.name = name;
|
||||
music_.loop = NEW_LOOP;
|
||||
music_.state = MusicState::PLAYING;
|
||||
}
|
||||
|
||||
// Reproduce la música por puntero (con crossfade opcional)
|
||||
void Audio::playMusic(Ja::Music* music, const int loop, const int crossfade_ms) {
|
||||
if (!music_enabled_ || music == nullptr) { return; }
|
||||
|
||||
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
||||
Ja::crossfadeMusic(music, crossfade_ms, loop);
|
||||
} else {
|
||||
if (music_.state == MusicState::PLAYING) {
|
||||
Ja::stopMusic();
|
||||
}
|
||||
Ja::playMusic(music, loop);
|
||||
}
|
||||
|
||||
music_.name.clear(); // nom desconegut quan es passa per punter
|
||||
music_.loop = (loop != 0);
|
||||
music_.state = MusicState::PLAYING;
|
||||
}
|
||||
|
||||
// Pausa la música
|
||||
void Audio::pauseMusic() {
|
||||
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||
Ja::pauseMusic();
|
||||
music_.state = MusicState::PAUSED;
|
||||
}
|
||||
}
|
||||
|
||||
// Continua la música pausada
|
||||
void Audio::resumeMusic() {
|
||||
if (music_enabled_ && music_.state == MusicState::PAUSED) {
|
||||
Ja::resumeMusic();
|
||||
music_.state = MusicState::PLAYING;
|
||||
}
|
||||
}
|
||||
|
||||
// Detiene la música
|
||||
void Audio::stopMusic() {
|
||||
if (music_enabled_) {
|
||||
Ja::stopMusic();
|
||||
music_.state = MusicState::STOPPED;
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduce un sonido por nombre
|
||||
void Audio::playSound(const std::string& name, Group group) const {
|
||||
if (sound_enabled_) {
|
||||
Ja::playSound(AudioResource::getSound(name), 0, static_cast<int>(group));
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduce un sonido por puntero directo
|
||||
void Audio::playSound(Ja::Sound* sound, Group group) const {
|
||||
if (sound_enabled_ && sound != nullptr) {
|
||||
Ja::playSound(sound, 0, static_cast<int>(group));
|
||||
}
|
||||
}
|
||||
|
||||
// Detiene todos los sonidos
|
||||
void Audio::stopAllSounds() const {
|
||||
if (sound_enabled_) {
|
||||
Ja::stopChannel(-1);
|
||||
}
|
||||
}
|
||||
|
||||
// Realiza un fundido de salida de la música
|
||||
void Audio::fadeOutMusic(int milliseconds) const {
|
||||
if (music_enabled_ && getRealMusicState() == MusicState::PLAYING) {
|
||||
Ja::fadeOutMusic(milliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
// Consulta directament l'estat real de la música a jail_audio
|
||||
auto Audio::getRealMusicState() -> MusicState {
|
||||
const Ja::MusicState JA_STATE = Ja::getMusicState();
|
||||
switch (JA_STATE) {
|
||||
case Ja::MusicState::PLAYING:
|
||||
return MusicState::PLAYING;
|
||||
case Ja::MusicState::PAUSED:
|
||||
return MusicState::PAUSED;
|
||||
case Ja::MusicState::STOPPED:
|
||||
case Ja::MusicState::INVALID:
|
||||
case Ja::MusicState::DISABLED:
|
||||
default:
|
||||
return MusicState::STOPPED;
|
||||
}
|
||||
}
|
||||
|
||||
// Estableix el volum dels sons (float 0.0..1.0)
|
||||
void Audio::setSoundVolume(float sound_volume, Group group) const {
|
||||
sound_volume = std::clamp(sound_volume, MIN_VOLUME, MAX_VOLUME);
|
||||
const bool ACTIVE = enabled_ && sound_enabled_;
|
||||
const float CONVERTED_VOLUME = ACTIVE ? sound_volume * config_.volume : 0.0F;
|
||||
Ja::setSoundVolume(CONVERTED_VOLUME, static_cast<int>(group));
|
||||
}
|
||||
|
||||
// Estableix el volum de la música (float 0.0..1.0)
|
||||
void Audio::setMusicVolume(float music_volume) const {
|
||||
music_volume = std::clamp(music_volume, MIN_VOLUME, MAX_VOLUME);
|
||||
const bool ACTIVE = enabled_ && music_enabled_;
|
||||
const float CONVERTED_VOLUME = ACTIVE ? music_volume * config_.volume : 0.0F;
|
||||
Ja::setMusicVolume(CONVERTED_VOLUME);
|
||||
}
|
||||
|
||||
// Aplica una nova configuració (substitueix la cache i reaplica enables/volums)
|
||||
void Audio::applySettings(const Config& config) {
|
||||
config_ = config;
|
||||
sound_enabled_ = config_.sound_enabled;
|
||||
music_enabled_ = config_.music_enabled;
|
||||
enable(config_.enabled);
|
||||
}
|
||||
|
||||
// Estableix l'estat general
|
||||
void Audio::enable(bool value) {
|
||||
enabled_ = value;
|
||||
|
||||
setSoundVolume(enabled_ ? config_.sound_volume : MIN_VOLUME);
|
||||
setMusicVolume(enabled_ ? config_.music_volume : MIN_VOLUME);
|
||||
}
|
||||
|
||||
// Inicialitza SDL Audio
|
||||
void Audio::initSDLAudio() {
|
||||
if (!SDL_Init(SDL_INIT_AUDIO)) {
|
||||
std::cout << "SDL_AUDIO could not initialize! SDL Error: " << SDL_GetError() << '\n';
|
||||
} else {
|
||||
Ja::init(FREQUENCY, SDL_AUDIO_S16LE, 2);
|
||||
sound_enabled_ = config_.sound_enabled;
|
||||
music_enabled_ = config_.music_enabled;
|
||||
enable(config_.enabled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#pragma once
|
||||
|
||||
#include <cmath> // Para std::lround
|
||||
#include <cstdint> // Para int8_t, uint8_t
|
||||
#include <memory> // Para std::unique_ptr
|
||||
#include <string> // Para string
|
||||
#include <utility> // Para move
|
||||
|
||||
// Forward-declares per no incloure core/audio/jail_audio.hpp al header (conté
|
||||
// l'engine complet de streaming amb stb_vorbis).
|
||||
namespace Ja {
|
||||
struct Music;
|
||||
struct Sound;
|
||||
} // namespace Ja
|
||||
|
||||
// --- Clase Audio: gestor de audio (singleton) ---
|
||||
// Port del subsistema d'àudio del projecte ../aee, desacoblat d'Options:
|
||||
// la configuració entra per la struct Audio::Config a init()/applySettings(),
|
||||
// en lloc de llegir directament Options::audio. Això deixa audio.cpp independent
|
||||
// del layout d'Options i permet substituir la font de configuració.
|
||||
//
|
||||
// Els volums es manegen internament com a float 0.0–1.0; la capa de
|
||||
// presentació (menús, notificacions) usa les helpers toPercent/fromPercent
|
||||
// per mostrar 0–100 a l'usuari.
|
||||
class Audio {
|
||||
public:
|
||||
// --- Configuració injectada (Options la construeix via buildAudioConfig) ---
|
||||
struct Config {
|
||||
bool enabled{true};
|
||||
float volume{1.0F}; // Master 0..1
|
||||
bool music_enabled{true};
|
||||
float music_volume{0.8F};
|
||||
bool sound_enabled{true};
|
||||
float sound_volume{1.0F};
|
||||
};
|
||||
|
||||
// --- Enums ---
|
||||
enum class Group : std::int8_t {
|
||||
ALL = -1, // Todos los grupos
|
||||
GAME = 0, // Sonidos del juego
|
||||
INTERFACE = 1 // Sonidos de la interfaz
|
||||
};
|
||||
|
||||
enum class MusicState : std::uint8_t {
|
||||
PLAYING, // Reproduciendo música
|
||||
PAUSED, // Música pausada
|
||||
STOPPED, // Música detenida
|
||||
};
|
||||
|
||||
// --- Constantes ---
|
||||
static constexpr float MAX_VOLUME = 1.0F; // Volumen máximo (float 0..1)
|
||||
static constexpr float MIN_VOLUME = 0.0F; // Volumen mínimo (float 0..1)
|
||||
static constexpr float VOLUME_STEP = 0.05F; // Pas estàndard per a UI (5%)
|
||||
static constexpr int FREQUENCY = 48000; // Frecuencia de audio
|
||||
static constexpr int DEFAULT_CROSSFADE_MS = 1500; // Duració del crossfade per defecte (ms)
|
||||
|
||||
// --- Singleton ---
|
||||
static void init(const Config& config); // Inicialitza amb la configuració rebuda
|
||||
static void destroy(); // Libera el objeto Audio
|
||||
static auto get() -> Audio*; // Obtiene el puntero al objeto Audio
|
||||
~Audio(); // Destructor (públic per a std::unique_ptr)
|
||||
Audio(const Audio&) = delete; // Evitar copia
|
||||
Audio(Audio&&) = delete;
|
||||
auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación
|
||||
auto operator=(Audio&&) -> Audio& = delete;
|
||||
|
||||
static void update(); // Actualización del sistema de audio
|
||||
|
||||
// --- Control de música ---
|
||||
void playMusic(const std::string& name, int loop = -1, int crossfade_ms = 0); // Reproducir música por nombre (con crossfade opcional)
|
||||
void playMusic(Ja::Music* music, int loop = -1, int crossfade_ms = 0); // Reproducir música por puntero (con crossfade opcional)
|
||||
void pauseMusic(); // Pausar reproducción de música
|
||||
void resumeMusic(); // Continua la música pausada
|
||||
void stopMusic(); // Detener completamente la música
|
||||
void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música
|
||||
|
||||
// --- Control de sonidos ---
|
||||
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual por nombre
|
||||
void playSound(Ja::Sound* sound, Group group = Group::GAME) const; // Reproducir sonido puntual por puntero
|
||||
void stopAllSounds() const; // Detener todos los sonidos
|
||||
|
||||
// --- Control de volumen (API interna: float 0.0..1.0) ---
|
||||
void setSoundVolume(float volume, Group group = Group::ALL) const; // Ajustar volumen de efectos
|
||||
void setMusicVolume(float volume) const; // Ajustar volumen de música
|
||||
|
||||
// --- Helpers de conversió per a la capa de presentació ---
|
||||
// UI (menús, notificacions) manega enters 0..100; internament viu float 0..1.
|
||||
// No són constexpr perquè std::lround no ho és en C++20; s'usen en runtime.
|
||||
static auto toPercent(float volume) -> int {
|
||||
return static_cast<int>(std::lround(volume * 100.0F));
|
||||
}
|
||||
static auto fromPercent(int percent) -> float {
|
||||
return static_cast<float>(percent) / 100.0F;
|
||||
}
|
||||
|
||||
// --- Configuración general ---
|
||||
void enable(bool value); // Establecer estado general
|
||||
void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general
|
||||
void applySettings(const Config& config); // Aplica una nova configuració
|
||||
|
||||
// --- Configuración de sonidos ---
|
||||
void enableSound() { sound_enabled_ = true; } // Habilitar sonidos
|
||||
void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos
|
||||
void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos
|
||||
void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos
|
||||
|
||||
// --- Configuración de música ---
|
||||
void enableMusic() { music_enabled_ = true; } // Habilitar música
|
||||
void disableMusic() { music_enabled_ = false; } // Deshabilitar música
|
||||
void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música
|
||||
void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música
|
||||
|
||||
// --- Consultas de estado ---
|
||||
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
|
||||
[[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; }
|
||||
[[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; }
|
||||
[[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; }
|
||||
[[nodiscard]] static auto getRealMusicState() -> MusicState;
|
||||
[[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; }
|
||||
|
||||
private:
|
||||
// --- Tipos anidados ---
|
||||
struct Music {
|
||||
MusicState state{MusicState::STOPPED}; // Estado actual de la música
|
||||
std::string name; // Última pista de música reproducida
|
||||
bool loop{false}; // Indica si se reproduce en bucle
|
||||
};
|
||||
|
||||
// --- Métodos ---
|
||||
explicit Audio(const Config& config); // Constructor privat: rep la config
|
||||
void initSDLAudio(); // Inicializa SDL Audio
|
||||
|
||||
// --- Variables miembro ---
|
||||
static std::unique_ptr<Audio> instance; // Instància única d'Audio
|
||||
|
||||
Config config_{}; // Configuració injectada (volums, enables)
|
||||
Music music_; // Estado de la música
|
||||
bool enabled_{true}; // Estado general del audio
|
||||
bool sound_enabled_{true}; // Estado de los efectos de sonido
|
||||
bool music_enabled_{true}; // Estado de la música
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
#include "core/audio/audio_adapter.hpp"
|
||||
|
||||
#include "core/resources/resource_cache.hpp"
|
||||
|
||||
namespace AudioResource {
|
||||
|
||||
auto getMusic(const std::string& name) -> Ja::Music* {
|
||||
return Resource::Cache::get().getMusic(name);
|
||||
}
|
||||
|
||||
auto getSound(const std::string& name) -> Ja::Sound* {
|
||||
return Resource::Cache::get().getSound(name);
|
||||
}
|
||||
|
||||
} // namespace AudioResource
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
// --- Audio Resource Adapter ---
|
||||
// Aquest fitxer exposa una interfície comuna a Audio per obtenir Ja::Music* /
|
||||
// Ja::Sound* per nom. Cada projecte la implementa en audio_adapter.cpp delegant
|
||||
// al seu singleton de recursos (Resource::Cache::get(), ...). Així audio.hpp
|
||||
// i audio.cpp es poden compartir entre projectes.
|
||||
|
||||
#include <string> // Para string
|
||||
|
||||
namespace Ja {
|
||||
struct Music;
|
||||
struct Sound;
|
||||
} // namespace Ja
|
||||
|
||||
namespace AudioResource {
|
||||
auto getMusic(const std::string& name) -> Ja::Music*;
|
||||
auto getSound(const std::string& name) -> Ja::Sound*;
|
||||
} // namespace AudioResource
|
||||
@@ -0,0 +1,677 @@
|
||||
#pragma once
|
||||
|
||||
// --- Includes ---
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// clang-format off
|
||||
#define STB_VORBIS_HEADER_ONLY
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include)
|
||||
#include "external/stb_vorbis.c" // Para stb_vorbis_open_memory i streaming
|
||||
// clang-format on
|
||||
|
||||
// Deleter stateless per a buffers reservats amb `SDL_malloc` / `SDL_LoadWAV*`.
|
||||
// Compatible amb `std::unique_ptr<Uint8[], SdlFreeDeleter>` — zero size overhead
|
||||
// gràcies a EBO, igual que un unique_ptr amb default_delete.
|
||||
struct SdlFreeDeleter {
|
||||
void operator()(Uint8* p) const noexcept {
|
||||
if (p != nullptr) { SDL_free(p); }
|
||||
}
|
||||
};
|
||||
|
||||
// Engine de baix nivell d'àudio del projecte jailgames: streaming OGG (stb_vorbis)
|
||||
// + N canals d'efectes (SDL3 audio). No depèn d'Options ni de cap singleton del
|
||||
// joc; només de SDL3 i stb_vorbis. La capa superior (Audio) li passa recursos
|
||||
// pel punter i fa el bookkeeping d'usuari.
|
||||
namespace Ja {
|
||||
|
||||
// --- Public Enums ---
|
||||
enum class ChannelState : std::uint8_t {
|
||||
INVALID,
|
||||
FREE,
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
SOUND_DISABLED,
|
||||
};
|
||||
|
||||
enum class MusicState : std::uint8_t {
|
||||
INVALID,
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
STOPPED,
|
||||
DISABLED,
|
||||
};
|
||||
|
||||
// --- Struct Definitions ---
|
||||
inline constexpr int MAX_SIMULTANEOUS_CHANNELS = 20;
|
||||
inline constexpr int MAX_GROUPS = 2;
|
||||
|
||||
struct Sound {
|
||||
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
||||
Uint32 length{0};
|
||||
// Buffer descomprimit (PCM) propietat del sound. Reservat per SDL_LoadWAV
|
||||
// via SDL_malloc; el deleter `SdlFreeDeleter` allibera amb SDL_free.
|
||||
std::unique_ptr<Uint8[], SdlFreeDeleter> buffer;
|
||||
};
|
||||
|
||||
// L'ordre (punters primer, ints després, enum de 8 bits al final) minimitza
|
||||
// el padding a 64-bit (evita avisos de clang-analyzer-optin.performance.Padding).
|
||||
struct Channel {
|
||||
Sound* sound{nullptr};
|
||||
SDL_AudioStream* stream{nullptr};
|
||||
int pos{0};
|
||||
int times{0};
|
||||
int group{0};
|
||||
ChannelState state{ChannelState::FREE};
|
||||
};
|
||||
|
||||
struct Music {
|
||||
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
||||
|
||||
// OGG comprimit en memòria. Propietat nostra; es copia des del buffer
|
||||
// d'entrada una sola vegada en loadMusic i es descomprimix en chunks
|
||||
// per streaming. Com que stb_vorbis guarda un punter persistent al
|
||||
// `.data()` d'aquest vector, no el podem resize'jar un cop establert
|
||||
// (una reallocation invalidaria el punter que el decoder conserva).
|
||||
std::vector<Uint8> ogg_data;
|
||||
stb_vorbis* vorbis{nullptr}; // handle del decoder, viu tot el cicle del Music
|
||||
|
||||
std::string filename;
|
||||
|
||||
int times{0}; // loops restants (-1 = infinit, 0 = un sol play)
|
||||
SDL_AudioStream* stream{nullptr};
|
||||
MusicState state{MusicState::INVALID};
|
||||
};
|
||||
|
||||
// --- Crossfade / Fade State ---
|
||||
struct FadeState {
|
||||
bool active{false};
|
||||
Uint64 start_time{0};
|
||||
int duration_ms{0};
|
||||
float initial_volume{0.0F};
|
||||
};
|
||||
|
||||
struct OutgoingMusic {
|
||||
SDL_AudioStream* stream{nullptr};
|
||||
FadeState fade;
|
||||
};
|
||||
|
||||
// --- Internal Global State (inline, C++17) ---
|
||||
inline Music* current_music{nullptr};
|
||||
inline Channel channels[MAX_SIMULTANEOUS_CHANNELS];
|
||||
|
||||
inline SDL_AudioSpec audio_spec{SDL_AUDIO_S16, 2, 48000};
|
||||
inline float music_volume{1.0F};
|
||||
inline float sound_volume[MAX_GROUPS];
|
||||
inline bool music_enabled{true};
|
||||
inline bool sound_enabled{true};
|
||||
inline SDL_AudioDeviceID sdl_audio_device{0};
|
||||
|
||||
inline OutgoingMusic outgoing_music;
|
||||
inline FadeState incoming_fade;
|
||||
|
||||
// --- Forward Declarations ---
|
||||
inline void stopMusic();
|
||||
inline void stopChannel(int channel);
|
||||
inline auto playSoundOnChannel(Sound* sound, int channel, int loop = 0, int group = 0) -> int;
|
||||
inline void crossfadeMusic(Music* music, int crossfade_ms, int loop = -1);
|
||||
|
||||
// --- Music streaming internals ---
|
||||
// Bytes-per-sample per canal (sempre s16)
|
||||
inline constexpr int 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.
|
||||
inline constexpr int 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.
|
||||
inline constexpr float 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 auto feedMusicChunk(Music* music) -> int {
|
||||
if (music == nullptr || music->vorbis == nullptr || music->stream == nullptr) { return 0; }
|
||||
|
||||
short chunk[MUSIC_CHUNK_SHORTS];
|
||||
const int NUM_CHANNELS = music->spec.channels;
|
||||
const int SAMPLES_PER_CHANNEL = stb_vorbis_get_samples_short_interleaved(
|
||||
music->vorbis,
|
||||
NUM_CHANNELS,
|
||||
static_cast<short*>(chunk),
|
||||
MUSIC_CHUNK_SHORTS);
|
||||
if (SAMPLES_PER_CHANNEL <= 0) { return 0; }
|
||||
|
||||
const int BYTES = SAMPLES_PER_CHANNEL * NUM_CHANNELS * MUSIC_BYTES_PER_SAMPLE;
|
||||
SDL_PutAudioStreamData(music->stream, static_cast<const void*>(chunk), BYTES);
|
||||
return SAMPLES_PER_CHANNEL;
|
||||
}
|
||||
|
||||
// Reompli l'stream fins que tinga ≥ MUSIC_LOW_WATER_SECONDS bufferats.
|
||||
// En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
|
||||
inline void pumpMusic(Music* music) {
|
||||
if (music == nullptr || music->vorbis == nullptr || music->stream == nullptr) { return; }
|
||||
|
||||
const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
|
||||
const int LOW_WATER_BYTES = static_cast<int>(MUSIC_LOW_WATER_SECONDS * static_cast<float>(BYTES_PER_SECOND));
|
||||
|
||||
while (SDL_GetAudioStreamAvailable(music->stream) < LOW_WATER_BYTES) {
|
||||
const int DECODED = 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-carrega `duration_ms` de so dins l'stream actual abans que l'stream
|
||||
// siga robat per outgoing_music (crossfade o fade-out). Imprescindible amb
|
||||
// streaming: l'stream robat no es pot re-alimentar perquè perd la referència
|
||||
// al seu vorbis decoder. No aplica loop — si el vorbis s'esgota abans, parem.
|
||||
inline void preFillOutgoing(Music* music, int duration_ms) {
|
||||
if (music == nullptr || music->vorbis == nullptr || music->stream == nullptr) { return; }
|
||||
|
||||
const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
|
||||
const int NEEDED_BYTES = static_cast<int>((static_cast<std::int64_t>(duration_ms) * BYTES_PER_SECOND) / 1000);
|
||||
|
||||
while (SDL_GetAudioStreamAvailable(music->stream) < NEEDED_BYTES) {
|
||||
const int DECODED = feedMusicChunk(music);
|
||||
if (DECODED <= 0) { break; } // EOF: deixem drenar el que hi haja
|
||||
}
|
||||
}
|
||||
|
||||
// --- Core Functions ---
|
||||
|
||||
// Avança el fade-out de l'outgoing music (crossfade o fade-out a silenci).
|
||||
inline void updateOutgoingFade() {
|
||||
if (outgoing_music.stream == nullptr || !outgoing_music.fade.active) { return; }
|
||||
|
||||
const Uint64 ELAPSED = SDL_GetTicks() - outgoing_music.fade.start_time;
|
||||
if (ELAPSED >= static_cast<Uint64>(outgoing_music.fade.duration_ms)) {
|
||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||
outgoing_music.stream = nullptr;
|
||||
outgoing_music.fade.active = false;
|
||||
} else {
|
||||
const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(outgoing_music.fade.duration_ms);
|
||||
SDL_SetAudioStreamGain(outgoing_music.stream, outgoing_music.fade.initial_volume * (1.0F - PERCENT));
|
||||
}
|
||||
}
|
||||
|
||||
// Avança el fade-in de la pista actual (si hi ha un crossfade en curs).
|
||||
inline void updateIncomingFade() {
|
||||
if (!incoming_fade.active) { return; }
|
||||
|
||||
const Uint64 ELAPSED = SDL_GetTicks() - incoming_fade.start_time;
|
||||
if (ELAPSED >= static_cast<Uint64>(incoming_fade.duration_ms)) {
|
||||
incoming_fade.active = false;
|
||||
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||
} else {
|
||||
const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(incoming_fade.duration_ms);
|
||||
SDL_SetAudioStreamGain(current_music->stream, music_volume * PERCENT);
|
||||
}
|
||||
}
|
||||
|
||||
// Alimenta la pista actual i la para si s'ha esgotat el stream vorbis.
|
||||
inline void updateCurrentMusic() {
|
||||
if (!music_enabled || current_music == nullptr || current_music->state != MusicState::PLAYING) { return; }
|
||||
|
||||
updateIncomingFade();
|
||||
|
||||
pumpMusic(current_music);
|
||||
if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
|
||||
stopMusic();
|
||||
}
|
||||
}
|
||||
|
||||
// Reompli (si cal loop) o para els canals d'efectes actius.
|
||||
inline void updateSoundChannels() {
|
||||
if (!sound_enabled) { return; }
|
||||
|
||||
for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; ++i) {
|
||||
if (channels[i].state != ChannelState::PLAYING) { continue; }
|
||||
|
||||
if (channels[i].times != 0) {
|
||||
if (static_cast<Uint32>(SDL_GetAudioStreamAvailable(channels[i].stream)) < (channels[i].sound->length / 2)) {
|
||||
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer.get(), channels[i].sound->length);
|
||||
if (channels[i].times > 0) { channels[i].times--; }
|
||||
}
|
||||
} else if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) {
|
||||
stopChannel(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void update() {
|
||||
updateOutgoingFade();
|
||||
updateCurrentMusic();
|
||||
updateSoundChannels();
|
||||
}
|
||||
|
||||
inline void init(const int freq, const SDL_AudioFormat format, const int num_channels) {
|
||||
audio_spec = {.format = format, .channels = num_channels, .freq = freq};
|
||||
if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
|
||||
sdl_audio_device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_spec);
|
||||
if (sdl_audio_device == 0) { std::cout << "Failed to initialize SDL audio!" << '\n'; }
|
||||
for (auto& channel : channels) { channel.state = ChannelState::FREE; }
|
||||
std::ranges::fill(sound_volume, 0.5F);
|
||||
}
|
||||
|
||||
inline void quit() {
|
||||
if (outgoing_music.stream != nullptr) {
|
||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||
outgoing_music.stream = nullptr;
|
||||
}
|
||||
if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
|
||||
sdl_audio_device = 0;
|
||||
}
|
||||
|
||||
// --- Music Functions ---
|
||||
|
||||
inline auto loadMusic(const Uint8* buffer, Uint32 length) -> Music* {
|
||||
if (buffer == nullptr || length == 0) { return nullptr; }
|
||||
|
||||
// Allocem el Music primer per aprofitar el seu `std::vector<Uint8>`
|
||||
// com a propietari del OGG comprimit. stb_vorbis guarda un punter
|
||||
// persistent al buffer; com que ací no el resize'jem, el .data() és
|
||||
// estable durant tot el cicle de vida del music.
|
||||
auto music = std::make_unique<Music>();
|
||||
music->ogg_data.assign(buffer, buffer + length);
|
||||
|
||||
int vorbis_error = 0;
|
||||
music->vorbis = stb_vorbis_open_memory(music->ogg_data.data(),
|
||||
static_cast<int>(length),
|
||||
&vorbis_error,
|
||||
nullptr);
|
||||
if (music->vorbis == nullptr) {
|
||||
std::cout << "loadMusic: stb_vorbis_open_memory failed (error " << vorbis_error << ")" << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const stb_vorbis_info INFO = stb_vorbis_get_info(music->vorbis);
|
||||
music->spec.channels = static_cast<int>(INFO.channels);
|
||||
music->spec.freq = static_cast<int>(INFO.sample_rate);
|
||||
music->spec.format = SDL_AUDIO_S16;
|
||||
music->state = MusicState::STOPPED;
|
||||
|
||||
return music.release();
|
||||
}
|
||||
|
||||
// Overload amb filename — els callers l'usen per poder comparar la música
|
||||
// en curs amb getMusicFilename() i no rearrancar-la si ja és la mateixa.
|
||||
inline auto loadMusic(const Uint8* buffer, Uint32 length, const char* filename) -> Music* {
|
||||
Music* music = loadMusic(buffer, length);
|
||||
if (music != nullptr && filename != nullptr) { music->filename = filename; }
|
||||
return music;
|
||||
}
|
||||
|
||||
inline void playMusic(Music* music, const int loop = -1) {
|
||||
if (!music_enabled || music == nullptr || music->vorbis == nullptr) { return; }
|
||||
|
||||
stopMusic();
|
||||
|
||||
current_music = music;
|
||||
current_music->state = MusicState::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, &audio_spec);
|
||||
if (current_music->stream == nullptr) {
|
||||
std::cout << "Failed to create audio stream!" << '\n';
|
||||
current_music->state = MusicState::STOPPED;
|
||||
return;
|
||||
}
|
||||
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||
|
||||
// Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
|
||||
pumpMusic(current_music);
|
||||
|
||||
if (!SDL_BindAudioStream(sdl_audio_device, current_music->stream)) {
|
||||
std::cout << "[ERROR] SDL_BindAudioStream failed!" << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
inline auto getMusicFilename(const Music* music = nullptr) -> const char* {
|
||||
if (music == nullptr) { music = current_music; }
|
||||
if (music == nullptr || music->filename.empty()) { return nullptr; }
|
||||
return music->filename.c_str();
|
||||
}
|
||||
|
||||
inline void pauseMusic() {
|
||||
if (!music_enabled) { return; }
|
||||
if (current_music == nullptr || current_music->state != MusicState::PLAYING) { return; }
|
||||
|
||||
current_music->state = MusicState::PAUSED;
|
||||
SDL_UnbindAudioStream(current_music->stream);
|
||||
}
|
||||
|
||||
inline void resumeMusic() {
|
||||
if (!music_enabled) { return; }
|
||||
if (current_music == nullptr || current_music->state != MusicState::PAUSED) { return; }
|
||||
|
||||
current_music->state = MusicState::PLAYING;
|
||||
SDL_BindAudioStream(sdl_audio_device, current_music->stream);
|
||||
}
|
||||
|
||||
inline void stopMusic() {
|
||||
// Limpiar outgoing crossfade si existe
|
||||
if (outgoing_music.stream != nullptr) {
|
||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||
outgoing_music.stream = nullptr;
|
||||
outgoing_music.fade.active = false;
|
||||
}
|
||||
incoming_fade.active = false;
|
||||
|
||||
if (current_music == nullptr || current_music->state == MusicState::INVALID || current_music->state == MusicState::STOPPED) { return; }
|
||||
|
||||
current_music->state = MusicState::STOPPED;
|
||||
if (current_music->stream != nullptr) {
|
||||
SDL_DestroyAudioStream(current_music->stream);
|
||||
current_music->stream = nullptr;
|
||||
}
|
||||
// Deixem el handle de vorbis viu — es tanca en deleteMusic.
|
||||
// Rebobinem perquè un futur playMusic comence des del principi.
|
||||
if (current_music->vorbis != nullptr) {
|
||||
stb_vorbis_seek_start(current_music->vorbis);
|
||||
}
|
||||
}
|
||||
|
||||
inline void fadeOutMusic(const int milliseconds) {
|
||||
if (!music_enabled) { return; }
|
||||
if (current_music == nullptr || current_music->state != MusicState::PLAYING) { return; }
|
||||
|
||||
// Destruir outgoing anterior si existe
|
||||
if (outgoing_music.stream != nullptr) {
|
||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||
outgoing_music.stream = nullptr;
|
||||
}
|
||||
|
||||
// Pre-omplim l'stream amb `milliseconds` de so: un cop robat, ja no
|
||||
// tindrà accés al vorbis decoder i només podrà drenar el que tinga.
|
||||
preFillOutgoing(current_music, milliseconds);
|
||||
|
||||
// Robar el stream del current_music al outgoing
|
||||
outgoing_music.stream = current_music->stream;
|
||||
outgoing_music.fade = {
|
||||
.active = true,
|
||||
.start_time = SDL_GetTicks(),
|
||||
.duration_ms = milliseconds,
|
||||
.initial_volume = music_volume,
|
||||
};
|
||||
|
||||
// Dejar current_music sin stream (ya lo tiene outgoing)
|
||||
current_music->stream = nullptr;
|
||||
current_music->state = MusicState::STOPPED;
|
||||
if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
|
||||
incoming_fade.active = false;
|
||||
}
|
||||
|
||||
inline void crossfadeMusic(Music* music, const int crossfade_ms, const int loop) {
|
||||
if (!music_enabled || music == nullptr || music->vorbis == nullptr) { return; }
|
||||
|
||||
// Destruir outgoing anterior si existe (crossfade durante crossfade)
|
||||
if (outgoing_music.stream != nullptr) {
|
||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||
outgoing_music.stream = nullptr;
|
||||
outgoing_music.fade.active = false;
|
||||
}
|
||||
|
||||
// Robar el stream de la musica actual al outgoing para el fade-out.
|
||||
// Pre-omplim amb `crossfade_ms` de so perquè no es quede en silenci
|
||||
// abans d'acabar el fade (l'stream robat ja no pot alimentar-se).
|
||||
if (current_music != nullptr && current_music->state == MusicState::PLAYING && current_music->stream != nullptr) {
|
||||
preFillOutgoing(current_music, crossfade_ms);
|
||||
outgoing_music.stream = current_music->stream;
|
||||
outgoing_music.fade = {
|
||||
.active = true,
|
||||
.start_time = SDL_GetTicks(),
|
||||
.duration_ms = crossfade_ms,
|
||||
.initial_volume = music_volume,
|
||||
};
|
||||
current_music->stream = nullptr;
|
||||
current_music->state = MusicState::STOPPED;
|
||||
if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
|
||||
}
|
||||
|
||||
// Iniciar la nueva pista con gain=0 (el fade-in la sube gradualmente)
|
||||
current_music = music;
|
||||
current_music->state = MusicState::PLAYING;
|
||||
current_music->times = loop;
|
||||
|
||||
stb_vorbis_seek_start(current_music->vorbis);
|
||||
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &audio_spec);
|
||||
if (current_music->stream == nullptr) {
|
||||
std::cout << "Failed to create audio stream for crossfade!" << '\n';
|
||||
current_music->state = MusicState::STOPPED;
|
||||
return;
|
||||
}
|
||||
SDL_SetAudioStreamGain(current_music->stream, 0.0F);
|
||||
pumpMusic(current_music); // pre-carrega abans de bindejar
|
||||
SDL_BindAudioStream(sdl_audio_device, current_music->stream);
|
||||
|
||||
// Configurar fade-in
|
||||
incoming_fade = {
|
||||
.active = true,
|
||||
.start_time = SDL_GetTicks(),
|
||||
.duration_ms = crossfade_ms,
|
||||
.initial_volume = 0.0F,
|
||||
};
|
||||
}
|
||||
|
||||
inline auto getMusicState() -> MusicState {
|
||||
if (!music_enabled) { return MusicState::DISABLED; }
|
||||
if (current_music == nullptr) { return MusicState::INVALID; }
|
||||
|
||||
return current_music->state;
|
||||
}
|
||||
|
||||
inline void deleteMusic(Music* music) {
|
||||
if (music == nullptr) { return; }
|
||||
if (current_music == music) {
|
||||
stopMusic();
|
||||
current_music = nullptr;
|
||||
}
|
||||
if (music->stream != nullptr) { SDL_DestroyAudioStream(music->stream); }
|
||||
if (music->vorbis != nullptr) { stb_vorbis_close(music->vorbis); }
|
||||
// ogg_data (std::vector) i filename (std::string) s'alliberen sols
|
||||
// al destructor de Music.
|
||||
delete music;
|
||||
}
|
||||
|
||||
inline auto setMusicVolume(float volume) -> float {
|
||||
music_volume = SDL_clamp(volume, 0.0F, 1.0F);
|
||||
if (current_music != nullptr && current_music->stream != nullptr) {
|
||||
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||
}
|
||||
return music_volume;
|
||||
}
|
||||
|
||||
inline void setMusicPosition(float /*value*/) {
|
||||
// No implementat amb el backend de streaming.
|
||||
}
|
||||
|
||||
inline auto getMusicPosition() -> float {
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
inline void enableMusic(const bool value) {
|
||||
if (!value && current_music != nullptr && (current_music->state == MusicState::PLAYING)) { stopMusic(); }
|
||||
music_enabled = value;
|
||||
}
|
||||
|
||||
// --- Sound Functions ---
|
||||
|
||||
inline auto loadSound(std::uint8_t* buffer, std::uint32_t size) -> Sound* {
|
||||
auto sound = std::make_unique<Sound>();
|
||||
Uint8* raw = nullptr;
|
||||
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), true, &sound->spec, &raw, &sound->length)) {
|
||||
std::cout << "Failed to load WAV from memory: " << SDL_GetError() << '\n';
|
||||
return nullptr;
|
||||
}
|
||||
sound->buffer.reset(raw); // adopta el SDL_malloc'd buffer
|
||||
return sound.release();
|
||||
}
|
||||
|
||||
inline auto playSound(Sound* sound, const int loop = 0, const int group = 0) -> int {
|
||||
if (!sound_enabled || sound == nullptr) { return -1; }
|
||||
|
||||
int channel = 0;
|
||||
while (channel < MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != ChannelState::FREE) { channel++; }
|
||||
if (channel == MAX_SIMULTANEOUS_CHANNELS) {
|
||||
// No hay canal libre, reemplazamos el primero
|
||||
channel = 0;
|
||||
}
|
||||
|
||||
return playSoundOnChannel(sound, channel, loop, group);
|
||||
}
|
||||
|
||||
inline auto playSoundOnChannel(Sound* sound, const int channel, const int loop, const int group) -> int {
|
||||
if (!sound_enabled || sound == nullptr) { return -1; }
|
||||
if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return -1; }
|
||||
|
||||
stopChannel(channel);
|
||||
|
||||
channels[channel].sound = sound;
|
||||
channels[channel].times = loop;
|
||||
channels[channel].pos = 0;
|
||||
channels[channel].group = group;
|
||||
channels[channel].state = ChannelState::PLAYING;
|
||||
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &audio_spec);
|
||||
|
||||
if (channels[channel].stream == nullptr) {
|
||||
std::cout << "Failed to create audio stream for sound!" << '\n';
|
||||
channels[channel].state = ChannelState::FREE;
|
||||
return -1;
|
||||
}
|
||||
|
||||
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer.get(), channels[channel].sound->length);
|
||||
SDL_SetAudioStreamGain(channels[channel].stream, sound_volume[group]);
|
||||
SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
inline void deleteSound(Sound* sound) {
|
||||
if (sound == nullptr) { return; }
|
||||
for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||
if (channels[i].sound == sound) { stopChannel(i); }
|
||||
}
|
||||
// buffer es destrueix automàticament via RAII (SdlFreeDeleter).
|
||||
delete sound;
|
||||
}
|
||||
|
||||
inline void pauseChannel(const int channel) {
|
||||
if (!sound_enabled) { return; }
|
||||
|
||||
if (channel == -1) {
|
||||
for (auto& ch : channels) {
|
||||
if (ch.state == ChannelState::PLAYING) {
|
||||
ch.state = ChannelState::PAUSED;
|
||||
SDL_UnbindAudioStream(ch.stream);
|
||||
}
|
||||
}
|
||||
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state == ChannelState::PLAYING) {
|
||||
channels[channel].state = ChannelState::PAUSED;
|
||||
SDL_UnbindAudioStream(channels[channel].stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void resumeChannel(const int channel) {
|
||||
if (!sound_enabled) { return; }
|
||||
|
||||
if (channel == -1) {
|
||||
for (auto& ch : channels) {
|
||||
if (ch.state == ChannelState::PAUSED) {
|
||||
ch.state = ChannelState::PLAYING;
|
||||
SDL_BindAudioStream(sdl_audio_device, ch.stream);
|
||||
}
|
||||
}
|
||||
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state == ChannelState::PAUSED) {
|
||||
channels[channel].state = ChannelState::PLAYING;
|
||||
SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline void stopChannel(const int channel) {
|
||||
if (channel == -1) {
|
||||
for (auto& ch : channels) {
|
||||
if (ch.state != ChannelState::FREE) {
|
||||
if (ch.stream != nullptr) { SDL_DestroyAudioStream(ch.stream); }
|
||||
ch.stream = nullptr;
|
||||
ch.state = ChannelState::FREE;
|
||||
ch.pos = 0;
|
||||
ch.sound = nullptr;
|
||||
}
|
||||
}
|
||||
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||
if (channels[channel].state != ChannelState::FREE) {
|
||||
if (channels[channel].stream != nullptr) { SDL_DestroyAudioStream(channels[channel].stream); }
|
||||
channels[channel].stream = nullptr;
|
||||
channels[channel].state = ChannelState::FREE;
|
||||
channels[channel].pos = 0;
|
||||
channels[channel].sound = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline auto getChannelState(const int channel) -> ChannelState {
|
||||
if (!sound_enabled) { return ChannelState::SOUND_DISABLED; }
|
||||
if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return ChannelState::INVALID; }
|
||||
|
||||
return channels[channel].state;
|
||||
}
|
||||
|
||||
inline auto setSoundVolume(float volume, const int group = -1) -> float {
|
||||
const float V = SDL_clamp(volume, 0.0F, 1.0F);
|
||||
|
||||
if (group == -1) {
|
||||
std::ranges::fill(sound_volume, V);
|
||||
} else if (group >= 0 && group < MAX_GROUPS) {
|
||||
sound_volume[group] = V;
|
||||
} else {
|
||||
return V;
|
||||
}
|
||||
|
||||
// Aplicar volum als canals actius.
|
||||
for (auto& ch : channels) {
|
||||
if ((ch.state == ChannelState::PLAYING) || (ch.state == ChannelState::PAUSED)) {
|
||||
if (group == -1 || ch.group == group) {
|
||||
if (ch.stream != nullptr) {
|
||||
SDL_SetAudioStreamGain(ch.stream, sound_volume[ch.group]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return V;
|
||||
}
|
||||
|
||||
inline void enableSound(const bool value) {
|
||||
if (!value) {
|
||||
stopChannel(-1);
|
||||
}
|
||||
sound_enabled = value;
|
||||
}
|
||||
|
||||
inline auto setVolume(float volume) -> float {
|
||||
const float V = setMusicVolume(volume);
|
||||
setSoundVolume(V, -1);
|
||||
return V;
|
||||
}
|
||||
|
||||
} // namespace Ja
|
||||
@@ -4,10 +4,21 @@
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "core/audio/jail_audio.hpp"
|
||||
#include "core/resources/palette_loader.hpp"
|
||||
#include "core/resources/resource_helper.hpp"
|
||||
#include "utils/utils.hpp"
|
||||
|
||||
// Deleters dels recursos d'àudio: necessiten veure el tipus complet de
|
||||
// Ja::Music / Ja::Sound (definits a jail_audio.hpp), per això van ací.
|
||||
void MusicDeleter::operator()(Ja::Music* music) const noexcept {
|
||||
if (music != nullptr) { Ja::deleteMusic(music); }
|
||||
}
|
||||
|
||||
void SoundDeleter::operator()(Ja::Sound* sound) const noexcept {
|
||||
if (sound != nullptr) { Ja::deleteSound(sound); }
|
||||
}
|
||||
|
||||
namespace Resource {
|
||||
|
||||
auto Cache::get() -> Cache& {
|
||||
@@ -62,4 +73,53 @@ namespace Resource {
|
||||
return it->palette;
|
||||
}
|
||||
|
||||
void Cache::loadMusic(const std::string& name, const std::string& file_path) {
|
||||
auto bytes = Helper::loadFile(file_path);
|
||||
if (bytes.empty()) {
|
||||
throw std::runtime_error("Cache: cannot load music " + file_path);
|
||||
}
|
||||
Ja::Music* raw = Ja::loadMusic(bytes.data(), static_cast<Uint32>(bytes.size()), file_path.c_str());
|
||||
if (raw == nullptr) {
|
||||
throw std::runtime_error("Cache: Ja::loadMusic failed for " + file_path);
|
||||
}
|
||||
musics_.emplace_back(MusicResource{.name = name, .music = std::unique_ptr<Ja::Music, MusicDeleter>(raw)});
|
||||
printWithDots("Music : ", getFileName(file_path), "[ LOADED ]");
|
||||
}
|
||||
|
||||
void Cache::loadSound(const std::string& name, const std::string& file_path) {
|
||||
auto bytes = Helper::loadFile(file_path);
|
||||
if (bytes.empty()) {
|
||||
throw std::runtime_error("Cache: cannot load sound " + file_path);
|
||||
}
|
||||
Ja::Sound* raw = Ja::loadSound(bytes.data(), static_cast<std::uint32_t>(bytes.size()));
|
||||
if (raw == nullptr) {
|
||||
throw std::runtime_error("Cache: Ja::loadSound failed for " + file_path);
|
||||
}
|
||||
sounds_.emplace_back(SoundResource{.name = name, .sound = std::unique_ptr<Ja::Sound, SoundDeleter>(raw)});
|
||||
printWithDots("Sound : ", getFileName(file_path), "[ LOADED ]");
|
||||
}
|
||||
|
||||
auto Cache::getMusic(const std::string& name) -> Ja::Music* {
|
||||
auto it = std::ranges::find_if(musics_, [&name](const auto& m) { return m.name == name; });
|
||||
if (it == musics_.end()) {
|
||||
std::cerr << "Cache: music not found: " << name << '\n';
|
||||
throw std::runtime_error("Music not found: " + name);
|
||||
}
|
||||
return it->music.get();
|
||||
}
|
||||
|
||||
auto Cache::getSound(const std::string& name) -> Ja::Sound* {
|
||||
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) { return s.name == name; });
|
||||
if (it == sounds_.end()) {
|
||||
std::cerr << "Cache: sound not found: " << name << '\n';
|
||||
throw std::runtime_error("Sound not found: " + name);
|
||||
}
|
||||
return it->sound.get();
|
||||
}
|
||||
|
||||
void Cache::clearAudio() {
|
||||
musics_.clear();
|
||||
sounds_.clear();
|
||||
}
|
||||
|
||||
} // namespace Resource
|
||||
@@ -28,10 +28,24 @@ namespace Resource {
|
||||
// Carrega una paleta (.pal JASC o .gif) i la registra amb el nom donat.
|
||||
// Pensat per a paletes compartides (UI, fonts, tilesets reciclats).
|
||||
void loadPalette(const std::string& name, const std::string& file_path);
|
||||
// Carrega una pista OGG de música (streaming) i la registra amb el nom donat.
|
||||
void loadMusic(const std::string& name, const std::string& file_path);
|
||||
// Carrega un so WAV (descomprimit a memòria) i el registra amb el nom donat.
|
||||
void loadSound(const std::string& name, const std::string& file_path);
|
||||
|
||||
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
|
||||
auto getAnimationData(const std::string& name) -> const AnimationResource&;
|
||||
auto getPalette(const std::string& name) -> const Palette&;
|
||||
// Retornen el punter cru; l'ownership queda al Cache.
|
||||
auto getMusic(const std::string& name) -> Ja::Music*;
|
||||
auto getSound(const std::string& name) -> Ja::Sound*;
|
||||
|
||||
// Allibera explícitament música i sons. Cal cridar-la des de ~Director
|
||||
// ABANS de destruir Audio i de SDL_Quit(): com que el Cache és Meyers
|
||||
// i es destrueix a la sortida del programa, si esperem els seus
|
||||
// destructors els streams de SDL ja estarien invalidats i la deletion
|
||||
// de Ja::Music crashejaria.
|
||||
void clearAudio();
|
||||
|
||||
private:
|
||||
Cache() = default;
|
||||
@@ -40,6 +54,8 @@ namespace Resource {
|
||||
std::vector<SurfaceResource> surfaces_;
|
||||
std::vector<AnimationResource> animations_;
|
||||
std::vector<PaletteResource> palettes_;
|
||||
std::vector<MusicResource> musics_;
|
||||
std::vector<SoundResource> sounds_;
|
||||
};
|
||||
|
||||
} // namespace Resource
|
||||
@@ -7,6 +7,12 @@
|
||||
|
||||
#include "core/rendering/surface.hpp"
|
||||
|
||||
// Forward-declares per no incloure core/audio/jail_audio.hpp al header.
|
||||
namespace Ja {
|
||||
struct Music;
|
||||
struct Sound;
|
||||
} // namespace Ja
|
||||
|
||||
struct SurfaceResource {
|
||||
std::string name;
|
||||
std::shared_ptr<Surface> surface;
|
||||
@@ -21,3 +27,22 @@ struct PaletteResource {
|
||||
std::string name;
|
||||
Palette palette;
|
||||
};
|
||||
|
||||
// Deleters amb implementació al .cpp (fan delete de tipus incomplets ací).
|
||||
struct MusicDeleter {
|
||||
void operator()(Ja::Music* music) const noexcept;
|
||||
};
|
||||
|
||||
struct SoundDeleter {
|
||||
void operator()(Ja::Sound* sound) const noexcept;
|
||||
};
|
||||
|
||||
struct MusicResource {
|
||||
std::string name;
|
||||
std::unique_ptr<Ja::Music, MusicDeleter> music;
|
||||
};
|
||||
|
||||
struct SoundResource {
|
||||
std::string name;
|
||||
std::unique_ptr<Ja::Sound, SoundDeleter> sound;
|
||||
};
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/input/key_config.hpp"
|
||||
#include "core/locale/locale.hpp"
|
||||
#include "core/rendering/notifier.hpp"
|
||||
@@ -69,6 +70,15 @@ Director::Director() {
|
||||
Resource::Cache::get().loadSurface("8bithud.gif", "data/font/8bithud.gif");
|
||||
Resource::Cache::get().getSurface("8bithud.gif")->setPalette(Resource::Cache::get().getPalette("ui"));
|
||||
|
||||
// Música de la piràmide 1 (primer i únic track de moment). Carreguem ací
|
||||
// perquè forma part del preload d'assets, com la font i la paleta.
|
||||
Resource::Cache::get().loadMusic("pyramid_1.ogg", "data/music/pyramid_1.ogg");
|
||||
|
||||
// Audio: singleton manual propietari d'un SDL audio device. Es destrueix
|
||||
// explícitament a ~Director abans que Resource::Cache (Meyers) buide els
|
||||
// JA_Music_t que continga, així que no queden streams orfes.
|
||||
Audio::init(Options::buildAudioConfig());
|
||||
|
||||
RenderInfo::get().init();
|
||||
Notifier::get().init();
|
||||
|
||||
@@ -77,11 +87,16 @@ Director::Director() {
|
||||
}
|
||||
|
||||
Director::~Director() {
|
||||
// Ordre imprescindible: primer l'escena (pot tenir recursos), després
|
||||
// Screen (GPU device, finestra, subsystem de vídeo), i finalment SDL_Quit.
|
||||
// Fer-ho així -- NO via atexit -- evita crashes a vkDestroyInstance quan
|
||||
// el runtime desfà les llibreries abans que corren els destructors estàtics.
|
||||
// Ordre imprescindible: primer l'escena (pot tenir recursos); després
|
||||
// alliberem els recursos d'àudio del Cache mentre SDL encara està viu
|
||||
// (en Meyers, el Cache es destrueix després de SDL_Quit i els streams
|
||||
// dels JA_Music_t quedarien invalidats); després Audio (tanca l'audio
|
||||
// device), Screen (GPU + finestra) i finalment SDL_Quit. Fer-ho així --
|
||||
// NO via atexit -- evita crashes a vkDestroyInstance quan el runtime
|
||||
// desfà les llibreries abans que corren els destructors estàtics.
|
||||
current_scene_.reset();
|
||||
Resource::Cache::get().clearAudio();
|
||||
Audio::destroy();
|
||||
Screen::get().shutdown();
|
||||
SDL_Quit();
|
||||
}
|
||||
@@ -136,6 +151,7 @@ auto Director::iterate() -> SDL_AppResult {
|
||||
delta_ms = std::max(delta_ms, 0);
|
||||
last_ticks_ms_ = NOW_MS;
|
||||
|
||||
Audio::update();
|
||||
current_scene_->update(delta_ms);
|
||||
current_scene_->render();
|
||||
|
||||
|
||||
Vendored
+5584
File diff suppressed because it is too large.
Load diff
@@ -429,6 +429,17 @@ namespace Options {
|
||||
return config;
|
||||
}
|
||||
|
||||
auto buildAudioConfig() -> ::Audio::Config {
|
||||
return {
|
||||
.enabled = audio.enabled,
|
||||
.volume = audio.volume,
|
||||
.music_enabled = audio.music.enabled,
|
||||
.music_volume = audio.music.volume,
|
||||
.sound_enabled = audio.sound.enabled,
|
||||
.sound_volume = audio.sound.volume,
|
||||
};
|
||||
}
|
||||
|
||||
void setPostFXFile(const std::string& path) {
|
||||
postfx_file_path = path;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/rendering/screen.hpp"
|
||||
#include "core/rendering/shader_backend.hpp"
|
||||
#include "utils/defaults.hpp"
|
||||
@@ -120,5 +121,8 @@ namespace Options {
|
||||
[[nodiscard]] auto buildPostFXParams() -> Rendering::PostFXParams;
|
||||
[[nodiscard]] auto buildCrtPiParams() -> Rendering::CrtPiParams;
|
||||
[[nodiscard]] auto buildActiveShader() -> Rendering::ShaderType;
|
||||
// `::Audio` és la classe global d'àudio (no `Options::Audio`, que és la
|
||||
// struct serialitzable). Retornem la seua Config per passar-la a init().
|
||||
[[nodiscard]] auto buildAudioConfig() -> ::Audio::Config;
|
||||
|
||||
} // namespace Options
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <iterator>
|
||||
#include <vector>
|
||||
|
||||
#include "core/audio/audio.hpp"
|
||||
#include "core/input/global_inputs.hpp"
|
||||
#include "core/rendering/notifier.hpp"
|
||||
#include "core/rendering/render_info.hpp"
|
||||
@@ -42,6 +43,13 @@ GameScene::GameScene()
|
||||
constexpr auto SPAWN_X = CORRIDOR_CENTER_X - (static_cast<float>(Player::SPRITE_WIDTH) / 2.0F);
|
||||
constexpr auto SPAWN_Y = CORRIDOR_CENTER_Y - static_cast<float>(Player::COLLISION_Y_OFFSET) - (static_cast<float>(Player::COLLISION_SIZE) / 2.0F);
|
||||
players_.emplace_back(std::make_unique<Player>(SPAWN_X, SPAWN_Y, CONTROLS_P1));
|
||||
|
||||
// Música de fons de la piràmide 1 en bucle infinit. El track ja està al
|
||||
// Resource::Cache (preload al Director), així que playMusic només mou el
|
||||
// punter cap a jail_audio i obri l'stream.
|
||||
if (Audio::get() != nullptr) {
|
||||
Audio::get()->playMusic("pyramid_1.ogg", -1);
|
||||
}
|
||||
}
|
||||
|
||||
GameScene::~GameScene() = default;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace Texts {
|
||||
constexpr const char* WINDOW_TITLE = "© 2026 Aventures en Egipte — JailDesigner";
|
||||
constexpr const char* COPYRIGHT = "© 2026 JailDesigner";
|
||||
constexpr const char* VERSION = "0.14.0"; // Single source of truth — Makefile el grep
|
||||
constexpr const char* VERSION = "0.15.0"; // Single source of truth — Makefile el grep
|
||||
} // namespace Texts
|
||||
|
||||
namespace GameCanvas {
|
||||
|
||||
Reference in new issue
Block a user