- logo_scene, title_scene, intro_scene, room_fsm: missatges de cicle d'escena com a Log::info amb tag "scene" o "RoomFsm". Eliminats els TODO obsolets sobre el logger pendent. - game_scene (16 logs): events del bus (LEVEL COMPLETE, PLAYER HIT, PLAYER KILLED) com a info; transicions de ROOM com a info; warns als casos d'àudio absent o música no arrencada. - hud (3 logs): init i events com a info. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
422 lines
17 KiB
C++
422 lines
17 KiB
C++
#include "game/scenes/title_scene.hpp"
|
|
|
|
#include <SDL3/SDL.h>
|
|
|
|
#include <algorithm>
|
|
#include <cstdint>
|
|
#include <string>
|
|
#include <utility>
|
|
|
|
#include "core/audio/audio.hpp"
|
|
#include "core/input/gamepad_bindings.hpp"
|
|
#include "core/input/gamepad_manager.hpp"
|
|
#include "core/input/global_inputs.hpp"
|
|
#include "core/locale/locale.hpp"
|
|
#include "core/rendering/notifier.hpp"
|
|
#include "core/rendering/render_info.hpp"
|
|
#include "core/rendering/screen.hpp"
|
|
#include "core/rendering/surface.hpp"
|
|
#include "core/rendering/text.hpp"
|
|
#include "core/resources/resource_cache.hpp"
|
|
#include "core/system/event_buffer.hpp"
|
|
#include "core/ui/ui_config.hpp"
|
|
#include "game/options.hpp"
|
|
#include "game/scenes/scene_flow.hpp"
|
|
#include "utils/defaults.hpp"
|
|
#include "utils/defines.hpp"
|
|
#include "utils/easing.hpp"
|
|
#include "utils/log.hpp"
|
|
|
|
namespace {
|
|
|
|
// TODO: migrar a un logger unificat quan es decideixi (veure INC-03 a
|
|
// docs/audit-core-rendering.md).
|
|
const char* const SCENE_NAME = "TITLE";
|
|
|
|
// Detecta una pulsació de START dins el frame actual per al jugador
|
|
// indicat. Combina events de teclat (scancode hardcoded a Defaults::
|
|
// KeysGame[P2]) i events de gamepad (botó remapejable via
|
|
// GamepadBindings, lligat al pad assignat al jugador via Options).
|
|
auto pressedStart(int player_id) -> bool {
|
|
const SDL_Scancode KB = (player_id == 0) ? Defaults::KeysGame::START : Defaults::KeysGameP2::START;
|
|
SDL_Gamepad* pad = GamepadManager::get().getForPlayer(player_id);
|
|
const SDL_JoystickID PAD_ID = (pad != nullptr) ? SDL_GetGamepadID(pad) : 0;
|
|
const auto& slot = (player_id == 0) ? Options::controls().gamepad_p1
|
|
: Options::controls().gamepad_p2;
|
|
const int START_BTN = GamepadBindings::get().getButton(slot.name, slot.path, GamepadBindings::Action::START);
|
|
|
|
return std::ranges::any_of(EventBuffer::events, [&](const SDL_Event& ev) {
|
|
if (ev.type == SDL_EVENT_KEY_DOWN && ev.key.scancode == KB) { return true; }
|
|
if (ev.type == SDL_EVENT_GAMEPAD_BUTTON_DOWN && pad != nullptr && ev.gbutton.which == PAD_ID && static_cast<int>(ev.gbutton.button) == START_BTN) {
|
|
return true;
|
|
}
|
|
return false;
|
|
});
|
|
}
|
|
|
|
// Reproducció del so de START. Centralitzat ací per disparar-lo des
|
|
// dels punts on una pulsació té efecte real (entrada a STARTING o
|
|
// upgrade a BOTH); l'attract timeout no l'ha de tocar.
|
|
void playStartSound() {
|
|
if (auto* audio = Audio::get(); audio != nullptr) {
|
|
audio->playSound(UiConfig::get().playerStartSound(), Audio::Group::INTERFACE);
|
|
}
|
|
}
|
|
|
|
} // namespace
|
|
|
|
TitleScene::TitleScene(std::shared_ptr<Text> condensed_font, std::shared_ptr<Text> copyright_font, std::shared_ptr<Surface> background, std::shared_ptr<Surface> game_logo, std::shared_ptr<Surface> mini_logo)
|
|
: condensed_font_(std::move(condensed_font)),
|
|
copyright_font_(std::move(copyright_font)),
|
|
background_(std::move(background)),
|
|
game_logo_(std::move(game_logo)),
|
|
mini_logo_(std::move(mini_logo)),
|
|
timer_ms_(UiConfig::get().titleDurationMs()) {
|
|
Log::info("scene", "{} start", SCENE_NAME);
|
|
const auto& hh = UiConfig::get().titleHeatHaze();
|
|
if (hh.enabled) {
|
|
heat_haze_.emplace(Effects::HeatHaze::Params{
|
|
.amplitude_px = hh.amplitude_px,
|
|
.wavelength_px = hh.wavelength_px,
|
|
.speed_hz = hh.speed_hz,
|
|
});
|
|
}
|
|
fade_out_.emplace(Transitions::Mosaic::Params{
|
|
.max_block_size = UiConfig::get().titleFadeOutMaxBlock(),
|
|
});
|
|
attract_fade_.emplace();
|
|
// Fade-in inicial: arrenquem en negre opac i ens esvaïm cap a la
|
|
// imatge de fons. Sense lligar a cap fase — viu sempre al frame i
|
|
// un cop finished, `render()` és no-op fins que la TitleScene mor.
|
|
intro_fade_.begin(UiConfig::get().titleIntro().fade_in_ms, Transitions::FadeToBlack::Direction::FADE_IN);
|
|
|
|
// Música de fons en bucle. Es preloda al Director, així que la
|
|
// primera crida és immediata. El fade-out arrenca en entrar a
|
|
// STARTING (vore enterStarting); en ATTRACT_OUT NO es toca, la
|
|
// música segueix sonant cap a LOGO.
|
|
if (auto* audio = Audio::get(); audio != nullptr) {
|
|
audio->playMusic("title.ogg", -1);
|
|
}
|
|
}
|
|
|
|
TitleScene::~TitleScene() = default;
|
|
|
|
void TitleScene::update(int delta_ms) {
|
|
GlobalInputs::update(delta_ms);
|
|
if (GlobalInputs::wantsQuit()) {
|
|
wants_quit_ = true;
|
|
return;
|
|
}
|
|
|
|
if (heat_haze_) { heat_haze_->tick(delta_ms); }
|
|
|
|
// Fade-in inicial: tica sempre. Un cop finished, FadeToBlack::tick
|
|
// és idempotent (clamp intern al duration_ms_) i `render()` pinta
|
|
// alpha=0 (no-op) durant la resta del cicle.
|
|
intro_fade_.tick(delta_ms);
|
|
|
|
// Comptador del parpadeig: avança sempre amb `delta_ms` cru. La
|
|
// lectura (cicle/visible) la decideix `render()` segons la fase:
|
|
// IDLE usa visible_ms / hidden_ms del yaml (asimètric, 80/20 per
|
|
// defecte); STARTING usa un cicle simètric 50/50 amb període
|
|
// `starting_blink_period_ms`.
|
|
blink_elapsed_ms_ += delta_ms;
|
|
|
|
// Rellotge de la seqüència d'intro. Avança sempre — `enterStarting()`
|
|
// ja el força al final de la seqüència, així el seu valor a STARTING
|
|
// i ATTRACT_OUT és inofensiu (els consumidors clampen).
|
|
intro_elapsed_ms_ += delta_ms;
|
|
if (!press_start_armed_) {
|
|
const auto& intro = UiConfig::get().titleIntro();
|
|
if (intro_elapsed_ms_ >= intro.press_start_at_ms) {
|
|
// Resetegem el cicle del parpadeig a l'instant en què el
|
|
// PRESS START passa a ser visible per primera vegada, perquè
|
|
// el primer frame caigui en estat "on" (si no, el modulus
|
|
// amb el contador acumulat des de t=0 podria caure mig
|
|
// cicle i donar un primer "off" estrany).
|
|
press_start_armed_ = true;
|
|
blink_elapsed_ms_ = 0;
|
|
}
|
|
}
|
|
|
|
const bool P1_START = pressedStart(0);
|
|
const bool P2_START = pressedStart(1);
|
|
|
|
switch (phase_) {
|
|
case Phase::IDLE:
|
|
tickIdle(delta_ms, P1_START, P2_START);
|
|
break;
|
|
case Phase::STARTING:
|
|
tickStarting(delta_ms, P1_START, P2_START);
|
|
break;
|
|
case Phase::ATTRACT_OUT:
|
|
tickAttract(delta_ms);
|
|
break;
|
|
}
|
|
|
|
Notifier::get().update(delta_ms);
|
|
RenderInfo::get().update(delta_ms, Options::buildRenderInfoFrame(UiConfig::get().renderInfoText(), UiConfig::get().renderInfoShadow()));
|
|
}
|
|
|
|
void TitleScene::enterStarting(DebugConfig::StartingPlayers players) {
|
|
phase_ = Phase::STARTING;
|
|
pending_players_ = players;
|
|
starting_timer_ms_ = UiConfig::get().titleStartingMs();
|
|
// Resetem el comptador del parpadeig perquè el primer frame de
|
|
// STARTING comenci visible — sense això, el modulus amb el nou
|
|
// període podria caure mig cicle i donar un primer "off" estrany.
|
|
blink_elapsed_ms_ = 0;
|
|
|
|
// Shortcut: si l'usuari ha premut START durant la intro, saltem al
|
|
// final de la seqüència perquè el frame de STARTING comenci amb
|
|
// tot a la posició final i visible (sense salts ni elements en
|
|
// moviment a meitat). FadeToBlack::tick clampeja internament a
|
|
// duration_ms, així que un delta gegant l'avança a finished sense
|
|
// efectes secundaris.
|
|
const auto& intro = UiConfig::get().titleIntro();
|
|
const int INTRO_END_MS = std::max({
|
|
intro.game_logo_at_ms,
|
|
intro.mini_logo_at_ms + intro.mini_logo_slide_ms,
|
|
intro.copyright_at_ms + intro.copyright_slide_ms,
|
|
intro.press_start_at_ms,
|
|
});
|
|
intro_elapsed_ms_ = std::max(intro_elapsed_ms_, INTRO_END_MS);
|
|
press_start_armed_ = true;
|
|
intro_fade_.tick(INTRO_END_MS);
|
|
|
|
// Fade-out de la música. Si l'altre jugador prem START i el timer
|
|
// es reseteja, no rearranquem la música: es manté la fosa iniciada
|
|
// ací (consistent amb el fade visual, que tampoc es reverteix).
|
|
if (auto* audio = Audio::get(); audio != nullptr) {
|
|
audio->fadeOutMusic(UiConfig::get().titleMusicFadeOutMs());
|
|
}
|
|
Log::info("scene", "{} STARTING (players={})", SCENE_NAME, DebugConfig::toString(players));
|
|
}
|
|
|
|
void TitleScene::tickIdle(int delta_ms, bool p1_start, bool p2_start) {
|
|
timer_ms_ -= delta_ms;
|
|
if (p1_start) {
|
|
playStartSound();
|
|
enterStarting(DebugConfig::StartingPlayers::P1);
|
|
} else if (p2_start) {
|
|
playStartSound();
|
|
enterStarting(DebugConfig::StartingPlayers::P2);
|
|
} else if (timer_ms_ <= 0) {
|
|
// Attract timeout: ningú ha premut. Sortida silenciosa cap a
|
|
// LOGO amb fade-to-black; música i parpadeig intactes.
|
|
enterAttract();
|
|
}
|
|
}
|
|
|
|
void TitleScene::tickStarting(int delta_ms, bool p1_start, bool p2_start) {
|
|
starting_timer_ms_ -= delta_ms;
|
|
// Si l'altre jugador prem START dins de la finestra (i el fade
|
|
// encara no ha arrencat), pugem a BOTH i resetegem el comptador.
|
|
// Una vegada el fade ja està actiu, ignorem pulsacions per no
|
|
// saltar visualment la transició.
|
|
const bool OTHER_PRESSED =
|
|
(pending_players_ == DebugConfig::StartingPlayers::P1 && p2_start) ||
|
|
(pending_players_ == DebugConfig::StartingPlayers::P2 && p1_start);
|
|
const bool FADE_LOCKED = fade_out_ && (fade_out_->isActive() || fade_out_->isFinished());
|
|
if (OTHER_PRESSED && !FADE_LOCKED) {
|
|
playStartSound();
|
|
pending_players_ = DebugConfig::StartingPlayers::BOTH;
|
|
starting_timer_ms_ = UiConfig::get().titleStartingMs();
|
|
}
|
|
|
|
// Arrenca el fade quan al comptador li queden <= fade_out_ms, i
|
|
// només una vegada (ni en repeticions ni si l'altre jugador ha
|
|
// resetejat el timer).
|
|
const int FADE_MS = UiConfig::get().titleFadeOutMs();
|
|
if (fade_out_ && !fade_out_->isActive() && !fade_out_->isFinished() && starting_timer_ms_ <= FADE_MS && FADE_MS > 0) {
|
|
fade_out_->begin(FADE_MS);
|
|
}
|
|
if (fade_out_ && fade_out_->isActive()) { fade_out_->tick(delta_ms); }
|
|
|
|
if (starting_timer_ms_ <= 0) {
|
|
advanceToIntro(pending_players_);
|
|
}
|
|
}
|
|
|
|
void TitleScene::tickAttract(int delta_ms) {
|
|
// Sortida d'attract: només avancem el fade-to-black. Quan s'acaba
|
|
// demanem transició a LOGO. Cap input ni música ni canvi de
|
|
// freqüència de parpadeig — el text "press start" segueix amb el
|
|
// cicle d'IDLE per damunt del fade.
|
|
if (!attract_fade_) { return; }
|
|
attract_fade_->tick(delta_ms);
|
|
if (attract_fade_->isFinished()) {
|
|
advanceToLogo();
|
|
}
|
|
}
|
|
|
|
void TitleScene::enterAttract() {
|
|
phase_ = Phase::ATTRACT_OUT;
|
|
if (attract_fade_) {
|
|
attract_fade_->begin(UiConfig::get().titleAttractFadeToBlackMs());
|
|
}
|
|
Log::info("scene", "{} ATTRACT_OUT", SCENE_NAME);
|
|
}
|
|
|
|
void TitleScene::advanceToIntro(DebugConfig::StartingPlayers players) {
|
|
exit_request_ = ExitRequest{
|
|
.next = SceneId::INTRO,
|
|
.params = IntroParams{.starting_players = players},
|
|
};
|
|
}
|
|
|
|
void TitleScene::advanceToLogo() {
|
|
exit_request_ = ExitRequest{
|
|
.next = SceneId::LOGO,
|
|
.params = LogoParams{},
|
|
};
|
|
}
|
|
|
|
void TitleScene::render() {
|
|
const auto& intro = UiConfig::get().titleIntro();
|
|
|
|
renderBackground();
|
|
renderGameLogo(intro);
|
|
renderPressStart(intro);
|
|
renderFooter(intro);
|
|
Notifier::get().render();
|
|
renderTransitions();
|
|
RenderInfo::get().render();
|
|
Screen::get().present();
|
|
}
|
|
|
|
void TitleScene::renderBackground() {
|
|
// Fons: la imatge si està disponible (cobreix tot el canvas amb la
|
|
// seua paleta nadiua), opcionalment amb heat-haze; en cas contrari,
|
|
// color pla de la paleta UI com a fallback defensiu.
|
|
if (background_) {
|
|
if (heat_haze_) {
|
|
heat_haze_->render(*background_, 0, 0);
|
|
} else {
|
|
background_->render(0, 0);
|
|
}
|
|
return;
|
|
}
|
|
const auto& ui_config = UiConfig::get();
|
|
const auto& palette = Resource::Cache::get().getPalette("ui");
|
|
Screen::get().fillRect(0, 0, GameCanvas::WIDTH, GameCanvas::HEIGHT, palette[ui_config.titleBgColor()]);
|
|
}
|
|
|
|
void TitleScene::renderGameLogo(const UiConfig::TitleIntro& intro) {
|
|
// Visibilitat binària gestionada per la seqüència d'intro: a IDLE
|
|
// només es pinta a partir de `game_logo_at_ms`; fora d'IDLE sempre.
|
|
// TODO: aplicar fade-in alpha quan Surface suporti renderWithAlpha.
|
|
const bool VISIBLE = phase_ != Phase::IDLE || intro_elapsed_ms_ >= intro.game_logo_at_ms;
|
|
if (!game_logo_ || !VISIBLE) { return; }
|
|
const auto& ui_config = UiConfig::get();
|
|
const int LOGO_Y = (GameCanvas::HEIGHT * ui_config.titleLogoYPercent()) / 100;
|
|
const int LOGO_X = GameCanvas::CENTER_X - (game_logo_->getWidth() / 2);
|
|
game_logo_->render(LOGO_X, LOGO_Y);
|
|
}
|
|
|
|
void TitleScene::renderPressStart(const UiConfig::TitleIntro& intro) {
|
|
// A IDLE només apareix a partir de `press_start_at_ms`; fora d'IDLE
|
|
// (STARTING o ATTRACT_OUT) sempre, com fins ara.
|
|
const bool VISIBLE = phase_ != Phase::IDLE || intro_elapsed_ms_ >= intro.press_start_at_ms;
|
|
if (!condensed_font_ || !VISIBLE) { return; }
|
|
|
|
// Cicle de parpadeig: a IDLE pren visible_ms+hidden_ms del yaml
|
|
// (asimètric, 80/20 per defecte); a STARTING commuta a 50/50 amb
|
|
// `starting_blink_period_ms` per donar feedback de "polsat".
|
|
// Si el cicle val 0 (configuració degenerada), cau a "sempre visible".
|
|
const auto& ui_config = UiConfig::get();
|
|
int cycle_ms = 0;
|
|
int visible_ms = 0;
|
|
if (phase_ == Phase::STARTING) {
|
|
cycle_ms = std::max(0, ui_config.titleStartingBlinkPeriodMs());
|
|
visible_ms = cycle_ms / 2;
|
|
} else {
|
|
visible_ms = std::max(0, ui_config.titleBlinkVisibleMs());
|
|
cycle_ms = visible_ms + std::max(0, ui_config.titleBlinkHiddenMs());
|
|
}
|
|
const bool BLINK_ON = (cycle_ms == 0) || ((blink_elapsed_ms_ % cycle_ms) < visible_ms);
|
|
if (!BLINK_ON) { return; }
|
|
|
|
constexpr Uint8 OUTLINE_DIST = 1;
|
|
constexpr Uint8 STROKE4 = Text::CENTER_FLAG | Text::COLOR_FLAG | Text::STROKE4_FLAG;
|
|
const int PROMPT_Y = (GameCanvas::HEIGHT * ui_config.titlePromptYPercent()) / 100;
|
|
condensed_font_->writeDX(STROKE4,
|
|
GameCanvas::CENTER_X,
|
|
PROMPT_Y,
|
|
Locale::get().text("title.press_start"),
|
|
condensed_font_->getDefaultKerning() - 1,
|
|
ui_config.titleTextColor(),
|
|
OUTLINE_DIST,
|
|
ui_config.titlePressStartOutlineColor());
|
|
}
|
|
|
|
void TitleScene::renderFooter(const UiConfig::TitleIntro& intro) {
|
|
// Footer: minilogo centrat horitzontalment damunt del © de
|
|
// copyright. El text va al `title.copyright_y_percent`, el logo just
|
|
// damunt amb un petit gap (`title.mini_logo_gap_px`). El copyright fa
|
|
// servir una font pixel-art pròpia (Tiny5-Regular size 8) — més neta
|
|
// i petita que la del "press start" perquè la jerarquia tipogràfica
|
|
// del peu quedi clara.
|
|
if (!copyright_font_) { return; }
|
|
|
|
const auto& ui_config = UiConfig::get();
|
|
const int COPY_Y = (GameCanvas::HEIGHT * ui_config.titleCopyrightYPercent()) / 100;
|
|
const bool IDLE = phase_ == Phase::IDLE;
|
|
|
|
// Mini-logo: slide-in vertical des del marge inferior amb la corba
|
|
// `slide_curve`. Fora d'IDLE (o un cop completat) la Y és la final.
|
|
if (mini_logo_ && (!IDLE || intro_elapsed_ms_ >= intro.mini_logo_at_ms)) {
|
|
const int FINAL_Y = COPY_Y - mini_logo_->getHeight() - ui_config.titleMiniLogoGapPx();
|
|
int y = FINAL_Y;
|
|
if (IDLE && intro.mini_logo_slide_ms > 0) {
|
|
const float T = std::clamp(
|
|
static_cast<float>(intro_elapsed_ms_ - intro.mini_logo_at_ms) / static_cast<float>(intro.mini_logo_slide_ms),
|
|
0.0F,
|
|
1.0F);
|
|
y = Easing::lerpInt(GameCanvas::HEIGHT, FINAL_Y, intro.slide_curve(T));
|
|
}
|
|
const int LOGO_X = GameCanvas::CENTER_X - (mini_logo_->getWidth() / 2);
|
|
mini_logo_->render(LOGO_X, y);
|
|
}
|
|
|
|
// Copyright: mateix patró amb el seu propi tempo. La diferència
|
|
// de temps entre `mini_logo_at_ms` i `copyright_at_ms` controla
|
|
// el decalatge entre les dues entrades (per defecte 200 ms).
|
|
if (!IDLE || intro_elapsed_ms_ >= intro.copyright_at_ms) {
|
|
int y = COPY_Y;
|
|
if (IDLE && intro.copyright_slide_ms > 0) {
|
|
const float T = std::clamp(
|
|
static_cast<float>(intro_elapsed_ms_ - intro.copyright_at_ms) / static_cast<float>(intro.copyright_slide_ms),
|
|
0.0F,
|
|
1.0F);
|
|
y = Easing::lerpInt(GameCanvas::HEIGHT, COPY_Y, intro.slide_curve(T));
|
|
}
|
|
copyright_font_->writeDX(Text::CENTER_FLAG | Text::COLOR_FLAG,
|
|
GameCanvas::CENTER_X,
|
|
y,
|
|
"© 2026 JailDesigner",
|
|
copyright_font_->getDefaultKerning(),
|
|
ui_config.titleCopyrightColor());
|
|
}
|
|
}
|
|
|
|
void TitleScene::renderTransitions() {
|
|
// Fade-in inicial: capa negra que s'esvaeix cap a l'escena durant
|
|
// els primers `title.intro.fade_in_ms` ms. `render()` és no-op un
|
|
// cop finished, així que es queda penjat aquí sense lògica
|
|
// condicional. Va per damunt del Notifier — coherent amb la resta
|
|
// de transicions — però per davall del RenderInfo de debug.
|
|
intro_fade_.render();
|
|
|
|
// Capa de transició final segons la fase. Sempre cobreix l'escena
|
|
// i el Notifier, mai el RenderInfo (overlay de debug, sempre
|
|
// visible). STARTING usa mosaic dissolve; ATTRACT_OUT, fade-to-black
|
|
// lineal (sense efecte chunky perquè la sortida silenciosa s'integre
|
|
// amb la pista visual del LOGO).
|
|
if (phase_ == Phase::ATTRACT_OUT && attract_fade_) {
|
|
attract_fade_->render();
|
|
} else if (fade_out_ && (fade_out_->isActive() || fade_out_->isFinished())) {
|
|
fade_out_->render();
|
|
}
|
|
}
|