diff --git a/source/audio.cpp b/source/audio.cpp index 5f5ce13..a55675a 100644 --- a/source/audio.cpp +++ b/source/audio.cpp @@ -32,6 +32,11 @@ Audio::~Audio() { #endif } +// Método principal +void Audio::update() { + JA_Update(); +} + // Reproduce la música void Audio::playMusic(const std::string &name, const int loop) { music_.name = name; diff --git a/source/audio.h b/source/audio.h index 3d4aa8a..05afd93 100644 --- a/source/audio.h +++ b/source/audio.h @@ -24,6 +24,9 @@ class Audio { Audio(const Audio &) = delete; // Evitar copia auto operator=(const Audio &) -> Audio & = delete; // Evitar asignación + // --- Método principal --- + void update(); + // --- Control de Música --- void playMusic(const std::string &name, int loop = -1); // Reproducir música en bucle void pauseMusic(); // Pausar reproducción de música diff --git a/source/external/jail_audio.cpp b/source/external/jail_audio.cpp index da7c848..477e520 100644 --- a/source/external/jail_audio.cpp +++ b/source/external/jail_audio.cpp @@ -1,135 +1,139 @@ #ifndef JA_USESDLMIXER #include "jail_audio.h" - -#include // Para SDL_AudioFormat, SDL_BindAudioStream, SDL_Se... -#include // Para uint32_t, uint8_t -#include // Para NULL, fseek, printf, fclose, fopen, fread -#include // Para free, malloc -#include // Para strcpy, strlen - -#include "stb_vorbis.h" // Para stb_vorbis_decode_memory +#include "stb_vorbis.h" +#include +#include #define JA_MAX_SIMULTANEOUS_CHANNELS 20 #define JA_MAX_GROUPS 2 -struct JA_Sound_t { - SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; - Uint32 length{0}; - Uint8 *buffer{NULL}; +struct JA_Sound_t +{ + SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; + Uint32 length { 0 }; + Uint8 *buffer { NULL }; }; -struct JA_Channel_t { - JA_Sound_t *sound{nullptr}; - int pos{0}; - int times{0}; - int group{0}; - SDL_AudioStream *stream{nullptr}; - JA_Channel_state state{JA_CHANNEL_FREE}; +struct JA_Channel_t +{ + JA_Sound_t *sound { nullptr }; + int pos { 0 }; + int times { 0 }; + int group { 0 }; + SDL_AudioStream *stream { nullptr }; + JA_Channel_state state { JA_CHANNEL_FREE }; }; -struct JA_Music_t { - SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000}; - Uint32 length{0}; - Uint8 *buffer{nullptr}; - char *filename{nullptr}; +struct JA_Music_t +{ + SDL_AudioSpec spec { SDL_AUDIO_S16, 2, 48000 }; + Uint32 length { 0 }; + Uint8 *buffer { nullptr }; + char *filename { nullptr }; - int pos{0}; - int times{0}; - SDL_AudioStream *stream{nullptr}; - JA_Music_state state{JA_MUSIC_INVALID}; + int pos { 0 }; + int times { 0 }; + SDL_AudioStream *stream { nullptr }; + JA_Music_state state { JA_MUSIC_INVALID }; }; -JA_Music_t *current_music{nullptr}; -JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; +JA_Music_t *current_music { nullptr }; +JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS]; -SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000}; -float JA_musicVolume{1.0f}; -float JA_soundVolume[JA_MAX_GROUPS]; -bool JA_musicEnabled{true}; -bool JA_soundEnabled{true}; -SDL_AudioDeviceID sdlAudioDevice{0}; -SDL_TimerID JA_timerID{0}; +SDL_AudioSpec JA_audioSpec { SDL_AUDIO_S16, 2, 48000 }; +float JA_musicVolume { 1.0f }; +float JA_soundVolume[JA_MAX_GROUPS]; +bool JA_musicEnabled { true }; +bool JA_soundEnabled { true }; +SDL_AudioDeviceID sdlAudioDevice { 0 }; +//SDL_TimerID JA_timerID { 0 }; bool fading = false; int fade_start_time; int fade_duration; int fade_initial_volume; -Uint32 JA_UpdateCallback(void *userdata, SDL_TimerID timerID, Uint32 interval) { - if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) { + +void JA_Update() +{ + if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) + { if (fading) { int time = SDL_GetTicks(); - if (time > (fade_start_time + fade_duration)) { + if (time > (fade_start_time+fade_duration)) { fading = false; JA_StopMusic(); - return 30; + return; } else { const int time_passed = time - fade_start_time; const float percent = (float)time_passed / (float)fade_duration; - SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume * (1.0 - percent)); + SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume*(1.0 - percent)); } } - if (current_music->times != 0) { - if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length / 2)) { + if (current_music->times != 0) + { + if ((Uint32)SDL_GetAudioStreamAvailable(current_music->stream) < (current_music->length/2)) { SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length); } - if (current_music->times > 0) - current_music->times--; - } else { - if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) - JA_StopMusic(); + if (current_music->times>0) current_music->times--; + } + else + { + if (SDL_GetAudioStreamAvailable(current_music->stream) == 0) JA_StopMusic(); } } - if (JA_soundEnabled) { - for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) - if (channels[i].state == JA_CHANNEL_PLAYING) { - if (channels[i].times != 0) { - if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) { + if (JA_soundEnabled) + { + for (int i=0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) + if (channels[i].state == JA_CHANNEL_PLAYING) + { + if (channels[i].times != 0) + { + if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length/2)) { SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer, channels[i].sound->length); - if (channels[i].times > 0) - channels[i].times--; + if (channels[i].times>0) channels[i].times--; } - } else { - if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) - JA_StopChannel(i); + } + else + { + if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i); } } + } - return 30; + return; } -void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) { -#ifdef _DEBUG +void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) +{ + #ifdef DEBUG SDL_SetLogPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_DEBUG); -#endif - + #endif + SDL_Log("Iniciant JailAudio..."); - JA_audioSpec = {format, num_channels, freq}; - if (!sdlAudioDevice) - SDL_CloseAudioDevice(sdlAudioDevice); + JA_audioSpec = {format, num_channels, freq }; + if (!sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice); sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec); - SDL_Log((sdlAudioDevice == 0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); - for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) - channels[i].state = JA_CHANNEL_FREE; - for (int i = 0; i < JA_MAX_GROUPS; ++i) - JA_soundVolume[i] = 0.5f; - // SDL_PauseAudioDevice(sdlAudioDevice); - JA_timerID = SDL_AddTimer(30, JA_UpdateCallback, nullptr); + SDL_Log( (sdlAudioDevice==0) ? "Failed to initialize SDL audio!\n" : "OK!\n"); + for (int i=0; ispec.channels = chan; music->spec.freq = samplerate; music->spec.format = SDL_AUDIO_S16; - music->buffer = (Uint8 *)SDL_malloc(music->length); + music->buffer = (Uint8*)SDL_malloc(music->length); SDL_memcpy(music->buffer, output, music->length); free(output); music->pos = 0; @@ -148,19 +152,19 @@ JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length) { return music; } -JA_Music_t *JA_LoadMusic(const char *filename) { +JA_Music_t *JA_LoadMusic(const char* filename) +{ // [RZC 28/08/22] Carreguem primer el arxiu en memòria i després el descomprimim. Es algo més rapid. FILE *f = fopen(filename, "rb"); fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); - Uint8 *buffer = (Uint8 *)malloc(fsize + 1); - if (fread(buffer, fsize, 1, f) != 1) - return NULL; + Uint8 *buffer = (Uint8*)malloc(fsize + 1); + if (fread(buffer, fsize, 1, f)!=1) return NULL; fclose(f); JA_Music_t *music = JA_LoadMusic(buffer, fsize); - music->filename = (char *)malloc(strlen(filename) + 1); + music->filename = (char*)malloc(strlen(filename)+1); strcpy(music->filename, filename); free(buffer); @@ -168,9 +172,9 @@ JA_Music_t *JA_LoadMusic(const char *filename) { return music; } -void JA_PlayMusic(JA_Music_t *music, const int loop) { - if (!JA_musicEnabled) - return; +void JA_PlayMusic(JA_Music_t *music, const int loop) +{ + if (!JA_musicEnabled) return; JA_StopMusic(); @@ -180,62 +184,56 @@ void JA_PlayMusic(JA_Music_t *music, const int loop) { current_music->times = loop; current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec); - if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) - printf("[ERROR] SDL_PutAudioStreamData failed!\n"); + if (!SDL_PutAudioStreamData(current_music->stream, current_music->buffer, current_music->length)) printf("[ERROR] SDL_PutAudioStreamData failed!\n"); SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); - if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) - printf("[ERROR] SDL_BindAudioStream failed!\n"); - // SDL_ResumeAudioStreamDevice(current_music->stream); + if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) printf("[ERROR] SDL_BindAudioStream failed!\n"); + //SDL_ResumeAudioStreamDevice(current_music->stream); } -char *JA_GetMusicFilename(JA_Music_t *music) { - if (!music) - music = current_music; +char *JA_GetMusicFilename(JA_Music_t *music) +{ + if (!music) music = current_music; return music->filename; } -void JA_PauseMusic() { - if (!JA_musicEnabled) - return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) - return; +void JA_PauseMusic() +{ + if (!JA_musicEnabled) return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; current_music->state = JA_MUSIC_PAUSED; - // SDL_PauseAudioStreamDevice(current_music->stream); + //SDL_PauseAudioStreamDevice(current_music->stream); SDL_UnbindAudioStream(current_music->stream); } -void JA_ResumeMusic() { - if (!JA_musicEnabled) - return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) - return; +void JA_ResumeMusic() +{ + if (!JA_musicEnabled) return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; current_music->state = JA_MUSIC_PLAYING; - // SDL_ResumeAudioStreamDevice(current_music->stream); + //SDL_ResumeAudioStreamDevice(current_music->stream); SDL_BindAudioStream(sdlAudioDevice, current_music->stream); } -void JA_StopMusic() { - if (!JA_musicEnabled) - return; - if (!current_music || current_music->state == JA_MUSIC_INVALID) - return; +void JA_StopMusic() +{ + if (!JA_musicEnabled) return; + if (!current_music || current_music->state == JA_MUSIC_INVALID) return; current_music->pos = 0; current_music->state = JA_MUSIC_STOPPED; - // SDL_PauseAudioStreamDevice(current_music->stream); + //SDL_PauseAudioStreamDevice(current_music->stream); SDL_DestroyAudioStream(current_music->stream); current_music->stream = nullptr; free(current_music->filename); current_music->filename = nullptr; } -void JA_FadeOutMusic(const int milliseconds) { - if (!JA_musicEnabled) - return; - if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) - return; +void JA_FadeOutMusic(const int milliseconds) +{ + if (!JA_musicEnabled) return; + if (current_music == NULL || current_music->state == JA_MUSIC_INVALID) return; fading = true; fade_start_time = SDL_GetTicks(); @@ -243,81 +241,83 @@ void JA_FadeOutMusic(const int milliseconds) { fade_initial_volume = JA_musicVolume; } -JA_Music_state JA_GetMusicState() { - if (!JA_musicEnabled) - return JA_MUSIC_DISABLED; - if (!current_music) - return JA_MUSIC_INVALID; +JA_Music_state JA_GetMusicState() +{ + if (!JA_musicEnabled) return JA_MUSIC_DISABLED; + if (!current_music) return JA_MUSIC_INVALID; return current_music->state; } -void JA_DeleteMusic(JA_Music_t *music) { - if (current_music == music) - current_music = nullptr; +void JA_DeleteMusic(JA_Music_t *music) +{ + if (current_music == music) current_music = nullptr; SDL_free(music->buffer); - if (music->stream) - SDL_DestroyAudioStream(music->stream); + if (music->stream) SDL_DestroyAudioStream(music->stream); delete music; } -float JA_SetMusicVolume(float volume) { - JA_musicVolume = SDL_clamp(volume, 0.0f, 1.0f); - if (current_music) - SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); +float JA_SetMusicVolume(float volume) +{ + JA_musicVolume = SDL_clamp( volume, 0.0f, 1.0f ); + if (current_music) SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume); return JA_musicVolume; } -void JA_SetMusicPosition(float value) { - if (!current_music) - return; +void JA_SetMusicPosition(float value) +{ + if (!current_music) return; current_music->pos = value * current_music->spec.freq; } -float JA_GetMusicPosition() { - if (!current_music) - return 0; - return float(current_music->pos) / float(current_music->spec.freq); +float JA_GetMusicPosition() +{ + if (!current_music) return 0; + return float(current_music->pos)/float(current_music->spec.freq); } -void JA_EnableMusic(const bool value) { - if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) - JA_StopMusic(); +void JA_EnableMusic(const bool value) +{ + if ( !value && current_music && (current_music->state==JA_MUSIC_PLAYING) ) JA_StopMusic(); JA_musicEnabled = value; } -JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length) { + + + + +JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length) +{ JA_Sound_t *sound = new JA_Sound_t(); sound->buffer = buffer; sound->length = length; return sound; } -JA_Sound_t *JA_LoadSound(uint8_t *buffer, uint32_t size) { +JA_Sound_t *JA_LoadSound(uint8_t* buffer, uint32_t size) +{ JA_Sound_t *sound = new JA_Sound_t(); - SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &sound->buffer, &sound->length); + SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size),1, &sound->spec, &sound->buffer, &sound->length); return sound; } -JA_Sound_t *JA_LoadSound(const char *filename) { +JA_Sound_t *JA_LoadSound(const char* filename) +{ JA_Sound_t *sound = new JA_Sound_t(); SDL_LoadWAV(filename, &sound->spec, &sound->buffer, &sound->length); return sound; } -int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group) { - if (!JA_soundEnabled) - return -1; +int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group) +{ + if (!JA_soundEnabled) return -1; int channel = 0; - while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { - channel++; - } - if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) - channel = 0; + while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; } + if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) channel = 0; JA_StopChannel(channel); channels[channel].sound = sound; @@ -332,12 +332,11 @@ int JA_PlaySound(JA_Sound_t *sound, const int loop, const int group) { return channel; } -int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, const int group) { - if (!JA_soundEnabled) - return -1; +int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, const int group) +{ + if (!JA_soundEnabled) return -1; - if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) - return -1; + if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1; JA_StopChannel(channel); channels[channel].sound = sound; @@ -352,71 +351,82 @@ int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop, return channel; } -void JA_DeleteSound(JA_Sound_t *sound) { +void JA_DeleteSound(JA_Sound_t *sound) +{ for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].sound == sound) - JA_StopChannel(i); + if (channels[i].sound == sound) JA_StopChannel(i); } SDL_free(sound->buffer); delete sound; } -void JA_PauseChannel(const int channel) { - if (!JA_soundEnabled) - return; +void JA_PauseChannel(const int channel) +{ + if (!JA_soundEnabled) return; - if (channel == -1) { + if (channel == -1) + { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) - if (channels[i].state == JA_CHANNEL_PLAYING) { + if (channels[i].state == JA_CHANNEL_PLAYING) + { channels[i].state = JA_CHANNEL_PAUSED; - // SDL_PauseAudioStreamDevice(channels[i].stream); + //SDL_PauseAudioStreamDevice(channels[i].stream); SDL_UnbindAudioStream(channels[i].stream); } - } else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { - if (channels[channel].state == JA_CHANNEL_PLAYING) { + } + else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) + { + if (channels[channel].state == JA_CHANNEL_PLAYING) + { channels[channel].state = JA_CHANNEL_PAUSED; - // SDL_PauseAudioStreamDevice(channels[channel].stream); + //SDL_PauseAudioStreamDevice(channels[channel].stream); SDL_UnbindAudioStream(channels[channel].stream); } } } -void JA_ResumeChannel(const int channel) { - if (!JA_soundEnabled) - return; +void JA_ResumeChannel(const int channel) +{ + if (!JA_soundEnabled) return; - if (channel == -1) { + if (channel == -1) + { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) - if (channels[i].state == JA_CHANNEL_PAUSED) { + if (channels[i].state == JA_CHANNEL_PAUSED) + { channels[i].state = JA_CHANNEL_PLAYING; - // SDL_ResumeAudioStreamDevice(channels[i].stream); + //SDL_ResumeAudioStreamDevice(channels[i].stream); SDL_BindAudioStream(sdlAudioDevice, channels[i].stream); } - } else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { - if (channels[channel].state == JA_CHANNEL_PAUSED) { + } + else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) + { + if (channels[channel].state == JA_CHANNEL_PAUSED) + { channels[channel].state = JA_CHANNEL_PLAYING; - // SDL_ResumeAudioStreamDevice(channels[channel].stream); + //SDL_ResumeAudioStreamDevice(channels[channel].stream); SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream); } } } -void JA_StopChannel(const int channel) { - if (!JA_soundEnabled) - return; +void JA_StopChannel(const int channel) +{ + if (!JA_soundEnabled) return; - if (channel == -1) { + if (channel == -1) + { for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].state != JA_CHANNEL_FREE) - SDL_DestroyAudioStream(channels[i].stream); + if (channels[i].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[i].stream); channels[i].stream = nullptr; channels[i].state = JA_CHANNEL_FREE; channels[i].pos = 0; channels[i].sound = NULL; } - } else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) { - if (channels[channel].state != JA_CHANNEL_FREE) - SDL_DestroyAudioStream(channels[channel].stream); + } + else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) + { + if (channels[channel].state != JA_CHANNEL_FREE) SDL_DestroyAudioStream(channels[channel].stream); channels[channel].stream = nullptr; channels[channel].state = JA_CHANNEL_FREE; channels[channel].pos = 0; @@ -424,40 +434,41 @@ void JA_StopChannel(const int channel) { } } -JA_Channel_state JA_GetChannelState(const int channel) { - if (!JA_soundEnabled) - return JA_SOUND_DISABLED; +JA_Channel_state JA_GetChannelState(const int channel) +{ + if (!JA_soundEnabled) return JA_SOUND_DISABLED; - if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) - return JA_CHANNEL_INVALID; + if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID; return channels[channel].state; } -float JA_SetSoundVolume(float volume, const int group) { - const float v = SDL_clamp(volume, 0.0f, 1.0f); +float JA_SetSoundVolume(float volume, const int group) +{ + const float v = SDL_clamp( volume, 0.0f, 1.0f ); for (int i = 0; i < JA_MAX_GROUPS; ++i) { - if (group == -1 || group == i) - JA_soundVolume[i] = v; + if (group==-1 || group==i) JA_soundVolume[i]=v; } for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) - if (((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) && - ((group == -1) || (channels[i].group == group))) + if ( ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) && + ((group==-1) || (channels[i].group==group)) ) SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[i]); return v; } -void JA_EnableSound(const bool value) { - for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) { - if (channels[i].state == JA_CHANNEL_PLAYING) - JA_StopChannel(i); +void JA_EnableSound(const bool value) +{ + for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) + { + if (channels[i].state == JA_CHANNEL_PLAYING) JA_StopChannel(i); } JA_soundEnabled = value; } -float JA_SetVolume(float volume) { +float JA_SetVolume(float volume) +{ JA_SetSoundVolume(JA_SetMusicVolume(volume) / 2.0f); return JA_musicVolume; diff --git a/source/external/jail_audio.h b/source/external/jail_audio.h index 42a89cd..716b7f9 100644 --- a/source/external/jail_audio.h +++ b/source/external/jail_audio.h @@ -1,29 +1,19 @@ #pragma once #include -enum JA_Channel_state { - JA_CHANNEL_INVALID, - JA_CHANNEL_FREE, - JA_CHANNEL_PLAYING, - JA_CHANNEL_PAUSED, - JA_SOUND_DISABLED -}; -enum JA_Music_state { - JA_MUSIC_INVALID, - JA_MUSIC_PLAYING, - JA_MUSIC_PAUSED, - JA_MUSIC_STOPPED, - JA_MUSIC_DISABLED -}; +enum JA_Channel_state { JA_CHANNEL_INVALID, JA_CHANNEL_FREE, JA_CHANNEL_PLAYING, JA_CHANNEL_PAUSED, JA_SOUND_DISABLED }; +enum JA_Music_state { JA_MUSIC_INVALID, JA_MUSIC_PLAYING, JA_MUSIC_PAUSED, JA_MUSIC_STOPPED, JA_MUSIC_DISABLED }; struct JA_Sound_t; struct JA_Music_t; +void JA_Update(); + void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels); void JA_Quit(); -JA_Music_t *JA_LoadMusic(const char *filename); -JA_Music_t *JA_LoadMusic(Uint8 *buffer, Uint32 length); +JA_Music_t *JA_LoadMusic(const char* filename); +JA_Music_t *JA_LoadMusic(Uint8* buffer, Uint32 length); void JA_PlayMusic(JA_Music_t *music, const int loop = -1); char *JA_GetMusicFilename(JA_Music_t *music = nullptr); void JA_PauseMusic(); @@ -37,17 +27,17 @@ void JA_SetMusicPosition(float value); float JA_GetMusicPosition(); void JA_EnableMusic(const bool value); -JA_Sound_t *JA_NewSound(Uint8 *buffer, Uint32 length); -JA_Sound_t *JA_LoadSound(Uint8 *buffer, Uint32 length); -JA_Sound_t *JA_LoadSound(const char *filename); -int JA_PlaySound(JA_Sound_t *sound, const int loop = 0, const int group = 0); -int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0, const int group = 0); +JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length); +JA_Sound_t *JA_LoadSound(Uint8* buffer, Uint32 length); +JA_Sound_t *JA_LoadSound(const char* filename); +int JA_PlaySound(JA_Sound_t *sound, const int loop = 0, const int group=0); +int JA_PlaySoundOnChannel(JA_Sound_t *sound, const int channel, const int loop = 0, const int group=0); void JA_PauseChannel(const int channel); void JA_ResumeChannel(const int channel); void JA_StopChannel(const int channel); JA_Channel_state JA_GetChannelState(const int channel); void JA_DeleteSound(JA_Sound_t *sound); -float JA_SetSoundVolume(float volume, const int group = 0); +float JA_SetSoundVolume(float volume, const int group=0); void JA_EnableSound(const bool value); float JA_SetVolume(float volume); diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index 384c81d..e6de052 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -104,18 +104,17 @@ void Credits::update() { fillCanvas(); } + static const auto audio = Audio::get(); + audio->update(); } // Dibuja Credits::en patalla void Credits::render() { - // Prepara para empezar a dibujar en la textura de juego - Screen::get()->start(); + static const auto screen = Screen::get(); - // Copia la textura con la zona de juego a la pantalla - SDL_RenderTexture(Screen::get()->getRenderer(), canvas_, nullptr, nullptr); - - // Vuelca el contenido del renderizador en pantalla - Screen::get()->render(); + screen->start(); // Prepara para empezar a dibujar en la textura de juego + SDL_RenderTexture(screen->getRenderer(), canvas_, nullptr, nullptr); // Copia la textura con la zona de juego a la pantalla + screen->render(); // Vuelca el contenido del renderizador en pantalla } // Comprueba el manejador de eventos diff --git a/source/sections/game.cpp b/source/sections/game.cpp index 3b1a5cb..9a1479c 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -6,8 +6,8 @@ #include // Para array #include // Para rand, size_t #include // Para function -#include // Para distance, size #include // Para std::cout, std::endl +#include // Para distance, size #include "asset.h" // Para Asset #include "audio.h" // Para Audio @@ -886,40 +886,59 @@ void Game::updateTimeStopped() { void Game::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { ticks_ = SDL_GetTicks(); + screen_->update(); checkServiceMenu(); updateDemo(); #ifdef RECORDING updateRecording(); #endif - if (!paused_) { - switch (state_) { - case GameState::FADE_IN: - updateGameStateFadeIn(); - break; - case GameState::ENTERING_PLAYER: - updateGameStateEnteringPlayer(); - break; - case GameState::SHOWING_GET_READY_MESSAGE: - updateGameStateShowingGetReadyMessage(); - break; - case GameState::PLAYING: - updateGameStatePlaying(); - break; - case GameState::COMPLETED: - updateGameStateCompleted(); - break; - case GameState::GAME_OVER: - updateGameStateGameOver(); - break; - default: - break; - } - } - - screen_->update(); + updateGameStates(); fillCanvas(); } + + static const auto audio = Audio::get(); + audio->update(); +} + +// Dibuja el juego +void Game::render() { + screen_->start(); // Prepara para empezar a dibujar en la textura de juego + + SDL_RenderTexture(renderer_, canvas_, nullptr, ¶m.game.play_area.rect); // Copia la textura con la zona de juego a la pantalla + scoreboard_->render(); // Dibuja el marcador + fade_in_->render(); // Dibuja el fade de entrada + fade_out_->render(); // Dibuja el fade de salida + + screen_->render(); // Vuelca el contenido del renderizador en pantalla +} + +// Actualiza los estados del juego +void Game::updateGameStates() { + if (!paused_) { + switch (state_) { + case GameState::FADE_IN: + updateGameStateFadeIn(); + break; + case GameState::ENTERING_PLAYER: + updateGameStateEnteringPlayer(); + break; + case GameState::SHOWING_GET_READY_MESSAGE: + updateGameStateShowingGetReadyMessage(); + break; + case GameState::PLAYING: + updateGameStatePlaying(); + break; + case GameState::COMPLETED: + updateGameStateCompleted(); + break; + case GameState::GAME_OVER: + updateGameStateGameOver(); + break; + default: + break; + } + } } // Actualiza el fondo @@ -971,25 +990,6 @@ void Game::fillCanvas() { SDL_SetRenderTarget(renderer_, temp); } -// Dibuja el juego -void Game::render() { - // Prepara para empezar a dibujar en la textura de juego - screen_->start(); - - // Copia la textura con la zona de juego a la pantalla - SDL_RenderTexture(renderer_, canvas_, nullptr, ¶m.game.play_area.rect); - - // Dibuja el marcador - scoreboard_->render(); - - // Dibuja el fade - fade_in_->render(); - fade_out_->render(); - - // Vuelca el contenido del renderizador en pantalla - screen_->render(); -} - // Habilita el efecto del item de detener el tiempo void Game::enableTimeStopItem() { balloon_manager_->stopAllBalloons(); @@ -1786,8 +1786,8 @@ void Game::playSound(const std::string &name) const { return; } - static auto *audio_ = Audio::get(); - audio_->playSound(name); + static auto audio = Audio::get(); + audio->playSound(name); } // Organiza los jugadores para que los vivos se pinten sobre los muertos @@ -1895,14 +1895,14 @@ void Game::checkDebugEvents(const SDL_Event &event) { tabe_->enable(); break; } - case SDLK_KP_PLUS:{ + case SDLK_KP_PLUS: { ++formation_id; balloon_manager_->destroyAllBalloons(); balloon_manager_->deployFormation(formation_id); std::cout << formation_id << std::endl; break; } - case SDLK_KP_MINUS:{ + case SDLK_KP_MINUS: { --formation_id; balloon_manager_->destroyAllBalloons(); balloon_manager_->deployFormation(formation_id); diff --git a/source/sections/game.h b/source/sections/game.h index 13c3a63..afc320f 100644 --- a/source/sections/game.h +++ b/source/sections/game.h @@ -150,101 +150,152 @@ class Game { #ifdef _DEBUG bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados - - // Comprueba los eventos en el modo DEBUG - void checkDebugEvents(const SDL_Event &event); #endif - // --- Métodos internos --- - void update(); // Actualiza el juego - void render(); // Dibuja el juego - void checkEvents(); // Comprueba los eventos que hay en cola - void setResources(); // Asigna texturas y animaciones - void updateHiScore(); // Actualiza el valor de HiScore en caso necesario - void updatePlayers(); // Actualiza las variables del jugador - void renderPlayers(); // Dibuja a los jugadores - void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables - void updateGameStateGameOver(); // Actualiza el estado de fin de la partida - void destroyAllItems(); // Destruye todos los items - auto checkPlayerBalloonCollision(std::shared_ptr &player) -> std::shared_ptr; // Comprueba la colisión entre el jugador y los globos activos - void checkPlayerItemCollision(std::shared_ptr &player); // Comprueba la colisión entre el jugador y los items - void checkBulletCollision(); // Comprueba y procesa la colisión de las balas - void updateBullets(); // Mueve las balas activas - void renderBullets(); // Pinta las balas activas - void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea un objeto bala - void freeBullets(); // Vacia el vector de balas - void updateItems(); // Actualiza los items - void renderItems(); // Pinta los items activos - auto dropItem() -> ItemType; // Devuelve un item en función del azar - void createItem(ItemType type, float x, float y); // Crea un objeto item - void freeItems(); // Vacia el vector de items - void createItemText(int x, std::shared_ptr texture); // Crea un objeto PathSprite - void createMessage(const std::vector &paths, std::shared_ptr texture); // Crea un objeto PathSprite - void freeSmartSprites(); // Vacia el vector de smartsprites - void freePathSprites(); // Vacia el vector de pathsprites - void throwCoffee(int x, int y); // Crea un SpriteSmart para arrojar el item café al recibir un impacto - void updateSmartSprites(); // Actualiza los SpriteSmarts - void renderSmartSprites(); // Pinta los SpriteSmarts activos - void updatePathSprites(); // Actualiza los PathSprites - void renderPathSprites(); // Pinta los PathSprites activos - void handlePlayerCollision(std::shared_ptr &player); // Acciones a realizar cuando el jugador colisiona con un globo - void updateTimeStopped(); // Actualiza y comprueba el valor de la variable - void updateBackground(); // Actualiza el fondo - void initPaths(); // Inicializa las variables que contienen puntos de ruta para mover objetos - void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo - void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo - void updateHelper(); // Actualiza las variables de ayuda - auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar - auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar - auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar - void updateScoreboard(); // Actualiza el marcador - void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura - void pause(bool value); // Pausa el juego - void addScoreToScoreBoard(const std::shared_ptr &player); // Añade una puntuación a la tabla de records - void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo - void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores - auto getPlayer(int id) -> std::shared_ptr; // Obtiene un jugador a partir de su "id" - static auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador - void checkInput(); // Gestiona la entrada durante el juego - void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego. - void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos. - void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo. - void demoHandlePlayerInput(const std::shared_ptr &player, int index); // Procesa las entradas para un jugador específico durante el modo demo. - void handleFireInput(const std::shared_ptr &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos. - void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo). - void handleNormalPlayerInput(const std::shared_ptr &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal. - void handleFireInputs(const std::shared_ptr &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado. - void handlePlayerContinue(const std::shared_ptr &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio. - void handleNameInput(const std::shared_ptr &player); // Procesa las entradas para la introducción del nombre del jugador. - void initDemo(int player_id); // Inicializa las variables para el modo DEMO - void setTotalPower(); // Calcula el poder total necesario para completar el juego - void initScoreboard(); // Inicializa el marcador - void initDifficultyVars(); // Inicializa las opciones relacionadas con la dificultad - void initPlayers(int player_id); // Inicializa los jugadores - static void playMusic(); // Hace sonar la música - void stopMusic() const; // Detiene la música - void playSound(const std::string &name) const; // Hace sonar un sonido - void updateDemo(); // Actualiza las variables durante el modo demo - void updateGameStateFadeIn(); // Actualiza las variables durante dicho estado - void updateGameStateEnteringPlayer(); // Actualiza las variables durante dicho estado - void updateGameStateShowingGetReadyMessage(); // Actualiza las variables durante dicho estado - void updateGameStatePlaying(); // Actualiza las variables durante el transcurso normal del juego - void updateGameStateCompleted(); // Gestiona eventos para el estado del final del juego - void checkState(); // Comprueba el estado del juego - void cleanVectors(); // Vacía los vectores de elementos deshabilitados - void updateMenace(); // Gestiona el nivel de amenaza - void evaluateAndSetMenace(); // Calcula y establece el valor de amenaza en funcion de los globos activos - void checkAndUpdateBalloonSpeed(); // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase - void setState(GameState state); // Cambia el estado del juego - void movePlayersToFront(); // Organiza los jugadores para que los vivos se pinten sobre los muertos - void checkServiceMenu(); // Comprueba si está activo el menu de servicio para poner el juego en pausa - auto checkBulletTabeCollision(std::shared_ptr bullet) -> bool; - void handleTabeHitEffects(); - auto checkBulletBalloonCollision(std::shared_ptr bullet) -> bool; - void processBalloonHit(std::shared_ptr bullet, std::shared_ptr balloon); - void handleItemDrop(std::shared_ptr balloon, std::shared_ptr player); - void handleBalloonDestruction(std::shared_ptr balloon, std::shared_ptr player); + // --- Ciclo principal del juego --- + void update(); // Actualiza la lógica principal del juego + void render(); // Renderiza todos los elementos del juego + void checkEvents(); // Procesa los eventos del sistema en cola + void checkState(); // Verifica y actualiza el estado actual del juego + void setState(GameState state); // Cambia el estado del juego + void pause(bool value); // Pausa o reanuda el juego + void cleanVectors(); // Limpia vectores de elementos deshabilitados + + // --- Gestión de estados del juego --- + void updateGameStates(); // Actualiza todos los estados del juego + void updateGameStateFadeIn(); // Gestiona el estado de transición de entrada + void updateGameStateEnteringPlayer(); // Gestiona el estado de entrada de jugador + void updateGameStateShowingGetReadyMessage(); // Gestiona el estado de mensaje "preparado" + void updateGameStatePlaying(); // Gestiona el estado de juego activo + void updateGameStateCompleted(); // Gestiona el estado de juego completado + void updateGameStateGameOver(); // Gestiona el estado de fin de partida + + // --- Gestión de jugadores --- + void initPlayers(int player_id); // Inicializa los datos de los jugadores + void updatePlayers(); // Actualiza las variables y estados de los jugadores + void renderPlayers(); // Renderiza todos los jugadores en pantalla + void movePlayersToFront(); // Reorganiza el orden de dibujado de jugadores + auto getPlayer(int id) -> std::shared_ptr; // Obtiene un jugador por su identificador + static auto getController(int player_id) -> int; // Obtiene el controlador asignado a un jugador + + // --- Estado de jugadores --- + void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Actualiza estado entre jugadores + void checkPlayersStatusPlaying(); // Verifica el estado de juego de todos los jugadores + auto allPlayersAreWaitingOrGameOver() -> bool; // Verifica si todos esperan o han perdido + auto allPlayersAreGameOver() -> bool; // Verifica si todos los jugadores han perdido + auto allPlayersAreNotPlaying() -> bool; // Verifica si ningún jugador está activo + + // --- Colisiones de jugadores --- + void handlePlayerCollision(std::shared_ptr &player); // Procesa colisión de jugador con globo + auto checkPlayerBalloonCollision(std::shared_ptr &player) -> std::shared_ptr; // Detecta colisión jugador-globo + void checkPlayerItemCollision(std::shared_ptr &player); // Detecta colisión jugador-ítem + + // --- Sistema de entrada (input) --- + void checkInput(); // Gestiona toda la entrada durante el juego + void checkPauseInput(); // Verifica solicitudes de pausa de controladores + + // --- Entrada de jugadores normales --- + void handlePlayersInput(); // Gestiona entrada de todos los jugadores + void handleNormalPlayerInput(const std::shared_ptr &player); // Procesa entrada de un jugador específico + void handleFireInput(const std::shared_ptr &player, BulletType bullet_type); // Gestiona disparo de jugador + void handleFireInputs(const std::shared_ptr &player, bool autofire, int controller_index); // Procesa disparos automáticos + void handlePlayerContinue(const std::shared_ptr &player); // Permite continuar al jugador + void handleNameInput(const std::shared_ptr &player); // Gestiona entrada de nombre del jugador + + // --- Entrada en modo demo --- + void demoHandleInput(); // Gestiona entrada durante el modo demostración + void demoHandlePassInput(); // Permite saltar la demostración + void demoHandlePlayerInput(const std::shared_ptr &player, int index); // Procesa entrada de jugador en demo + + // --- Sistema de balas y proyectiles --- + void updateBullets(); // Actualiza posición y estado de todas las balas + void renderBullets(); // Renderiza todas las balas activas + void createBullet(int x, int y, BulletType kind, bool powered_up, int owner); // Crea una nueva bala + void checkBulletCollision(); // Verifica colisiones de todas las balas + void freeBullets(); // Libera memoria del vector de balas + + // --- Colisiones específicas de balas --- + auto checkBulletTabeCollision(std::shared_ptr bullet) -> bool; // Detecta colisión bala-Tabe + auto checkBulletBalloonCollision(std::shared_ptr bullet) -> bool; // Detecta colisión bala-globo + void processBalloonHit(std::shared_ptr bullet, std::shared_ptr balloon); // Procesa impacto en globo + + // --- Sistema de ítems y power-ups --- + void updateItems(); // Actualiza posición y estado de todos los ítems + void renderItems(); // Renderiza todos los ítems activos + auto dropItem() -> ItemType; // Determina aleatoriamente qué ítem soltar + void createItem(ItemType type, float x, float y); // Crea un nuevo ítem en posición específica + void freeItems(); // Libera memoria del vector de ítems + void destroyAllItems(); // Elimina todos los ítems activos de la pantalla + + // --- ítems especiales --- + void enableTimeStopItem(); // Activa el efecto de detener el tiempo + void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo + void updateTimeStopped(); // Actualiza el estado del tiempo detenido + void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado + + // --- Gestión de caída de ítems --- + void handleItemDrop(std::shared_ptr balloon, std::shared_ptr player); // Gestiona caída de ítem desde globo + + // --- Sprites inteligentes (smartsprites) --- + void updateSmartSprites(); // Actualiza todos los sprites con lógica propia + void renderSmartSprites(); // Renderiza todos los sprites inteligentes + void freeSmartSprites(); // Libera memoria de sprites inteligentes + + // --- Sprites por ruta (pathsprites) --- + void updatePathSprites(); // Actualiza sprites que siguen rutas predefinidas + void renderPathSprites(); // Renderiza sprites animados por ruta + void freePathSprites(); // Libera memoria de sprites por ruta + void initPaths(); // Inicializa rutas predefinidas para animaciones + + // --- Creación de sprites especiales --- + void createItemText(int x, std::shared_ptr texture); // Crea texto animado para ítems + void createMessage(const std::vector &paths, std::shared_ptr texture); // Crea mensaje con animación por ruta + + // --- Sistema de globos y enemigos --- + void handleBalloonDestruction(std::shared_ptr balloon, std::shared_ptr player); // Procesa destrucción de globo + void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe + void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso + + // --- Gestión de fases y progresión --- + void updateStage(); // Verifica y actualiza cambio de fase + void setTotalPower(); // Calcula poder total necesario para completar el juego + void initDifficultyVars(); // Inicializa variables de dificultad + + // --- Sistema de amenaza --- + void updateMenace(); // Gestiona el nivel de amenaza del juego + void evaluateAndSetMenace(); // Calcula y establece amenaza según globos activos + + // --- Puntuación y marcador --- + void updateHiScore(); // Actualiza el récord máximo si es necesario + void updateScoreboard(); // Actualiza la visualización del marcador + void addScoreToScoreBoard(const std::shared_ptr &player); // Añade puntuación del jugador al marcador + void initScoreboard(); // Inicializa el sistema de puntuación + + // --- Modo demostración --- + void initDemo(int player_id); // Inicializa variables para el modo demostración + void updateDemo(); // Actualiza lógica específica del modo demo + + // --- Recursos y renderizado --- + void setResources(); // Asigna texturas y animaciones a los objetos + void updateBackground(); // Actualiza elementos del fondo + void fillCanvas(); // Renderiza elementos del área de juego en su textura + void updateHelper(); // Actualiza variables auxiliares de renderizado + + // --- Sistema de audio --- + static void playMusic(); // Reproduce la música de fondo + void stopMusic() const; // Detiene la reproducción de música + void playSound(const std::string &name) const; // Reproduce un efecto de sonido específico + + // --- Utilidades y servicios --- + void checkServiceMenu(); // Verifica si el menú de servicio está activo + +// SISTEMA DE GRABACIÓN (CONDICIONAL) #ifdef RECORDING - void updateRecording(); // Actualiza las variables durante el modo de grabación + void updateRecording(); // Actualiza variables durante modo de grabación +#endif + +// --- Depuración (solo en modo DEBUG) --- +#ifdef _DEBUG + void checkDebugEvents(const SDL_Event &event); // Comprueba los eventos en el modo DEBUG #endif }; \ No newline at end of file diff --git a/source/sections/hiscore_table.cpp b/source/sections/hiscore_table.cpp index db376be..f754fee 100644 --- a/source/sections/hiscore_table.cpp +++ b/source/sections/hiscore_table.cpp @@ -56,29 +56,33 @@ HiScoreTable::~HiScoreTable() { // Actualiza las variables void HiScoreTable::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { - // Actualiza el contador de ticks - ticks_ = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks + Screen::get()->update(); // Actualiza el objeto screen - // Actualiza las posiciones de los sprites de texto - updateSprites(); - - // Actualiza el fondo - background_->update(); - - // Gestiona el fade - updateFade(); - - // Gestiona el contador y sus eventos - updateCounter(); - - // Dibuja los sprites en la textura - fillTexture(); - - // Actualiza el objeto screen - Screen::get()->update(); - - // Actualiza las variables de globalInputs + updateSprites(); // Actualiza las posiciones de los sprites de texto + background_->update(); // Actualiza el fondo + updateFade(); // Gestiona el fade + updateCounter(); // Gestiona el contador y sus eventos + fillTexture(); // Dibuja los sprites en la textura } + + static const auto audio = Audio::get(); + audio->update(); +} + +// Pinta en pantalla +void HiScoreTable::render() { + static const auto screen = Screen::get(); + + screen->start(); // Prepara para empezar a dibujar en la textura de juego + screen->clean(); // Limpia la pantalla + + background_->render(); // Pinta el fondo + view_area_.y = std::max(0.0F, param.game.height - counter_ + 100); // Establece la ventana del backbuffer + SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador + fade_->render(); // Renderiza el fade + + screen->render(); // Vuelca el contenido del renderizador en pantalla } // Dibuja los sprites en la textura @@ -101,30 +105,6 @@ void HiScoreTable::fillTexture() { SDL_SetRenderTarget(renderer_, temp); } -// Pinta en pantalla -void HiScoreTable::render() { - // Prepara para empezar a dibujar en la textura de juego - Screen::get()->start(); - - // Limpia la pantalla - Screen::get()->clean(); - - // Pinta el fondo - background_->render(); - - // Establece la ventana del backbuffer - view_area_.y = std::max(0.0F, param.game.height - counter_ + 100); - - // Copia el backbuffer al renderizador - SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); - - // Renderiza el fade - fade_->render(); - - // Vuelca el contenido del renderizador en pantalla - Screen::get()->render(); -} - // Comprueba los eventos void HiScoreTable::checkEvents() { SDL_Event event; diff --git a/source/sections/instructions.cpp b/source/sections/instructions.cpp index 8e57af1..1a85126 100644 --- a/source/sections/instructions.cpp +++ b/source/sections/instructions.cpp @@ -206,42 +206,29 @@ void Instructions::fillBackbuffer() { // Actualiza las variables void Instructions::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { - // Actualiza el contador de ticks - ticks_ = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks + Screen::get()->update(); // Actualiza el objeto screen - // Actualiza el objeto screen - Screen::get()->update(); - - // Incrementa el contador - counter_++; - - // Actualiza los sprites - updateSprites(); - - // Gestiona la textura con los graficos - updateBackbuffer(); - - // Actualiza el mosaico de fondo - tiled_bg_->update(); - - // Actualiza el objeto "fade" - fade_->update(); - - // Rellena el backbuffer - fillBackbuffer(); + counter_++; // Incrementa el contador + updateSprites(); // Actualiza los sprites + updateBackbuffer(); // Gestiona la textura con los graficos + tiled_bg_->update(); // Actualiza el mosaico de fondo + fade_->update(); // Actualiza el objeto "fade" + fillBackbuffer(); // Rellena el backbuffer } + + static const auto audio = Audio::get(); + audio->update(); } // Pinta en pantalla void Instructions::render() { - // Prepara para empezar a dibujar en la textura de juego - Screen::get()->start(); + static const auto screen = Screen::get(); + + screen->start();// Prepara para empezar a dibujar en la textura de juego + screen->clean();// Limpia la pantalla - // Limpia la pantalla - Screen::get()->clean(); - - // Dibuja el mosacico de fondo - tiled_bg_->render(); + tiled_bg_->render();// Dibuja el mosacico de fondo // Copia la textura y el backbuffer al renderizador if (view_.y == 0) { @@ -250,10 +237,9 @@ void Instructions::render() { SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_); } - fade_->render(); - - // Vuelca el contenido del renderizador en pantalla - Screen::get()->render(); + fade_->render(); // Renderiza el fundido + + screen->render();// Vuelca el contenido del renderizador en pantalla } // Comprueba los eventos diff --git a/source/sections/intro.cpp b/source/sections/intro.cpp index 25eafbc..18c7b03 100644 --- a/source/sections/intro.cpp +++ b/source/sections/intro.cpp @@ -222,11 +222,10 @@ void Intro::switchText(int from_index, int to_index) { // Actualiza las variables del objeto void Intro::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { - // Actualiza el contador de ticks - ticks_ = SDL_GetTicks(); + ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks + Screen::get()->update(); // Actualiza el objeto screen - // Actualiza el fondo - tiled_bg_->update(); + tiled_bg_->update(); // Actualiza el fondo switch (state_) { case IntroState::SCENES: @@ -239,22 +238,20 @@ void Intro::update() { updatePostState(); break; } - - // Actualiza el objeto screen - Screen::get()->update(); } + + static const auto audio = Audio::get(); + audio->update(); } // Dibuja el objeto en pantalla void Intro::render() { - // Prepara para empezar a dibujar en la textura de juego - Screen::get()->start(); + static const auto screen = Screen::get(); + + screen->start();// Prepara para empezar a dibujar en la textura de juego + screen->clean();// Limpia la pantalla - // Limpia la pantalla - Screen::get()->clean(); - - // Dibuja el fondo - tiled_bg_->render(); + tiled_bg_->render();// Dibuja el fondo switch (state_) { case IntroState::SCENES: { @@ -266,9 +263,8 @@ void Intro::render() { case IntroState::POST: break; } - - // Vuelca el contenido del renderizador en pantalla - Screen::get()->render(); + + screen->render();// Vuelca el contenido del renderizador en pantalla } // Bucle principal diff --git a/source/sections/logo.cpp b/source/sections/logo.cpp index 601c2cc..de31cea 100644 --- a/source/sections/logo.cpp +++ b/source/sections/logo.cpp @@ -132,31 +132,28 @@ void Logo::updateTextureColors() { // Actualiza las variables void Logo::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { - // Actualiza el contador de ticks - ticks_ = SDL_GetTicks(); - - // Actualiza el objeto screen - Screen::get()->update(); - - // Comprueba las entradas - checkInput(); - - updateJAILGAMES(); - updateTextureColors(); - - // Gestiona el contador - ++counter_; + ticks_ = SDL_GetTicks(); // Actualiza el contador de ticks + Screen::get()->update(); // Actualiza el objeto screen + + updateJAILGAMES(); // Actualiza el logo de JAILGAMES + updateTextureColors(); // Actualiza los colores de las texturas + ++counter_; // Gestiona el contador } + + static const auto audio = Audio::get(); + audio->update(); } // Dibuja en pantalla void Logo::render() { - Screen::get()->start(); - Screen::get()->clean(); + static const auto screen = Screen::get(); + + screen->start(); + screen->clean(); renderJAILGAMES(); - Screen::get()->render(); + screen->render(); } // Bucle para el logo del juego diff --git a/source/sections/title.cpp b/source/sections/title.cpp index 5b9189f..e124aa7 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -79,29 +79,34 @@ Title::~Title() { void Title::update() { if (SDL_GetTicks() - ticks_ > param.game.speed) { ticks_ = SDL_GetTicks(); + Screen::get()->update(); + updateFade(); updateState(); updateStartPrompt(); updatePlayers(); - Screen::get()->update(); } + + static const auto audio = Audio::get(); + audio->update(); } // Dibuja el objeto en pantalla void Title::render() { - Screen::get()->start(); - Screen::get()->clean(); + static const auto screen = Screen::get(); + + screen->start(); + screen->clean(); tiled_bg_->render(); game_logo_->render(); renderPlayers(); renderStartPrompt(); renderCopyright(); - define_buttons_->render(); fade_->render(); - Screen::get()->render(); + screen->render(); } // Comprueba los eventos